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))
await client.connect()
await client.subscribe("home/+/temperature")
await client.publish("home/office/light", "on")
Properties
clientID
string
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
string
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
{[key: string]: number}
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.
Declaration
connect() -> Promise<boolean>
Returns
Promise<boolean>
A Promise resolving once the broker has accepted the connection, to `true` if the broker resumed a previous session for this client (see the `cleanSession` option), or `false` if it started a new one
Example
try {
await client.connect()
} 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.
Declaration
disconnect() -> Promise<void>
Returns
Promise<void>
A Promise resolving once the client has disconnected
Example
await client.disconnect()
publish(topic, payload, options) -> Promise<void>
Publishes a message.
Declaration
publish(topic, payload, options) -> Promise<void>
Parameters
| 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`) |
Returns
Promise<void>
A Promise resolving once the message has been sent (QoS 0) or the broker has acknowledged it (QoS 1 and 2)
Example
await client.publish("home/office/light", "on")
await client.publish("home/status", JSON.stringify({ away: true }), { qos: 1, retain: true })
subscribe(topicFilter, qos) -> Promise<number>
Subscribes to a topic filter, so messages published to matching topics arrive as `"message"` events.
Declaration
subscribe(topicFilter, qos) -> Promise<number>
Parameters
| 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` |
Returns
Promise<number>
A Promise resolving to the QoS level the broker granted, which may be lower than requested. It rejects if the broker refuses the subscription
Example
await client.subscribe("home/#")
await client.subscribe("alerts/critical", 1)
unsubscribe(topicFilter) -> Promise<void>
Unsubscribes from a topic filter.
Declaration
unsubscribe(topicFilter) -> Promise<void>
Parameters
| Name | Type | Description |
|---|---|---|
| topicFilter | string | The topic filter originally passed to `subscribe()` |
Returns
Promise<void>
A Promise resolving once the broker has acknowledged the request
Example
await client.unsubscribe("home/#")
on(event, listener) -> None
Register a listener for this client's events.
A client with listeners stays alive until you remove them or call `destroy()`.
Declaration
on(event, listener) -> None
Parameters
| Name | Type | Description |
|---|---|---|
| event | string | The event to listen for |
| listener | function | Called when the event occurs |
Returns
None
Throws
Throws an Error on failure; wrap calls in try/catch to handle it.
Example
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.
Declaration
off(event, listener) -> None
Parameters
| Name | Type | Description |
|---|---|---|
| event | string | The event the listener was registered for |
| listener | function | The function originally passed to `on` |
Returns
None
Example
client.off("message", myListener)
once(event, listener) -> None
Register a listener that fires at most once for one of this client's events.
Declaration
once(event, listener) -> None
Parameters
| Name | Type | Description |
|---|---|---|
| event | string | The event to listen for |
| listener | function | Called once, then automatically removed |
Returns
None
Throws
Throws an Error on failure; wrap calls in try/catch to handle it.
Example
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.
Declaration
destroy() -> None
Returns
None
Example
client.destroy()