NodeMCU MQTT with RabbitMQ and LavinMQ

NodeMCU is Lua firmware for ESP8266 and ESP32 boards. Its mqtt module is an MQTT 3.1.1 client. Build a firmware with the mqtt, wifi and node modules, and tls for port 8883, for example with the NodeMCU custom build service.

Publish and subscribe

Set the MQTT details from your instance’s details page in the CloudAMQP console at the top of both files. Port 8883 uses TLS.

Save the publisher as publisher.lua:

-- The MQTT details from your instance's details page in the CloudAMQP console
local MQTT_HOST = "host.cloudamqp.com"
local MQTT_PORT = 8883 -- TLS
local MQTT_USERNAME = "vhost:user"
local MQTT_PASSWORD = "password"

local client = mqtt.Client("publisher-" .. node.chipid(), 120, MQTT_USERNAME, MQTT_PASSWORD)
client:connect(MQTT_HOST, MQTT_PORT, MQTT_PORT == 8883, function()
  -- QoS 1, and the callback runs once the broker has sent its PUBACK
  client:publish("hello", "Hello world!", 1, 0, function()
    print(" [x] Sent 'Hello world!'")
    client:close()
  end)
end, function(_, reason)
  print("Connection failed: " .. reason)
end)

Save the subscriber as worker.lua:

-- The MQTT details from your instance's details page in the CloudAMQP console
local MQTT_HOST = "host.cloudamqp.com"
local MQTT_PORT = 8883 -- TLS
local MQTT_USERNAME = "vhost:user"
local MQTT_PASSWORD = "password"

local client = mqtt.Client("worker-" .. node.chipid(), 120, MQTT_USERNAME, MQTT_PASSWORD)
client:on("message", function(_, _, message)
  print(" [x] Received '" .. message .. "'")
end)
client:connect(MQTT_HOST, MQTT_PORT, MQTT_PORT == 8883, function()
  client:subscribe("hello", 1, function()
    print(" [*] Waiting for messages")
  end)
end, function(_, reason)
  print("Connection failed: " .. reason)
end)

Upload both, connect to WiFi, then run dofile("worker.lua") on one device and dofile("publisher.lua") on another.

The example is in lua/nodemcu in cloudamqp/examples. Unlike the other examples there, it isn’t tested in CI, as it needs NodeMCU firmware to run.

Good to know

  • Put the vhost in the username, as vhost:user. MQTT has no vhost of its own, and the console shows the username that way.
  • Load a CA certificate to verify the server. On port 8883 the connection is encrypted, but NodeMCU only verifies the server certificate once you’ve loaded a CA certificate with tls.cert.verify().
  • Use QoS 1, so the publish callback runs once the broker has sent its PUBACK.
Was this page helpful?

Thanks for your feedback!