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 publishingconnection_id(number, optional) - Target connection ID (default: 0)
Returns:
true- Message scheduled successfullyfalse- 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
- Lua Script Overview - Core Lua scripting concepts and hooks
- Message API - Message object methods and binary reading functions
- Modbus Helpers - Modbus protocol helpers
- UDP Helpers - UDP datagram sending helper