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.
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
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.
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.
advertisement
[String: Any]
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
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.
Declaration
readBatteryLevel() -> Promise<number | null>
Returns
Promise<number | null>
A Promise resolving to the battery percentage, or `null` if the peripheral has no Battery service
Example
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.
Declaration
connect() -> Promise<HSBluetoothPeripheral>
Returns
Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's connected, or rejecting if the connection fails or takes longer than 20 seconds
Example
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.
Declaration
disconnect() -> Promise<HSBluetoothPeripheral>
Returns
Promise<HSBluetoothPeripheral>
A Promise resolving to this peripheral once it's disconnected
Example
await sensor.disconnect()
readRSSI() -> Promise<number>
Reads the current signal strength of a connected peripheral.
Declaration
readRSSI() -> Promise<number>
Returns
Promise<number>
A Promise resolving to the signal strength in dBm, or rejecting if the peripheral isn't connected
Example
console.log(await sensor.readRSSI() + " dBm")
discoverServices() -> Promise<string[]>
Discovers the GATT services of a connected peripheral.
Declaration
discoverServices() -> Promise<string[]>
Returns
Promise<string[]>
A Promise resolving to the UUIDs of the peripheral's services, e.g. `["180A", "180F"]`
Example
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.
Declaration
discoverCharacteristics(service) -> Promise<{uuid: string, properties: string[], isNotifying: boolean}[]>
Parameters
| Name | Type | Description |
|---|---|---|
| service | string | The service UUID: 16-bit (`"180F"`), 32-bit, or 128-bit |
Returns
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"`
Example
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.
Declaration
readValue(service, characteristic) -> Promise<Uint8Array>
Parameters
| Name | Type | Description |
|---|---|---|
| service | string | The service UUID, e.g. `"180F"` |
| characteristic | string | The characteristic UUID, e.g. `"2A19"` |
Returns
Promise<Uint8Array>
A Promise resolving to the characteristic's value
Example
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.
Declaration
writeValue(service, characteristic, value, options) -> Promise<void>
Parameters
| 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` |
Returns
Promise<void>
A Promise resolving once the peripheral has accepted the write (or, without a response, once it has been sent)
Example
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()`).
Declaration
subscribe(service, characteristic) -> Promise<void>
Parameters
| Name | Type | Description |
|---|---|---|
| service | string | The service UUID |
| characteristic | string | The characteristic UUID, which must support `"notify"` or `"indicate"` |
Returns
Promise<void>
A Promise resolving once the peripheral has started sending values
Example
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()`.
Declaration
unsubscribe(service, characteristic) -> Promise<void>
Parameters
| Name | Type | Description |
|---|---|---|
| service | string | The service UUID |
| characteristic | string | The characteristic UUID |
Returns
Promise<void>
A Promise resolving once the peripheral has stopped sending values
Example
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.
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 {
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.
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
sensor.off('value', myListener)
once(event, listener) -> None
Register a listener that fires at most once for one of this peripheral'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 {
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.
Declaration
toJSON() -> {[key: string]: any}
Returns
{[key: string]: any}
An object with the peripheral's `identifier`, `name`, `isConnected`, `rssi`, `lastSeen` and `batteryLevel`
Example
console.log(JSON.stringify(await hs.bluetooth.scan(), null, 2))