MQTT.js 使用与 Aedes broker 基础配置实践

最近一起在学习嵌入式开发,用 ESP32 开发板发送温湿度数据到基于 Node.js Aedes 模块的 MQTT broker。

当我尝试使用 wss 协议配置 MQTT broker,并使用 MQTT.js 客户端与之进行数据交互时,却报如下错误:

Error: Invalid header flag bits, must be 0x0 for puback packet

这一错误主要是提示数据传输使用的是纯 http 或 https。经过查询 MQTT.js 的文档,其仅支持 tcp/tls 或 ws/wss 。

所以我就尝试使用 aedes-server-factory 库进行配置的解决方案。经过阅读文档与不断尝试多种配置,总结出如下基本配置实践:

  • mqtts 需要使用 tls 参数配置 key/cert 密钥与证书,形如:

options = { tls: { key, cert } }
  • wss 需要使用 https 参数配置 key/cert 密钥与证书,形如:

options = { ws: true, https: { key, cert } }

经过实测已经编写集成 PostgreSQL 进行数据持久化的 MQTT broker 项目代码,基本达到可用状态,已经发布在 codeberg 上。其中主要的配置相关代码形如:

// 其他辅助代码
  const _port = port || 1883
  const options = { ws: opts.ws || false }
  if (opts.keypath && opts.certpath) {
    const key = readFileSync(opts.keypath)
    const cert = readFileSync(opts.certpath)
    if (options.ws) {
      options.https = { key, cert }//wss
    } else {
      options.tls = { key, cert }//mqtts
    }
  } else if (opts.key && opts.cert) {
    const { key, cert } = opts
    if (options.ws) {
      options.https = { key, cert }//wss
    } else {
      options.tls = { key, cert }//mqtts
    }
  }

  const httpServer = createServer(aedes, { ..._opt, ...options })
  httpServer.listen(_port, function () {
    let protocols = ' server listening on port'
    if (options.ws) {
      if (options.https) {
        protocols = 'wss' + protocols
      } else {
        protocols = 'ws' + protocols
      }
    } else {
      if (options.tls) {
        protocols = 'mqtts' + protocols
      } else {
        protocols = 'mqtt' + protocols
      }
    }
    console.log('Broker', aedes.id, protocols, _port)
  })

另外还部署了几个 MQTT brokers 演示服务,仅有基础功能,未保存任何数据日志或交互记录,仅在内存中保存有交互状态信息。网址如下:

# mqtt
mqtt://mqtt.anflext.com:11883
# mqtts
mqtts://mqtts.anflext.com:12883
# ws
ws://ws.anflext.com:21883
# wss
wss://wss.anflext.com:22883

欢迎大家试用,共同学习提高。

56