bare-bluetooth-android
Android Bluetooth bindings for Bare
v0.11.7bare-bluetooth-android — Android Bluetooth bindings for Bare. It is a native addon that needs the app's Java VM, which it reads from the bare.android.jvm.v1 context key when it loads. So it runs only inside an app whose host publishes that key. Bare Kit does so from 2.5.0, so a Bare Kit worklet needs Bare Kit 2.5.0 or later.
npm i bare-bluetooth-androidAs of v0.11.2, the prebuilds link the C++ standard library statically, so they no longer list libc++_shared.so among their needed libraries. As of v0.9.3, they also no longer list libnativehelper.so.
The addon finds its Java helper classes (to.holepunch.bare.bluetooth.*) by name through JNI, which R8 can't see when it shrinks an app. As of v0.11.7, the classes JAR embeds a keep rule for them (bare-bluetooth-android.pro), so R8 applies it to an app that depends on that JAR. With an earlier version, a release build that shrinks the app needs -keep class to.holepunch.bare.bluetooth.** { *; } in its own R8 rules.
Usage
The central role scans for peripherals and connects to them.
const { Central } = require('bare-bluetooth-android')
const central = new Central()
central.on('stateChange', (state) => {
if (state === 'on') {
central.startScan(['180D']) // Heart Rate service UUID
}
})
central.on('discover', (peripheral) => {
console.log('Found:', peripheral.name, peripheral.id)
central.stopScan()
central.connect(peripheral)
})
central.on('connect', (peripheral) => {
peripheral.discoverServices()
peripheral.on('servicesDiscover', (services) => {
// Discover characteristics for each service
})
})The peripheral role advertises GATT services through a Server. Open the GATT server once the adapter is on, before adding services.
const { Server, Service, Characteristic } = require('bare-bluetooth-android')
const SERVICE_UUID = '01230000-0000-1000-8000-00805F9B34FB'
const server = new Server()
server.on('stateChange', (state) => {
if (state !== 'on') return
// The GATT server does not survive the adapter turning off, so reopen it and
// add the services again on every transition to 'on'. close() is a no-op
// when the server is not open, and open() throws when it already is.
server.close()
server.open()
const characteristic = new Characteristic('01230001-0000-1000-8000-00805F9B34FB', {
read: true,
value: new Uint8Array([0x01])
})
server.addService(new Service(SERVICE_UUID, [characteristic]))
})
server.on('serviceAdd', () => {
server.startAdvertising({ serviceUUIDs: [SERVICE_UUID] })
})
server.on('error', (err) => {
console.error('server error:', err.code, err.message)
})API
BluetoothError
The package root exports BluetoothError as of v0.11.3. Earlier versions did not export the class from the package root, although the errors they raised were instances of it.
Failures reach your code three ways. A call can throw when the Android call itself fails, with the Java exception in the message, for example java.lang.IllegalStateException: BT Adapter is not turned ON. An operation that fails after the call went through is emitted as an 'error' event carrying a BluetoothError. A failed write on an L2CAPChannel destroys the stream, so listen for 'error' on the channel.
new BluetoothError(msg: string, fn?: Function, code?: string)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | A human-readable error message. |
fn? | Function | — | The function to omit from the captured stack trace (default BluetoothError). |
code? | string | — | The error code; defaults to fn.name (for example SCAN_FAILED). |
BluetoothError.ADAPTER_UNAVAILABLE(msg: string): BluetoothError
Thrown by the Central and Server constructors on a device with no Bluetooth adapter. The error message reads ADAPTER_UNAVAILABLE: Bluetooth adapter unavailable. Added in v0.11.3.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | A human-readable error message. |
BluetoothError.ADVERTISE_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.CHANNEL_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.CHANNEL_PUBLISH_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.CONNECTION_FAILED(msg: string, id: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | A human-readable error message. |
id | string | — | The id of the peripheral the connection attempt targeted. |
BluetoothError.DISCONNECT(msg: string, id: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | A human-readable error message. |
id | string | — | The id of the peripheral that disconnected. |
BluetoothError.DISCOVER_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.MTU_CHANGE_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.NOT_CONNECTED(msg: string): BluetoothError
Thrown by the Peripheral methods that talk to the device when the peripheral is not connected: before 'connect', and once the link is gone. The error message reads NOT_CONNECTED: Peripheral is not connected. Added in v0.11.6. As of v0.11.6, lib/errors.d.ts does not declare this factory, although lib/errors.js defines it.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | A human-readable error message. |
BluetoothError.NOTIFY_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.NOTIFY_STATE_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.READ_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.SCAN_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.SERVICE_ADD_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
BluetoothError.WRITE_FAILED(msg: string): BluetoothError
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
msg | string | — | — |
code: string
BluetoothError.id: string
The id of the peripheral, as passed to BluetoothError.CONNECTION_FAILED() or BluetoothError.DISCONNECT(). Left unset by every other factory.
name: 'BluetoothError'
The name of the error, always 'BluetoothError'.
L2CAPChannel
new L2CAPChannel(channelHandle: ArrayBuffer)
A duplex stream representing an L2CAP connection-oriented channel. Extends Duplex from <https://github.com/holepunchto/bare-stream>. Typically obtained via the 'channelOpen' event rather than constructed directly.
A failed write does not throw from write(). As of v0.11.1 it destroys the stream with the Java exception, for example java.io.IOException: Broken pipe once the peer is gone, so listen for 'error' on the channel. An unhandled 'error' still throws. A native channel error destroys the stream with that error, and a native close destroys it, instead of either being emitted directly.
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 address of the remote peer, or null.
psm: number
The Protocol/Service Multiplexer number of the channel.
Service
new Service(uuid: string, characteristics?: Characteristic[], opts?: ServiceOptions)
Create a new 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 array of characteristics belonging to the service.
primary: boolean
Whether the service is a primary service.
Service.uuid: string
The UUID of the service.
Characteristic
new Characteristic(uuid: string, opts?: CharacteristicOptions)
Create a new GATT characteristic definition.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
uuid | string | — | The characteristic's UUID. |
opts? | CharacteristicOptions | — | Options selecting the characteristic properties, permissions, and initial value. |
Characteristic.PROPERTY_INDICATE: number
Characteristic property constants.
Characteristic.PROPERTY_NOTIFY: number
Characteristic.PROPERTY_READ: number
Characteristic.PROPERTY_WRITE: number
Characteristic.PROPERTY_WRITE_WITHOUT_RESPONSE: number
permissions: number | null
The permission flags of the characteristic, or null if inferred.
properties: number
The property flags of the characteristic.
Characteristic.uuid: string
The UUID of the characteristic.
value: Uint8Array | null
The current value of the characteristic, or null. As of v0.11.4, 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 server.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.
Server
As of v0.11.0, new Server() no longer opens the GATT server. Call server.open() once server.state is 'on', before addService(), respondToRequest(), or updateValue(). Code written for v0.10.0 or earlier does not call open(), so on v0.11.0 and later it throws GATT server unavailable from those calls.
new Server()
Create a new BLE peripheral server for advertising services and handling client requests. The constructor does not open the GATT server; call open() once state is 'on'. It throws a BluetoothError with code ADAPTER_UNAVAILABLE on a device with no Bluetooth adapter, as of v0.11.3.
addService(service: Service): void
Add a service to the GATT server. The 'serviceAdd' event is emitted when the service has been registered. The GATT server has to be open: this throws GATT server unavailable before open() and after close().
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
service | Service | — | The Service to register with the GATT server. |
close(): void
Close the GATT server, dropping its services. Does nothing if the server is not open. Added in v0.11.0.
Server.destroy(): void
Destroy the server, stopping advertising, unpublishing all L2CAP channels, and closing the GATT server if it is open.
open(): void
Open the GATT server. Call it once state is 'on'; it throws unless the adapter is on, and it throws GATT server already open when the server is already open. The GATT server does not survive the adapter turning off, so on every transition back to 'on' call close() and then open() again. Services do not survive a reopen and have to be added again. Added in v0.11.0.
startAdvertising() and publishChannel() do not check whether the GATT server is open.
publishChannel(opts?: ChannelOptions): void
Publish an L2CAP channel. The 'channelPublish' event is emitted with the assigned PSM.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | ChannelOptions | — | Options for the L2CAP channel to publish. |
respondToRequest(request: ReadRequest, result: number, data?: Uint8Array): void
Respond to a read or write request with a result code and optional data. Use the Server.ATT_* constants for the result.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
request | ReadRequest | — | The read or write request to respond to. |
result | number | — | The ATT result code; use the Server.ATT_* constants. |
data? | Uint8Array | — | The value to return for a read request; omit for write responses. |
Server.ATT_INSUFFICIENT_RESOURCES: number
Server.ATT_INVALID_HANDLE: number
Server.ATT_READ_NOT_PERMITTED: number
Server.ATT_SUCCESS: number
Server.ATT_UNLIKELY_ERROR: number
ATT result codes for use with server.respondToRequest().
Server.ATT_WRITE_NOT_PERMITTED: number
Server.CONNECTION_STATE_CONNECTED: number
Server.CONNECTION_STATE_CONNECTING: number
Server.CONNECTION_STATE_DISCONNECTED: number
Server.CONNECTION_STATE_DISCONNECTING: number
Server.PERMISSION_READ_ENCRYPTED: number
Server.PERMISSION_READABLE: number
Server.PERMISSION_WRITE_ENCRYPTED: number
Characteristic permission constants.
Server.PERMISSION_WRITEABLE: number
Server.PROPERTY_INDICATE: number
Characteristic property constants.
Server.PROPERTY_NOTIFY: number
Server.PROPERTY_READ: number
Server.PROPERTY_WRITE: number
Server.PROPERTY_WRITE_WITHOUT_RESPONSE: number
Server.STATE_OFF: number
Server.STATE_ON: number
Server.STATE_TURNING_OFF: number
Server.STATE_TURNING_ON: number
startAdvertising(opts?: AdvertisingOptions): void
Start advertising the server.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | AdvertisingOptions | — | Advertising options. serviceUUIDs lists the service UUIDs to advertise. When name is set, the adapter's own device name is included in the advertisement; only the presence of the option is used, not the string itself. On Apple platforms name is advertised as the local name. |
Server.state: BluetoothState
The current Bluetooth adapter state. One of 'off', 'turningOn', 'on', or 'turningOff'.
stopAdvertising(): void
Stop advertising.
unpublishChannel(psm: number): void
Unpublish an L2CAP channel with the given 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 characteristic with data and notify subscribed clients.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic whose value changed. |
data | Uint8Array | — | The new value to send to subscribed clients. |
Returns boolean — Whether the notification was sent to subscribed clients successfully.
Central
new Central()
Create a new BLE central manager for scanning and connecting to peripherals. It throws a BluetoothError with code ADAPTER_UNAVAILABLE on a device with no Bluetooth adapter, as of v0.11.3.
Central.CALLBACK_TYPE_ALL_MATCHES: number
Central.CALLBACK_TYPE_FIRST_MATCH: number
Central.CALLBACK_TYPE_MATCH_LOST: number
Central.SCAN_MODE_BALANCED: number
Central.SCAN_MODE_LOW_LATENCY: number
Scan mode constants for use with central.startScan().
Central.SCAN_MODE_LOW_POWER: number
Central.SCAN_MODE_OPPORTUNISTIC: number
Central.STATE_OFF: number
Central.STATE_ON: number
Central.STATE_TURNING_OFF: number
Central.STATE_TURNING_ON: number
connect(peripheral: Peripheral): void
Connect to a discovered peripheral, or to one built from a Device without a scan, such as a bonded device from getBondedDevices(). peripheral.connecting is true from this call until the 'connect' event delivers the same peripheral.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
peripheral | Peripheral | — | A discovered peripheral, or one built from a Device, to connect to. |
Central.destroy(): void
Destroy the central manager, stopping any active scan and destroying every connected peripheral.
disconnect(peripheral: Peripheral): void
Disconnect from a connected peripheral.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
peripheral | Peripheral | — | The connected peripheral to disconnect from. |
getBondedDevices(): Device[]
Return the devices bonded with the adapter, mirroring Android's BluetoothAdapter.getBondedDevices(). Each entry is a Device with its type set. The array is empty unless the adapter is on, and the call throws if the BLUETOOTH_CONNECT permission is not granted. To connect to a bonded device, build a Peripheral from it and pass that to connect(). Added in v0.10.0.
const { Central, Device, Peripheral } = require('bare-bluetooth-android')
const central = new Central()
central.on('stateChange', (state) => {
if (state !== 'on') return
// Choose a bonded device that is not a Classic device
const [device] = central.getBondedDevices().filter((d) => d.type !== Device.DEVICE_TYPE_CLASSIC)
if (device) central.connect(new Peripheral({ device }))
})startScan(serviceUUIDs?: string[], opts?: { scanMode?: number; callbackType?: number }): void
Start scanning for peripherals advertising the given serviceUUIDs. Pass null to scan for all peripherals.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
serviceUUIDs? | string[] | — | The service UUIDs to filter advertisements by; pass null to scan for all peripherals. |
opts? | { scanMode?: number; callbackType?: number } | — | Options; scanMode selects the Android scan mode (one of the Central.SCAN_MODE_* constants). |
Central.state: BluetoothState
The current Bluetooth adapter state. One of 'off', 'turningOn', 'on', or 'turningOff'.
stopScan(): void
Stop scanning for peripherals.
Peripheral
new Peripheral(opts: PeripheralOptions)
Create a new peripheral instance from a ScanResult or from a Device. Typically obtained via the 'discover' event on Central rather than constructed directly. Its identity and advertised metadata are derived from the scan result. Build one from a Device to connect without a scan, such as to a bonded device from central.getBondedDevices(); such a peripheral has no scan result, so scanResult, rssi, and serviceData are null. The constructor throws Peripheral needs a device or a scanResult when opts carries neither. Building a peripheral from a Device was added in v0.10.0.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts | PeripheralOptions | — | Options carrying the ScanResult or the Device this peripheral is derived from. |
connected: boolean
Whether the peripheral is connected
connecting: boolean
Whether a dial is in flight and has not connected yet
Peripheral.destroy(): void
Destroy the peripheral, releasing its underlying resources.
discoverCharacteristics(service: Service): void
Discover characteristics for the given service. Results are emitted via the 'characteristicsDiscover' event.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
service | Service | — | The service to discover characteristics on. |
discoverServices(): void
Discover services offered by the peripheral. Results are emitted via the 'servicesDiscover' event.
Peripheral.id: string
The unique identifier of the peripheral, equal to the device address (scanResult.device.address for a scanned peripheral). It is the hardware address of the device. On Apple platforms the id is a per host UUID instead.
name: string | null
The advertised name, or the device's own name once connected. null while neither is available yet. The advertised name is the name of the peripheral's Device. The fallback, added in v0.11.5, asks Android for the device's name while the peripheral is connected.
openL2CAPChannel(psm: number): void
Open an L2CAP channel to the peripheral using the given psm. The result is emitted via the 'channelOpen' event.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
psm | number | — | The PSM (Protocol/Service Multiplexer) of the channel to open. |
Peripheral.PROPERTY_INDICATE: number
Characteristic property constants.
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 characteristic. The result is emitted via the 'read' event.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to read. |
requestMtu(mtu: number): void
Request a new MTU size. The result is emitted via the 'mtuChanged' event.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
mtu | number | — | The desired ATT MTU size, in bytes. |
rssi: number | null
The signal strength of the most recent advertisement, equal to scanResult.rssi, or null when the peripheral was built from a Device and has no scan result.
scanResult: ScanResult | null
The ScanResult from the most recent advertisement for this peripheral, or null when the peripheral was built from a Device.
serviceData: ServiceData | null
The advertised service data, or null when the advertisement carried no scan record or no service data, or when there is no scan result.
subscribe(characteristic: Characteristic): void
Subscribe to notifications for characteristic.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to start receiving notifications for. |
unsubscribe(characteristic: Characteristic): void
Unsubscribe from notifications for 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 characteristic. If withResponse is true (the default), a write confirmation is requested.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
characteristic | Characteristic | — | The characteristic to write to. |
data | Uint8Array | — | The bytes to write. |
withResponse? | boolean | — | Whether a write confirmation is requested (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
}BluetoothState
type BluetoothState = 'off' | 'turningOn' | 'on' | 'turningOff'AdvertisingOptions
interface AdvertisingOptions {
name?: string
serviceUUIDs?: string[]
}ChannelOptions
interface ChannelOptions {
encrypted?: boolean
}ReadRequest
interface ReadRequest {
handle: unknown
requestId: number
characteristicUuid: string
offset: number
}WriteRequest
interface WriteRequest {
handle: unknown
requestId: number
characteristicUuid: string
data: Uint8Array
offset: number
responseNeeded: boolean
}PeripheralOptions
interface PeripheralOptions {
scanResult?: ScanResult
device?: Device
}Pass scanResult for a peripheral that came from a scan, or device to dial a device without a scan, such as one from central.getBondedDevices(). At least one is required. device was added in v0.10.0.
CentralEventMap
interface CentralEventMap {
stateChange: [state: BluetoothState]
discover: [peripheral: Peripheral]
connect: [peripheral: Peripheral]
disconnect: [peripheral: Peripheral | null]
error: [error: BluetoothError]
}connect carries the connected Peripheral. disconnect carries the disconnected Peripheral, or null if it was not tracked as connected; when the disconnect carried an error, error is emitted instead. The event map types are declared in the package's type files and are not re-exported from the package root.
PeripheralEventMap
interface PeripheralEventMap {
servicesDiscover: [services: Service[]]
characteristicsDiscover: [service: Service | null, characteristics: Characteristic[]]
read: [characteristic: Characteristic | null, data: Uint8Array]
write: [characteristic: Characteristic | null]
notify: [characteristic: Characteristic | null, data: Uint8Array]
notifyState: [characteristic: Characteristic | null, isNotifying: boolean]
channelOpen: [channel: L2CAPChannel]
mtuChanged: [mtu: number]
disconnect: []
error: [error: BluetoothError]
}disconnect is emitted when the peripheral has disconnected without error. As of v0.9.2, read, write, notify, and notifyState are dropped, rather than emitted with null, when the characteristic is not one this peripheral has discovered.
ServerEventMap
interface ServerEventMap {
stateChange: [state: BluetoothState]
serviceAdd: [uuid: string]
channelPublish: [psm: number]
channelOpen: [channel: L2CAPChannel]
readRequest: [request: ReadRequest]
writeRequest: [requests: WriteRequest[]]
subscribe: [deviceAddress: string, characteristicUuid: string]
unsubscribe: [deviceAddress: string, characteristicUuid: string]
connecting: [deviceAddress: string]
connected: [deviceAddress: string]
disconnecting: [deviceAddress: string]
disconnected: [deviceAddress: string]
notifySent: [deviceAddress: string, status: number]
error: [error: BluetoothError]
}subscribe and unsubscribe carry the address of the connected device and the UUID of the characteristic. On Apple platforms they carry a native central handle instead.
ServiceData
type ServiceData = {
[uuid: string]: Uint8Array
}Classes
ScanResult
class ScanResult {
device: Device
rssi: number
scanRecord: ScanRecord | null
}ScanRecord
class ScanRecord {
serviceData: ServiceData | null
}Device
class Device {
address: string
Device.DEVICE_TYPE_CLASSIC: number
Device.DEVICE_TYPE_DUAL: number
Device.DEVICE_TYPE_LE: number
Device.DEVICE_TYPE_UNKNOWN: number
name: string | null
type: number | null
}type is one of Device.DEVICE_TYPE_UNKNOWN (0), Device.DEVICE_TYPE_CLASSIC (1), Device.DEVICE_TYPE_LE (2), or Device.DEVICE_TYPE_DUAL (3), mirroring Android's BluetoothDevice.getType(). It is set on the devices that central.getBondedDevices() returns, and is null on a device that came from a scan. Added in v0.10.0.
Events
Each class is an EventEmitter. These are the events each one emits and the arguments they carry. Failures arrive as 'error' events; see Errors for the other ways a call can fail.
Central events
| Event | Arguments | Description |
|---|---|---|
'stateChange' | state: BluetoothState | The adapter state changed. |
'discover' | peripheral: Peripheral | A peripheral was found while scanning. Repeated advertisements from the same device reuse the same Peripheral. |
'connect' | peripheral: Peripheral | A connection was established. |
'disconnect' | peripheral: Peripheral | null | A peripheral disconnected, or null if it was not tracked as connected. If the disconnect carried an error, 'error' is emitted with code DISCONNECT instead. |
'error' | error: BluetoothError | An operation failed: SCAN_FAILED, CONNECTION_FAILED or DISCONNECT. The last two carry the device address as error.id. |
Peripheral events
| Event | Arguments | Description |
|---|---|---|
'servicesDiscover' | services: Service[] | Result of discoverServices(). |
'characteristicsDiscover' | service: Service | null, characteristics: Characteristic[] | Result of discoverCharacteristics(). |
'read' | characteristic: Characteristic, data: Uint8Array | A read completed. |
'write' | characteristic: Characteristic | A write completed. |
'notify' | characteristic: Characteristic, data: Uint8Array | A subscribed characteristic changed value. |
'notifyState' | characteristic: Characteristic, isNotifying: boolean | Notifications were turned on or off for the characteristic. |
'channelOpen' | channel: L2CAPChannel | An L2CAP channel opened (result of openL2CAPChannel()). |
'mtuChanged' | mtu: number | The MTU changed (result of requestMtu()). |
'disconnect' | none | The peripheral disconnected without error. |
'error' | error: BluetoothError | An operation failed, for example READ_FAILED, CHANNEL_FAILED or MTU_CHANGE_FAILED. |
The type declarations allow null for the characteristic of 'read', 'write', 'notify' and 'notifyState', but the module drops those events for a characteristic the peripheral has not discovered rather than emitting null.
Server events
| Event | Arguments | Description |
|---|---|---|
'stateChange' | state: BluetoothState | The adapter state changed. Call open() again after every transition back to 'on'. |
'serviceAdd' | uuid: string | A service was registered with the GATT server (result of addService()). |
'channelPublish' | psm: number | An L2CAP channel was published, with its assigned PSM. |
'channelOpen' | channel: L2CAPChannel | A remote device opened a published L2CAP channel. |
'readRequest' | request: ReadRequest | A client asked to read a characteristic. Every read reaches this event; answer it with respondToRequest(). |
'writeRequest' | requests: WriteRequest[] | A client wrote to a characteristic. If responseNeeded is set, answer with respondToRequest(). |
'subscribe' | deviceAddress: string, characteristicUuid: string | A connected device subscribed to notifications for a characteristic. |
'unsubscribe' | deviceAddress: string, characteristicUuid: string | A connected device unsubscribed from notifications for a characteristic. |
'connecting', 'connected', 'disconnecting', 'disconnected' | deviceAddress: string | The connection state of a remote device changed. |
'notifySent' | deviceAddress: string, status: number | A notification was sent to a device, with the platform status code. |
'error' | error: BluetoothError | An operation failed: SERVICE_ADD_FAILED, ADVERTISE_FAILED, CHANNEL_PUBLISH_FAILED or CHANNEL_FAILED. |
Errors
Failures arrive three ways:
- Thrown - the Android call itself failed. The message carries the Java exception, for example
java.lang.IllegalStateException: BT Adapter is not turned ON. Wrap the call intry/catch. As of v0.11.6, thePeripheralmethods that talk to the device (discoverServices(),discoverCharacteristics(),read(),write(),subscribe(),unsubscribe(),openL2CAPChannel()andrequestMtu()) also throw aBluetoothErrorwith codeNOT_CONNECTEDbefore'connect'and once the link is gone. - Emitted - the call went through and the operation failed later. The
errorevent carries aBluetoothErrorwith acodesuch asSCAN_FAILEDorCONNECTION_FAILED. - Streamed - an
L2CAPChannelis aDuplex, so a failed write does not throw from the write itself. It destroys the stream with the Java exception, for examplejava.io.IOException: Broken pipeonce the peer is gone. Listen forerroron the channel; an unhandled one still throws.
See also
- Builds on
bare-eventsandbare-stream. - Runs on Android only — on Apple platforms use
bare-bluetooth-apple. The two share most concepts under different names: the peripheral role isServerhere andPeripheralManagerthere, adapter states are'on'and'off'here and'poweredOn'and'poweredOff'there, and a peripheralidis a hardware address here and a per host UUID there. To connect without a scan, this package builds aPeripheralfrom aDevice, such as one fromgetBondedDevices(), while that one resolves saved ids withretrievePeripherals(). bare-bluetooth— the cross-platform API over this module,bare-bluetooth-appleandbare-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