@stoprocent/bleno 0.8.6 → 0.9.0

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.
Files changed (39) hide show
  1. package/README.md +197 -30
  2. package/examples/echo/async.js +47 -0
  3. package/examples/echo/characteristic.js +15 -17
  4. package/examples/echo/main.js +19 -1
  5. package/examples/uart/main.js +3 -2
  6. package/examples/with-bindings/main.js +35 -0
  7. package/index.d.ts +166 -121
  8. package/index.js +5 -1
  9. package/lib/bleno.js +108 -17
  10. package/lib/characteristic.js +27 -10
  11. package/lib/hci-socket/acl-stream.js +3 -3
  12. package/lib/hci-socket/bindings.js +36 -29
  13. package/lib/hci-socket/gatt.js +177 -105
  14. package/lib/hci-socket/hci.js +5 -3
  15. package/lib/hci-socket/mgmt.js +1 -1
  16. package/lib/hci-socket/smp.js +5 -4
  17. package/lib/mac/src/ble_peripheral_manager.h +3 -7
  18. package/lib/mac/src/ble_peripheral_manager.mm +101 -171
  19. package/lib/mac/src/bleno_mac.h +0 -1
  20. package/lib/mac/src/bleno_mac.mm +21 -33
  21. package/lib/mac/src/callbacks.h +12 -48
  22. package/lib/mac/src/callbacks.mm +34 -45
  23. package/lib/mac/src/napi_objc.mm +9 -30
  24. package/lib/mac/src/objc_cpp.h +2 -2
  25. package/lib/mac/src/objc_cpp.mm +3 -37
  26. package/lib/resolve-bindings.js +27 -6
  27. package/package.json +7 -9
  28. package/prebuilds/darwin-x64+arm64/@stoprocent+bleno.node +0 -0
  29. package/prebuilds/win32-ia32/@stoprocent+bleno.node +0 -0
  30. package/prebuilds/win32-x64/@stoprocent+bleno.node +0 -0
  31. package/test/characteristic.test.js +158 -11
  32. package/examples/battery-service/README.md +0 -14
  33. package/examples/blink1/README.md +0 -44
  34. package/examples/pizza/README.md +0 -16
  35. package/lib/mac/src/noble_mac.h +0 -34
  36. package/lib/mac/src/noble_mac.mm +0 -267
  37. package/lib/mac/src/peripheral.h +0 -23
  38. package/with-bindings.js +0 -5
  39. package/with-custom-binding.js +0 -6
