Node MQTT.js

如果您是使用Node MQTT,請參考下方範例程式, 請先下載certificate.zip檔案,將解壓縮後的 private.pem.key、certificate.pem.crt和AmazonRootCA1.pem放置在下列程式檔同樣的路徑下,並輸入在程式中KEYCERTTRUSTED_CA_LIST的變數中。

程式內的HOST請輸入文件頁面右上角的端點topic為平台頁面中的topic字串,data需透過JSON.stringify轉為string,資料內容請見資料格式PORT請使用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')
})

```

最后更新于