@stoprocent/bleno 0.7.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 (77) hide show
  1. package/.jshintrc +5 -0
  2. package/LICENSE +20 -0
  3. package/README.md +409 -0
  4. package/binding.gyp +17 -0
  5. package/examples/battery-service/README.md +14 -0
  6. package/examples/battery-service/battery-level-characteristic.js +45 -0
  7. package/examples/battery-service/battery-service.js +16 -0
  8. package/examples/battery-service/main.js +28 -0
  9. package/examples/battery-service/package-lock.json +1314 -0
  10. package/examples/battery-service/package.json +20 -0
  11. package/examples/blink1/README.md +44 -0
  12. package/examples/blink1/blink1-fade-rgb-characteristic.js +42 -0
  13. package/examples/blink1/blink1-rgb-characteristic.js +38 -0
  14. package/examples/blink1/blink1-service.js +19 -0
  15. package/examples/blink1/device-information-service.js +19 -0
  16. package/examples/blink1/hardware-revision-characteristic.js +32 -0
  17. package/examples/blink1/main.js +32 -0
  18. package/examples/blink1/serial-number-characteristic.js +21 -0
  19. package/examples/echo/characteristic.js +45 -0
  20. package/examples/echo/main.js +33 -0
  21. package/examples/pizza/README.md +16 -0
  22. package/examples/pizza/peripheral.js +57 -0
  23. package/examples/pizza/pizza-bake-characteristic.js +40 -0
  24. package/examples/pizza/pizza-crust-characteristic.js +52 -0
  25. package/examples/pizza/pizza-service.js +20 -0
  26. package/examples/pizza/pizza-toppings-characteristic.js +41 -0
  27. package/examples/pizza/pizza.js +58 -0
  28. package/examples/uart/main.js +23 -0
  29. package/index.d.ts +153 -0
  30. package/index.js +1 -0
  31. package/lib/bleno.js +231 -0
  32. package/lib/characteristic.js +91 -0
  33. package/lib/descriptor.js +17 -0
  34. package/lib/hci-socket/acl-stream.js +37 -0
  35. package/lib/hci-socket/bindings.js +219 -0
  36. package/lib/hci-socket/crypto.js +74 -0
  37. package/lib/hci-socket/gap.js +212 -0
  38. package/lib/hci-socket/gatt.js +1028 -0
  39. package/lib/hci-socket/hci-status.json +67 -0
  40. package/lib/hci-socket/hci.js +796 -0
  41. package/lib/hci-socket/mgmt.js +89 -0
  42. package/lib/hci-socket/smp.js +160 -0
  43. package/lib/hci-socket/vs.js +156 -0
  44. package/lib/mac/binding.gyp +39 -0
  45. package/lib/mac/bindings.js +12 -0
  46. package/lib/mac/src/ble_peripheral_manager.h +32 -0
  47. package/lib/mac/src/ble_peripheral_manager.mm +241 -0
  48. package/lib/mac/src/bleno_mac.h +26 -0
  49. package/lib/mac/src/bleno_mac.mm +167 -0
  50. package/lib/mac/src/callbacks.h +76 -0
  51. package/lib/mac/src/callbacks.mm +124 -0
  52. package/lib/mac/src/napi_objc.h +30 -0
  53. package/lib/mac/src/napi_objc.mm +286 -0
  54. package/lib/mac/src/noble_mac.h +34 -0
  55. package/lib/mac/src/noble_mac.mm +260 -0
  56. package/lib/mac/src/objc_cpp.h +27 -0
  57. package/lib/mac/src/objc_cpp.mm +144 -0
  58. package/lib/mac/src/peripheral.h +23 -0
  59. package/lib/primary-service.js +19 -0
  60. package/lib/resolve-bindings.js +19 -0
  61. package/lib/uuid-util.js +7 -0
  62. package/package.json +77 -0
  63. package/prebuilds/android-arm/node.napi.armv7.node +0 -0
  64. package/prebuilds/android-arm64/node.napi.armv8.node +0 -0
  65. package/prebuilds/darwin-x64+arm64/node.napi.node +0 -0
  66. package/prebuilds/linux-arm/node.napi.armv6.node +0 -0
  67. package/prebuilds/linux-arm/node.napi.armv7.node +0 -0
  68. package/prebuilds/linux-arm64/node.napi.armv8.node +0 -0
  69. package/prebuilds/linux-x64/node.napi.glibc.node +0 -0
  70. package/prebuilds/linux-x64/node.napi.musl.node +0 -0
  71. package/prebuilds/win32-ia32/node.napi.node +0 -0
  72. package/prebuilds/win32-x64/node.napi.node +0 -0
  73. package/test/characteristic.test.js +174 -0
  74. package/test/descriptor.test.js +46 -0
  75. package/test/mocha.setup.js +0 -0
  76. package/with-bindings.js +5 -0
  77. package/with-custom-binding.js +6 -0
