thegecko / webbluetooth

Node.js implementation of the Web Bluetooth Specification
https://thegecko.github.io/webbluetooth/
MIT License
148 stars 23 forks source link

Node Web Bluetooth

Node.js implementation of the Web Bluetooth Specification

Build Status npm Licence MIT

Prerequisites

Node.js > v10.20.0, which includes npm.

Installation

$ npm install webbluetooth

Getting Started

See the examples or view the API documentation at:

https://thegecko.github.io/webbluetooth/

Usage

The module exports a default navigator.bluetooth instance, the Bluetooth class to allow you to instantiate your own bluetooth instances and the Bluetooth helper methods:

Using the default bluetooth instance

To use existing Web Bluetooth scripts, you can simply use the default bluetooth instance in place of the navigator.bluetooth object:

const bluetooth = require('webbluetooth').bluetooth;

const device = await bluetooth.requestDevice({
    filters:[{ services:[ 'heart_rate' ] }]
});

const server = await device.gatt.connect();
...

The first device matching the filters will be returned.

Creating your own bluetooth instances

You may want to create your own instance of the Bluetooth class. For example, to inject a device chooser function or control the referring device:

const Bluetooth = require('webbluetooth').Bluetooth;

const deviceFound = (device, selectFn) => {
    // If device can be automatically selected, do so by returning true
    if (device.name === 'myName') return true;

    // Otherwise store the selectFn somewhere and execute it later to select this device
};

const bluetooth = new Bluetooth({ deviceFound });

const device = await bluetooth.requestDevice({
    filters:[{ services:[ 'heart_rate' ] }]
});

const server = await device.gatt.connect();
...

Specification

The Web Bluetooth specification can be found here:

https://webbluetoothcg.github.io/web-bluetooth/

Implementation Status

bluetooth

BluetoothDevice

BluetoothRemoteGATTServer

BluetoothRemoteGATTService

BluetoothRemoteGATTCharacteristic

BluetoothRemoteGATTDescriptor

BluetoothUUID

Events

Bluetooth

Bluetooth Device

Bluetooth Service

Bluetooth Characteristic

Other

Development

Cloning

This repository uses a submodule to reference the SimpleBLE library. Clone it as follows:

git clone https://github.com/thegecko/webbluetooth
cd webbluetooth
git submodule update --init

Building

To build the SimpleBLE module, bindings and TypeScriptsource, run:

yarn build:all

Testing

The tests are set up to use a BBC micro:bit in range with the following services available:

Sample code and hex file for the v2 micro:bit can be found in the firmware folder.

To run the tests:

yarn test