Skip to content

Commit

Permalink
Support notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
evanxd committed Jun 21, 2015
1 parent dbb0c63 commit 316e228
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
44 changes: 33 additions & 11 deletions lib/bluetooth_device.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global EventEmitter2 */
/* global Bluetooth, EventEmitter2 */
'use strict';

(function(exports) {
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions lib/bluetooth_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -87,6 +88,7 @@
});
if (devcie) {
// XXX: Workaround to connect multiple devices correctly.
devcie.gatt = gatt;
setTimeout(() => {
gatt.connect().then(() => {
this._discoverServices(devcie, gatt);
Expand Down

0 comments on commit 316e228

Please sign in to comment.