mqtt API reference
An MQTT 3.1.1 publish/subscribe client over the net system library - the same "protocol clients are modules, net is the transport" line the other network clients follow. MQTT packets are a 1-byte fixed header, a variable remaining-length integer, then a length-prefixed payload, all built and parsed here with Jennifer's bitwise operators and bytes. QoS 0 and QoS 1 publish / subscribe (a synchronous PUBACK handshake), retained messages, a Last-Will set in the CONNECT, and reconnect for session resumption, on top of a single-threaded poll with timeout (via net.setReadDeadline) so one flow can wait for a packet and send keepalives without a spawned reader, plus blocking receive, ping, and disconnect. A PUBLISH that arrives while a call waits for its PUBACK or SUBACK is acknowledged and queued on the Client, and the next receive / poll returns it, in arrival order. QoS 2 and MQTT 5 properties are out of scope. Needs the default jennifer binary (uses net).
A protocol failure throws an mqtt.MqttError (kind "mqtt"); a broker refusing the connection sets its CONNACK connackCode (4 bad user name or password, 5 not authorized, ...), a refused subscription its topic. The generic kinds pass as they are: a peer closing mid-packet "closed", a packet over the cap or a full message queue "limit", a stall "timeout", a socket failure "net".
Import with import "mqtt.j" as mqtt;. See the mqtt guide for prose and examples.
Contents
| Name | What it is |
|---|---|
connect | Open a connection, send CONNECT, and check the CONNACK return code. |
connectWith | Open a connection with an explicit Last-Will and clean-session flag. |
disconnect | Send DISCONNECT and close the connection. |
ping | Send a PINGREQ keepalive (fire and forget). |
poll | Poll for a message, waiting up to timeoutMs milliseconds. |
publish | Publish a text message to a topic at QoS 0 (UTF-8 encoded). |
publishBytes | Publish a raw byte payload to a topic at QoS 0 (fire and forget). |
publishBytesRetain | Publish a raw byte payload at QoS 0 with an explicit retain flag. |
publishQos1 | Publish a raw byte payload at QoS 1 (at-least-once) and block until the matching PUBACK. |
publishRetain | Publish a text message at QoS 0 with an explicit retain flag (UTF-8 encoded). |
receive | Block until the next application message arrives, returning it. |
reconnect | Re-dial the broker and re-CONNECT with this client's stored settings, then re-subscribe every tracked subsc... |
subscribe | Subscribe to a topic filter at QoS 0, wait for the SUBACK, and track the subscription on the returned Clien... |
subscribeQos1 | Subscribe to a topic filter requesting QoS 1, wait for the SUBACK, and track the subscription (with the QoS... |
Client | struct: An open MQTT connection. |
Message | struct: One received application message. |
MqttError | struct: A failed MQTT operation. |
Options | struct: Connection settings for mqtt.connect. |
Subscription | struct: One tracked subscription, remembered on the Client so reconnect can restore the session's routes. |
Will | struct: A Last-Will-and-Testament message the broker publishes on this client's behalf if the connection drops with... |
Functions
connect
mqtt.connect(opts as Options)Open a connection, send CONNECT, and check the CONNACK return code. Uses a clean session and no Last-Will; for a will or session resumption use connectWith.
opts- the connection settings
- Returns
Client - the open client
- Throws
MqttError - kind "mqtt" when the broker refuses the connection
connectWith
mqtt.connectWith(opts as Options, will as Will, cleanSession as bool)Open a connection with an explicit Last-Will and clean-session flag. A will whose topic is "" registers no will; cleanSession false asks the broker to resume a persistent session keyed by opts.clientId (retained subscriptions and queued QoS-1 messages).
opts- the connection settings
will- the Last-Will to register ("" topic disables it)
cleanSession- false to resume a persistent session
- Returns
Client - the open client
- Throws
MqttError - kind "mqtt" when the broker refuses the connection
disconnect
mqtt.disconnect(client as Client)Send DISCONNECT and close the connection.
client- the open client
ping
mqtt.ping(client as Client)Send a PINGREQ keepalive (fire and forget). The matching PINGRESP is consumed by the next poll / receive.
client- the open client
poll
mqtt.poll(client as Client, timeoutMs as int)Poll for a message, waiting up to timeoutMs milliseconds. Returns a list of zero or one Message: empty when nothing arrived in the window (the caller can then ping and loop), one Message when a PUBLISH was received. A message queued while publishQos1 / subscribe waited for an ack is returned first, without reading the socket. A QoS-1 PUBLISH is acknowledged with a PUBACK before it is returned. Non-PUBLISH control packets are consumed and reported as an empty poll.
client- the open client
timeoutMs- how long to wait for the next packet, in milliseconds
- Returns
list of Message - zero or one received message
publish
mqtt.publish(client as Client, topic as string, message as string)Publish a text message to a topic at QoS 0 (UTF-8 encoded).
client- the open client
topic- the topic to publish to
message- the message text
publishBytes
mqtt.publishBytes(client as Client, topic as string, payload as bytes)Publish a raw byte payload to a topic at QoS 0 (fire and forget).
client- the open client
topic- the topic to publish to
payload- the message bytes
publishBytesRetain
mqtt.publishBytesRetain(
client as Client,
topic as string,
payload as bytes,
retain as bool)Publish a raw byte payload at QoS 0 with an explicit retain flag. A retained message is stored by the broker and delivered to every future subscriber of the topic; publishing an empty payload with retain true clears it.
client- the open client
topic- the topic to publish to
payload- the message bytes
retain- whether the broker retains the message
publishQos1
mqtt.publishQos1(
client as Client,
topic as string,
payload as bytes,
retain as bool)Publish a raw byte payload at QoS 1 (at-least-once) and block until the matching PUBACK. The PUBLISH carries a packet identifier; an unacknowledged send is retried as a DUP (the duplicate-delivery flag set) up to a fixed number of attempts, so at-least-once delivery is honored across a slow or flapping link. Because the call blocks for the PUBACK, only one message is ever in flight, so a fixed non-zero packet identifier is safe. A duplicate the broker already delivered is de-duplicated by the packet id on its side. A PUBLISH that arrives during the wait is acknowledged and queued for the next receive / poll.
client- the open client
topic- the topic to publish to
payload- the message bytes
retain- whether the broker retains the message
- Throws
MqttError - kind "mqtt" when no PUBACK arrives within the retry budget
publishRetain
mqtt.publishRetain(
client as Client,
topic as string,
message as string,
retain as bool)Publish a text message at QoS 0 with an explicit retain flag (UTF-8 encoded).
client- the open client
topic- the topic to publish to
message- the message text
retain- whether the broker retains the message
receive
mqtt.receive(client as Client)Block until the next application message arrives, returning it. A message queued while publishQos1 / subscribe waited for an ack comes first. A QoS-1 PUBLISH is acknowledged with a PUBACK before it is returned. Non-PUBLISH control packets (e.g. a PINGRESP) are consumed and skipped.
client- the open client
- Returns
Message - the next received message
reconnect
mqtt.reconnect(client as Client)Re-dial the broker and re-CONNECT with this client's stored settings, then re-subscribe every tracked subscription. Returns a fresh Client the caller reassigns (value semantics - the old handle is best-effort closed). Messages still queued on the old Client move to the new one, ahead of any the re-subscribe queues.
Session resumption: when the client connected with cleanSession false, the broker keeps the session (subscriptions and queued QoS-1 messages) across the drop and reports it in the CONNACK; the re-subscribe here is idempotent and also covers the clean-session case, where the broker discarded the session.
client- the (typically disconnected) client to re-establish
- Returns
Client - a freshly connected client with the tracked routes restored
- Throws
MqttError - kind "mqtt" when the re-connect or a re-subscribe fails
subscribe
mqtt.subscribe(client as Client, topic as string)Subscribe to a topic filter at QoS 0, wait for the SUBACK, and track the subscription on the returned Client (so reconnect can restore it). Reassign the result: $c = mqtt.subscribe($c, "topic");.
client- the open client
topic- the topic filter (may contain
+/#wildcards) - Returns
Client - the client with the subscription tracked
- Throws
MqttError - kind "mqtt" when the broker rejects the subscription
subscribeQos1
mqtt.subscribeQos1(client as Client, topic as string)Subscribe to a topic filter requesting QoS 1, wait for the SUBACK, and track the subscription (with the QoS the broker granted) on the returned Client. With QoS 1 the broker delivers each matching message as a QoS-1 PUBLISH, which receive / poll acknowledge with a PUBACK. Reassign the result: $c = mqtt.subscribeQos1($c, "topic");.
client- the open client
topic- the topic filter (may contain
+/#wildcards) - Returns
Client - the client with the subscription tracked
- Throws
MqttError - kind "mqtt" when the broker rejects the subscription
Structs
Client
An open MQTT connection. Beyond the socket it carries the settings needed to re-establish the session (opts, will, cleanSession) and the list of subscriptions subscribe / subscribeQos1 have tracked, so reconnect can re-dial and re-subscribe. Value-semantic: copies share the socket handle and the queue of messages that arrived while a call waited for an ack, but each carries its own settings and subscription list.
def struct Client {
conn as net.Conn,
opts as Options,
will as Will,
cleanSession as bool,
subs as list of Subscription,
pending as channel of Message,
pendingBytes as channel of int
};conn- the underlying socket
opts- the settings this client connected with
will- the Last-Will registered in the CONNECT ("" topic = none)
cleanSession- the clean-session flag (false resumes the session)
subs- the tracked subscriptions for reconnect
pending- messages that arrived while
publishQos1orsubscribewaited for an ack;receive/pollreturn them first pendingBytes- one value: the payload bytes queued on
pending
Message
One received application message.
def struct Message {
topic as string,
payload as bytes
};topic- the topic it was published to
payload- the raw message bytes (convert to text as needed)
MqttError
A failed MQTT operation. Every error of kind "mqtt" is one, so its fields are safe to read once the kind matches.
def struct MqttError {
kind as string,
message as string,
connackCode as int,
topic as string
};kind- always
"mqtt" messagemqtt:and what went wrongconnackCode- the broker's CONNACK return code when it refused the connection: 1 unacceptable protocol version, 2 identifier rejected, 3 server unavailable, 4 bad user name or password, 5 not authorized; 0 otherwise
topic- the topic of a subscription the broker rejected; "" otherwise
Options
Connection settings for mqtt.connect.
def struct Options {
host as string,
port as int,
clientId as string,
keepalive as int,
security as transport.Security,
username as string,
password as string
};host- the broker host
port- the broker port (1883 plaintext, 8883 TLS by convention)
clientId- the client identifier the broker sees
keepalive- the keepalive interval in seconds (0 disables)
securitytransport.Security.None(plaintext) or.Tls(mqtts);.Starttlsis rejected (MQTT has no in-band upgrade)username- the CONNECT username ("" to omit)
password- the CONNECT password ("" to omit)
Subscription
One tracked subscription, remembered on the Client so reconnect can restore the session's routes.
def struct Subscription {
topic as string,
qos as int
};topic- the subscribed topic filter
qos- the QoS the broker granted (0x80 means it was rejected)
Will
A Last-Will-and-Testament message the broker publishes on this client's behalf if the connection drops without a clean DISCONNECT. An empty topic means "no will" (the CONNECT sets no will flags).
def struct Will {
topic as string,
payload as bytes,
qos as int,
retain as bool
};topic- the will topic ("" disables the will)
payload- the will message bytes
qos- the will QoS (0 or 1)
retain- whether the broker retains the will message