Skip to main content

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 flag
  • delay_ms (number) - Delay in ms before publishing
  • connection_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:

KeyTypeDescription
"mqtt_topic"stringThe topic the message was published on
"mqtt_qos"numberQoS level (0, 1, or 2)
"mqtt_retain"booleanWhether 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