-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathble.js
299 lines (231 loc) · 10.3 KB
/
ble.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
NanoPlay Web API
Copyright (C) Subnodal Technologies. All Rights Reserved.
https://nanoplay.subnodal.com
Licenced by the Subnodal Open-Source Licence, which can be found at LICENCE.md.
*/
namespace("com.subnodal.nanoplay.webapi.ble", function(exports) {
const BLE_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
const BLE_RX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
const BLE_TX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
const CHUNK_SIZE = 20;
const DATA_TIMEOUT = 200;
var characteristicValueChangeHandler;
function stringToArrayBuffer(string) {
var buffer = new ArrayBuffer(string.length);
var bufferView = new Uint8Array(buffer);
for (var i = 0; i < string.length; i++) {
bufferView[i] = string.charCodeAt(i);
}
return buffer;
}
function arrayBufferToString(buffer) {
return String.fromCharCode.apply(this, new Uint8Array(buffer));
}
exports.SystemSupportError = class extends Error {};
exports.QueuedData = class {
constructor(data, promiseResolver) {
this.data = data;
this.promiseResolver = promiseResolver;
this.maxLength = this.data.length;
}
};
exports.Connection = class {
constructor() {
if (window.location.protocol != "https:" && window.location.hostname != "localhost" && window.location.hostname != "127.0.0.1") {
throw new exports.SystemSupportError("Web Bluetooth can only be used in HTTPS contexts (or if the page is served as localhost)");
}
if (!exports.Connection.systemSupported()) {
throw new exports.SystemSupportError("This system does not support Web Bluetooth");
}
this.bleDevice = null;
this.bleServer = null;
this.bleService = null;
this.bleRxCharacteristic = null;
this.bleTxCharacteristic = null;
this.bleTxQueue = [];
this.bleFlowXoff = null;
this.isOpen = false;
this.isOpening = false;
this.isBusy = false;
this.txInProgress = false;
this.rxData = "";
}
static systemSupported() {
return !!navigator.bluetooth;
}
connect() {
var thisScope = this;
return navigator.bluetooth.requestDevice({
filters: [
{namePrefix: "NanoPlay "},
{services: [BLE_SERVICE]}
],
optionalServices: [BLE_SERVICE]
}).then(function(device) {
thisScope.bleDevice = device;
device.addEventListener("gattserverdisconnected", function() {
thisScope.disconnect();
});
return device.gatt.connect();
}).then(function(server) {
thisScope.bleServer = server;
return server.getPrimaryService(BLE_SERVICE);
}).then(function(service) {
thisScope.bleService = service;
return service.getCharacteristic(BLE_RX);
}).then(function(characteristic) {
thisScope.bleRxCharacteristic = characteristic;
if (!characteristicValueChangeHandler) {
characteristicValueChangeHandler = function(event) {
var dataView = event.target.value;
for (var i = 0; i < dataView.length; i++) {
var byte = dataView.getUint8(i);
if (byte == 0x11) { // XON
thisScope.bleFlowXoff = false;
} else if (byte == 0x13) { // XOFF
thisScope.bleFlowXoff = true;
}
}
var dataString = arrayBufferToString(dataView.buffer);
thisScope.rxData += dataString;
}
}
thisScope.bleRxCharacteristic.removeEventListener("characteristicvaluechanged", characteristicValueChangeHandler);
thisScope.bleRxCharacteristic.addEventListener("characteristicvaluechanged", characteristicValueChangeHandler);
return characteristic.startNotifications();
}).then(function() {
return thisScope.bleService.getCharacteristic(BLE_TX);
}).then(function(characteristic) {
thisScope.bleTxCharacteristic = characteristic;
}).then(function() {
thisScope.bleTxQueue = [];
thisScope.isOpen = true;
thisScope.isOpening = false;
thisScope.isBusy = false;
thisScope.txInProgress = false;
thisScope.write();
return Promise.resolve();
}).catch(function(error) {
thisScope.disconnect();
return Promise.reject(error);
});
}
disconnect() {
if (this.bleServer != null) {
this.bleServer.disconnect();
}
this.bleDevice = null;
this.bleServer = null;
this.bleRxCharacteristic = null;
this.bleTxCharacteristic = null;
this.isOpen = false;
this.isOpening = false;
}
write(data, progressCallback = function() {}) {
var thisScope = this;
this.rxData = "";
this.isBusy = true;
return new Promise(function(resolve, reject) {
function writeChunk() {
if (thisScope.bleFlowXoff) {
setTimeout(writeChunk, 100);
return;
}
if (thisScope.bleTxQueue.length == 0) {
thisScope.isBusy = false;
return;
}
var chunk = null;
var dataToTx = thisScope.bleTxQueue[0];
progressCallback(dataToTx.maxLength - dataToTx.data.length, dataToTx.maxLength);
if (dataToTx.data.length <= CHUNK_SIZE) {
chunk = dataToTx.data;
dataToTx.data = "";
} else {
chunk = dataToTx.data.substring(0, CHUNK_SIZE);
dataToTx.data = dataToTx.data.substring(CHUNK_SIZE);
}
thisScope.txInProgress = true;
thisScope.bleTxCharacteristic.writeValue(stringToArrayBuffer(chunk)).then(function() {
if (dataToTx.data.length == 0) {
thisScope.bleTxQueue.shift();
dataToTx.promiseResolver();
}
thisScope.txInProgress = false;
writeChunk();
}).catch(function(error) {
thisScope.bleTxQueue = [];
thisScope.disconnect();
reject(error);
thisScope.isBusy = false;
});
}
if (data) {
thisScope.bleTxQueue.push(new exports.QueuedData(data, resolve));
}
if (thisScope.isOpen && !thisScope.txInProgress) {
writeChunk();
}
});
}
communicate(data, progressCallback = function() {}) {
var thisScope = this;
if (!this.isOpen) {
return Promise.reject({type: "connection", message: "Please connect to your NanoPlay first"});
}
return new Promise(function(resolve, reject) {
if (thisScope.isBusy) {
setTimeout(function() {
thisScope.communicate(data, progressCallback).then(resolve);
}, 100);
return;
}
thisScope.write(data, progressCallback).then(function() {
var timeoutStart = new Date().getTime();
var lastData = thisScope.rxData;
setTimeout(function timeout() {
if (thisScope.rxData != lastData) {
timeoutStart = new Date().getTime();
lastData = thisScope.rxData;
setTimeout(timeout, 10);
} else if (new Date().getTime() - timeoutStart < DATA_TIMEOUT) {
setTimeout(timeout, 10);
} else {
resolve(thisScope.rxData);
thisScope.rxData = "";
}
}, 10);
});
});
}
evaluate(expression, progressCallback = function() {}) {
var thisScope = this;
if (!this.isOpen) {
return Promise.reject({type: "connection", message: "Please connect to your NanoPlay first"});
}
thisScope.rxData = "";
return thisScope.communicate(`;print(btoa(JSON.stringify(eval(atob(\`${btoa(expression)}\`)))))\n`, progressCallback).then(function(data) {
try {
var jsonData = "";
if (data.trim().split("\n").length > 1) {
if (data.trim().split("\n")[0] == "") {
data = data.trim().split("\n").slice(1).join("\n");
}
jsonData = atob(data.split("print(btoa(JSON.stringify(eval(atob(")[1].split("\n")[1].trim());
} else {
return Promise.resolve(undefined);
}
if (jsonData == "undefined") {
return Promise.resolve(undefined);
} else {
return Promise.resolve(JSON.parse(jsonData));
}
} catch (e) {
console.warn(`Couldn't decode evaluated result: ${e}\nData: ${data.trim()}`);
return Promise.reject({type: "evaluation", message: "Couldn't decode evaluated result"});
}
});
}
};
});