Bare Docs

bare-bluetooth-linux

BlueZ D-Bus bindings for Bare

Documented against v0.9.2
experimental

bare-bluetooth-linux — BlueZ bindings for Bare. Provides central and peripheral roles, GATT services and characteristics, and L2CAP channels on Linux. It is a native addon that talks to the BlueZ daemon (bluetoothd) over D-Bus, so bluetoothd must be running and the adapter powered on. Upstream marks it experimental: its API is subject to change and may break at any time.

npm i bare-bluetooth-linux

Usage

Central, scanning for a Heart Rate monitor and reading its measurement:

const { Adapter } = require('bare-bluetooth-linux')

const adapter = new Adapter()

adapter.on('device', async (device) => {
  if (!device.uuids.includes('0000180d-0000-1000-8000-00805f9b34fb')) return

  await adapter.stopDiscovery()
  await device.connect()

  device.on('servicesResolved', (resolved) => {
    if (!resolved) return

    for (const service of device.services.values()) {
      for (const characteristic of service.characteristics.values()) {
        if (characteristic.flags.includes('notify')) {
          characteristic.on('data', (value) => console.log(new Uint8Array(value)))
          characteristic.startNotify()
        }
      }
    }
  })
})

adapter.setDiscoveryFilter({ transport: 'le' }).then(() => adapter.startDiscovery())

Peripheral, publishing a Heart Rate service and notifying a new value every second:

const {
  Adapter,
  Advertisement,
  Agent,
  GattApplication,
  GattService,
  GattCharacteristic
} = require('bare-bluetooth-linux')

const SERVICE = '0000180d-0000-1000-8000-00805f9b34fb'

const characteristic = new GattCharacteristic({
  uuid: '00002a37-0000-1000-8000-00805f9b34fb',
  flags: ['read', 'notify'],
  value: new Uint8Array([0, 60])
})

const service = new GattService({ uuid: SERVICE })
service.addCharacteristic(characteristic)

const app = new GattApplication({ path: '/com/example/heart' })
app.addService(service)

class AcceptAll extends Agent {
  requestAuthorization() {
    return Promise.resolve(true)
  }
}

const adapter = new Adapter()

async function main() {
  await adapter.registerAgent(new AcceptAll())
  await adapter.requestDefaultAgent()
  await adapter.registerApplication(app)
  await adapter.registerAdvertisement(
    new Advertisement({ localName: 'bare', serviceUUIDs: [SERVICE] })
  )

  setInterval(() => {
    characteristic.value = new Uint8Array([0, 60 + Math.round(Math.random() * 10)])
  }, 1000)
}

main()

API

Adapter

new Adapter(opts?: AdapterOptions)

Parameters

ParameterTypeDefaultDescription
opts?AdapterOptions——

address: string | null

Bluetooth address of the controller, null without one at path

destroy(): void

Releases the D-Bus connection, every later call rejects

devices: Map<string, Device>

Every device known to bluetoothd, keyed by D-Bus path

discovering: boolean

Whether a discovery session is active

Adapter.path: string

D-Bus path of the controller

powered: boolean

Switches the controller on or off, throws when BlueZ refuses

publishL2CAPChannel(opts?: ChannelOptions): void

Listens for L2CAP connections, channelPublish carries the PSM

Parameters

ParameterTypeDefaultDescription
opts?ChannelOptions——

registerAdvertisement(advertisement: Advertisement): Promise<void>

Registers an advertisement to be sent over the LE advertising channel

Parameters

ParameterTypeDefaultDescription
advertisementAdvertisement——

registerAgent(agent: Agent, capability?: AgentCapability): Promise<void>

Registers the pairing agent, NoInputNoOutput capability by default

Parameters

ParameterTypeDefaultDescription
agentAgent——
capability?AgentCapability——

registerApplication(application: GattApplication): Promise<void>

Registers a local GATT service hierarchy, the GATT server role

Parameters

ParameterTypeDefaultDescription
applicationGattApplication——

removeDevice(device: Device): Promise<void>

