API Docs

A 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

identifier

string
The unique identifier of this client object.

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.

host

string
The host name of the broker.

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"`.

isConnected

boolean
Whether the client is connected to the broker.

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.
connect() -> Promise<boolean>
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
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.
disconnect() -> Promise<void>
Promise<void>
A Promise resolving once the client has disconnected
await client.disconnect()

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`)
Promise<void>
A Promise resolving once the message has been sent (QoS 0) or the broker has acknowledged it (QoS 1 and 2)
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.
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`
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
await client.subscribe("home/#")
await client.subscribe("alerts/critical", 1)

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()`
Promise<void>
A Promise resolving once the broker has acknowledged the request
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()`.
on(event, listener) -> None
Name Type Description
event string The event to listen for
listener function Called when the event occurs
None
Throws an Error on failure; wrap calls in try/catch to handle it.
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`
None
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
None
Throws an Error on failure; wrap calls in try/catch to handle it.
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
None
client.destroy()