0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Node.js: Let's Encrypt の証明書を使ったブローカーに接続

Posted at

こちらで作成したブローカーに接続する方法です。
Mosquitto で Let's Encrypt の証明書を使う

.env
HOST=abc.example.com
TOPIC=sensors/topic_1
publish_ca.js
# ! /usr/bin/node
// ---------------------------------------------------------------
//	publish_ca.js
//
//					Jan/23/2021
//
// ---------------------------------------------------------------
'use strict'
const mqtt = require('mqtt')
const fs = require('fs')
const dotenv = require('dotenv')
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
dotenv.config()
const host = `${process.env.HOST}`
const topic = `${process.env.TOPIC}`

const caFile = fs.readFileSync("/etc/ssl/certs/ca-certificates.crt")
const options = {
	rejectUnauthorized : false,
	ca:caFile 
}

const client  = mqtt.connect('mqtts://' + host + ':8883',options)

client.on('connect', function () {
	const today = new Date ()
	var ddx = (1900 + today.getYear ()) + "-" + (today.getMonth () +1)
	ddx += "-" + today.getDate () + " " + today.getHours()
	ddx += ":" + today.getMinutes () + ":" + today.getSeconds()
	client.publish(topic, ddx)
	console.log(ddx)
	client.publish(topic, 'Good Afternoon mqtts')
	client.publish(topic, 'こんにちは')
	client.end()
	console.error ("*** 終了 ***")
})

// ---------------------------------------------------------------

実行コマンド

export NODE_PATH=/usr/lib/node_modules
./publish_ca.js
subscribe_ca.js
# ! /usr/bin/node
// ---------------------------------------------------------------
//	subscribe.js
//
//						Jan/23/2021
//
// ---------------------------------------------------------------
'use strict'
const mqtt = require('mqtt')
const fs = require('fs')
const dotenv = require('dotenv')

// ---------------------------------------------------------------
console.error ("*** 開始 ***")
dotenv.config()
const host = `${process.env.HOST}`
const topic = `${process.env.TOPIC}`

const caFile = fs.readFileSync("/etc/ssl/certs/ca-certificates.crt")
const options = {
	rejectUnauthorized : false,
	ca:caFile
}

const client  = mqtt.connect('mqtts://www2.ekzemplaro.org:8883',options)

client.on('connect', function () {
    client.subscribe(topic)
})

client.on('message', function (topic, message) {
  // message is Buffer
    console.log(message.toString())
})

// ---------------------------------------------------------------

実行コマンド

export NODE_PATH=/usr/lib/node_modules
./subscribe_ca.js
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?