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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| 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