package/.jshintrc ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "esversion": 6,
3
+ "undef": true,
4
+ "node": true
5
+ }
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2013 Sandeep Mistry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,409 @@
1
+ # bleno
2
+
3
+ [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sandeepmistry/bleno?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4
+
5
+
6
+ A Node.js module for implementing BLE (Bluetooth Low Energy) peripherals.
7
+
8
+ Need a BLE central module? See [noble](https://github.com/abandonware/noble).
9
+
10
+ __Note:__ Starting with version 0.6 bleno is basing on ES6 classes and supports Node.js 14.x and higher only. For older versions of Node.js use bleno 0.5.x.
11
+
12
+ __Note:__ macOS / Mac OS X, Linux, FreeBSD and Windows are currently the only supported OSes.
13
+
14
+ ## Prerequisites
15
+
16
+ ### OS X
17
+
18
+ * install the XCode command line tools via `xcode-select --install`
19
+ * 10.9 or later
20
+
21
+ ### Linux
22
+
23
+ * Kernel version 3.6 or above
24
+ * ```libbluetooth-dev```
25
+ * ```bluetoothd``` disabled, if BlueZ 5.14 or later is installed. Use ```sudo hciconfig hci0 up``` to power Bluetooth adapter up after stopping or disabling ```bluetoothd```.
26
+ * ```System V```:
27
+ * ```sudo service bluetooth stop``` (once)
28
+ * ```sudo update-rc.d bluetooth remove``` (persist on reboot)
29
+ * ```systemd```
30
+ * ```sudo systemctl stop bluetooth``` (once)
31
+ * ```sudo systemctl disable bluetooth``` (persist on reboot)
32
+
33
+ If you're using [noble](https://github.com/sandeepmistry/noble) *and* bleno at the same time, connected BLE devices may not be able to retrieve a list of services from the BLE adaptor. Check out noble's [documentation on bleno compatibility](https://github.com/sandeepmistry/noble#bleno-compatibility)
34
+
35
+ #### Ubuntu/Debian/Raspbian
36
+
37
+ ```sh
38
+ sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev libusb-1.0-0-dev
39
+ ```
40
+
41
+ Make sure ```node``` is on your path, if it's not, some options:
42
+ * symlink ```nodejs``` to ```node```: ```sudo ln -s /usr/bin/nodejs /usr/bin/node```
43
+ * [install Node.js using the NodeSource package](https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions)
44
+
45
+ #### Fedora / Other-RPM based
46
+
47
+ ```sh
48
+ sudo yum install bluez bluez-libs bluez-libs-devel
49
+ ```
50
+
51
+ #### Intel Edison
52
+
53
+ See [Configure Intel Edison for Bluetooth LE (Smart) Development](http://rexstjohn.com/configure-intel-edison-for-bluetooth-le-smart-development/)
54
+
55
+ ### FreeBSD
56
+
57
+ Make sure you have GNU Make:
58
+
59
+ ```sh
60
+ sudo pkg install gmake
61
+ ```
62
+
63
+ Disable automatic loading of the default Bluetooth stack by putting [no-ubt.conf](https://gist.github.com/myfreeweb/44f4f3e791a057bc4f3619a166a03b87) into ```/usr/local/etc/devd/no-ubt.conf``` and restarting devd (```sudo service devd restart```).
64
+
65
+ Unload ```ng_ubt``` kernel module if already loaded:
66
+
67
+ ```sh
68
+ sudo kldunload ng_ubt
69
+ ```
70
+
71
+ Make sure you have read and write permissions on the ```/dev/usb/*``` device that corresponds to your Bluetooth adapter.
72
+
73
+ ### Windows
74
+
75
+ * [node-gyp requirements for Windows](https://github.com/TooTallNate/node-gyp#installation)
76
+ * Python 2.7
77
+ * Visual Studio ([Express](https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx))
78
+ * [node-bluetooth-hci-socket prerequisites](https://github.com/sandeepmistry/node-bluetooth-hci-socket#windows)
79
+ * Compatible Bluetooth 4.0 USB adapter
80
+ * [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/)
81
+
82
+ ## Install
83
+
84
+ ```sh
85
+ npm install bleno@npm:@abandonware/bleno
86
+ ```
87
+
88
+ ## Usage
89
+
90
+ ```javascript
91
+ var bleno = require('bleno');
92
+ ```
93
+
94
+ See [examples folder](https://github.com/sandeepmistry/bleno/blob/master/examples) for code examples.
95
+
96
+ ### Actions
97
+
98
+ #### Advertising
99
+
100
+ ##### Start advertising
101
+
102
+ NOTE: ```bleno.state``` must be ```poweredOn``` before advertising is started. ```bleno.on('stateChange', callback(state));``` can be used register for state change events.
103
+
104
+ ```javascript
105
+ var name = 'name';
106
+ var serviceUuids = ['fffffffffffffffffffffffffffffff0']
107
+
108
+ bleno.startAdvertising(name, serviceUuids[, callback(error)]);
109
+ ```
110
+
111
+ __Note:__: there are limits on the name and service UUID's
112
+
113
+ * name
114
+ * maximum 26 bytes
115
+ * service UUID's
116
+ * 1 128-bit service UUID
117
+ * 1 128-bit service UUID + 2 16-bit service UUID's
118
+ * 7 16-bit service UUID
119
+
120
+
121
+ ##### Start advertising iBeacon
122
+
123
+ ```javascript
124
+ var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';
125
+ var major = 0; // 0x0000 - 0xffff
126
+ var minor = 0; // 0x0000 - 0xffff
127
+ var measuredPower = -59; // -128 - 127
128
+
129
+ bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower[, callback(error)]);
130
+ ```
131
+
132
+ __Notes:__:
133
+ * OS X:
134
+ * in iBeacon mode your peripheral is non-connectable!
135
+
136
+ ##### Start advertising with EIR data (__Linux only__)
137
+
138
+ ```javascript
139
+ var scanData = Buffer.alloc(...); // maximum 31 bytes
140
+ var advertisementData = Buffer.alloc(...); // maximum 31 bytes
141
+
142
+ bleno.startAdvertisingWithEIRData(advertisementData[, scanData, callback(error)]);
143
+ ```
144
+
145
+ * 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.
146
+
147
+ ##### Stop advertising
148
+
149
+ ```javascript
150
+ bleno.stopAdvertising([callback]);
151
+ ```
152
+
153
+ #### Set services
154
+
155
+ Set the primary services available on the peripheral.
156
+
157
+ ```javascript
158
+ var services = [
159
+ ... // see PrimaryService for data type
160
+ ];
161
+
162
+ bleno.setServices(services[, callback(error)]);
163
+ ```
164
+
165
+ #### Disconnect client
166
+
167
+ ```javascript
168
+ bleno.disconnect(); // Linux only
169
+ ```
170
+
171
+ #### Update RSSI
172
+
173
+ ```javascript
174
+ bleno.updateRssi([callback(error, rssi)]); // not available in OS X 10.9
175
+ ```
176
+
177
+ ### Primary Service
178
+
179
+ ```javascript
180
+ var PrimaryService = bleno.PrimaryService;
181
+
182
+ var primaryService = new PrimaryService({
183
+ uuid: 'fffffffffffffffffffffffffffffff0', // or 'fff0' for 16-bit
184
+ characteristics: [
185
+ // see Characteristic for data type
186
+ ]
187
+ });
188
+ ```
189
+
190
+ ### Characteristic
191
+
192
+ ```javascript
193
+ var Characteristic = bleno.Characteristic;
194
+
195
+ var characteristic = new Characteristic({
196
+ uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
197
+ properties: [ ... ], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
198
+ secure: [ ... ], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
199
+ value: null, // optional static value, must be of type Buffer - for read only characteristics
200
+ descriptors: [
201
+ // see Descriptor for data type
202
+ ],
203
+ onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
204
+ onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
205
+ onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
206
+ onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
207
+ onNotify: null, // optional notify sent handler, function() { ...}
208
+ onIndicate: null // optional indicate confirmation received handler, function() { ...}
209
+ });
210
+ ```
211
+
212
+ #### Result codes
213
+
214
+ * Characteristic.RESULT_SUCCESS
215
+ * Characteristic.RESULT_INVALID_OFFSET
216
+ * Characteristic.RESULT_INVALID_ATTRIBUTE_LENGTH
217
+ * Characteristic.RESULT_UNLIKELY_ERROR
218
+
219
+ #### Read requests
220
+
221
+ Can specify read request handler via constructor options or by extending Characteristic and overriding onReadRequest.
222
+
223
+ Parameters to handler are
224
+ * ```offset``` (0x0000 - 0xffff)
225
+ * ```callback```
226
+
227
+
228
+ ```callback``` must be called with result and data (of type ```Buffer```) - can be async.
229
+
230
+ ```javascript
231
+ var result = Characteristic.RESULT_SUCCESS;
232
+ var data = Buffer.alloc( ... );
233
+
234
+ callback(result, data);
235
+ ```
236
+
237
+ #### Write requests
238
+
239
+ Can specify write request handler via constructor options or by extending Characteristic and overriding onWriteRequest.
240
+
241
+ Parameters to handler are
242
+ * ```data``` (Buffer)
243
+ * ```offset``` (0x0000 - 0xffff)
244
+ * ```withoutResponse``` (true | false)
245
+ * ```callback```.
246
+
247
+ ```callback``` must be called with result code - can be async.
248
+
249
+ ```javascript
250
+ var result = Characteristic.RESULT_SUCCESS;
251
+
252
+ callback(result);
253
+ ```
254
+
255
+ #### Notify subscribe
256
+
257
+ Can specify notify subscribe handler via constructor options or by extending Characteristic and overriding onSubscribe.
258
+
259
+ Parameters to handler are
260
+ * ```maxValueSize``` (maximum data size)
261
+ * ```updateValueCallback``` (callback to call when value has changed)
262
+
263
+ #### Notify unsubscribe
264
+
265
+ Can specify notify unsubscribe handler via constructor options or by extending Characteristic and overriding onUnsubscribe.
266
+
267
+ #### Notify value changes
268
+
269
+ Call the ```updateValueCallback``` callback (see Notify subscribe), with an argument of type ```Buffer```
270
+
271
+ Can specify notify sent handler via constructor options or by extending Characteristic and overriding onNotify.
272
+
273
+ ### Descriptor
274
+
275
+ ```javascript
276
+ var Descriptor = bleno.Descriptor;
277
+
278
+ var descriptor = new Descriptor({
279
+ uuid: '2901',
280
+ value: 'value' // static value, must be of type Buffer or string if set
281
+ });
282
+ ```
283
+
284
+ ### Events
285
+
286
+ #### Adapter state change
287
+
288
+ ```javascript
289
+ state = <"unknown" | "resetting" | "unsupported" | "unauthorized" | "poweredOff" | "poweredOn">
290
+
291
+ bleno.on('stateChange', callback(state));
292
+ ```
293
+
294
+ #### Advertisement started
295
+
296
+ ```javascript
297
+ bleno.on('advertisingStart', callback(error));
298
+
299
+ bleno.on('advertisingStartError', callback(error));
300
+ ```
301
+
302
+ #### Advertisement stopped
303
+
304
+ ```javascript
305
+ bleno.on('advertisingStop', callback);
306
+ ```
307
+
308
+ #### Services set
309
+
310
+ ```javascript
311
+ bleno.on('servicesSet', callback(error));
312
+
313
+ bleno.on('servicesSetError', callback(error));
314
+ ```
315
+
316
+ #### Accept
317
+
318
+ ```javascript
319
+ bleno.on('accept', callback(clientAddress)); // not available on OS X 10.9
320
+ ```
321
+
322
+ #### Disconnect
323
+
324
+ ```javascript
325
+ bleno.on('disconnect', callback(clientAddress)); // Linux only
326
+ ```
327
+
328
+ #### RSSI Update
329
+
330
+ ```javascript
331
+ bleno.on('rssiUpdate', callback(rssi)); // not available on OS X 10.9
332
+ ```
333
+
334
+ ### Running on Linux
335
+
336
+ __Note:__ Make sure you've also checked the [Linux Prerequisites](#linux)
337
+
338
+ #### Running without root/sudo
339
+
340
+ Run the following command:
341
+
342
+ ```sh
343
+ sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
344
+ ```
345
+
346
+ This grants the ```node``` binary ```cap_net_raw``` privileges, so it can start/stop BLE advertising.
347
+
348
+ __Note:__ The above command requires ```setcap``` to be installed, it can be installed using the following:
349
+
350
+ * apt: ```sudo apt-get install libcap2-bin```
351
+ * yum: ```su -c \'yum install libcap2-bin\'```
352
+
353
+ #### Multiple Adapters
354
+
355
+ ```hci0``` is used by default to override set the ```BLENO_HCI_DEVICE_ID``` environment variable to the interface number.
356
+
357
+ Example, specify ```hci1```:
358
+
359
+ ```sh
360
+ sudo BLENO_HCI_DEVICE_ID=1 node <your file>.js
361
+ ```
362
+
363
+ #### Set custom device name
364
+
365
+ By default bleno uses the hostname (```require('os').hostname()```) as the value for the device name (0x2a00) characterisic, to match the behaviour of OS X.
366
+
367
+ A custom device name can be specified by setting the ```BLENO_DEVICE_NAME``` environment variable:
368
+
369
+ ```sh
370
+ sudo BLENO_DEVICE_NAME="custom device name" node <your file>.js
371
+ ```
372
+
373
+ or
374
+
375
+ ```js
376
+ process.env['BLENO_DEVICE_NAME'] = 'custom device name';
377
+ ```
378
+
379
+ #### Set Advertising Interval
380
+
381
+ bleno uses a 100 ms advertising interval by default.
382
+
383
+ A custom advertising interval can be specified by setting the ```BLENO_ADVERTISING_INTERVAL``` environment variable with the desired value in milliseconds:
384
+
385
+ ```sh
386
+ sudo BLENO_ADVERTISING_INTERVAL=500 node <your file>.js
387
+ ```
388
+
389
+ Advertising intervals must be between 20 ms to 10 s (10,000 ms).
390
+
391
+ ## Useful tools/links
392
+
393
+ * Tools
394
+ * LightBlue for [iOS](https://itunes.apple.com/us/app/lightblue/id557428110)/[OS X](https://itunes.apple.com/us/app/lightblue/id639944780)
395
+ * [nRF Master Control Panel (BLE)](https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp&hl=en) for Android
396
+ * [hcitool](http://linux.die.net/man/1/hcitool) and ```gatttool``` by [BlueZ](http://www.bluez.org) for Linux
397
+
398
+
399
+ ## License
400
+
401
+ Copyright (C) 2015 Sandeep Mistry <sandeep.mistry@gmail.com>
402
+
403
+ 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:
404
+
405
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
406
+
407
+ 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.
408
+
409
+ [![Analytics](https://ga-beacon.appspot.com/UA-56089547-1/sandeepmistry/bleno?pixel)](https://github.com/igrigorik/ga-beacon)
package/binding.gyp ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ 'variables': {
3
+ 'openssl_fips' : ''
4
+ },
5
+ 'targets': [
6
+ {
7
+ 'target_name': 'bleno',
8
+ 'conditions': [
9
+ ['OS=="mac"', {
10
+ 'dependencies': [
11
+ 'lib/mac/binding.gyp:binding',
12
+ ],
13
+ }],
14
+ ],
15
+ },
16
+ ],
17
+ }
@@ -0,0 +1,14 @@
1
+ # BLE Battery Service
2
+
3
+ This example provides a BLE battery service (0x180F) for your Mac.
4
+
5
+ Install dependencies
6
+
7
+ npm install
8
+
9
+ Run the example
10
+
11
+ node main.js
12
+
13
+
14
+ NOTE: This example no longer works on OSX starting in 10.10 (Yosemite). Apple has apparently blacklisted the battery uuid.
@@ -0,0 +1,45 @@
1
+ const os = require('os');
2
+ const bleno = require('../..');
3
+ const { execSync } = require('child_process');
4
+ const Descriptor = bleno.Descriptor;
5
+ const Characteristic = bleno.Characteristic;
6
+
7
+ class BatteryLevelCharacteristic extends Characteristic {
8
+ constructor () {
9
+ super({
10
+ uuid: '2A19',
11
+ properties: ['read'],
12
+ descriptors: [
13
+ new Descriptor({
14
+ uuid: '2901',
15
+ value: 'Battery level between 0 and 100 percent'
16
+ }),
17
+ new Descriptor({
18
+ uuid: '2904',
19
+ value: Buffer.from([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00]) // maybe 12 0xC unsigned 8 bit
20
+ })
21
+ ]
22
+ });
23
+ }
24
+
25
+ onReadRequest (offset, callback) {
26
+ if (os.platform() === 'darwin') {
27
+ try {
28
+ const { stdout } = execSync('pmset -g batt');
29
+ const data = stdout.toString();
30
+ // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n'
31
+ let percent = data.split('\t')[1].split(';')[0];
32
+ console.log(percent);
33
+ percent = parseInt(percent, 10);
34
+ callback(this.RESULT_SUCCESS, Buffer.from([percent]));
35
+ } catch (error) {
36
+ callback(this.RESULT_UNLIKELY_ERROR);
37
+ }
38
+ } else {
39
+ // return hardcoded value
40
+ callback(this.RESULT_SUCCESS, Buffer.from([98]));
41
+ }
42
+ }
43
+ }
44
+
45
+ module.exports = BatteryLevelCharacteristic;
@@ -0,0 +1,16 @@
1
+ const bleno = require('../..');
2
+ const BlenoPrimaryService = bleno.PrimaryService;
3
+ const BatteryLevelCharacteristic = require('./battery-level-characteristic');
4
+
5
+ class BatteryService extends BlenoPrimaryService {
6
+ constructor () {
7
+ super({
8
+ uuid: '180F',
9
+ characteristics: [
10
+ new BatteryLevelCharacteristic()
11
+ ]
12
+ });
13
+ }
14
+ }
15
+
16
+ module.exports = BatteryService;
@@ -0,0 +1,28 @@
1
+ /*
2
+ NOTE: This example no longer works on OSX starting in 10.10 (Yosemite). Apple has apparently blacklisted the battery uuid.
3
+ */
4
+
5
+ const bleno = require('../..');
6
+ const BatteryService = require('./battery-service');
7
+
8
+ const primaryService = new BatteryService();
9
+
10
+ bleno.on('stateChange', function (state) {
11
+ console.log('on -> stateChange: ' + state);
12
+
13
+ if (state === 'poweredOn') {
14
+ bleno.startAdvertising('Battery', [primaryService.uuid]);
15
+ } else {
16
+ bleno.stopAdvertising();
17
+ }
18
+ });
19
+
20
+ bleno.on('advertisingStart', function (error) {
21
+ console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
22
+
23
+ if (!error) {
24
+ bleno.setServices([primaryService], function (error) {
25
+ console.log('setServices: ' + (error ? 'error ' + error : 'success'));
26
+ });
27
+ }
28
+ });