7.7.190-stable Switch to dev

MQTT Library

@library("mqtt", "0.0.0");

The GreyCat MQTT library provides a native MQTT client for publishing and subscribing to messages on an MQTT broker.

Installation

Add the MQTT library to your GreyCat project:

use mqtt;

API Reference

Mqtt type

Field Type Description
uri String Broker URI in the form protocol://host:port
username String? Optional username for authentication
password String? Optional password for authentication
client_id String Unique client identifier sent to the broker on connect
clean_session bool? Controls session state persistence. true discards state, false resumes.

Supported URI protocols

Protocol Transport
tcp:// / mqtt:// Insecure TCP
ssl:// / mqtts:// Encrypted SSL/TLS
ws:// Insecure WebSocket
wss:// Secure WebSocket

Methods

subscribe(topic: String, function: function, qos: MqttQoS?)

Subscribes to a topic (supports + single-level and # multi-level wildcards). When a message arrives, the provided function is spawned as a task. The callback function must match one of these signatures:

  • fn(topic: String, msg: String)
  • fn(msg: String)
  • fn(topic: String, msg: T)T is parsed from JSON automatically
  • fn(msg: T)T is parsed from JSON automatically

If qos is null, defaults to AtLeastOnce.

unsubscribe(topic: String): bool

Unsubscribes from a topic. Returns true if the topic was previously subscribed.

publish(topic: String, msg: any?, timeout: duration?, qos: MqttQoS?)

Publishes a message to a topic. If msg is a String it is sent as-is; any other type is serialized to JSON. If qos is null, defaults to AtLeastOnce.

MqttQoS enum

Variant Value Description
AtMostOnce 0 Best-effort, message may be lost
AtLeastOnce 1 Guaranteed delivery, possible duplicates
ExactlyOnce 2 Guaranteed delivery exactly once

Example

type SensorData {
    temperature: float;
    humidity: float;
}

fn main() {
    // Subscriber
    var recv = Mqtt {
        uri: "tcp://localhost:1883",
        client_id: "greycat_recv",
    };
    recv.subscribe("sensors/+", on_sensor_data, null);

    // Publisher
    var sender = Mqtt {
        uri: "tcp://localhost:1883",
        client_id: "greycat_sender",
    };
    sender.publish("sensors/fridge", SensorData { temperature: 4.1, humidity: 39.0 }, null, null);
}

fn on_sensor_data(msg: String) {
    var writer = TextWriter {
        path: "${File::userDir()}/sensors.ndjson",
        append: true,
    };
    writer.writeln(msg);
}

Authentication

var mqtt = Mqtt {
    uri: "ssl://broker.example.com:8883",
    client_id: "my_client",
    username: "user",
    password: "secret",
};