Removes the device and its cached information, bonding included

Parameters

ParameterTypeDefaultDescription
deviceDevice——

requestDefaultAgent(): Promise<void>

Makes the registered agent the default one for pairing requests

setDiscoveryFilter(filter?: DiscoveryFilter): Promise<void>

Sets the discovery filter for this adapter, no filter removes it

Parameters

ParameterTypeDefaultDescription
filter?DiscoveryFilter——

startDiscovery(): Promise<void>

Starts a discovery session: inquiry, scanning and name resolving

stopDiscovery(): Promise<void>

Stops the session started by startDiscovery

unpublishL2CAPChannel(psm: number): void

Stops listening on the PSM

Parameters

ParameterTypeDefaultDescription
psmnumber——

unregisterAdvertisement(advertisement: Advertisement): Promise<void>

Unregisters an advertisement registered with registerAdvertisement

Parameters

ParameterTypeDefaultDescription
advertisementAdvertisement——

unregisterAgent(): Promise<void>

Unregisters the agent registered with registerAgent

unregisterApplication(application: GattApplication): Promise<void>

Unregisters the hierarchy registered with registerApplication

Parameters

ParameterTypeDefaultDescription
applicationGattApplication——

Device

address: string

Bluetooth address of the remote device

addressType: AddressType

public for dual-mode and BR/EDR devices, either for LE only ones

connect(): Promise<void>

Connects every profile the device supports and flags auto-connectable

connected: boolean

disconnect(): Promise<void>

Disconnects every profile, then the ACL link

manufacturerData: { [id: number]: Uint8Array }

Manufacturer specific advertisement data, keyed by manufacturer id

name: string | undefined

Remote name, once a scan response or a connection carried it

openL2CAPChannel(psm: number, opts?: { security?: number }): void

Opens an L2CAP channel on the PSM, delivered on channelOpen

Parameters

ParameterTypeDefaultDescription
psmnumber——
opts?{ security?: number }——

pair(): Promise<void>

Connects, pairs, then discovers services

paired: boolean

Whether the devices exchanged keys for an encrypted connection

Device.path: string

D-Bus path of the device

preferredBearer: PreferredBearer | undefined

Bearer to try first when connecting, dual-mode devices only

rssi: number | undefined

Signal strength of the last advertisement, in dBm

Device.serviceData: { [uuid: string]: Uint8Array }

Service advertisement data, keyed by UUID

services: Map<string, Service>

Services discovered so far, keyed by D-Bus path

servicesResolved: boolean

Whether the GATT tree in services is complete

uuids: string[]

128-bit UUIDs of the remote services

Characteristic

descriptors: Map<string, Descriptor>

Descriptors discovered so far, keyed by D-Bus path

Characteristic.flags: string[]

How the value can be used: read, write, notify...

mtu: number

MTU for read and write

Characteristic.path: string

D-Bus path of the characteristic

Characteristic.read(): Promise<ArrayBuffer>

Reads the value from the peer

startNotify(): Promise<void>

Starts a notification session, values arrive on data

stopNotify(): Promise<void>

Stops the session started by startNotify

Characteristic.uuid: string

128-bit characteristic UUID

write(value: Uint8Array, opts?: WriteOptions): Promise<void>

Writes the value to the peer

Parameters

ParameterTypeDefaultDescription
valueUint8Array——
opts?WriteOptions——

Descriptor

Descriptor.flags: string[]

How the value can be used: read, write...

Descriptor.path: string

D-Bus path of the descriptor

Descriptor.read(): Promise<ArrayBuffer>

Reads the value from the peer

Descriptor.uuid: string

128-bit descriptor UUID

write(value: Uint8Array): Promise<void>

Writes the value to the peer

Parameters

ParameterTypeDefaultDescription
valueUint8Array——

new Advertisement(opts?: AdvertisementOptions)

Parameters

ParameterTypeDefaultDescription
opts?AdvertisementOptions——

localName: string | undefined

Advertisement.serviceData: { [uuid: string]: Uint8Array }

serviceUUIDs: string[]

