|
1 |
| -/* global EventEmitter2 */ |
| 1 | +/* global Bluetooth, EventEmitter2 */ |
2 | 2 | 'use strict';
|
3 | 3 |
|
4 | 4 | (function(exports) {
|
|
9 | 9 |
|
10 | 10 | BluetoothDevice.prototype = Object.create(EventEmitter2.prototype);
|
11 | 11 |
|
12 |
| - ['writeCharacteristic', 'notifyCharacteristic'].forEach(function(item) { |
13 |
| - Object.defineProperty(BluetoothDevice.prototype, item, { |
14 |
| - set: function(value) { |
15 |
| - this['_' + item] = value; |
16 |
| - }, |
17 |
| - get: function() { |
18 |
| - return this['_' + item]; |
19 |
| - } |
20 |
| - }); |
21 |
| - }); |
| 12 | + BluetoothDevice.prototype.gatt = null; |
| 13 | + BluetoothDevice.prototype.writeCharacteristic = null; |
| 14 | + BluetoothDevice.prototype.notifyCharacteristic = null; |
| 15 | + BluetoothDevice.prototype._isNotificationsStarted = false; |
22 | 16 |
|
23 | 17 | BluetoothDevice.prototype.send = function(data) {
|
24 | 18 | data = this._parseHexString(data);
|
25 | 19 | this.writeCharacteristic.writeValue(data);
|
26 | 20 | };
|
27 | 21 |
|
| 22 | + BluetoothDevice.prototype.startNotifications = function() { |
| 23 | + if (this._isNotificationsStarted) { |
| 24 | + return; |
| 25 | + } else { |
| 26 | + this._isNotificationsStarted = true; |
| 27 | + } |
| 28 | + var characteristic = this.notifyCharacteristic; |
| 29 | + this.gatt.addEventListener('characteristicchanged', (evt) => { |
| 30 | + this.emit('data', evt.characteristic.value); |
| 31 | + }); |
| 32 | + characteristic.startNotifications(); |
| 33 | + var descriptor = characteristic.descriptors.find(function(descriptor) { |
| 34 | + return descriptor.uuid === Bluetooth.CCCD_UUID; |
| 35 | + }); |
| 36 | + if (descriptor) { |
| 37 | + var arrayBuffer = new ArrayBuffer(2); |
| 38 | + var uint8Array = new Uint8Array(arrayBuffer); |
| 39 | + uint8Array[0] = 0x01; |
| 40 | + uint8Array[1] = 0x00; |
| 41 | + descriptor.writeValue(arrayBuffer); |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + BluetoothDevice.prototype.stopNotifications = function() { |
| 46 | + this._isNotificationsStarted = false; |
| 47 | + this.notifyCharacteristic.stopNotifications(); |
| 48 | + }; |
| 49 | + |
28 | 50 | BluetoothDevice.prototype._parseHexString = function(str) {
|
29 | 51 | var arrayBuffer = new ArrayBuffer(Math.ceil(str.length / 2));
|
30 | 52 | var uint8Array = new Uint8Array(arrayBuffer);
|
|
0 commit comments