MQTT.js and Aedes broker basic practices

I use ESP32 publish message to MQTT broker powered by Aedes.

There are below error when I config wss MQTT broker and test with MQTT.js client.

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

The error tip data transfer by http/https. And MQTT.js only support tcp/tls or ws/wss.

So I try to find an solution with aedes-server-factory lib. After read docs and try many config options. I find the basic practices.

  • mqtts should use tls with key/cert like:

options = { tls: { key, cert } }
  • wss should use https with key/cert and add ws like:

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

Then I write my mqtt broker project with PostgreSQL persistence MQTT data. And publish on codeberg. The main options code like:

// other codes before...
  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)
  })

I deploy several MQTT brokers demo with basic function and no data log at below url:

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

Welcome to use for testing.

36