package/README.md CHANGED
@@ -23,12 +23,18 @@ Need a BLE central module? See [@stoprocent/noble](https://github.com/stoprocent
23
23
  This fork of `bleno` was created to introduce several key improvements and new features:
24
24
 
25
25
  1. **HCI UART Support**: This version enables HCI UART communication through the `@stoprocent/node-bluetooth-hci-socket` dependency, allowing more flexible use of Bluetooth devices across platforms.
26
-
27
- 2. **macOS Native Bindings Fix**: I have fixed the native bindings for macOS, ensuring better compatibility and performance on Apple devices.
28
26
 
29
- 3. **New Features**: A `setAddress` function has been added, allowing users to set the MAC address of the peripheral device. Additionally, I plan to add raw L2CAP channel support, enhancing low-level Bluetooth communication capabilities.
27
+ 2. **Multi-Connection Support**: Added support for multiple concurrent BLE central connections, allowing the peripheral to handle several connected devices simultaneously. This enables scenarios where multiple clients can connect and interact with the peripheral at the same time.
30
28
 
31
- If you appreciate these enhancements and the continued development of this project, please consider supporting my work.
29
+ 3. **macOS Native Bindings Fix**: I have fixed the native bindings for macOS, ensuring better compatibility and performance on Apple devices.
30
+
31
+ 4. **Modern Async API**: Added Promise-based async methods for all major operations, making it easier to use with modern JavaScript/TypeScript applications.
32
+
33
+ 5. **TypeScript Support**: Full TypeScript definitions included for better development experience and type safety.
34
+
35
+ 6. **New Features**: A `setAddress` function has been added, allowing users to set the MAC address of the peripheral device. Additionally, I plan to add raw L2CAP channel support, enhancing low-level Bluetooth communication capabilities.
36
+
37
+ If you appreciate these enhancements and the continued development of this project, please consider supporting my work.
32
38
 
33
39
  [![Buy me a coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/stoprocent)
34
40
 
@@ -41,6 +47,12 @@ npm install @stoprocent/bleno --save
41
47
 
42
48
  ## Usage
43
49
 
50
+ #### TypeScript
51
+ ``` typescript
52
+ import bleno from "@stoprocent/bleno";
53
+ ```
54
+
55
+ #### JavaScript
44
56
  ```javascript
45
57
  const bleno = require('@stoprocent/bleno');
46
58
  ```
@@ -50,11 +62,31 @@ See [examples folder](https://github.com/stoprocent/bleno/blob/master/examples)
50
62
 
51
63
  ## Prerequisites
52
64
 
65
+ ### Import
66
+
67
+ #### Binding will be picked automatically
68
+
69
+ ``` typescript
70
+ import bleno from "@stoprocent/bleno";
71
+ ```
72
+
73
+ #### Binding picked manually
74
+
75
+ ``` typescript
76
+ import { withBindings } from "@stoprocent/bleno";
77
+
78
+ const bleno = withBindings('default');
79
+ const bleno = withBindings('mac');
80
+ const bleno = withBindings('hci', { hciDriver: '...', bindParams: ... });
81
+ ```
82
+
83
+ > For available `hciDriver: DriverType` and `bindParams: BindParams` please refer to [@stoprocent/bluetooth-hci-socket](https://github.com/stoprocent/node-bluetooth-hci-socket/blob/main/index.d.ts) interface.
84
+
53
85
  #### UART (Any OS)
54
86
 
55
87
  Please refer to [https://github.com/stoprocent/node-bluetooth-hci-socket#uartserial-any-os](https://github.com/stoprocent/node-bluetooth-hci-socket#uartserial-any-os)
56
88
 
57
- ##### Example 1 (UART port spcified as enviromental variable)
89
+ ##### Example 1 (UART port specified as environmental variable)
58
90
 
59
91
  ```bash
60
92
  $ export BLUETOOTH_HCI_SOCKET_UART_PORT=/dev/tty...
@@ -67,21 +99,53 @@ __NOTE:__ `BLUETOOTH_HCI_SOCKET_UART_BAUDRATE` defaults to `1000000` so only nee
67
99
  const bleno = require('@stoprocent/bleno');
68
100
  ```
69
101
 
70
- ##### Example 2 (UART port spcified in `bindParams`)
102
+ ##### Example 2 (UART port specified in `bindParams`)
71
103
 
72
- ```bash
73
- $ export BLUETOOTH_HCI_SOCKET_FORCE_UART=1
74
- ```
104
+ ```typescript
105
+ import { withBindings } from "@stoprocent/bleno";
75
106
 
76
- ```javascript
77
- const bleno = require('@stoprocent/bleno/with-custom-binding') ( {
78
- bindParams: {
79
- uart: {
80
- port: '/dev/tty...',
81
- baudRate: 1000000
107
+ const bleno = withBindings('hci', {
108
+ hciDriver: 'uart',
109
+ bindParams: {
110
+ uart: {
111
+ port: '/dev/cu.usbserial-1420'
112
+ }
82
113
  }
83
- }
84
- } );
114
+ });
115
+
116
+ await bleno.waitForPoweredOnAsync(1000); // Timeout of 1s
117
+ await bleno.startAdvertisingAsync('hello', ['d00d', 'b00b']);
118
+ ```
119
+
120
+ ### Multi-Connection Support
121
+
122
+ This fork of bleno supports multiple concurrent BLE central connections, allowing several clients to connect to your peripheral simultaneously.
123
+
124
+ The library automatically restarts advertising after accepting a connection, enabling seamless multi-client connectivity by default. If you want to prevent additional connections, you can explicitly stop advertising in the accept callback:
125
+
126
+ ```typescript
127
+ // Default behavior - allows multiple connections
128
+ bleno.on('accept', async (address, handle) => {
129
+ console.log(`New connection accepted: ${address}, handle: ${handle}`);
130
+ // Advertising automatically continues - no action needed
131
+ });
132
+
133
+ // Optional: Stop additional connections
134
+ bleno.on('accept', async (address, handle) => {
135
+ console.log(`New connection accepted: ${address}, handle: ${handle}`);
136
+ // Explicitly stop advertising if you want to prevent additional connections
137
+ await bleno.stopAdvertisingAsync();
138
+ });
139
+ ```
140
+
141
+ If you stop advertising, you'll need to manually restart it after the last client disconnects to keep the device connectable.
142
+
143
+ ```typescript
144
+ bleno.on('disconnect', async (address, handle) => {
145
+ console.log(`Client disconnected: ${address}, handle: ${handle}`);
146
+ // Only need to restart advertising if you explicitly stopped it
147
+ // await bleno.startAdvertisingAsync('my-device', ['service-uuid']);
148
+ });
85
149
  ```
86
150
 
87
151
  ### OS X
@@ -150,17 +214,29 @@ Make sure you have read and write permissions on the ```/dev/usb/*``` device tha
150
214
  * Compatible Bluetooth 4.0 USB adapter
151
215
  * [WinUSB](https://msdn.microsoft.com/en-ca/library/windows/hardware/ff540196(v=vs.85).aspx) driver setup for Bluetooth 4.0 USB adapter, using [Zadig tool](http://zadig.akeo.ie/)
152
216
 
217
+ ## API Reference
218
+
153
219
  ### Actions
154
220
 
221
+ #### Wait for powered on state
222
+
223
+ ```typescript
224
+ // Promise-based
225
+ await bleno.waitForPoweredOnAsync(timeout: number); // timeout in milliseconds
226
+ ```
227
+
155
228
  #### Set address
156
229
 
157
230
  ```javascript
231
+ // Callback-based
158
232
  bleno.setAddress('00:11:22:33:44:55'); // set adapter's mac address
233
+
234
+ // Promise-based
235
+ await bleno.setAddressAsync('00:11:22:33:44:55');
159
236
  ```
160
- __NOTE:__ Curently this feature is only supported on HCI as it's using vendor specific commands. Source of the commands is based on the [BlueZ bdaddr.c](https://github.com/pauloborges/bluez/blob/master/tools/bdaddr.c).
237
+ __NOTE:__ Currently this feature is only supported on HCI as it's using vendor specific commands. Source of the commands is based on the [BlueZ bdaddr.c](https://github.com/pauloborges/bluez/blob/master/tools/bdaddr.c).
161
238
  __NOTE:__ `bleno.state` must be `poweredOn` before address can be set. `bleno.on('stateChange', callback(state));` can be used to listen for state change events.
162
239
 
163
-
164
240
  #### Advertising
165
241
 
166
242
  ##### Start advertising
@@ -168,10 +244,13 @@ __NOTE:__ `bleno.state` must be `poweredOn` before address can be set. `bleno.on
168
244
  NOTE: ```bleno.state``` must be ```poweredOn``` before advertising is started. ```bleno.on('stateChange', callback(state));``` can be used register for state change events.
169
245
 
170
246
  ```javascript
247
+ // Callback-based
171
248
  var name = 'name';
172
249
  var serviceUuids = ['fffffffffffffffffffffffffffffff0']
173
-
174
250
  bleno.startAdvertising(name, serviceUuids[, callback(error)]);
251
+
252
+ // Promise-based
253
+ await bleno.startAdvertisingAsync(name, serviceUuids);
175
254
  ```
176
255
 
177
256
  __Note:__: there are limits on the name and service UUID's
@@ -187,12 +266,16 @@ bleno.startAdvertising(name, serviceUuids[, callback(error)]);
187
266
  ##### Start advertising iBeacon
188
267
 
189
268
  ```javascript
269
+ // Callback-based
190
270
  var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';
191
271
  var major = 0; // 0x0000 - 0xffff
192
272
  var minor = 0; // 0x0000 - 0xffff
193
273
  var measuredPower = -59; // -128 - 127
194
274
 
195
275
  bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower[, callback(error)]);
276
+
277
+ // Promise-based
278
+ await bleno.startAdvertisingIBeaconAsync(uuid, major, minor, measuredPower);
196
279
  ```
197
280
 
198
281
  __Notes:__:
@@ -202,10 +285,14 @@ bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower[, callback(error
202
285
  ##### Start advertising with EIR data (__Linux only__)
203
286
 
204
287
  ```javascript
288
+ // Callback-based
205
289
  var scanData = Buffer.alloc(...); // maximum 31 bytes
206
290
  var advertisementData = Buffer.alloc(...); // maximum 31 bytes
207
291
 
208
292
  bleno.startAdvertisingWithEIRData(advertisementData[, scanData, callback(error)]);
293
+
294
+ // Promise-based
295
+ await bleno.startAdvertisingWithEIRDataAsync(advertisementData[, scanData]);
209
296
  ```
210
297
 
211
298
  * For EIR format section [Bluetooth Core Specification](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=229737) sections and 8 and 18 for more information the data format.
@@ -213,7 +300,11 @@ bleno.startAdvertisingWithEIRData(advertisementData[, scanData, callback(error)]
213
300
  ##### Stop advertising
214
301
 
215
302
  ```javascript
303
+ // Callback-based
216
304
  bleno.stopAdvertising([callback]);
305
+
306
+ // Promise-based
307
+ await bleno.stopAdvertisingAsync();
217
308
  ```
218
309
 
219
310
  #### Set services
@@ -221,11 +312,15 @@ bleno.stopAdvertising([callback]);
221
312
  Set the primary services available on the peripheral.
222
313
 
223
314
  ```javascript
315
+ // Callback-based
224
316
  var services = [
225
317
  ... // see PrimaryService for data type
226
318
  ];
227
319
 
228
320
  bleno.setServices(services[, callback(error)]);
321
+
322
+ // Promise-based
323
+ await bleno.setServicesAsync(services);
229
324
  ```
230
325
 
231
326
  #### Disconnect client
@@ -237,7 +332,11 @@ bleno.disconnect(); // Linux only
237
332
  #### Update RSSI
238
333
 
239
334
  ```javascript
335
+ // Callback-based
240
336
  bleno.updateRssi([callback(error, rssi)]); // not available in OS X 10.9
337
+
338
+ // Promise-based
339
+ const rssi = await bleno.updateRssiAsync();
241
340
  ```
242
341
 
243
342
  ### Primary Service
@@ -266,13 +365,53 @@ var characteristic = new Characteristic({
266
365
  descriptors: [
267
366
  // see Descriptor for data type
268
367
  ],
269
- onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
270
- onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
271
- onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
272
- onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
273
- onNotify: null, // optional notify sent handler, function() { ...}
274
- onIndicate: null // optional indicate confirmation received handler, function() { ...}
368
+ onReadRequest: null, // optional read request handler, function(handle, offset, callback) { ... }
369
+ onWriteRequest: null, // optional write request handler, function(handle, data, offset, withoutResponse, callback) { ...}
370
+ onSubscribe: null, // optional notify/indicate subscribe handler, function(handle, maxValueSize, updateValueCallback) { ...}
371
+ onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function(handle) { ...}
372
+ onNotify: null, // optional notify sent handler, function(handle) { ...}
373
+ onIndicate: null // optional indicate confirmation received handler, function(handle) { ...}
374
+ });
375
+ ```
376
+
377
+ #### Multi-Connection Support
378
+
379
+ With multi-connection support, each handler now receives a `handle` parameter to identify which client connection is making the request:
380
+
381
+ ```javascript
382
+ // Example of a characteristic with multi-connection support
383
+ var multiConnectionCharacteristic = new Characteristic({
384
+ uuid: 'fff1',
385
+ properties: ['read', 'write', 'notify'],
386
+ onReadRequest: function(handle, offset, callback) {
387
+ console.log('Read request from connection: ' + handle);
388
+ // Process the read request for this specific connection
389
+ callback(Characteristic.RESULT_SUCCESS, Buffer.from('Data for connection ' + handle));
390
+ },
391
+ onWriteRequest: function(handle, data, offset, withoutResponse, callback) {
392
+ console.log('Write request from connection: ' + handle);
393
+ // Process the write request for this specific connection
394
+ console.log('Data received: ' + data.toString());
395
+ callback(Characteristic.RESULT_SUCCESS);
396
+ },
397
+ onSubscribe: function(handle, maxValueSize, updateValueCallback) {
398
+ console.log('Subscribe from connection: ' + handle);
399
+ // Store the callback for this specific connection to use later
400
+ // You might want to store these in a Map keyed by handle
401
+ connectionCallbacks.set(handle, updateValueCallback);
402
+ },
403
+ onUnsubscribe: function(handle) {
404
+ console.log('Unsubscribe from connection: ' + handle);
405
+ // Remove the callback for this connection
406
+ connectionCallbacks.delete(handle);
407
+ }
275
408
  });
409
+
410
+ // Later, to notify a specific connection:
411
+ const callback = connectionCallbacks.get(someConnectionHandle);
412
+ if (callback) {
413
+ callback(Buffer.from('Notification for connection ' + someConnectionHandle));
414
+ }
276
415
  ```
277
416
 
278
417
  #### Result codes
@@ -281,12 +420,14 @@ var characteristic = new Characteristic({
281
420
  * Characteristic.RESULT_INVALID_OFFSET
282
421
  * Characteristic.RESULT_INVALID_ATTRIBUTE_LENGTH
283
422
  * Characteristic.RESULT_UNLIKELY_ERROR
423
+ * Characteristic.RESULT_ATTR_NOT_LONG
284
424
 
285
425
  #### Read requests
286
426
 
287
427
  Can specify read request handler via constructor options or by extending Characteristic and overriding onReadRequest.
288
428
 
289
429
  Parameters to handler are
430
+ * ```handle``` (connection handle)
290
431
  * ```offset``` (0x0000 - 0xffff)
291
432
  * ```callback```
292
433
 
@@ -305,6 +446,7 @@ callback(result, data);
305
446
  Can specify write request handler via constructor options or by extending Characteristic and overriding onWriteRequest.
306
447
 
307
448
  Parameters to handler are
449
+ * ```handle``` (connection handle)
308
450
  * ```data``` (Buffer)
309
451
  * ```offset``` (0x0000 - 0xffff)
310
452
  * ```withoutResponse``` (true | false)
@@ -323,6 +465,7 @@ callback(result);
323
465
  Can specify notify subscribe handler via constructor options or by extending Characteristic and overriding onSubscribe.
324
466
 
325
467
  Parameters to handler are
468
+ * ```handle``` (connection handle)
326
469
  * ```maxValueSize``` (maximum data size)
327
470
  * ```updateValueCallback``` (callback to call when value has changed)
328
471
 
@@ -330,12 +473,18 @@ Parameters to handler are
330
473
 
331
474
  Can specify notify unsubscribe handler via constructor options or by extending Characteristic and overriding onUnsubscribe.
332
475
 
476
+ Parameters to handler are
477
+ * ```handle``` (connection handle)
478
+
333
479
  #### Notify value changes
334
480
 
335
481
  Call the ```updateValueCallback``` callback (see Notify subscribe), with an argument of type ```Buffer```
336
482
 
337
483
  Can specify notify sent handler via constructor options or by extending Characteristic and overriding onNotify.
338
484
 
485
+ Parameters to handler are
486
+ * ```handle``` (connection handle)
487
+
339
488
  ### Descriptor
340
489
 
341
490
  ```javascript
@@ -357,6 +506,24 @@ state = <"unknown" | "resetting" | "unsupported" | "unauthorized" | "poweredOff"
357
506
  bleno.on('stateChange', callback(state));
358
507
  ```
359
508
 
509
+ #### Platform
510
+
511
+ ```javascript
512
+ bleno.on('platform', callback(platform));
513
+ ```
514
+
515
+ #### Address change
516
+
517
+ ```javascript
518
+ bleno.on('addressChange', callback(address));
519
+ ```
520
+
521
+ #### MTU change
522
+
523
+ ```javascript
524
+ bleno.on('mtuChange', callback(mtu));
525
+ ```
526
+
360
527
  #### Advertisement started
361
528
 
362
529
  ```javascript
@@ -382,19 +549,19 @@ bleno.on('servicesSetError', callback(error));
382
549
  #### Accept
383
550
 
384
551
  ```javascript
385
- bleno.on('accept', callback(clientAddress)); // not available on OS X 10.9
552
+ bleno.on('accept', callback(address, handle)); // handle provided for multi-connection support
386
553
  ```
387
554
 
388
555
  #### Disconnect
389
556
 
390
557
  ```javascript
391
- bleno.on('disconnect', callback(clientAddress)); // Linux only
558
+ bleno.on('disconnect', callback(address, handle)); // handle provided for multi-connection support
392
559
  ```
393
560
 
394
561
  #### RSSI Update
395
562
 
396
563
  ```javascript
397
- bleno.on('rssiUpdate', callback(rssi)); // not available on OS X 10.9
564
+ bleno.on('rssiUpdate', callback(rssi));
398
565
  ```
399
566
 
400
567
  ### Running on Linux
@@ -459,4 +626,4 @@ Advertising intervals must be between 20 ms to 10 s (10,000 ms).
459
626
  * Tools
460
627
  * LightBlue for [iOS](https://itunes.apple.com/us/app/lightblue/id557428110)/[OS X](https://itunes.apple.com/us/app/lightblue/id639944780)
461
628
  * [nRF Master Control Panel (BLE)](https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp&hl=en) for Android
462
- * [hcitool](http://linux.die.net/man/1/hcitool) and ```gatttool``` by [BlueZ](http://www.bluez.org) for Linux
629
+ * [hcitool](http://linux.die.net/man/1/hcitool) and ```gatttool``` by [BlueZ](http://www.bluez.org) for Linux
@@ -0,0 +1,47 @@
1
+ const { withBindings } = require('../../');
2
+
3
+ const bleno = withBindings('default');
4
+ // const bleno = withBindings('mac');
5
+ // const bleno = withBindings('hci', { hciDriver: 'uart' });
6
+
7
+ const BlenoPrimaryService = bleno.PrimaryService;
8
+
9
+ const EchoCharacteristic = require('./characteristic');
10
+
11
+ console.log('bleno - echo');
12
+
13
+ async function run () {
14
+ try {
15
+ await bleno.waitForPoweredOnAsync();
16
+ console.log("Powered on");
17
+ await bleno.setAddressAsync('11:22:44:55:99:77');
18
+ console.log("Address set");
19
+ await bleno.startAdvertisingAsync('echo-async', ['ec00']);
20
+ console.log("Advertising started");
21
+ await bleno.setServicesAsync([
22
+ new BlenoPrimaryService ({
23
+ uuid: 'ec00',
24
+ characteristics: [
25
+ new EchoCharacteristic()
26
+ ]
27
+ })
28
+ ]);
29
+ console.log("Services set");
30
+ } catch (error) {
31
+ console.error("Error: ", error);
32
+ }
33
+ }
34
+
35
+ bleno.on('accept', async (address) => {
36
+ console.log("Accepted: ", address);
37
+ // We are not stopping advertising here because we want to allow another central to be able to connect
38
+ // await bleno.stopAdvertisingAsync();
39
+ });
40
+
41
+ bleno.on('disconnect', async (address) => {
42
+ console.log("Disconnected: ", address);
43
+ // We are not starting advertising here because we didnt stop advertising in the accept event
44
+ // await bleno.startAdvertisingAsync('echo-async', ['ec00']);
45
+ });
46
+
47
+ run();
@@ -1,8 +1,6 @@
1
- const bleno = require('../..');
1
+ const { Characteristic } = require('../../');
2
2
 
3
- const BlenoCharacteristic = bleno.Characteristic;
4
-
5
- class EchoCharacteristic extends BlenoCharacteristic {
3
+ class EchoCharacteristic extends Characteristic {
6
4
  constructor () {
7
5
  super({
8
6
  uuid: 'ec0e',
@@ -11,34 +9,34 @@ class EchoCharacteristic extends BlenoCharacteristic {
11
9
  });
12
10
 
13
11
  this._value = Buffer.alloc(0);
14
- this._updateValueCallback = null;
12
+ this._updateValueCallbacks = new Map();
15
13
  }
16
14
 
17
- onReadRequest (offset, callback) {
18
- console.log('EchoCharacteristic - onReadRequest: value = ' + this._value.toString('hex'));
15
+ onReadRequest (connection, offset, callback) {
16
+ console.log('EchoCharacteristic - onReadRequest: handle = ' + connection + ' value = ' + this._value.toString('hex'));
19
17
  callback(this.RESULT_SUCCESS, this._value);
20
18
  }
21
19
 
22
- onWriteRequest (data, offset, withoutResponse, callback) {
20
+ onWriteRequest (connection, data, offset, withoutResponse, callback) {
23
21
  this._value = data;
24
- console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value.toString('hex'));
22
+ console.log('EchoCharacteristic - onWriteRequest: handle = ' + connection + ' value = ' + this._value.toString('hex'));
25
23
 
26
- if (this._updateValueCallback) {
24
+ for (const updateValueCallback of this._updateValueCallbacks.values()) {
27
25
  console.log('EchoCharacteristic - onWriteRequest: notifying');
28
- this._updateValueCallback(this._value);
26
+ updateValueCallback(this._value);
29
27
  }
30
28
 
31
29
  callback(this.RESULT_SUCCESS);
32
30
  }
33
31
 
34
- onSubscribe (maxValueSize, updateValueCallback) {
35
- console.log('EchoCharacteristic - onSubscribe');
36
- this._updateValueCallback = updateValueCallback;
32
+ onSubscribe (connection, maxValueSize, updateValueCallback) {
33
+ console.log('EchoCharacteristic - onSubscribe: handle = ' + connection);
34
+ this._updateValueCallbacks.set(connection, updateValueCallback);
37
35
  }
38
36
 
39
- onUnsubscribe () {
40
- console.log('EchoCharacteristic - onUnsubscribe');
41
- this._updateValueCallback = null;
37
+ onUnsubscribe (connection) {
38
+ console.log('EchoCharacteristic - onUnsubscribe: handle = ' + connection);
39
+ this._updateValueCallbacks.delete(connection);
42
40
  }
43
41
  }
44
42
 
@@ -1,4 +1,8 @@
1
- const bleno = require('../..');
1
+ const { withBindings } = require('../../');
2
+
3
+ const bleno = withBindings('default');
4
+ // const bleno = withBindings('mac');
5
+ // const bleno = withBindings('hci', { hciDriver: 'uart' });
2
6
 
3
7
  const BlenoPrimaryService = bleno.PrimaryService;
4
8
 
@@ -17,6 +21,20 @@ bleno.on('stateChange', function (state) {
17
21
  }
18
22
  });
19
23
 
24
+ bleno.on('accept', function (device, handle) {
25
+ console.log('on -> accept: ' + device + ' ' + handle);
26
+ // If you want to stop advertising after a connection is accepted
27
+ // Another central will not be able to connect until advertising is started again
28
+ bleno.stopAdvertising();
29
+ });
30
+
31
+ bleno.on('disconnect', function (device, handle) {
32
+ console.log('on -> disconnect: ' + device + ' ' + handle);
33
+ // If you want to start advertising again after a disconnection
34
+ // Another central will not be able to connect until advertising is started again
35
+ bleno.startAdvertising('echo', ['ec00']);
36
+ });
37
+
20
38
  bleno.on('advertisingStart', function (error) {
21
39
  console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
22
40
 
@@ -1,7 +1,8 @@
1
- const bleno = require('../../with-custom-binding')({
1
+
2
+ const { withBindings } = require('../../');
3
+ const bleno = withBindings('hci', {
2
4
  bindParams: {
3
5
  uart: {
4
- port: '/dev/tty...', // Specify the path to the UART device
5
6
  baudRate: 1000000
6
7
  }
7
8
  }
@@ -0,0 +1,35 @@
1
+ const { withBindings } = require('../../');
2
+
3
+ const blenoMac = withBindings('mac');
4
+
5
+ const blenoUart = withBindings('hci', { hciDriver: 'uart' });
6
+
7
+ blenoMac.on('stateChange', state => {
8
+ console.log('[MAC] on -> stateChange: ' + state);
9
+
10
+ if (state === 'poweredOn') {
11
+ blenoMac.stopAdvertising();
12
+ blenoMac.startAdvertising('test', ['a2744045-7004-4da9-8ed3-6d2d9a208c0a']);
13
+ } else {
14
+ blenoMac.stopAdvertising();
15
+ }
16
+ });
17
+
18
+ blenoUart.on('stateChange', state => {
19
+ console.log('[UART] on -> stateChange: ' + state);
20
+
21
+ if (state === 'poweredOn') {
22
+ blenoUart.stopAdvertising();
23
+ blenoUart.startAdvertising('test', ['a2744045-7004-4da9-8ed3-6d2d9a208c0a']);
24
+ } else {
25
+ blenoUart.stopAdvertising();
26
+ }
27
+ });
28
+
29
+ blenoMac.on('advertisingStart', error => {
30
+ console.log('[MAC] on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
31
+ });
32
+
33
+ blenoUart.on('advertisingStart', error => {
34
+ console.log('[UART] on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
35
+ });