From 316e228a4216affd03fbc98f9bf5b6c1fb569416 Mon Sep 17 00:00:00 2001 From: Evan Xd Date: Sun, 21 Jun 2015 11:39:09 +0800 Subject: [PATCH] Support notifications --- lib/bluetooth_device.js | 44 ++++++++++++++++++++++++++++++----------- lib/bluetooth_helper.js | 2 ++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/lib/bluetooth_device.js b/lib/bluetooth_device.js index 7992fba..cee67d2 100644 --- a/lib/bluetooth_device.js +++ b/lib/bluetooth_device.js @@ -1,4 +1,4 @@ -/* global EventEmitter2 */ +/* global Bluetooth, EventEmitter2 */ 'use strict'; (function(exports) { @@ -9,22 +9,44 @@ BluetoothDevice.prototype = Object.create(EventEmitter2.prototype); - ['writeCharacteristic', 'notifyCharacteristic'].forEach(function(item) { - Object.defineProperty(BluetoothDevice.prototype, item, { - set: function(value) { - this['_' + item] = value; - }, - get: function() { - return this['_' + item]; - } - }); - }); + BluetoothDevice.prototype.gatt = null; + BluetoothDevice.prototype.writeCharacteristic = null; + BluetoothDevice.prototype.notifyCharacteristic = null; + BluetoothDevice.prototype._isNotificationsStarted = false; BluetoothDevice.prototype.send = function(data) { data = this._parseHexString(data); this.writeCharacteristic.writeValue(data); }; + BluetoothDevice.prototype.startNotifications = function() { + if (this._isNotificationsStarted) { + return; + } else { + this._isNotificationsStarted = true; + } + var characteristic = this.notifyCharacteristic; + this.gatt.addEventListener('characteristicchanged', (evt) => { + this.emit('data', evt.characteristic.value); + }); + characteristic.startNotifications(); + var descriptor = characteristic.descriptors.find(function(descriptor) { + return descriptor.uuid === Bluetooth.CCCD_UUID; + }); + if (descriptor) { + var arrayBuffer = new ArrayBuffer(2); + var uint8Array = new Uint8Array(arrayBuffer); + uint8Array[0] = 0x01; + uint8Array[1] = 0x00; + descriptor.writeValue(arrayBuffer); + } + }; + + BluetoothDevice.prototype.stopNotifications = function() { + this._isNotificationsStarted = false; + this.notifyCharacteristic.stopNotifications(); + }; + BluetoothDevice.prototype._parseHexString = function(str) { var arrayBuffer = new ArrayBuffer(Math.ceil(str.length / 2)); var uint8Array = new Uint8Array(arrayBuffer); diff --git a/lib/bluetooth_helper.js b/lib/bluetooth_helper.js index b271105..2a302b8 100644 --- a/lib/bluetooth_helper.js +++ b/lib/bluetooth_helper.js @@ -14,6 +14,7 @@ // The timeout to connect next device. It's used for workaround. BluetoothHelper.CONNECTING_TIMEOUT = 1000; + BluetoothHelper.prototype.CCCD_UUID = '00002902-0000-1000-8000-00805f9b34fb'; BluetoothHelper.prototype._scan = null; BluetoothHelper.prototype._devices = null, @@ -87,6 +88,7 @@ }); if (devcie) { // XXX: Workaround to connect multiple devices correctly. + devcie.gatt = gatt; setTimeout(() => { gatt.connect().then(() => { this._discoverServices(devcie, gatt);