IoT Networking — MQTT

On top of WiFi & HTTP, the HAL adds MQTT for publish/subscribe messaging. Construction carries the broker URI and client id, and the client keeps its session alive in the background — keepalives and message acks are handled for you, so messages keep arriving while your main code does other work.

class

Mqtt

An MQTT client. Construct with the broker URI and client id, connect, subscribe, publish. The background session handling keeps everything alive for you.

Example first

mqtt.ts
import { Mqtt, UART0 } from '@typecad/hal';

const mqtt = new Mqtt('mqtt://broker.local:1883', { clientId: 'esp32-client' });

mqtt.onMessage((topic, payload) => {
  UART0.writeLine(topic + ': ' + payload);   // fires for every subscribed publish
});

mqtt.connect();                 // open the session
mqtt.subscribe('sensors/temperature');
mqtt.subscribe('cmd/#');        // wildcard: all sub-topics under cmd/

// later, publish a reading
mqtt.publish('sensors/temperature', '23.4');

connect / linked connect(): void

connect() returns immediately — the session finishes connecting in the background. Poll linked(), and on a flaky link retry in a loop until it flips:

wait-for-session.ts
for (let i = 0; i < 10; i++) {
  mqtt.connect();
  for (let j = 0; j < 8; j++) {
    if (mqtt.linked()) { break; }
    Time.sleep(250);
  }
  if (mqtt.linked()) { break; }
}

publish / disconnect publish(topic, data): void

publish.ts
if (mqtt.linked()) {
  mqtt.publish('status', 'online');
}
mqtt.disconnect();   // disconnect and free the client

All methods

MethodDescription
new Mqtt(uri, { clientId })Broker URI (mqtt:// or mqtts://) and client id
connect()Open the session — returns immediately; poll linked()
onMessage(handler)Set a (topic, payload) => void callback for received publishes
subscribe(topic)Subscribe to a topic filter (supports # / + wildcards)
publish(topic, data)Publish a message (QoS 1)
linked()true while the broker session is up
disconnect()Disconnect and free the client
© 2026 typeCAD — code-defined electronics github