bare-bluetooth-apple
CoreBluetooth bindings for Bare
v0.8.0bare-bluetooth-apple — CoreBluetooth bindings for Bare. It is a native addon.
npm i bare-bluetooth-appleUsage
The peripheral role advertises GATT services through a PeripheralManager.
const bluetooth = require('bare-bluetooth-apple')
const manager = new bluetooth.PeripheralManager()
manager.on('stateChange', (state) => {
if (state !== 'poweredOn') return
const char = new bluetooth.Characteristic('01230001-0000-1000-8000-00805F9B34FB', {
write: true,
notify: true
})
const service = new bluetooth.Service('01230000-0000-1000-8000-00805F9B34FB', [char])
manager.addService(service)
})
manager.on('serviceAdd', (uuid) => {
manager.startAdvertising({
name: 'MyDevice',
serviceUUIDs: ['01230000-0000-1000-8000-00805F9B34FB']
})
})
manager.on('error', (err) => {
console.error('manager error:', err.code, err.message)
})
manager.on('writeRequest', (requests) => {
// Handle incoming write requests
manager.respondToRequest(requests[0], bluetooth.PeripheralManager.ATT_SUCCESS, null)
})A failure to add a service is emitted as an 'error' event. 'serviceAdd' carries only the service uuid.
The central role scans for peripherals and connects to them. To connect to a peripheral seen in an earlier scan, store its id and resolve it again with retrievePeripherals(), which needs no scan. The central has to be powered on first, because the call throws otherwise.
const bluetooth = require('bare-bluetooth-apple')
const savedId = '9D1F6A4C-0F3B-4E5A-8A52-5F3A8B7C1D20' // a peripheral.id stored by your app
const central = new bluetooth.Central()
central.on('stateChange', (state) => {
if (state !== 'poweredOn') return
const [peripheral] = central.retrievePeripherals([savedId])
if (peripheral) central.connect(peripheral)
})
central.on('connect', (peripheral) => {
peripheral.discoverServices()
})
central.on('error', (err) => {
console.error('central error:', err.code, err.message)
})API
L2CAPChannel
new L2CAPChannel(channelHandle: ArrayBuffer)
An L2CAP channel, obtained through the 'channelOpen' event on PeripheralManager or Peripheral. Extends Duplex from bare-stream and supports standard readable and writable stream operations.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
channelHandle | ArrayBuffer | — | The native channel handle backing the stream; supplied internally when a channel opens, not usually passed directly. |
peer: string | null
The UUID of the remote peer if available
psm: number
The L2CAP PSM (Protocol/Service Multiplexer) for this channel
Service
new Service(uuid: string, characteristics?: Characteristic[], opts?: ServiceOptions)
Create a GATT service definition.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
uuid | string | — | The service's UUID. |
characteristics? | Characteristic[] | — | The characteristics belonging to the service. |
opts? | ServiceOptions | — | Options; services are primary unless primary: false is set. |
characteristics: Characteristic[]
The characteristics belonging to this service
primary: boolean
Whether this is a primary service
Service.uuid: string
The service UUID
Characteristic
new Characteristic(uuid: string, opts?: CharacteristicOptions)
Create a GATT characteristic definition.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
uuid | string | — | The characteristic's UUID. |
opts? | CharacteristicOptions | — | Options selecting the characteristic properties (read, write, writeWithoutResponse, notify, indicate) and its optional permissions and initial value. |
Characteristic.PROPERTY_INDICATE: number
Characteristic property flags.
Characteristic.PROPERTY_NOTIFY: number
Characteristic.PROPERTY_READ: number
Characteristic.PROPERTY_WRITE: number
Characteristic.PROPERTY_WRITE_WITHOUT_RESPONSE: number
permissions: number | null
Bitmask of characteristic permissions, if set explicitly
properties: number
Bitmask of characteristic properties
Characteristic.uuid: string
The characteristic UUID
value: Uint8Array | null
The current value, if set. As of v0.7.1, assigning a value throws Cannot set the value of a discovered characteristic on a discovered characteristic. The check is on the native handle, which discovery sets and manager.addService() also sets, so assigning to a local characteristic throws once it has been passed to addService(). The value option of the constructor is not affected.
PeripheralManager
new PeripheralManager(opts?: PeripheralManagerOptions)
Create a new BLE peripheral manager. Advertises services and handles read/write requests from centrals.
As of v0.7.0 the manager no longer lets the system show its Bluetooth power alert when Bluetooth is off. Pass showPowerAlert: true to let the system show it.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | PeripheralManagerOptions | — | Manager options such as showPowerAlert. Added in v0.7.0. |
addService(service: Service): void
Add a service to the manager. The service and its characteristics will be registered with the system.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
service | Service | — | The Service to register with the system, along with its characteristics. |
PeripheralManager.destroy(): void
Destroy the instance and release all resources.
PeripheralManager.ATT_INSUFFICIENT_RESOURCES: number
PeripheralManager.ATT_INVALID_HANDLE: number
PeripheralManager.ATT_READ_NOT_PERMITTED: number
PeripheralManager.ATT_SUCCESS: number
PeripheralManager.ATT_UNLIKELY_ERROR: number
ATT result codes for use with manager.respondToRequest().
PeripheralManager.ATT_WRITE_NOT_PERMITTED: number
PeripheralManager.PERMISSION_READ_ENCRYPTED: number
PeripheralManager.PERMISSION_READABLE: number
PeripheralManager.PERMISSION_WRITE_ENCRYPTED: number
Characteristic permission flags.
PeripheralManager.PERMISSION_WRITEABLE: number
PeripheralManager.PROPERTY_INDICATE: number
Characteristic property flags.
PeripheralManager.PROPERTY_NOTIFY: number
PeripheralManager.PROPERTY_READ: number
PeripheralManager.PROPERTY_WRITE: number
PeripheralManager.PROPERTY_WRITE_WITHOUT_RESPONSE: number
PeripheralManager.STATE_POWERED_OFF: number
PeripheralManager.STATE_POWERED_ON: number
PeripheralManager.STATE_RESETTING: number
PeripheralManager.STATE_UNAUTHORIZED: number
PeripheralManager.STATE_UNKNOWN: number
PeripheralManager.STATE_UNSUPPORTED: number
Bluetooth state constants.
publishChannel(opts?: ChannelOptions): void
Publish an L2CAP channel.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | ChannelOptions | — | Options for the L2CAP channel to publish. |
removeAllServices(): void
Remove every service this instance has published, without destroying it.
respondToRequest(request: ReadRequest, result: number, data?: Uint8Array | null): void
Respond to a read or write request with the given ATT result code. Optionally include data for read responses.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
request | ReadRequest | — | The read or write request to respond to, as delivered by the 'readRequest'/'writeRequest' event. |
result | number | — | The ATT result code, for example PeripheralManager.ATT_SUCCESS. |
data? | Uint8Array | null | — | The value to return for a read request; omit for write responses. |
startAdvertising(opts?: AdvertisingOptions): void
Start advertising.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | AdvertisingOptions | — | Advertising options such as the local name and the serviceUUIDs to advertise. |
PeripheralManager.state: BluetoothState
The current Bluetooth adapter state
stopAdvertising(): void
Stop advertising.
unpublishChannel(psm: number): void
Unpublish a previously published L2CAP channel identified by psm.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
psm | number | — | The PSM of the channel to unpublish, as assigned when it was published. |
updateValue(characteristic: Characteristic, data: Uint8Array): boolean
Update the value of a characteristic and notify subscribed centrals.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic whose value changed. |
data | Uint8Array | — | The new value to send to subscribed centrals. |
Returns boolean — Whether the notification was sent to subscribed centrals successfully.
Central
new Central(opts?: CentralOptions)
Create a new BLE central manager. The central scans for and connects to peripherals.
As of v0.7.0 the manager no longer lets the system show its Bluetooth power alert when Bluetooth is off. Pass showPowerAlert: true to let the system show it.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | CentralOptions | — | Manager options such as showPowerAlert. Added in v0.7.0. |
Central.STATE_POWERED_OFF: number
Central.STATE_POWERED_ON: number
Central.STATE_RESETTING: number
Central.STATE_UNAUTHORIZED: number
Central.STATE_UNKNOWN: number
Central.STATE_UNSUPPORTED: number
Bluetooth state constants.
connect(peripheral: DiscoveredPeripheral | RetrievedPeripheral): void
Connect to a discovered or retrieved peripheral. The Peripheral delivered by 'connect' takes its name and serviceData from the latest 'discover' event this central emitted for the same id. As of v0.8.0 the central keeps those events until the next startScan(), so stopping the scan before the connection completes no longer loses them. For a peripheral this central has not discovered since its last startScan(), such as a retrieved one, serviceData is null and name falls back to the device's own name. Before v0.8.0, stopScan() discarded the saved events, so both were null if the scan had stopped by the time the connection completed.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
peripheral | DiscoveredPeripheral | RetrievedPeripheral | — | A discovered or retrieved peripheral to connect to. Connecting to a retrieved peripheral was added in v0.6.0. |
Central.destroy(): void
Destroy the instance and release all resources.
disconnect(peripheral: Peripheral | DiscoveredPeripheral | RetrievedPeripheral): void
Disconnect from a connected peripheral, or cancel a pending connection to a discovered or retrieved one.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
peripheral | Peripheral | DiscoveredPeripheral | RetrievedPeripheral | — | The connected peripheral to disconnect from, or a discovered or retrieved peripheral with a pending connection. |
retrieveConnectedPeripherals(services: string[]): RetrievedPeripheral[]
Return the peripherals already connected to the system that implement any of services. A peripheral connected by another app still needs connect() before this central can use it. Throws Bluetooth is not powered on unless the central is powered on. Added in v0.6.0.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
services | string[] | — | The service UUIDs to match; a peripheral is returned if it implements any of them. |
Returns RetrievedPeripheral[] — The matching peripherals. Each state may reflect a connection made by another app.
retrievePeripherals(ids: string[]): RetrievedPeripheral[]
Resolve peripherals from identifiers saved after an earlier scan, without scanning again. It returns one entry for each id the system knows, and no entry for an id it does not know. Pass an entry to connect() to connect to it. Throws Invalid peripheral id '<id>' if an id is not a UUID, and Bluetooth is not powered on unless the central is powered on. Added in v0.6.0.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ids | string[] | — | The per host UUIDs reported as peripheral.id, not MAC addresses. |
Returns RetrievedPeripheral[] — The peripherals the system knows, with no advertisement data. See RetrievedPeripheral.
startScan(serviceUUIDs?: string[], opts?: { allowDuplicates?: boolean }): void
Start scanning for peripherals. If serviceUUIDs is provided, only peripherals advertising those services will be discovered. As of v0.8.0, each call clears the 'discover' events that connect() takes a peripheral's name and serviceData from. Before v0.8.0, stopScan() cleared them.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
serviceUUIDs? | string[] | — | The service UUIDs to filter advertisements by; omit to discover all peripherals. |
opts? | { allowDuplicates?: boolean } | — | — |
Central.state: BluetoothState
The current Bluetooth adapter state
stopScan(): void
Stop scanning for peripherals.
Peripheral
new Peripheral(peripheralHandle: ArrayBuffer, opts?: PeripheralOptions)
Represents a connected BLE peripheral. Obtained through the 'connect' event on Central — not typically constructed directly.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
peripheralHandle | ArrayBuffer | — | The native peripheral handle; supplied internally when Central emits 'connect', not usually passed directly. |
opts? | PeripheralOptions | — | Options carrying the peripheral's advertised metadata. |
Peripheral.destroy(): void
Destroy the instance and release all resources.
discoverCharacteristics(service: Service, characteristicUUIDs?: string[]): void
Discover characteristics for a service. If characteristicUUIDs is provided, only those characteristics will be discovered.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
service | Service | — | The service to discover characteristics on. |
characteristicUUIDs? | string[] | — | The characteristic UUIDs to discover; omit to discover all characteristics of the service. |
discoverServices(serviceUUIDs?: string[]): void
Discover services on the peripheral. If serviceUUIDs is provided, only those services will be discovered.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
serviceUUIDs? | string[] | — | The service UUIDs to discover; omit to discover all services. |
id: string
The peripheral UUID identifier. It is a UUID that is specific to the host, not a hardware address, so it differs from the address bare-bluetooth-android reports as id for the same device. Save it to resolve the peripheral again later with central.retrievePeripherals().
name: string | null
The advertised name, or the GAP device name once connected. null while neither is available yet. The fallback to the device name was added in v0.7.2. Before that, a peripheral that connected without an advertised name kept null. The 'nameChange' event reports later changes.
openL2CAPChannel(psm: number): void
Open an L2CAP channel to the peripheral using the given psm.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
psm | number | — | The PSM (Protocol/Service Multiplexer) of the channel to open. |
Peripheral.PROPERTY_INDICATE: number
Characteristic property flags.
Peripheral.PROPERTY_NOTIFY: number
Peripheral.PROPERTY_READ: number
Peripheral.PROPERTY_WRITE: number
Peripheral.PROPERTY_WRITE_WITHOUT_RESPONSE: number
read(characteristic: Characteristic): void
Read the value of a characteristic.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to read. |
serviceData: { [uuid: string]: Uint8Array } | null
Service data captured from the most recent advertisement seen before connect, or null
subscribe(characteristic: Characteristic): void
Subscribe to notifications for a characteristic.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to start receiving notifications for. |
unsubscribe(characteristic: Characteristic): void
Unsubscribe from notifications for a characteristic.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to stop receiving notifications for. |
write(characteristic: Characteristic, data: Uint8Array, withResponse?: boolean): void
Write data to a characteristic. If withResponse is true (the default), the write will be confirmed by the peripheral.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to write to. |
data | Uint8Array | — | The bytes to write. |
withResponse? | boolean | — | Whether the peripheral confirms the write (default true). |
Types
ServiceOptions
interface ServiceOptions {
primary?: boolean
}CharacteristicOptions
interface CharacteristicOptions {
read?: boolean
write?: boolean
writeWithoutResponse?: boolean
notify?: boolean
indicate?: boolean
permissions?: number
value?: Uint8Array | null
}PeripheralManagerOptions
interface PeripheralManagerOptions {
showPowerAlert?: boolean
}showPowerAlert lets the system show its own Bluetooth power alert when Bluetooth is off. It defaults to false. Added in v0.7.0.
BluetoothState
type BluetoothState = 'unknown' | 'resetting' | 'unsupported' | 'unauthorized' | 'poweredOff' | 'poweredOn'AdvertisingOptions
interface AdvertisingOptions {
name?: string
serviceUUIDs?: string[]
serviceData?: { [uuid: string]: Uint8Array }
}ChannelOptions
interface ChannelOptions {
encrypted?: boolean
}ReadRequest
interface ReadRequest {
characteristicUuid: string
offset: number
}WriteRequest
interface WriteRequest {
characteristicUuid: string
data: Uint8Array
offset: number
}PeripheralManagerEventMap
interface PeripheralManagerEventMap {
stateChange: [state: BluetoothState]
error: [error: BluetoothError]
serviceAdd: [uuid: string]
channelPublish: [psm: number]
channelOpen: [channel: L2CAPChannel]
readRequest: [request: ReadRequest]
writeRequest: [requests: WriteRequest[]]
subscribe: [centralHandle: ArrayBuffer, characteristicUuid: string]
unsubscribe: [centralHandle: ArrayBuffer, characteristicUuid: string]
readyToUpdate: []
}subscribe and unsubscribe carry a native handle for the central. On Android they carry the address of the device instead.
CentralOptions
interface CentralOptions {
showPowerAlert?: boolean
}showPowerAlert lets the system show its own Bluetooth power alert when Bluetooth is off. It defaults to false. Added in v0.7.0.
DiscoveredPeripheral
interface DiscoveredPeripheral {
id: string
name: string | null
rssi: number
serviceData: { [uuid: string]: Uint8Array } | null
}RetrievedPeripheral
interface RetrievedPeripheral {
id: string
name: string | null
state: PeripheralState
}A peripheral resolved without scanning, as returned by central.retrievePeripherals() and central.retrieveConnectedPeripherals(). It carries no advertisement data, so it has no rssi or serviceData. state is the connection state, which may reflect a connection made by another app. Added in v0.6.0.
PeripheralState
type PeripheralState = 'disconnected' | 'connecting' | 'connected' | 'disconnecting'The connection state of a RetrievedPeripheral. Added in v0.6.0.
CentralEventMap
interface CentralEventMap {
stateChange: [state: BluetoothState]
error: [error: BluetoothError]
discover: [peripheral: DiscoveredPeripheral]
connect: [peripheral: Peripheral]
disconnect: [peripheral: Peripheral | null]
}PeripheralOptions
interface PeripheralOptions {
id?: string
name?: string | null
serviceData?: { [uuid: string]: Uint8Array } | null
}PeripheralEventMap
interface PeripheralEventMap {
error: [error: BluetoothError]
nameChange: [name: string | null]
servicesDiscover: [services: Service[]]
characteristicsDiscover: [service: Service | null, characteristics: Characteristic[]]
read: [characteristic: Characteristic | null, data: Uint8Array | null]
write: [characteristic: Characteristic | null]
notify: [characteristic: Characteristic | null, data: Uint8Array | null]
notifyState: [characteristic: Characteristic | null, isNotifying: boolean]
channelOpen: [channel: L2CAPChannel]
}'nameChange' is emitted when the device reports a new name, with null if it no longer has one. From then on peripheral.name returns the new value. Added in v0.8.0.
Errors
Failures are emitted as 'error' events carrying a BluetoothError. It is not exported from the module, but its code identifies the failure:
| Code | Emitted by | When |
|---|---|---|
CONNECTION_FAILED | Central | A connection attempt failed. The error's id is the peripheral's id. |
DISCONNECT | Central | A peripheral disconnected with an error. The error's id is the peripheral's id. |
DISCOVER_FAILED | Peripheral | Discovering services or characteristics failed. |
READ_FAILED | Peripheral | Reading a characteristic failed. |
WRITE_FAILED | Peripheral | Writing a characteristic failed. |
NOTIFY_FAILED | Peripheral | A notification update for a subscribed characteristic reported an error. |
NOTIFY_STATE_FAILED | Peripheral | Changing a characteristic's notification state (subscribing or unsubscribing) failed. |
CHANNEL_FAILED | Peripheral, PeripheralManager | Opening an L2CAP channel failed. |
ADVERTISE_FAILED | PeripheralManager | Advertising failed. |
SERVICE_ADD_FAILED | PeripheralManager | Adding a service failed. |
CHANNEL_PUBLISH_FAILED | PeripheralManager | Publishing an L2CAP channel failed. |
See also
- Builds on
bare-eventsandbare-stream. - Runs on Apple platforms (iOS and macOS) — on Android use
bare-bluetooth-android. The two share most concepts under different names: the peripheral role isPeripheralManagerhere andServerthere, adapter states are'poweredOn'and'poweredOff'here and'on'and'off'there, and a peripheralidis a per host UUID here and a hardware address there. To connect without a scan, this package resolves saved ids withretrievePeripherals(), while that one builds aPeripheralfrom aDevice, such as one fromgetBondedDevices(). bare-bluetooth— the cross-platform API over this module,bare-bluetooth-androidandbare-bluetooth-linux.- One core, many platforms — using platform bindings from a native shell.
- Connect over Bluetooth — how-to guides for scanning, GATT, L2CAP and mobile setup.
- Use platform-specific Bluetooth features — when to use this module directly instead of
bare-bluetooth. - Bare modules — the full
bare-*catalog. - Bare runtime API — the runtime these modules extend.
Last updated on