type: 'broadcast' | 'peripheral'

Agent

authorizeService(devicePath: string, uuid: string): Promise<boolean>

A connection or service request, true accepts

Parameters

ParameterTypeDefaultDescription
devicePathstring——
uuidstring——

cancel(): Promise<void>

The pending request failed before a reply was returned

displayPasskey(devicePath: string, passkey: number, entered: number): Promise<void>

bluetoothd wants the passkey shown, entered counts typed digits

Parameters

ParameterTypeDefaultDescription
devicePathstring——
passkeynumber——
enterednumber——

displayPinCode(devicePath: string, pincode: string): Promise<void>

bluetoothd wants the PIN code shown to the user

Parameters

ParameterTypeDefaultDescription
devicePathstring——
pincodestring——

release(): Promise<void>

bluetoothd unregistered the agent

requestAuthorization(devicePath: string): Promise<boolean>

A pairing that shows nothing to confirm or type, true accepts

Parameters

ParameterTypeDefaultDescription
devicePathstring——

requestConfirmation(devicePath: string, passkey: number): Promise<boolean>

bluetoothd needs the passkey confirmed, true accepts

Parameters

ParameterTypeDefaultDescription
devicePathstring——
passkeynumber——

requestPasskey(devicePath: string): Promise<number>

bluetoothd needs a passkey for an authentication

Parameters

ParameterTypeDefaultDescription
devicePathstring——

requestPinCode(devicePath: string): Promise<string>

bluetoothd needs a PIN code for an authentication

Parameters

ParameterTypeDefaultDescription
devicePathstring——

BluetoothError

new BluetoothError(msg: string, fn?: Function, code?: string)

Parameters

ParameterTypeDefaultDescription
msgstring——
fn?Function——
code?string——

BluetoothError.ADVERTISE_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.AGENT_CANCELED(msg: string): BluetoothError

