simplejsble 1.2.1-dev100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // Handlers answer questions a native thread asks and waits for, such as a local
3
+ // characteristic read or a Dongl pairing request. The addon passes only the
4
+ // handler's id with each question.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HandlerSlot = void 0;
7
+ exports.answer = answer;
8
+ const handlers = new Map();
9
+ let nextId = 1;
10
+ /** @internal */
11
+ function answer(id, argument, respond) {
12
+ const handler = handlers.get(id);
13
+ // NOTE: An error in a handler is unhandled, as one in a listener is uncaught,
14
+ // and the native side then gets no answer.
15
+ Promise.resolve()
16
+ .then(() => handler?.(argument))
17
+ .then(respond, error => {
18
+ respond?.(undefined);
19
+ throw error;
20
+ });
21
+ }
22
+ /**
23
+ * The handler of one native callback. A new handler reaches the native object
24
+ * through `install`, in call order with the object's other calls; the previous
25
+ * one answers until then.
26
+ * @internal
27
+ */
28
+ class HandlerSlot {
29
+ #current;
30
+ async set(handler, install) {
31
+ if (handler !== null && typeof handler !== 'function')
32
+ throw new TypeError('handler must be a function or null');
33
+ const id = handler === null ? undefined : nextId++;
34
+ if (id !== undefined)
35
+ handlers.set(id, handler);
36
+ const previous = this.#current;
37
+ this.#current = id;
38
+ try {
39
+ await install(id);
40
+ }
41
+ catch (error) {
42
+ if (id !== undefined)
43
+ handlers.delete(id);
44
+ if (this.#current === id)
45
+ this.#current = previous;
46
+ throw error;
47
+ }
48
+ if (previous !== undefined)
49
+ handlers.delete(previous);
50
+ }
51
+ /** Forgets the handler of a native object that is gone. */
52
+ drop() {
53
+ if (this.#current !== undefined)
54
+ handlers.delete(this.#current);
55
+ this.#current = undefined;
56
+ }
57
+ }
58
+ exports.HandlerSlot = HandlerSlot;
@@ -0,0 +1,7 @@
1
+ export { Adapter, type AdapterEvents } from './adapter';
2
+ export { Backend } from './backend';
3
+ export { Config, type DonglConfig, type SimpleBluezConfig, type WinRTConfig } from './config';
4
+ export { SimpleBLEError, type ErrorCode } from './errors';
5
+ export { Logging, type LogEntry, type LogLevel } from './logging';
6
+ export { LocalCharacteristic, LocalPeripheral, LocalService, type LocalCharacteristicEvents, type LocalPeripheralEvents, } from './local';
7
+ export { Peripheral, type BluetoothAddressType, type Characteristic, type CharacteristicCapability, type Descriptor, type PeripheralEvents, type Service, } from './peripheral';
package/dist/index.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Peripheral = exports.LocalService = exports.LocalPeripheral = exports.LocalCharacteristic = exports.Logging = exports.SimpleBLEError = exports.Config = exports.Backend = exports.Adapter = void 0;
4
+ const errors_1 = require("./errors");
5
+ const handlers_1 = require("./handlers");
6
+ const native_1 = require("./native");
7
+ const peripheral_1 = require("./peripheral");
8
+ const registry_1 = require("./registry");
9
+ native_1.native.setup({
10
+ makeError: (code, message, nativeCode) => new errors_1.SimpleBLEError(code, message, nativeCode),
11
+ // `argument` is the event's value, or a peripheral's key when `external` holds the peripheral.
12
+ dispatch: (key, event, argument, external) => {
13
+ // Objects with listeners are kept alive, so a missing object had none.
14
+ const target = (0, registry_1.lookup)(key);
15
+ if (!target)
16
+ return;
17
+ target[registry_1.onNativeEvent]?.(event);
18
+ if (target.listenerCount(event) === 0)
19
+ return;
20
+ if (external !== undefined) {
21
+ const peripheral = (0, registry_1.lookup)(argument) ?? peripheral_1.Peripheral.wrap(native_1.native.peripheralHandle(external));
22
+ target.emit(event, peripheral);
23
+ }
24
+ else if (argument === undefined) {
25
+ target.emit(event);
26
+ }
27
+ else {
28
+ target.emit(event, argument);
29
+ }
30
+ },
31
+ deliver: peripheral_1.deliver,
32
+ answer: handlers_1.answer,
33
+ });
34
+ var adapter_1 = require("./adapter");
35
+ Object.defineProperty(exports, "Adapter", { enumerable: true, get: function () { return adapter_1.Adapter; } });
36
+ var backend_1 = require("./backend");
37
+ Object.defineProperty(exports, "Backend", { enumerable: true, get: function () { return backend_1.Backend; } });
38
+ var config_1 = require("./config");
39
+ Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_1.Config; } });
40
+ var errors_2 = require("./errors");
41
+ Object.defineProperty(exports, "SimpleBLEError", { enumerable: true, get: function () { return errors_2.SimpleBLEError; } });
42
+ var logging_1 = require("./logging");
43
+ Object.defineProperty(exports, "Logging", { enumerable: true, get: function () { return logging_1.Logging; } });
44
+ var local_1 = require("./local");
45
+ Object.defineProperty(exports, "LocalCharacteristic", { enumerable: true, get: function () { return local_1.LocalCharacteristic; } });
46
+ Object.defineProperty(exports, "LocalPeripheral", { enumerable: true, get: function () { return local_1.LocalPeripheral; } });
47
+ Object.defineProperty(exports, "LocalService", { enumerable: true, get: function () { return local_1.LocalService; } });
48
+ var peripheral_2 = require("./peripheral");
49
+ Object.defineProperty(exports, "Peripheral", { enumerable: true, get: function () { return peripheral_2.Peripheral; } });
@@ -0,0 +1,78 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { CharacteristicCapability } from './peripheral';
3
+ export interface LocalPeripheralEvents {
4
+ clientConnected: [address: string];
5
+ clientDisconnected: [address: string];
6
+ }
7
+ /**
8
+ * GATT services this process hosts on an adapter, from
9
+ * Adapter.createLocalPeripheral(). Configure the advertisement and services
10
+ * before start(), and stop() before changing them.
11
+ *
12
+ * Client events carry the client's address, or a platform-specific identifier
13
+ * where the platform hides it. A started local peripheral keeps Node.js
14
+ * running until it stops; while it has listeners it stays alive, even if
15
+ * nothing else references it.
16
+ */
17
+ export declare class LocalPeripheral extends EventEmitter<LocalPeripheralEvents> {
18
+ #private;
19
+ private constructor();
20
+ /** Adds service UUIDs to the advertisement. */
21
+ addAdvertisedService(uuid: string | readonly string[]): void;
22
+ /** Sets the advertised manufacturer data of a company identifier. */
23
+ setAdvertisedManufacturerData(companyId: number, data: Uint8Array): void;
24
+ /** Whether clients can connect, true by default. */
25
+ setConnectable(connectable: boolean): void;
26
+ /**
27
+ * Sets the local name in the advertisement on macOS and Linux, or removes it
28
+ * with null. This changes only the advertisement, not the system's Bluetooth
29
+ * name. Other platforms throw OPERATION_NOT_SUPPORTED.
30
+ */
31
+ setAdvertisementLocalName(name: string | null): void;
32
+ addService(uuid: string): LocalService;
33
+ services(): LocalService[];
34
+ removeAllServices(): void;
35
+ /** Publishes the services and starts advertising. */
36
+ start(): Promise<void>;
37
+ stop(): Promise<void>;
38
+ isStarted(): boolean;
39
+ isAdvertising(): Promise<boolean>;
40
+ removeAllListeners(...args: Parameters<EventEmitter<LocalPeripheralEvents>['removeAllListeners']>): this;
41
+ }
42
+ /** A service of a LocalPeripheral. */
43
+ export declare class LocalService {
44
+ #private;
45
+ private constructor();
46
+ uuid(): string;
47
+ addCharacteristic(uuid: string, capabilities: readonly CharacteristicCapability[]): LocalCharacteristic;
48
+ characteristics(): LocalCharacteristic[];
49
+ }
50
+ export interface LocalCharacteristicEvents {
51
+ /** A client wrote `value`, which value() already returns. */
52
+ write: [value: Buffer];
53
+ /** The first client subscribed. */
54
+ subscribed: [];
55
+ /** The last client unsubscribed. */
56
+ unsubscribed: [];
57
+ }
58
+ /**
59
+ * A characteristic of a LocalService. Reads return value() unless a read
60
+ * handler computes the value. While it has listeners it stays alive, even if
61
+ * nothing else references it.
62
+ */
63
+ export declare class LocalCharacteristic extends EventEmitter<LocalCharacteristicEvents> {
64
+ #private;
65
+ private constructor();
66
+ uuid(): string;
67
+ capabilities(): CharacteristicCapability[];
68
+ /** The stored value, a copy. */
69
+ value(): Buffer;
70
+ /** Stores `value` and publishes it to subscribed clients. */
71
+ setValue(value: Uint8Array): Promise<void>;
72
+ /**
73
+ * Computes the value of each read, or stops doing so with null. The handler
74
+ * can return a promise, and the read waits for it.
75
+ */
76
+ setReadHandler(handler: (() => Uint8Array | Promise<Uint8Array>) | null): Promise<void>;
77
+ removeAllListeners(...args: Parameters<EventEmitter<LocalCharacteristicEvents>['removeAllListeners']>): this;
78
+ }
package/dist/local.js ADDED
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LocalCharacteristic = exports.LocalService = exports.LocalPeripheral = void 0;
4
+ const node_events_1 = require("node:events");
5
+ const handlers_1 = require("./handlers");
6
+ const registry_1 = require("./registry");
7
+ const construct = Symbol('construct');
8
+ const PERIPHERAL_EVENTS = ['clientConnected', 'clientDisconnected'];
9
+ /**
10
+ * GATT services this process hosts on an adapter, from
11
+ * Adapter.createLocalPeripheral(). Configure the advertisement and services
12
+ * before start(), and stop() before changing them.
13
+ *
14
+ * Client events carry the client's address, or a platform-specific identifier
15
+ * where the platform hides it. A started local peripheral keeps Node.js
16
+ * running until it stops; while it has listeners it stays alive, even if
17
+ * nothing else references it.
18
+ */
19
+ class LocalPeripheral extends node_events_1.EventEmitter {
20
+ #handle;
21
+ #rehook;
22
+ constructor(token, handle) {
23
+ if (token !== construct)
24
+ throw new TypeError('Use Adapter.createLocalPeripheral()');
25
+ super();
26
+ this.#handle = handle;
27
+ this.#rehook = (0, registry_1.retainWhileListening)(this, PERIPHERAL_EVENTS);
28
+ handle.subscribe();
29
+ }
30
+ /** @internal */
31
+ static wrap(handle) {
32
+ return (0, registry_1.intern)(handle.key(), () => new LocalPeripheral(construct, handle), () => handle.release());
33
+ }
34
+ /** Adds service UUIDs to the advertisement. */
35
+ addAdvertisedService(uuid) {
36
+ this.#handle.addAdvertisedService(uuid);
37
+ }
38
+ /** Sets the advertised manufacturer data of a company identifier. */
39
+ setAdvertisedManufacturerData(companyId, data) {
40
+ this.#handle.setAdvertisedManufacturerData(companyId, data);
41
+ }
42
+ /** Whether clients can connect, true by default. */
43
+ setConnectable(connectable) {
44
+ this.#handle.setConnectable(connectable);
45
+ }
46
+ /**
47
+ * Sets the local name in the advertisement on macOS and Linux, or removes it
48
+ * with null. This changes only the advertisement, not the system's Bluetooth
49
+ * name. Other platforms throw OPERATION_NOT_SUPPORTED.
50
+ */
51
+ setAdvertisementLocalName(name) {
52
+ this.#handle.setAdvertisementLocalName(name);
53
+ }
54
+ addService(uuid) {
55
+ return LocalService.wrap(this.#handle.addService(uuid));
56
+ }
57
+ services() {
58
+ return this.#handle.services().map(LocalService.wrap);
59
+ }
60
+ removeAllServices() {
61
+ this.#handle.removeAllServices();
62
+ }
63
+ /** Publishes the services and starts advertising. */
64
+ start() {
65
+ return this.#handle.start();
66
+ }
67
+ stop() {
68
+ return this.#handle.stop();
69
+ }
70
+ isStarted() {
71
+ return this.#handle.isStarted();
72
+ }
73
+ isAdvertising() {
74
+ return this.#handle.isAdvertising();
75
+ }
76
+ removeAllListeners(...args) {
77
+ super.removeAllListeners(...args);
78
+ this.#rehook();
79
+ return this;
80
+ }
81
+ /** @internal */
82
+ [registry_1.releaseFrom](adapterKey) {
83
+ if (this.#handle.owner() !== adapterKey)
84
+ return;
85
+ const key = this.#handle.key();
86
+ this.removeAllListeners();
87
+ this.#handle.release();
88
+ (0, registry_1.unregister)(key, this);
89
+ }
90
+ }
91
+ exports.LocalPeripheral = LocalPeripheral;
92
+ /** A service of a LocalPeripheral. */
93
+ class LocalService {
94
+ #handle;
95
+ constructor(token, handle) {
96
+ if (token !== construct)
97
+ throw new TypeError('Use LocalPeripheral.addService()');
98
+ this.#handle = handle;
99
+ }
100
+ /** @internal */
101
+ static wrap(handle) {
102
+ return (0, registry_1.intern)(handle.key(), () => new LocalService(construct, handle), () => handle.release());
103
+ }
104
+ uuid() {
105
+ return this.#handle.uuid();
106
+ }
107
+ addCharacteristic(uuid, capabilities) {
108
+ return LocalCharacteristic.wrap(this.#handle.addCharacteristic(uuid, capabilities));
109
+ }
110
+ characteristics() {
111
+ return this.#handle.characteristics().map(LocalCharacteristic.wrap);
112
+ }
113
+ /** @internal */
114
+ [registry_1.releaseFrom](adapterKey) {
115
+ if (this.#handle.owner() !== adapterKey)
116
+ return;
117
+ const key = this.#handle.key();
118
+ this.#handle.release();
119
+ (0, registry_1.unregister)(key, this);
120
+ }
121
+ }
122
+ exports.LocalService = LocalService;
123
+ const CHARACTERISTIC_EVENTS = ['write', 'subscribed', 'unsubscribed'];
124
+ /**
125
+ * A characteristic of a LocalService. Reads return value() unless a read
126
+ * handler computes the value. While it has listeners it stays alive, even if
127
+ * nothing else references it.
128
+ */
129
+ class LocalCharacteristic extends node_events_1.EventEmitter {
130
+ #handle;
131
+ #rehook;
132
+ #readHandler = new handlers_1.HandlerSlot();
133
+ constructor(token, handle) {
134
+ if (token !== construct)
135
+ throw new TypeError('Use LocalService.addCharacteristic()');
136
+ super();
137
+ this.#handle = handle;
138
+ this.#rehook = (0, registry_1.retainWhileListening)(this, CHARACTERISTIC_EVENTS);
139
+ handle.subscribe();
140
+ }
141
+ /** @internal */
142
+ static wrap(handle) {
143
+ return (0, registry_1.intern)(handle.key(), () => new LocalCharacteristic(construct, handle), () => handle.release());
144
+ }
145
+ uuid() {
146
+ return this.#handle.uuid();
147
+ }
148
+ capabilities() {
149
+ return this.#handle.capabilities();
150
+ }
151
+ /** The stored value, a copy. */
152
+ value() {
153
+ return this.#handle.value();
154
+ }
155
+ /** Stores `value` and publishes it to subscribed clients. */
156
+ async setValue(value) {
157
+ return this.#handle.setValue(value);
158
+ }
159
+ /**
160
+ * Computes the value of each read, or stops doing so with null. The handler
161
+ * can return a promise, and the read waits for it.
162
+ */
163
+ setReadHandler(handler) {
164
+ return this.#readHandler.set(handler, id => this.#handle.setReadHandler(id));
165
+ }
166
+ removeAllListeners(...args) {
167
+ super.removeAllListeners(...args);
168
+ this.#rehook();
169
+ return this;
170
+ }
171
+ /** @internal */
172
+ [registry_1.releaseFrom](adapterKey) {
173
+ if (this.#handle.owner() !== adapterKey)
174
+ return;
175
+ const key = this.#handle.key();
176
+ this.#readHandler.drop();
177
+ this.removeAllListeners();
178
+ this.#handle.release();
179
+ (0, registry_1.unregister)(key, this);
180
+ }
181
+ }
182
+ exports.LocalCharacteristic = LocalCharacteristic;
@@ -0,0 +1,22 @@
1
+ /** SimpleBLE's log levels, from 'none' (off) to the most detailed, 'verbose'. */
2
+ export type LogLevel = 'none' | 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'verbose';
3
+ /** One entry of SimpleBLE's log. */
4
+ export interface LogEntry {
5
+ readonly level: Exclude<LogLevel, 'none'>;
6
+ /** The component that logged it, such as `SimpleBLE` or `SimpleBLE->SimpleBluez`. */
7
+ readonly module: string;
8
+ readonly file: string;
9
+ readonly line: number;
10
+ readonly function: string;
11
+ readonly message: string;
12
+ }
13
+ /**
14
+ * SimpleBLE's log, process-wide. By default, entries up to 'info' go to
15
+ * standard output.
16
+ */
17
+ export declare const Logging: {
18
+ level: LogLevel;
19
+ setCallback(callback: ((entry: LogEntry) => void) | null): void;
20
+ logToStdout(): void;
21
+ logToFile(path?: string): void;
22
+ };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Logging = void 0;
4
+ const native_1 = require("./native");
5
+ /**
6
+ * SimpleBLE's log, process-wide. By default, entries up to 'info' go to
7
+ * standard output.
8
+ */
9
+ exports.Logging = Object.freeze({
10
+ /** The most detailed level that is logged; 'none' turns logging off. */
11
+ get level() {
12
+ return native_1.native.loggingGetLevel();
13
+ },
14
+ set level(level) {
15
+ native_1.native.loggingSetLevel(level);
16
+ },
17
+ /**
18
+ * Delivers each entry to `callback` on the JavaScript thread, in the order
19
+ * they were logged, instead of writing it out. null discards entries.
20
+ */
21
+ setCallback(callback) {
22
+ if (callback === null) {
23
+ native_1.native.loggingSetCallback(null);
24
+ return;
25
+ }
26
+ if (typeof callback !== 'function')
27
+ throw new TypeError('callback must be a function or null');
28
+ native_1.native.loggingSetCallback(entry => callback(Object.freeze(entry)));
29
+ },
30
+ /** Writes entries to standard output, the default. */
31
+ logToStdout() {
32
+ native_1.native.loggingToStdout();
33
+ },
34
+ /** Appends entries to `path`, or to a new timestamped file in the working directory. */
35
+ logToFile(path) {
36
+ native_1.native.loggingToFile(path);
37
+ },
38
+ });
@@ -0,0 +1 @@
1
+ export {};
package/dist/native.js ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.native = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ function load() {
7
+ const target = `${process.platform}-${process.arch}`;
8
+ const path = (0, node_path_1.join)(__dirname, '..', 'prebuilds', target, 'simplejsble.node');
9
+ if (!(0, node_fs_1.existsSync)(path)) {
10
+ throw new Error(`simplejsble has no native addon for ${target}`);
11
+ }
12
+ return require(path);
13
+ }
14
+ /** @internal */
15
+ exports.native = load();
@@ -0,0 +1,77 @@
1
+ import { EventEmitter } from 'node:events';
2
+ export type BluetoothAddressType = 'public' | 'random' | 'unspecified';
3
+ export type CharacteristicCapability = 'read' | 'writeRequest' | 'writeCommand' | 'notify' | 'indicate';
4
+ export interface Descriptor {
5
+ readonly uuid: string;
6
+ }
7
+ export interface Characteristic {
8
+ readonly uuid: string;
9
+ readonly capabilities: readonly CharacteristicCapability[];
10
+ readonly descriptors: readonly Descriptor[];
11
+ }
12
+ export interface Service {
13
+ readonly uuid: string;
14
+ /** Advertised service data. */
15
+ readonly data: Buffer;
16
+ readonly characteristics: readonly Characteristic[];
17
+ }
18
+ export interface PeripheralEvents {
19
+ connected: [];
20
+ disconnected: [];
21
+ }
22
+ /**
23
+ * A remote device. There is one Peripheral object per native peripheral object,
24
+ * so an Adapter's events, scan results and peripheral lists return the same
25
+ * object for the same device.
26
+ *
27
+ * A peripheral with listeners or subscriptions stays alive, even if nothing
28
+ * else references it. An open connection keeps Node.js running until it ends.
29
+ */
30
+ export declare class Peripheral extends EventEmitter<PeripheralEvents> {
31
+ #private;
32
+ private constructor();
33
+ identifier(): string;
34
+ address(): string;
35
+ addressType(): BluetoothAddressType;
36
+ /** The last received signal strength in dBm, if any. */
37
+ rssi(): number | undefined;
38
+ /** The advertised transmit power in dBm, if any. */
39
+ txPower(): number | undefined;
40
+ mtu(): number;
41
+ isConnected(): boolean;
42
+ isConnectable(): boolean;
43
+ isPaired(): Promise<boolean>;
44
+ /** Advertised manufacturer data by company identifier. The buffers are copies. */
45
+ manufacturerData(): Map<number, Buffer>;
46
+ connect(): Promise<void>;
47
+ disconnect(): Promise<void>;
48
+ unpair(): Promise<void>;
49
+ /** The services of a connected peripheral, or the advertised ones before connecting. */
50
+ services(): Service[];
51
+ read(service: string, characteristic: string): Promise<Buffer>;
52
+ writeRequest(service: string, characteristic: string, data: Uint8Array): Promise<void>;
53
+ writeCommand(service: string, characteristic: string, data: Uint8Array): Promise<void>;
54
+ readDescriptor(service: string, characteristic: string, descriptor: string): Promise<Buffer>;
55
+ writeDescriptor(service: string, characteristic: string, descriptor: string, data: Uint8Array): Promise<void>;
56
+ /** Calls `callback` with each notified value until unsubscribe() or a disconnection. */
57
+ notify(service: string, characteristic: string, callback: (value: Buffer) => void): Promise<void>;
58
+ /** Calls `callback` with each indicated value until unsubscribe() or a disconnection. */
59
+ indicate(service: string, characteristic: string, callback: (value: Buffer) => void): Promise<void>;
60
+ unsubscribe(service: string, characteristic: string): Promise<void>;
61
+ /**
62
+ * Answers a Dongl's request for the passkey the peer shows, with six digits,
63
+ * or undefined to reject pairing. Set it before connect(), as pairing can
64
+ * start as soon as the link is up. The handler can return a promise, e.g. of
65
+ * the user's input, and the Dongl waits for it.
66
+ */
67
+ setPasskeyRequestHandler(handler: (() => string | undefined | Promise<string | undefined>) | null): Promise<void>;
68
+ /** Shows a Dongl's six-digit passkey, which the user enters on the peer. Set it before connect(). */
69
+ setPasskeyDisplayHandler(handler: ((passkey: string) => void) | null): Promise<void>;
70
+ /**
71
+ * Answers whether the peer shows the same six-digit number as a Dongl,
72
+ * accepting or rejecting pairing. Set it before connect(). The handler can
73
+ * return a promise.
74
+ */
75
+ setNumericComparisonHandler(handler: ((passkey: string) => boolean | Promise<boolean>) | null): Promise<void>;
76
+ removeAllListeners(...args: Parameters<EventEmitter<PeripheralEvents>['removeAllListeners']>): this;
77
+ }