Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,28 @@

Napi::Value GetAdapters(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();

const size_t count = simpleble_adapter_get_count();

// Respect `SIMPLEBLE_ADAPTER` if it exists.
const char* adapterIndexEnv = std::getenv("SIMPLEBLE_ADAPTER");
if (adapterIndexEnv) {
int adapterIndex = -1;
char* end;
long index = std::strtol(adapterIndexEnv, &end, 10);
if (end != adapterIndexEnv && *end == '\0') {
adapterIndex = static_cast<int>(index);
}
if (adapterIndex < 0 || adapterIndex >= count) {
Napi::RangeError::New(env, "SIMPLEBLE_ADAPTER is out of range")
.ThrowAsJavaScriptException();
return env.Null();
}
Napi::Value adapterInstance = Adapter::constructor.New({Napi::Number::New(env, adapterIndex)});
Napi::Array adapters = Napi::Array::New(env, 1);
adapters.Set(0u, adapterInstance);
return adapters;
}

Napi::Array adapters = Napi::Array::New(env, count);

for (size_t i = 0; i < count; i++) {
Expand Down
123 changes: 75 additions & 48 deletions src/adapters/simpleble-adapter.ts → src/adapter/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,72 @@
/*
* Node Web Bluetooth
* Copyright (c) 2023 Rob Moran
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { EventEmitter } from 'events';
import { Adapter as BluetoothAdapter } from './adapter';
* Node Web Bluetooth
* Copyright (c) 2017-2023 Rob Moran
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { adapters, isEnabled } from './adapters';
import { BluetoothUUID } from '../uuid';
import { BluetoothDeviceImpl } from '../device';
import { BluetoothRemoteGATTCharacteristicImpl } from '../characteristic';
import { BluetoothRemoteGATTServiceImpl } from '../service';
import { BluetoothRemoteGATTDescriptorImpl } from '../descriptor';
import {
isEnabled,
getAdapters,
import type { BluetoothDevice } from '../device';
import type { BluetoothRemoteGATTService } from '../service';
import type { BluetoothRemoteGATTCharacteristic } from '../characteristic';
import type { BluetoothRemoteGATTDescriptor } from '../descriptor';
import type { CustomEventListener } from '../common';
import type {
Adapter,
Peripheral,
Service,
Characteristic
} from './simpleble';

/**
* @hidden
*/
export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
/** @hidden BluetoothAdapter event map. */
export interface BluetoothAdapterEventMap {
enabledchanged: Event;
}

/** @hidden Type-safe BluetoothAdapter events. */
export interface BluetoothAdapter extends EventTarget {
addEventListener<K extends keyof BluetoothAdapterEventMap>(
type: K,
listener: CustomEventListener<BluetoothAdapter, BluetoothAdapterEventMap[K]>,
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: string,
listener: CustomEventListener<BluetoothAdapter, Event>,
options?: boolean | AddEventListenerOptions,
): void;
removeEventListener<K extends keyof BluetoothAdapterEventMap>(
type: K,
listener: CustomEventListener<BluetoothAdapter, BluetoothAdapterEventMap[K]>,
options?: boolean | EventListenerOptions,
): void;
removeEventListener(
type: string,
listener: CustomEventListener<BluetoothAdapter, Event>,
options?: boolean | EventListenerOptions,
): void;
}

/** @hidden Wrapper around SimpleBLE. */
export class BluetoothAdapter extends EventTarget {
private adapter: Adapter;
private peripherals = new Map<string, Peripheral>();
private servicesByPeripheral = new Map<Peripheral, Service[]>();
Expand All @@ -53,7 +77,7 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
private descriptors = new Map<string, string[]>();
private charEvents = new Map<string, (value: DataView) => void>();

private validDevice(device: Partial<BluetoothDeviceImpl>, serviceUUIDs: Array<string>): boolean {
private validDevice(device: Partial<BluetoothDevice>, serviceUUIDs: Array<string>): boolean {
if (serviceUUIDs.length === 0) {
// Match any device
return true;
Expand All @@ -70,7 +94,7 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
return serviceUUIDs.some(serviceUUID => advertisedUUIDs.indexOf(serviceUUID) >= 0);
}

private buildBluetoothDevice(device: Peripheral): Partial<BluetoothDeviceImpl> {
private buildBluetoothDevice(device: Peripheral): Partial<BluetoothDevice> {
const name = device.identifier;
const address = device.address;
const rssi = device.rssi;
Expand Down Expand Up @@ -136,7 +160,7 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
this.servicesByPeripheral.set(peripheral, services);
}

private get state(): boolean {
public get state(): boolean {
const adapterEnabled = isEnabled();
return !!adapterEnabled;
}
Expand All @@ -147,11 +171,12 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {

public async startScan(serviceUUIDs: Array<string>, foundFn: (device: Partial<BluetoothDevice>) => void): Promise<void> {
if (this.state === false) {
throw new Error('adapter not enabled');
// TODO: DOMException("Adapter not enabled", "NotFoundError") was added in Node 17.
throw new Error('Adapter not enabled');
}

if (!this.adapter) {
this.adapter = getAdapters()[0];
this.adapter = adapters[0];
}

this.adapter.setCallbackOnScanFound(peripheral => {
Expand All @@ -168,15 +193,15 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
this.peripherals.clear();
const success = this.adapter.scanStart();
if (!success) {
throw new Error('scan start failed');
throw new Error('Scan start failed');
}
}

public stopScan(_errorFn?: (errorMsg: string) => void): void {
if (this.adapter) {
const success = this.adapter.scanStop();
if (!success) {
throw new Error('scan stop failed');
throw new Error('Scan stop failed');
}
}
}
Expand Down Expand Up @@ -215,7 +240,7 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
}
}

public async discoverServices(id: string, serviceUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTServiceImpl>>> {
public async discoverServices(id: string, serviceUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTService>>> {
const peripheral = this.peripherals.get(id);
if (!peripheral) {
throw new Error('Peripheral not found');
Expand All @@ -234,12 +259,12 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
return discovered;
}

public async discoverIncludedServices(_handle: string, _serviceUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTServiceImpl>>> {
public async discoverIncludedServices(_handle: string, _serviceUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTService>>> {
// Currently not implemented
return [];
}

public async discoverCharacteristics(serviceUuid: string, characteristicUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTCharacteristicImpl>>> {
public async discoverCharacteristics(serviceUuid: string, characteristicUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTCharacteristic>>> {
const peripheral = this.peripheralByService.get(serviceUuid);
const characteristics = this.characteristicsByService.get(serviceUuid);
const discovered = [];
Expand Down Expand Up @@ -288,7 +313,7 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
return discovered;
}

public async discoverDescriptors(charUuid: string, descriptorUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTDescriptorImpl>>> {
public async discoverDescriptors(charUuid: string, descriptorUUIDs?: Array<string>): Promise<Array<Partial<BluetoothRemoteGATTDescriptor>>> {
const descriptors = this.descriptors.get(charUuid);
const discovered = [];

Expand Down Expand Up @@ -360,3 +385,5 @@ export class SimplebleAdapter extends EventEmitter implements BluetoothAdapter {
}
}
}

export const adapter = new BluetoothAdapter();
46 changes: 46 additions & 0 deletions src/adapter/adapters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Node Web Bluetooth
* Copyright (c) 2017-2023 Rob Moran
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import type { Adapter, SimpleBLE } from './simpleble';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const simpleble: SimpleBLE = require('bindings')('simpleble.node');

/** @hidden Array of Node-specific SimpleBLE implementation. */
export const adapters: Adapter[] = simpleble.getAdapters();

/** @hidden Is Bluetooth available? */
export const isEnabled = simpleble.isEnabled;

// Prevent memory leaks.
// Might not be necessary since all bindings do is delete `this`.
function unload() {
if (adapters) {
for (const adapter of adapters) {
adapter.release();
}
}
}
process.on('exit', unload);
process.on('SIGINT', unload);
69 changes: 34 additions & 35 deletions src/adapters/simpleble.ts → src/adapter/simpleble.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,39 @@
/*
* Node Web Bluetooth
* Copyright (c) 2022 Rob Moran
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
* Node Web Bluetooth
* Copyright (c) 2017-2023 Rob Moran
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

// eslint-disable-next-line @typescript-eslint/no-var-requires
const simpleble = require('bindings')('simpleble.node');
module.exports = simpleble;

/** SimpleBLE address type. */
/** @hidden SimpleBLE address type. */
export enum AddressType {
PUBLIC = 0,
RANDOM = 1,
UNSPECIFIED = 2,
}

/** SimpleBLE descriptor. */
/** @hidden SimpleBLE descriptor. */
export type Descriptor = string;

/** SimpleBLE characteristic. */
/** @hidden SimpleBLE characteristic. */
export interface Characteristic {
canRead: boolean;
canWriteRequest: boolean;
Expand All @@ -48,14 +44,14 @@ export interface Characteristic {
uuid: string;
}

/** SimpleBLE Service. */
/** @hidden SimpleBLE Service. */
export interface Service {
uuid: string;
data: Uint8Array;
characteristics: Characteristic[];
}

/** SimpleBLE Peripheral. */
/** @hidden SimpleBLE Peripheral. */
export interface Peripheral {
identifier: string;
address: string;
Expand Down Expand Up @@ -84,7 +80,7 @@ export interface Peripheral {
setCallbackOnDisconnected(cb: () => void): boolean;
}

/** SimpleBLE Adapter. */
/** @hidden SimpleBLE Adapter. */
export interface Adapter {
identifier: string;
address: string;
Expand All @@ -101,5 +97,8 @@ export interface Adapter {
release(): void;
}

export declare function getAdapters(): Adapter[];
export declare function isEnabled(): boolean;
/** @hidden SimpleBLE module. */
export interface SimpleBLE {
getAdapters(): Adapter[];
isEnabled(): boolean;
}
Loading