MQTT Helpers
mqtt_publish(topic, payload, qos, retain, delay_ms, connection_id) → boolean
Publish an MQTT message. Returns true on success, false on failure. Raises error if topic is nil.
topic(string) - MQTT topic name (required)payload(string) - Message payload (can be empty)qos(number) - QoS level: 0 (at most once), 1 (at least once), 2 (exactly once)retain(boolean) - Retain flagdelay_ms(number) - Delay in ms before publishingconnection_id(number, optional) - Target connection (default: 0)
Reading MQTT metadata from a received message
Incoming MQTT messages carry topic, QoS, and retain flag as metadata. Use message:get_metadata(key) to read them:
| Key | Type | Description |
|---|---|---|
"mqtt_topic" | string | The topic the message was published on |
"mqtt_qos" | number | QoS level (0, 1, or 2) |
"mqtt_retain" | boolean | Whether the retain flag was set |
Example:
function on_receive()
local topic = message:get_metadata("mqtt_topic")
local qos = message:get_metadata("mqtt_qos")
local retain = message:get_metadata("mqtt_retain")
if topic == "sensor/temperature" then
local temp = tonumber(msg.payload)
message:add_float_value("temperature", temp)
-- return true if message was modified
return true
end
return false
end