Node MQTT.js

If you are using Node MQTT, please refer to the example code below. First, download the certificate.zip file and place the decompressed private.pem.key, certificate.pem.crt, and AmazonRootCA1.pem files in the same path as the following program. Then, enter the variables KEY, CERT, and TRUSTED_CA_LIST in the program.

Please enter the HOST in the program, which can be found in the upper right corner of the document page. As for the topic, please check the "topic" document page. The "data" should be converted to a string using JSON.stringify, and the data format can be found in the documentation. As for Port, Please use 8883.

const mqtt = require('mqtt')
const fs = require('fs')
const path = require('path')
const KEY = fs.readFileSync(path.join(__dirname, '/private.pem.key'))
const CERT = fs.readFileSync(path.join(__dirname, '/certificate.pem.crt'))
const TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, '/AmazonRootCA1.pem'))

const PORT = 8883
const HOST = 'mqttssl.xplatform.tranx.io'
const topic = "XHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/XXXXX"
const options = {
  port: PORT,
  host: HOST,
  key: KEY,
  cert: CERT,
  rejectUnauthorized: true,
  // The CA list will be used to determine if server is authorized
  ca: TRUSTED_CA_LIST,
  protocol: 'mqtts'
}

const client = mqtt.connect(options)
let data = JSON.stringify({PowerUsage: 0, Temperature: 0, Motor: 0, DutyManager: 'John Doe'})
client.publish(topic, data)

client.on('connect', function () {
  console.log('Connected')
})

```

Last updated