The agent threw with this code: bluetoothd sees Canceled instead of Rejected

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.CHANNEL_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.CHANNEL_PUBLISH_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.CONNECTION_FAILED(msg: string, id: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——
idstring——

BluetoothError.DISCONNECT(msg: string, id: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——
idstring——

BluetoothError.NOTIFY_STATE_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.READ_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.SCAN_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.SERVICE_ADD_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

BluetoothError.WRITE_FAILED(msg: string): BluetoothError

Parameters

ParameterTypeDefaultDescription
msgstring——

code: string

id: string

Address of the device, on CONNECTION_FAILED and DISCONNECT

name: 'BluetoothError'

GattApplication

new GattApplication(opts?: GattApplicationOptions)

Parameters

ParameterTypeDefaultDescription
opts?GattApplicationOptions——

addService(service: GattService): void

Parameters

ParameterTypeDefaultDescription
serviceGattService——

GattApplication.path: string

services: GattService[]

GattService

new GattService(opts: GattServiceOptions)

Parameters

ParameterTypeDefaultDescription
optsGattServiceOptions——

addCharacteristic(characteristic: GattCharacteristic): void

Parameters

ParameterTypeDefaultDescription
characteristicGattCharacteristic——

characteristics: GattCharacteristic[]

primary: boolean

GattService.uuid: string

GattCharacteristic

new GattCharacteristic(opts: GattCharacteristicOptions)

Parameters

ParameterTypeDefaultDescription
optsGattCharacteristicOptions——

GattCharacteristic.flags: string[]

notifying: boolean

Whether a peer currently has notifications enabled

read: ReadHandler

registered: boolean

Whether the hierarchy holding it is registered with an adapter

GattCharacteristic.uuid: string

value: Uint8Array

Current value; setting it notifies subscribers, throws when not registered

write: WriteHandler

Constants and variables

constants

Types

AdapterOptions

interface AdapterOptions {
  path?: string
}

DiscoveryFilter

interface DiscoveryFilter {
  uuids?: string[]
  rssi?: number
  transport?: 'auto' | 'bredr' | 'le'
}

ChannelOptions

interface ChannelOptions {
  psm?: number
  security?: number
}

AdapterEventMap

interface AdapterEventMap {
  device: [device: Device]
  deviceCached: [device: Device]
  deviceRemoved: [device: Device]
  powered: [powered: boolean]
  discovering: [discovering: boolean]
  advertisementReleased: []
  channelPublish: [psm: number]
  channelOpen: [channel: L2CAPChannel]
  error: [error: BluetoothError]
}

AddressType

type AddressType = 'public' | 'random'

PreferredBearer

type PreferredBearer = 'last-used' | 'bredr' | 'le' | 'last-seen'

DeviceEventMap

interface DeviceEventMap {
  connected: [connected: boolean]
  paired: [paired: boolean]
  servicesResolved: [resolved: boolean]
  rssi: [rssi: number]
  name: [name: string]
  service: [service: Service]
  serviceCached: [service: Service]
  serviceRemoved: [service: Service]
  channelOpen: [channel: L2CAPChannel]
  error: [error: BluetoothError]
}

ServiceEventMap

interface ServiceEventMap {
  characteristic: [characteristic: Characteristic]
  characteristicCached: [characteristic: Characteristic]
  characteristicRemoved: [characteristic: Characteristic]
}

WriteOptions

interface WriteOptions {
  type?: 'request' | 'command'
}

CharacteristicEventMap

interface CharacteristicEventMap {
  data: [value: ArrayBuffer]
  descriptor: [descriptor: Descriptor]
  descriptorCached: [descriptor: Descriptor]
  descriptorRemoved: [descriptor: Descriptor]
}

AdvertisementOptions

interface AdvertisementOptions {
  type?: 'broadcast' | 'peripheral'
  localName?: string
  serviceUUIDs?: string[]
  serviceData?: { [uuid: string]: Uint8Array }
}

AgentCapability

type AgentCapability = 'DisplayOnly' | 'DisplayYesNo' | 'KeyboardOnly' | 'NoInputNoOutput' | 'KeyboardDisplay'

L2CAPChannelEventMap

interface L2CAPChannelEventMap {
  open: []
}

GattApplicationOptions

interface GattApplicationOptions {
  path?: string
}

GattServiceOptions

interface GattServiceOptions {
  uuid: string
  primary?: boolean
}

GattCharacteristicOptions

interface GattCharacteristicOptions {
  uuid: string
  flags?: string[]
  value?: Uint8Array
  read?: ReadHandler
  write?: WriteHandler
}

ReadOptions

interface ReadOptions {
  offset: number
  mtu: number
  device: string
  link: string
}

GattWriteOptions

interface GattWriteOptions {
  offset: number
  type: string
  mtu: number
  device: string
  link: string
  prepareAuthorize: boolean
}

GattCharacteristicEventMap

interface GattCharacteristicEventMap {
  write: [value: Uint8Array, options: GattWriteOptions]
  notifying: [notifying: boolean]
}

Classes

Service

class Service {
  characteristics: Map<string, Characteristic>
  path: string
  primary: boolean
  uuid: string
}

L2CAPChannel

class L2CAPChannel {
  mtu: number
  peer: string | null
  psm: number
}

See also

Last updated on

Was this helpful?

On this page

UsageAPIAdapternew Adapter(opts?: AdapterOptions)address: string | nulldestroy(): voiddevices: Map<string, Device>discovering: booleanAdapter.path: stringpowered: booleanpublishL2CAPChannel(opts?: ChannelOptions): voidregisterAdvertisement(advertisement: Advertisement): Promise<void>registerAgent(agent: Agent, capability?: AgentCapability): Promise<void>registerApplication(application: GattApplication): Promise<void>removeDevice(device: Device): Promise<void>requestDefaultAgent(): Promise<void>setDiscoveryFilter(filter?: DiscoveryFilter): Promise<void>startDiscovery(): Promise<void>stopDiscovery(): Promise<void>unpublishL2CAPChannel(psm: number): voidunregisterAdvertisement(advertisement: Advertisement): Promise<void>unregisterAgent(): Promise<void>unregisterApplication(application: GattApplication): Promise<void>Deviceaddress: stringaddressType: AddressTypeconnect(): Promise<void>connected: booleandisconnect(): Promise<void>manufacturerData: { [id: number]: Uint8Array }name: string | undefinedopenL2CAPChannel(psm: number, opts?: { security?: number }): voidpair(): Promise<void>paired: booleanDevice.path: stringpreferredBearer: PreferredBearer | undefinedrssi: number | undefinedDevice.serviceData: { [uuid: string]: Uint8Array }services: Map<string, Service>servicesResolved: booleanuuids: string[]Characteristicdescriptors: Map<string, Descriptor>Characteristic.flags: string[]mtu: numberCharacteristic.path: stringCharacteristic.read(): Promise<ArrayBuffer>startNotify(): Promise<void>stopNotify(): Promise<void>Characteristic.uuid: stringwrite(value: Uint8Array, opts?: WriteOptions): Promise<void>DescriptorDescriptor.flags: string[]Descriptor.path: stringDescriptor.read(): Promise<ArrayBuffer>Descriptor.uuid: stringwrite(value: Uint8Array): Promise<void>Advertisementnew Advertisement(opts?: AdvertisementOptions)localName: string | undefinedAdvertisement.serviceData: { [uuid: string]: Uint8Array }serviceUUIDs: string[]type: 'broadcast' | 'peripheral'AgentauthorizeService(devicePath: string, uuid: string): Promise<boolean>cancel(): Promise<void>displayPasskey(devicePath: string, passkey: number, entered: number): Promise<void>displayPinCode(devicePath: string, pincode: string): Promise<void>release(): Promise<void>requestAuthorization(devicePath: string): Promise<boolean>requestConfirmation(devicePath: string, passkey: number): Promise<boolean>requestPasskey(devicePath: string): Promise<number>requestPinCode(devicePath: string): Promise<string>BluetoothErrornew BluetoothError(msg: string, fn?: Function, code?: string)BluetoothError.ADVERTISE_FAILED(msg: string): BluetoothErrorBluetoothError.AGENT_CANCELED(msg: string): BluetoothErrorBluetoothError.CHANNEL_FAILED(msg: string): BluetoothErrorBluetoothError.CHANNEL_PUBLISH_FAILED(msg: string): BluetoothErrorBluetoothError.CONNECTION_FAILED(msg: string, id: string): BluetoothErrorBluetoothError.DISCONNECT(msg: string, id: string): BluetoothErrorBluetoothError.NOTIFY_STATE_FAILED(msg: string): BluetoothErrorBluetoothError.READ_FAILED(msg: string): BluetoothErrorBluetoothError.SCAN_FAILED(msg: string): BluetoothErrorBluetoothError.SERVICE_ADD_FAILED(msg: string): BluetoothErrorBluetoothError.WRITE_FAILED(msg: string): BluetoothErrorcode: stringid: stringname: 'BluetoothError'GattApplicationnew GattApplication(opts?: GattApplicationOptions)addService(service: GattService): voidGattApplication.path: stringservices: GattService[]GattServicenew GattService(opts: GattServiceOptions)addCharacteristic(characteristic: GattCharacteristic): voidcharacteristics: GattCharacteristic[]primary: booleanGattService.uuid: stringGattCharacteristicnew GattCharacteristic(opts: GattCharacteristicOptions)GattCharacteristic.flags: string[]notifying: booleanread: ReadHandlerregistered: booleanGattCharacteristic.uuid: stringvalue: Uint8Arraywrite: WriteHandlerConstants and variablesconstantsTypesAdapterOptionsDiscoveryFilterChannelOptionsAdapterEventMapAddressTypePreferredBearerDeviceEventMapServiceEventMapWriteOptionsCharacteristicEventMapAdvertisementOptionsAgentCapabilityL2CAPChannelEventMapGattApplicationOptionsGattServiceOptionsGattCharacteristicOptionsReadOptionsGattWriteOptionsGattCharacteristicEventMapClassesServiceL2CAPChannelSee also