Skip to main content

MQTT Helpers

MQTT helper functions provide convenient Lua APIs for publishing MQTT messages from scripts. These functions handle protocol validation, metadata creation, and message scheduling.

API Reference

mqtt_publish(topic, payload, qos, retain, delay, connection_id) → boolean

Publish an MQTT message with specified topic, QoS, and retain flag.

Parameters:

  • topic (string) - MQTT topic name (required, cannot be nil)
  • payload (string) - Message payload as binary string (can be empty)
  • qos (number) - Quality of Service level (0, 1, or 2)
  • retain (boolean) - Retain flag (true = broker retains message for new subscribers)
  • delay (number) - Delay in milliseconds before publishing
  • connection_id (number, optional) - Target connection ID (default: 0)

Returns:

  • true - Message scheduled successfully
  • false - Failed to schedule (channel closed or error)
  • Error - If topic is nil or validation fails

QoS Levels:

  • QoS 0: At most once delivery (fire and forget)
  • QoS 1: At least once delivery (acknowledged)
  • QoS 2: Exactly once delivery (guaranteed)

Example:

-- Publish sensor data with QoS 1, no retain
mqtt_publish("sensors/temperature", "23.5", 1, false, 0)

-- Publish to specific connection after 500ms delay
mqtt_publish("status/heartbeat", "alive", 0, false, 500, 1)

-- Publish binary data
local binary_payload = string.char(0x01, 0x02, 0x03, 0x04)
mqtt_publish("data/raw", binary_payload, 1, false, 0)

See Also