HSBluetoothPeripheral
TypeA 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
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.
rssi
The last known signal strength in dBm, or null if there is none. It is updated by hs.bluetooth.scan() and readRSSI().
lastSeen
When the peripheral was last seen, in Unix seconds: in a scan, or while connected. null if unknown.
advertisement
The peripheral's last advertisement, if a scan has seen one, otherwise null.
The object has localName (string or null), isConnectable (boolean or null), txPower (number or null), serviceUUIDs (string[]), manufacturerData (Uint8Array or null) and serviceData (an object mapping service UUIDs to Uint8Array).
batteryLevel
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>
null if the peripheral has no Battery serviceperipheral.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>
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>
sensor.disconnect().then(() => console.log("Disconnected"))
readRSSI() -> Promise<number>
Reads the current signal strength of a connected peripheral.
readRSSI() -> Promise<number>
sensor.readRSSI().then(rssi => console.log(rssi + " dBm"))
discoverServices() -> Promise<string[]>
Discovers the GATT services of a connected peripheral.
discoverServices() -> Promise<string[]>
["180A", "180F"]sensor.connect()
.then(() => sensor.discoverServices())
.then(services => console.log(services.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 |
properties lists what each supports: "read", "write", "writeWithoutResponse", "notify", "indicate", "broadcast", "authenticatedSignedWrites" and "extendedProperties"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" |
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 | 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 |
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" |
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 |
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 byreadValue()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 | string | The event to listen for |
| listener | function | Called when the event occurs |
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 |
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 |
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}
identifier, name, isConnected, rssi, lastSeen and batteryLevelhs.bluetooth.scan().then(nearby => console.log(JSON.stringify(nearby, null, 2)))