πŸ“¦ Archived documentation: r1 (committed 2026-07-24) View current documentation β†’

mqtt

MQTT publish/subscribe client for broker-based telemetry and control.

The mqtt object connects to an MQTT broker, publishes topics and subscribes with a callback. Requires firmware V91 or greater.

A robust pattern is to call mqtt.connect() at the top of every loop iteration: if the client is already connected it simply returns code 207 (Already Connected), and if the connection ever drops it will reconnect.

Functions

mqtt.connect()

mqtt.connect(options) β†’ number

Connects to an MQTT broker and registers topic subscriptions with a callback.

Options object fields:

Field Type Meaning
url string Broker address, e.g. "mqtt://172.16.220.22:1883".
client string MQTT client ID.
subscribe array Topic filters to subscribe, wildcards allowed, e.g. ["power_system/relays/+"].
callback function Called for each received message with an event object { retain, qos, message, topic }.

The callback's event.message can be a JSON string (parse with JSON.parse) or binary data (convert with the bin functions).

Returns 0 on success, 207 if already connected; any other value is an error code.

Arguments

NameTypeRequiredDefaultDescription
options object yes β€” { url, client, subscribe: [...], callback } β€” see table.

Returns

number 0 = connected, 207 = already connected, anything else = error code.

Example

function mqttSubscriberCallback(event){
  print("MQTT EVENT: ", string(event));
  // {"retain":false,"qos":0,"message":"Hello World","topic":"power_system/relays/1"}
}

let ret = mqtt.connect({
  url: "mqtt://172.16.220.22:1883",
  client: "Nikiah Repeater",
  subscribe: ["power_system/relays/+"],
  callback: mqttSubscriberCallback
});
print("connect:", ret); // 0 ok, 207 already connected

mqtt.publish()

mqtt.publish(topic, message) β†’ number

Publishes a message to an MQTT topic.

Publishes message to topic. Message data can be text or binary: convert objects with string(obj) first, and pack numeric arrays to binary with bin.fromArray().

Arguments

NameTypeRequiredDefaultDescription
topic string yes β€” Topic to publish to, e.g. "power_system/battery_voltage".
message string | binary yes β€” Payload. Objects: string(obj). Numeric arrays: bin.fromArray().

Returns

number 0 on success, otherwise an error code.

Example

let ret = mqtt.publish("power_system/battery_voltage", string(14.34));
print("publish:", ret);

mqtt.disconnect()

mqtt.disconnect()

Disconnects from the MQTT broker; call before the script exits.

Make sure the client is disconnected before the script exits.

Example

mqtt.disconnect();