Skip to main content

MQTT client

The startMQTTClient function connects to a MQTT broker using TCP or TLS.

import { startMQTTClient } from "@devicescript/net"

const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})
tip

You can use HiveMQ public broker for testing with public data.

publish

The publish function sends a message on a topic.

import { startMQTTClient } from "@devicescript/net"

const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})
await mqtt.publish("devs/log", "hello")

deviceIdentifier

You can use deviceIdentifier to uniquely identify the device in the topic

import { deviceIdentifier } from "@devicescript/core"
import { startMQTTClient } from "@devicescript/net"

const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})
const id = deviceIdentifier("self")
await mqtt.publish(`devs/log/${id}`, "hello")

subscribe

The subscribe function creates a subscription for a topic route. The function takes a an optional handler an returns an observable.

import { startMQTTClient } from "@devicescript/net"
const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})

await mqtt.subscribe(`devs/log/#`, msg => {
console.log(msg.content.toString("utf-8"))
})

stop

The MQTT client will automatically retry to connect once it detects that connectivity is lost. To close the current socket and stop the reconnect task, use stop.

Acknowledgements

The MQTT client is based on micro-mqtt.