hs.bluetooth
ModuleInspect, connect to and scan for Bluetooth devices, and watch them connect and disconnect.
The module offers two kinds of object, because macOS identifies them in two different ways:
HSBluetoothDevice: a device macOS knows by its Bluetooth address, such as headphones, a keyboard or a mouse paired with this Mac. These have battery levels and system-wide connect/disconnect events.HSBluetoothPeripheral: a Bluetooth Low Energy (BLE) peripheral, found byscan(), which Hammerspoon can connect to itself to read and write its GATT characteristics. macOS gives these a UUIDidentifierinstead of revealing their address.
hs.bluetooth.pairedDevices().forEach(d => console.log(d.name + " " + d.address))
hs.bluetooth.connectedDevices()
.filter(d => d.batteryLevel !== null)
.forEach(d => console.log(d.name + ": " + d.batteryLevel + "%"))
hs.bluetooth.on('connected', d => console.log(d.name + " connected"))
hs.bluetooth.on('powerChanged', on => console.log("Bluetooth is " + (on ? "on" : "off")))
hs.bluetooth.scan({ seconds: 5 })
.then(nearby => nearby.forEach(p => console.log((p.name ?? p.identifier) + " " + p.rssi + " dBm")))
macOS asks the user for Bluetooth permission the first time this module talks to Bluetooth.
Use hs.permissions.checkBluetooth() to see whether it has been granted.
Types
This module provides the following types:
Object Types
Plain JavaScript objects that this module's methods and properties take or return:
HSBluetoothBatteryLevels
The battery levels of a device with several batteries, each a percentage. Only the ones the device reports are present
| Field | Type | Description |
|---|---|---|
| left optional | number | The left earbud's battery |
| right optional | number | The right earbud's battery |
| case optional | number | The case's battery |
HSBluetoothAdvertisement
What a Bluetooth LE peripheral advertised
| Field | Type | Description |
|---|---|---|
| localName | string | null | The name it advertised |
| isConnectable | boolean | null | Whether it accepts connections |
| txPower | number | null | Its transmit power level, in dBm |
| serviceUUIDs | string[] | The UUIDs of the services it advertised |
| manufacturerData | Uint8Array | null | Its manufacturer-specific data |
| serviceData | Record<string, Uint8Array> | Its service data, keyed by service UUID |
Event Types
The events this module's watchers emit, and when. In TypeScript, each type is a union of its event names that you can use as a type of your own:
HSBluetoothDeviceEvent
An event name for HSBluetoothDevice.on(), HSBluetoothDevice.off() and HSBluetoothDevice.once()
| Event | Description |
|---|---|
"connected" |
macOS connected the device |
"disconnected" |
macOS disconnected the device |
HSBluetoothEvent
An event name for hs.bluetooth.on(), hs.bluetooth.off() and hs.bluetooth.once()
| Event | Description |
|---|---|
"connected" |
macOS connected a Bluetooth device |
"disconnected" |
macOS disconnected a Bluetooth device |
"powerChanged" |
Bluetooth was turned on or off |
"discovered" |
hs.bluetooth.scan() found a peripheral |
HSBluetoothPeripheralEvent
An event name for HSBluetoothPeripheral.on(), HSBluetoothPeripheral.off() and HSBluetoothPeripheral.once()
| 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 |
Properties
hs.bluetooth.isInquiring
Whether a search for classic devices started by inquiry() is running.
Methods
hs.bluetooth.pairedDevices() -> HSBluetoothDevice[]
All devices paired with this Mac, connected or not.
hs.bluetooth.pairedDevices() -> HSBluetoothDevice[]
HSBluetoothDevice objectshs.bluetooth.pairedDevices().forEach(d => console.log(d.name + " " + d.address))
hs.bluetooth.connectedDevices() -> HSBluetoothDevice[]
The paired devices macOS currently has connected.
hs.bluetooth.connectedDevices() -> HSBluetoothDevice[]
HSBluetoothDevice objectshs.bluetooth.connectedDevices().forEach(d => console.log(d.name + " is connected"))
hs.bluetooth.device(address) -> HSBluetoothDevice
Looks up a device macOS knows by its Bluetooth address.
hs.bluetooth.device(address) -> HSBluetoothDevice
| Name | Type | Description |
|---|---|---|
| address | string | The device's address, as "a4-83-e7-12-34-56" or "A4:83:E7:12:34:56" |
HSBluetoothDevice, or null if macOS doesn't know a device with that addressconst keyboard = hs.bluetooth.device("a4-83-e7-12-34-56")
if (keyboard) console.log(keyboard.name + " battery: " + keyboard.batteryLevel + "%")
hs.bluetooth.connectedPeripherals() -> HSBluetoothPeripheral[]
The BLE peripherals Hammerspoon is connected to, with HSBluetoothPeripheral.connect().
hs.bluetooth.connectedPeripherals() -> HSBluetoothPeripheral[]
HSBluetoothPeripheral objectshs.bluetooth.connectedPeripherals().forEach(p => console.log(p.name))
hs.bluetooth.peripheral(identifier) -> HSBluetoothPeripheral
Looks up a BLE peripheral by its identifier.
Hammerspoon must have seen the peripheral in a scan, or Bluetooth must already be in use, for it to be found. This lookup doesn't start Bluetooth itself, so it never shows the permission prompt.
hs.bluetooth.peripheral(identifier) -> HSBluetoothPeripheral
| Name | Type | Description |
|---|---|---|
| identifier | string | The peripheral's identifier, a UUID |
HSBluetoothPeripheral, or null if it isn't knownconst sensor = hs.bluetooth.peripheral("5D7E2C4A-1B3F-4E8A-9C6D-0F1E2D3C4B5A")
if (sensor) sensor.connect()
hs.bluetooth.scan(options) -> Promise<HSBluetoothPeripheral[]>
Scans for BLE peripherals nearby. Only one scan can run at a time.
Each peripheral found is also delivered to 'discovered' listeners (see on()) as soon as it's seen.
hs.bluetooth.scan(options) -> Promise<HSBluetoothPeripheral[]>
| Name | Type | Description |
|---|---|---|
| options optional | object | null | How to scan |
| seconds optional | number | How long to scan for, counted from when Bluetooth is ready (e.g. after the permission prompt is answered). Defaults to 10 |
| services optional | string[] | Only report peripherals advertising one of these service UUIDs |
| allowDuplicates optional | boolean | Deliver every advertisement to 'discovered' listeners, not just the first from each peripheral, e.g. to follow signal strength. Defaults to false |
stopScan() is called. Rejects if a scan is already running, the options are invalid, or Bluetooth is unavailablehs.bluetooth.scan({ seconds: 5 })
.then(nearby => nearby.forEach(p => console.log((p.name ?? p.identifier) + " " + p.rssi + " dBm")))
hs.bluetooth.scan({ services: ["180D"] })
.then(heartStraps => console.log("Found " + heartStraps.length + " heart rate straps"))
hs.bluetooth.stopScan() -> None
Ends a scan started by scan() early. Its Promise resolves with the peripherals found so far.
hs.bluetooth.stopScan() -> None
hs.bluetooth.once('discovered', p => hs.bluetooth.stopScan())
hs.bluetooth.scan({ seconds: 30 }).then(([first]) => console.log(first?.name))
hs.bluetooth.inquiry(options) -> Promise<HSBluetoothDevice[]>
Searches for discoverable classic Bluetooth devices nearby, such as headphones in pairing mode. Only one search can run at a time.
This interrupts the audio of connected Bluetooth headphones while it runs.
hs.bluetooth.inquiry(options) -> Promise<HSBluetoothDevice[]>
| Name | Type | Description |
|---|---|---|
| options optional | object | null | How to search |
| seconds optional | number | How long to search for, from 1 to 255. Defaults to 10 |
stopInquiry() is called. Rejects if a search is already running, the options are invalid, or the search failshs.bluetooth.inquiry({ seconds: 10 })
.then(found => found.forEach(d => console.log(d.name + " " + d.address)))
hs.bluetooth.stopInquiry() -> None
Ends a search started by inquiry() early. Its Promise resolves with the devices found so far.
hs.bluetooth.stopInquiry() -> None
hs.bluetooth.stopInquiry()
hs.bluetooth.on(event, listener) -> None
Register a listener for Bluetooth events.
Listeners receive:
"connected","disconnected": theHSBluetoothDevicethat macOS connected or disconnected. For Hammerspoon's own connections to BLE peripherals, listen on theHSBluetoothPeripheralinstead."powerChanged":truewhen Bluetooth is turned on,falsewhen it's turned off"discovered": eachHSBluetoothPeripheralfound whilehs.bluetooth.scan()runs
hs.bluetooth.on(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSBluetoothEvent | The event to listen for |
| listener | (arg: HSBluetoothDevice | HSBluetoothPeripheral | boolean) => void | Called with the event's device or peripheral, or for "powerChanged" the new power state |
| Event | Description |
|---|---|
"connected" |
macOS connected a Bluetooth device |
"disconnected" |
macOS disconnected a Bluetooth device |
"powerChanged" |
Bluetooth was turned on or off |
"discovered" |
hs.bluetooth.scan() found a peripheral |
try {
hs.bluetooth.on('connected', device => console.log(device.name + " connected"))
hs.bluetooth.on('disconnected', device => console.log(device.name + " disconnected"))
hs.bluetooth.on('powerChanged', on => console.log("Bluetooth is " + (on ? "on" : "off")))
} catch (err) {
console.error(err.message)
}
hs.bluetooth.off(event, listener) -> None
Remove a previously registered Bluetooth event listener.
hs.bluetooth.off(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSBluetoothEvent | The event the listener was registered for |
| listener | (arg: HSBluetoothDevice | HSBluetoothPeripheral | boolean) => void | The function originally passed to on |
| Event | Description |
|---|---|
"connected" |
macOS connected a Bluetooth device |
"disconnected" |
macOS disconnected a Bluetooth device |
"powerChanged" |
Bluetooth was turned on or off |
"discovered" |
hs.bluetooth.scan() found a peripheral |
const onConnected = device => console.log(device.name)
hs.bluetooth.on('connected', onConnected)
// later…
hs.bluetooth.off('connected', onConnected)
hs.bluetooth.once(event, listener) -> None
Register a listener that fires at most once for a Bluetooth event.
hs.bluetooth.once(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSBluetoothEvent | The event to listen for |
| listener | (arg: HSBluetoothDevice | HSBluetoothPeripheral | boolean) => void | Called the next time the event occurs, then automatically removed |
| Event | Description |
|---|---|
"connected" |
macOS connected a Bluetooth device |
"disconnected" |
macOS disconnected a Bluetooth device |
"powerChanged" |
Bluetooth was turned on or off |
"discovered" |
hs.bluetooth.scan() found a peripheral |
try {
hs.bluetooth.once('connected', device => console.log("First connection: " + device.name))
} catch (err) {
console.error(err.message)
}