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:
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).
Options (all optional, and overriding anything given in the URL):
port: the broker's portclientID: the MQTT client identifier. Defaults to"hammerspoon-"followed by eight random characters. Brokers disconnect an existing client when another connects with the same identifierusername,password: credentials for the brokertls:trueto connect with TLSwebsocket:trueto connect over a WebSocket, andwebsocketPathfor its pathversion: the MQTT version,"3.1.1"(the default) or"5"keepAlive: seconds between keep-alive pings. Defaults to60connectTimeout: seconds to wait for the broker to accept the connection. Defaults to10timeout: seconds to wait for the broker to acknowledge asubscribe(), anunsubscribe(), or apublish()with QoS 1 or 2, before its Promise rejects. Defaults to5cleanSession:falseto ask the broker to keep the client's subscriptions and queued messages while it's disconnected. Defaults totruewill:{topic, payload, qos, retain}, a message the broker publishes if the client disconnects without callingdisconnect()reconnectInterval: seconds to wait before trying to reconnect when the connection is lost, retrying untildisconnect()is called. While the network is unavailable, the client waits for it to return instead. Defaults to0, which doesn't reconnectcaCertificate: 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 with that name in your 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 trustedclientCertificate: the path of a PKCS#12 (.p12) file with a certificate and private key to identify the client, andclientCertificatePasswordfor its passwordallowUntrustedCertificates:trueto accept any certificate from the broker. This makes the connection insecure, so usecaCertificateinstead if you can
hs.mqtt.create(server, options) -> HSMQTTClient
| Name | Type | Description |
|---|---|---|
| server | string | The broker's host name or URL |
| options | [String: Any] | Connection options |
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" })