API Docs

A Bluetooth Low Energy (BLE) peripheral, found by hs.bluetooth.scan() or through a paired device's lowEnergyPeripheral().

Obtain peripherals from the hs.bluetooth module; do not instantiate them directly. A peripheral is identified by its identifier, and the same peripheral is returned as the same object for as long as you hold on to it.

Call connect() before using its GATT services. A connected peripheral stays connected, and keeps delivering its events, until you call disconnect(), even if you drop your reference to it.

async function watchSensor() {
    const [sensor] = await hs.bluetooth.scan({ seconds: 5, services: ["181A"] })
    await sensor.connect()
    const bytes = await sensor.readValue("181A", "2A6E")
    sensor.on("value", (service, characteristic, value) => console.log(characteristic + ": " + value))
    await sensor.subscribe("181A", "2A6E")
}
watchSensor()

Properties

identifier

string

The peripheral's identifier, a UUID that macOS assigns in place of its Bluetooth address, which it doesn't reveal. It is stable on this Mac, but differs between Macs.

name

string

The peripheral's name, or null if it hasn't reported one.

isConnected

boolean

Whether Hammerspoon is connected to the peripheral.

rssi

NSNumber

The last known signal strength in dBm, or null if there is none. It is updated by hs.bluetooth.scan() and readRSSI().

lastSeen

NSNumber

When the peripheral was last seen, in Unix seconds: in a scan, or while connected. null if unknown.

batteryLevel

NSNumber

The battery level last read by readBatteryLevel(), as a percentage, or null if it hasn't been read.

Methods

readBatteryLevel() -> Promise<number | null>

Reads the peripheral's battery level from its standard GATT Battery service. The peripheral must be connected.

readBatteryLevel() -> Promise<number | null>
Promise<number | null>
A Promise resolving to the battery percentage, or null if the peripheral has no Battery service
peripheral.connect()
    .then(() => peripheral.readBatteryLevel())
    .then(level => console.log(peripheral.name + ": " + level + "%"))

connect() -> Promise<HSBluetoothPeripheral>

Connects Hammerspoon to the peripheral, so its GATT services can be used. It stays connected until disconnect() is called, even if you drop your reference to it.

connect() -> Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's connected, or rejecting if the connection fails or takes longer than 20 seconds
sensor.connect()
    .then(() => console.log("Connected"))
    .catch(err => console.error("Unable to connect: " + err))

disconnect() -> Promise<HSBluetoothPeripheral>

Disconnects Hammerspoon from the peripheral. If macOS has its own connection to it (e.g. a paired keyboard), that connection stays.

disconnect() -> Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's disconnected
sensor.disconnect().then(() => console.log("Disconnected"))

readRSSI() -> Promise<number>

Reads the current signal strength of a connected peripheral.

readRSSI() -> Promise<number>
Promise<number>
A Promise resolving to the signal strength in dBm, or rejecting if the peripheral isn't connected
sensor.readRSSI().then(rssi => console.log(rssi + " dBm"))

discoverServices() -> Promise<string[]>

Discovers the GATT services of a connected peripheral.

discoverServices() -> Promise<string[]>
Promise<string[]>
A Promise resolving to the UUIDs of the peripheral's services, e.g. ["180A", "180F"]
sensor.connect()
    .then(() => sensor.discoverServices())
    .then(services => console.log(services.join(", ")))

discoverCharacteristics(service) -> Promise<object[]>

Discovers the characteristics of one of a connected peripheral's GATT services.

discoverCharacteristics(service) -> Promise<{uuid: string, properties: string[], isNotifying: boolean}[]>
Name Type Description
service string The service UUID: 16-bit ("180F"), 32-bit, or 128-bit
Promise<object[]>
A Promise resolving to the service's characteristics. properties lists what each supports: "read", "write", "writeWithoutResponse", "notify", "indicate", "broadcast", "authenticatedSignedWrites" and "extendedProperties"
Field Type Description
uuid string
properties string[]
isNotifying boolean
sensor.discoverCharacteristics("180F")
    .then(chars => chars.forEach(c => console.log(c.uuid + ": " + c.properties.join(", "))))

readValue(service, characteristic) -> Promise<Uint8Array>

Reads the value of a GATT characteristic of a connected peripheral. The service and characteristic are discovered first if needed.

readValue(service, characteristic) -> Promise<Uint8Array>
Name Type Description
service string The service UUID, e.g. "180F"
characteristic string The characteristic UUID, e.g. "2A19"
Promise<Uint8Array>
A Promise resolving to the characteristic's value
peripheral.readValue("180F", "2A19")
    .then(value => console.log("Battery: " + value[0] + "%"))

