hs.mqtt
ModuleConnect to MQTT brokers to publish messages and subscribe to topics.
MQTT is a lightweight publish/subscribe protocol, widely used for home automation (e.g. Home
Assistant, Zigbee2MQTT, Tasmota) and IoT devices. Create a client with create(), then
connect() it, and listen for messages with its on() method.
Both MQTT 3.1.1 and MQTT 5 brokers are supported, over plain TCP, TLS, and WebSockets.
Note: this module is new and has not yet been well tested. It has only been tested against a simple MQTT 3.1.1 test broker, not against real brokers, MQTT 5, TLS or WebSockets. Please report any problems you find.
- Example:
const client = hs.mqtt.create("mqtt://homeassistant.local", {
username: "hammerspoon",
password: "secret",
reconnectInterval: 5
})
client.on("message", msg => {
if (msg.topic === "home/doorbell" && msg.payload === "pressed") {
hs.notify.show("Doorbell", "Someone is at the door")
}
})
async function start() {
await client.connect()
await client.subscribe("home/doorbell")
await client.publish("home/mac/status", "online", { retain: true })
}
start()
Types
This module provides the following types:
Event Types
The events this module's watchers emit, and when. In TypeScript, each type is a union of its event names that you can use as a type of your own:
HSMQTTClientEvent
An event name for HSMQTTClient.on(), HSMQTTClient.off() and HSMQTTClient.once()
| Event | Description |
|---|---|
"connected" |
The client connected to the broker, including when it reconnects by itself |
"disconnected" |
The client's connection to the broker closed |
"message" |
A message arrived on a topic the client subscribed to |
Properties
This module has no properties.
Methods
hs.mqtt.create(server, options) -> HSMQTTClient
Creates an MQTT client. The client doesn't connect until you call its connect() method.
The server is either a host name, or a URL whose scheme chooses the transport:
mqtt:// (TCP, port 1883), mqtts:// (TLS, port 8883), ws:// (WebSocket, port 80) or
wss:// (WebSocket over TLS, port 443). A URL may include a port, a username and password
(mqtt://user:pass@host), and for WebSockets a path (defaults to /mqtt).
hs.mqtt.create(server, options) -> HSMQTTClient
| Name | Type | Description |
|---|---|---|
| server | string | The broker's host name or URL |
| options optional | object | null | Connection options, which override anything given in the URL |
| port optional | number | The broker's port |
| clientID optional | string | The MQTT client identifier. Defaults to "hammerspoon-" followed by eight random characters. Brokers disconnect an existing client when another connects with the same identifier |
| username optional | string | The username for the broker |
| password optional | string | The password for the broker |
| tls optional | boolean | true to connect with TLS |
| websocket optional | boolean | true to connect over a WebSocket |
| websocketPath optional | string | The WebSocket's path. Defaults to /mqtt |
| version optional | "3.1.1" | "5" | The MQTT version. Defaults to "3.1.1" |
| keepAlive optional | number | Seconds between keep-alive pings. Defaults to 60 |
| connectTimeout optional | number | Seconds to wait for the broker to accept the connection. Defaults to 10 |
| timeout optional | number | Seconds to wait for the broker to acknowledge a subscribe(), an unsubscribe(), or a publish() with QoS 1 or 2, before its Promise rejects. Defaults to 5 |
| cleanSession optional | boolean | false to ask the broker to keep the client's subscriptions and queued messages while it's disconnected. Defaults to true |
| will optional | object | A message the broker publishes if the client disconnects without calling disconnect() |
| topic | string | The topic to publish it to |
| payload optional | string | The message. Defaults to an empty one |
| qos optional | 0 | 1 | 2 | Its quality of service. Defaults to 0 |
| retain optional | boolean | true for the broker to retain it. Defaults to false |
| reconnectInterval optional | number | Seconds to wait before trying to reconnect when the connection is lost, retrying until disconnect() is called. While the network is unavailable, the client waits for it to return instead. Defaults to 0, which doesn't reconnect |
| caCertificate optional | string | The CA certificate to trust for the broker instead of the system's, e.g. for a self-signed certificate: the path of a DER or PEM file, or "keychain:<name>" for the certificates stored with hs.keychain.importCertificate() under that name (or else those with that name in your login keychain). Without it, the broker's certificate must be trusted by macOS, which includes CA certificates you've added to your keychain and marked as trusted |
| clientCertificate optional | string | A certificate and private key to identify the client: the path of a PKCS#12 (.p12) file, or "keychain:<name>" for the identity stored with hs.keychain.importIdentity() under that name (or else the one in your login keychain whose certificate has that name) |
| clientCertificatePassword optional | string | The password for a clientCertificate file |
| allowUntrustedCertificates optional | boolean | true to accept any certificate from the broker. This makes the connection insecure, so use caCertificate instead if you can |
HSMQTTClient, or null if the server or options are invalid (the reason is logged to the Console)const local = hs.mqtt.create("broker.local")
const secure = hs.mqtt.create("mqtts://broker.example.com", { username: "me", password: "secret" })
const custom = hs.mqtt.create("broker.local", { tls: true, caCertificate: "~/certs/ca.der", version: "5" })