# NodeMCU MQTT with RabbitMQ and LavinMQ

[NodeMCU](https://nodemcu.readthedocs.io) is Lua firmware for ESP8266 and ESP32 boards. Its [mqtt module](https://nodemcu.readthedocs.io/en/release/modules/mqtt/) 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](https://nodemcu-build.com).

## 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`:

```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`:

```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](https://github.com/cloudamqp/examples/tree/main/lua/nodemcu). 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()`](https://nodemcu.readthedocs.io/en/release/modules/tls/#tlscertverify).
- **Use QoS 1**, so the `publish` callback runs once the broker has sent its PUBACK.