writeValue(service, characteristic, value, options) -> Promise<void>

Writes the value of a GATT characteristic of a connected peripheral. Writes to one characteristic are sent in the order they're made.

writeValue(service, characteristic, value, options) -> Promise<void>
Name Type Description
service string The service UUID
characteristic string The characteristic UUID
value Uint8Array | ArrayBuffer | number[] | string The bytes to write. A string is written as UTF-8
options optional object With withoutResponse: true, write without asking the peripheral to confirm it, which is faster but can't tell whether it arrived. Defaults to false
withoutResponse optional boolean
Promise<void>
A Promise resolving once the peripheral has accepted the write (or, without a response, once it has been sent)
lamp.writeValue("FFE5", "FFE9", [0x56, 0xFF, 0x00, 0x00, 0x00, 0xF0, 0xAA])
    .then(() => console.log("Lamp updated"))
lamp.writeValue("FFE5", "FFE9", frame, { withoutResponse: true })

subscribe(service, characteristic) -> Promise<void>

Subscribes to a GATT characteristic of a connected peripheral, so each new value is delivered as a "value" event (see on()).

subscribe(service, characteristic) -> Promise<void>
Name Type Description
service string The service UUID
characteristic string The characteristic UUID, which must support "notify" or "indicate"
Promise<void>
A Promise resolving once the peripheral has started sending values
heartStrap.on("value", (service, characteristic, value) => console.log("Heart rate: " + value[1]))
heartStrap.subscribe("180D", "2A37")

unsubscribe(service, characteristic) -> Promise<void>

Stops a subscription started by subscribe().

unsubscribe(service, characteristic) -> Promise<void>
Name Type Description
service string The service UUID
characteristic string The characteristic UUID
Promise<void>
A Promise resolving once the peripheral has stopped sending values
heartStrap.unsubscribe("180D", "2A37").then(() => console.log("Unsubscribed"))

on(event, listener) -> None

Register a listener for this peripheral's events.

Listeners receive:

  • "connected", "disconnected": no arguments, when Hammerspoon's connection to the peripheral opens or closes
  • "value": (service, characteristic, value), the UUIDs and the new value (a Uint8Array) of a characteristic you subscribed to. While subscribed, values fetched by readValue() arrive here too, since the peripheral sends both the same way

A peripheral with listeners keeps working after you drop your reference to it.

on(event, listener) -> None
Name Type Description
event HSBluetoothPeripheralEvent The event to listen for
listener (service?: string, characteristic?: string, value?: Uint8Array) => void Called when the event occurs
Event Description
"connected" Hammerspoon's connection to the peripheral opened
"disconnected" Hammerspoon's connection to the peripheral closed
"value" A characteristic you subscribed to has a new value
None
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    sensor.on('disconnected', () => console.log(sensor.name + " went away"))
} catch (err) {
    console.error(err.message)
}

off(event, listener) -> None

Remove a previously registered listener for this peripheral's events.

off(event, listener) -> None
Name Type Description
event HSBluetoothPeripheralEvent The event the listener was registered for
listener function The function originally passed to on
Event Description
"connected" Hammerspoon's connection to the peripheral opened
"disconnected" Hammerspoon's connection to the peripheral closed
"value" A characteristic you subscribed to has a new value
None
sensor.off('value', myListener)

once(event, listener) -> None

Register a listener that fires at most once for one of this peripheral's events.

once(event, listener) -> None
Name Type Description
event HSBluetoothPeripheralEvent The event to listen for
listener (service?: string, characteristic?: string, value?: Uint8Array) => void Called once, then automatically removed
Event Description
"connected" Hammerspoon's connection to the peripheral opened
"disconnected" Hammerspoon's connection to the peripheral closed
"value" A characteristic you subscribed to has a new value
None
Throws an Error on failure; wrap calls in try/catch to handle it.
try {
    sensor.once('connected', () => console.log("Connected to " + sensor.name))
} catch (err) {
    console.error(err.message)
}

toJSON() -> object

Returns a plain object describing this peripheral, for JSON serialisation

JSON.stringify() calls this automatically, so you rarely need to call it yourself.

toJSON() -> object
object
An object describing the peripheral, with the values of its properties of the same names
Field Type Description
identifier string
name string | null
isConnected boolean
rssi number | null
lastSeen number | null
batteryLevel number | null
hs.bluetooth.scan().then(nearby => console.log(JSON.stringify(nearby, null, 2)))