HSMQTTClient
TypeA connection to an MQTT broker, created by hs.mqtt.create().
The client does nothing until you call connect(). Messages for the topics you subscribe()
to arrive as "message" events (see on()).
A connected client keeps working after you drop your reference to it, until you call
disconnect() or destroy(), or Hammerspoon reloads its configuration. So does a client
with listeners registered by on().
- Example:
const client = hs.mqtt.create("mqtt://broker.local")
client.on("message", msg => console.log(msg.topic + ": " + msg.payload))
async function start() {
await client.connect()
await client.subscribe("home/+/temperature")
await client.publish("home/office/light", "on")
}
start()
Properties
clientID
The MQTT client identifier sent to the broker. Unless you chose one with the clientID option, it is "hammerspoon-" followed by eight random characters.
state
The client's connection state: "disconnected", "connecting", "connected", "reconnecting" (the connection was lost and the client is trying to restore it, see the reconnectInterval option) or "disconnecting".
subscriptions
The topic filters this client has subscribed to, and the QoS level requested for each. These are restored automatically when the client reconnects.
Methods
connect() -> Promise<boolean>
Connects to the broker.
connect() -> Promise<boolean>
true if the broker resumed a previous session for this client (see the cleanSession option), or false if it started a new oneclient.connect()
.then(resumed => console.log(resumed ? "Resumed session" : "New session"))
.catch(err => console.error("Unable to connect: " + err))
disconnect() -> Promise<void>
Disconnects from the broker. This also stops a client that is reconnecting from trying again.
disconnect() -> Promise<void>
client.disconnect().then(() => console.log("Disconnected"))
publish(topic, payload, options) -> Promise<void>
Publishes a message.
publish(topic, payload, options) -> Promise<void>
| Name | Type | Description |
|---|---|---|
| topic | string | The topic to publish to |
| payload | string | The message, sent as UTF-8. Use JSON.stringify() to send an object |
| options | [String: Any] | The QoS level to send the message with (default 0), and whether the broker should keep it as the topic's retained message (default false) |
client.publish("home/office/light", "on")
client.publish("home/status", JSON.stringify({ away: true }), { qos: 1, retain: true })
.then(() => console.log("Status acknowledged"))
subscribe(topicFilter, qos) -> Promise<number>
Subscribes to a topic filter, so messages published to matching topics arrive as "message" events.
subscribe(topicFilter, qos) -> Promise<number>
| Name | Type | Description |
|---|---|---|
| topicFilter | string | The topic, which may contain the wildcards + (one level) and # (all remaining levels) |
| qos | number | The highest QoS level to receive messages with. Defaults to 0 |
client.subscribe("home/#")
client.subscribe("alerts/critical", 1)
.then(qos => console.log("Granted QoS " + qos))
unsubscribe(topicFilter) -> Promise<void>
Unsubscribes from a topic filter.
unsubscribe(topicFilter) -> Promise<void>
| Name | Type | Description |
|---|---|---|
| topicFilter | string | The topic filter originally passed to subscribe() |
client.unsubscribe("home/#").then(() => console.log("Unsubscribed"))
on(event, listener) -> None
Register a listener for this client's events.
Listeners receive:
"connected":(), each time the client connects, including when it reconnects by itself"disconnected":(reason),nullwhen you calleddisconnect(), otherwise a description of why the connection was lost"message":(message), an object with the message'stopic, itspayloaddecoded as UTF-8, its rawbytes(a Uint8Array), itsqos, and whether it isretained and aduplicate
A client with listeners stays alive until you remove them or call destroy().
on(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | string | The event to listen for |
| listener | function | Called when the event occurs |
try {
client.on("message", msg => console.log(msg.topic + ": " + msg.payload))
client.on("disconnected", reason => console.log("Disconnected: " + reason))
} catch (err) {
console.error(err.message)
}
off(event, listener) -> None
Remove a previously registered listener for this client's events.
off(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | string | The event the listener was registered for |
| listener | function | The function originally passed to on |
client.off("message", myListener)
once(event, listener) -> None
Register a listener that fires at most once for one of this client's events.
once(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | string | The event to listen for |
| listener | function | Called once, then automatically removed |
try {
client.once("connected", () => console.log("Connected to " + client.host))
} catch (err) {
console.error(err.message)
}
destroy() -> None
Disconnects from the broker, removes all listeners and releases the client. It can't be used again afterwards. Called automatically when Hammerspoon reloads its configuration.
destroy() -> None
client.destroy()