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.

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")

Properties

typeName

string
The type name for JavaScript introspection. Always `"HSBluetoothPeripheral"`.

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
await peripheral.connect()
console.log(peripheral.name + ": " + await peripheral.readBatteryLevel() + "%")

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>
Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's connected, or rejecting if the connection fails or takes longer than 20 seconds
await sensor.connect()

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>
Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's disconnected
await sensor.disconnect()

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
console.log(await sensor.readRSSI() + " 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"]`
await sensor.connect()
console.log((await sensor.discoverServices()).join(", "))

discoverCharacteristics(service) -> Promise<{uuid: string, properties: string[], isNotifying: boolean}[]>

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<{uuid: string, properties: string[], isNotifying: boolean}[]>
A Promise resolving to the service's characteristics. `properties` lists what each supports: `"read"`, `"write"`, `"writeWithoutResponse"`, `"notify"`, `"indicate"`, `"broadcast"`, `"authenticatedSignedWrites"` and `"extendedProperties"`
const chars = await sensor.discoverCharacteristics("180F")
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
const value = await peripheral.readValue("180F", "2A19")
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 JSValue The bytes to write. A string is written as UTF-8
options [String: Any] With `withoutResponse: true`, write without asking the peripheral to confirm it, which is faster but can't tell whether it arrived. Defaults to `false`
Promise<void>
A Promise resolving once the peripheral has accepted the write (or, without a response, once it has been sent)
await lamp.writeValue("FFE5", "FFE9", [0x56, 0xFF, 0x00, 0x00, 0x00, 0xF0, 0xAA])
await 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]))
await 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
await heartStrap.unsubscribe("180D", "2A37")

on(event, listener) -> None

Register a listener for this peripheral's events. A peripheral with listeners keeps working after you drop your reference to it.
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 {
    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 string The event the listener was registered for
listener function The function originally passed to `on`
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 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 {
    sensor.once('connected', () => console.log("Connected to " + sensor.name))
} catch (err) {
    console.error(err.message)
}

toJSON() -> {[key: string]: any}

Returns a plain object describing this peripheral, for JSON serialisation `JSON.stringify()` calls this automatically, so you rarely need to call it yourself.
toJSON() -> {[key: string]: any}
{[key: string]: any}
An object with the peripheral's `identifier`, `name`, `isConnected`, `rssi`, `lastSeen` and `batteryLevel`
console.log(JSON.stringify(await hs.bluetooth.scan(), null, 2))