MQTT Publish / Subscribe

Publishes telemetry and subscribes to command topics with a callback. Reconnects automatically by calling mqtt.connect() each loop (code 207 means already connected). Requires firmware V91 or greater.

// MQTT Publish and Subscribe Example, Requires Firmware V91 or greater


// Callback function which runs whenever a subscribed topic is received
// The 'event' object contains the topic info, the message can be binary
// data or a json string, json strings should be parsed, let data = json.parse(event.message);
// binary data can be converted into numerical arrays, see the binary data example

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



while (run()) {


    // Connecting before each publish ensures that if the connection is ever disconnected it will reconnect,
    // If the client is connected it will just return code 207 (Already Connected)
    // return: Any response other than 0 indicates an error and the corresponding error code

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


    let batteryVoltage = string(14.34);

    // Publish an event to the MQTT broker, the message data can be binary or text, if you are pushing an object it should
    // be converted to a string first, let msg = string( { object: "value" } );
    // arrays of numbers can be converted and packed to binary first, see the binary data examples

    ret = mqtt.publish("power_system/battery_voltage", batteryVoltage);
    print("publish:", ret);
    waitMS(5000);
}



mqtt.disconnect(); // Make sure the client is disconnected before exiting