-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathold_poweredup.js
More file actions
98 lines (76 loc) · 2.19 KB
/
old_poweredup.js
File metadata and controls
98 lines (76 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
(function() {
'use strict';
class PoweredUp {
constructor() {
this._EVENTS = {};
this._PROMISES = {};
this._CHARACTERISTIC = null;
this._QUEUE = [];
this._WORKING = false;
}
connect() {
return new Promise( async function(resolve, reject){
try {
let device = await navigator.bluetooth.requestDevice({
filters: [
{ namePrefix: 'HUB' }
],
optionalServices: [
'00001623-1212-efde-1623-785feabcd123'
]
});
device.addEventListener('gattserverdisconnected', this._disconnect.bind(this));
let server = await device.gatt.connect();
let service = await server.getPrimaryService('00001623-1212-efde-1623-785feabcd123');
this._CHARACTERISTIC = await service.getCharacteristic('00001624-1212-efde-1623-785feabcd123');
this._CHARACTERISTIC.startNotifications();
this._CHARACTERISTIC.addEventListener('characteristicvaluechanged', function(e) {
// received...
}.bind(this));
resolve();
}
catch(error) {
console.log('Could not connect! ' + error);
reject();
}
});
}
drive(left, right) {
this._queue(new Uint8Array([
0x08, 0x00, 0x81, 0x39, 0x11, 0x02, left, right
]));
}
stop() {
this._queue(new Uint8Array([
0x08, 0x00, 0x81, 0x39, 0x11, 0x02, 0x00, 0x00
]));
}
addEventListener(e, f) {
this._EVENTS[e] = f;
}
isConnected() {
return !!this._CHARACTERISTIC;
}
_disconnect() {
console.log('Disconnected from GATT Server...');
this._CHARACTERISTIC = null;
if (this._EVENTS['disconnected']) {
this._EVENTS['disconnected']();
}
}
_queue(message) {
var that = this;
function run() {
if (!that._QUEUE.length) {
that._WORKING = false;
return;
}
that._WORKING = true;
that._CHARACTERISTIC.writeValue(that._QUEUE.shift()).then(() => run() );
}
that._QUEUE.push(message);
if (!that._WORKING) run();
}
}
window.PoweredUp = new PoweredUp();
})();