forked from scratchfoundation/scratch-link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground.html
703 lines (619 loc) · 26.9 KB
/
playground.html
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
<!DOCTYPE html>
<html>
<head>
<title>Scratch Link Test Client Fun Stuff Yay</title>
<style>
button, input {
margin: 0.125rem auto;
}
</style>
</head>
<body>
<div><label for="log">Log</label></div>
<textarea id="log" title="log" readonly style="width: 40rem; height: 10rem;"></textarea>
<div>
<input id="follow" type="checkbox" title="Follow" checked>
<label for="follow">Follow</label>
</div>
<fieldset>
<legend>BLE</legend>
<div>
<button id="initBLE">Connect to app</button>
<button id="getVersionBLE">Get Version</button>
<button id="pingBLE">Request ping</button>
</div>
<div>
<button id="discoverBLE">Discover peripherals</button>
<button id="connectBLE">Connect to discovered peripheral</button>
<button id="getServicesBLE">Get services of connected peripheral</button>
</div>
<fieldset>
<legend>Optional Services</legend>
<textarea id="optionalServicesBLE" placeholder="Optional services, if any, separated by whitespace" style="width:20rem;height:3rem;"></textarea>
</fieldset>
<div id="filtersBLE">
<button id="addFilterBLE">Add a filter</button>
Discovery filters:
</div>
<fieldset>
<legend>micro:bit</legend>
<button id="setServiceMicroBit">Set service ID</button>
<button id="readMicroBit">Read and monitor data</button>
<button id="writeMicroBit">Change the LEDs</button>
</fieldset>
<fieldset>
<legend>WeDo 2.0</legend>
<button id="setServiceWeDo2">Set service ID</button>
</fieldset>
<fieldset>
<legend>GDX-FOR</legend>
<button id="setGDXFOR">Set discovery parameters</button>
</fieldset>
</fieldset>
<fieldset>
<legend>BT / EV3</legend>
<div>
<button id="initBT">Connect to app (BT)</button>
<button id="getVersionBT">Get Version</button>
<button id="discoverBT">Find BT devices</button>
<button id="closeBT">Goodbye</button>
</div>
<div>
<input id="peripheralId" value="0016533d0504" type="text" placeholder="Peripheral id">
<button id="connectBT">Make friends</button>
</div>
<div>
<input id="messageBody" style="width:20em;" value="DQAAAAAEAJkdAAAAAgFg" type="text" placeholder="data">
<button id="send">Converse!</button>
<button id="beep">Yell</button>
</div>
</fieldset>
<script>
class JSONRPC {
constructor() {
this._requestID = 0;
this._openRequests = {};
}
/**
* Make an RPC Request and retrieve the result.
* @param {string} method - the remote method to call
* @param {object} params - the parameters to pass to the remote method
* @returns {Promise} - a promise for the result of the call
*/
sendRemoteRequest(method, params) {
const requestID = this._requestID++;
const promise = new Promise((resolve, reject) => {
this._openRequests[requestID] = { resolve, reject };
});
this._sendRequest(method, params, requestID);
return promise;
}
/**
* Make an RPC Notification with no expectation of a result or callback.
* @param {string} method - the remote method to call
* @param {object} params - the parameters to pass to the remote method
*/
sendRemoteNotification(method, params) {
this._sendRequest(method, params);
}
/**
* Handle an RPC request from remote.
* @param {string} method - the method requested by the remote caller
* @param {object} params - the parameters sent with the remote caller's request
* @returns a result or Promise for result, if appropriate.
*/
didReceiveCall(method, params) {
throw new Error("Must override didReceiveCall");
}
/**
* Send a JSON-style message object over the transport.
* @param {object} jsonMessageObject - the message to send
* @private
*/
_sendMessage(jsonMessageObject) {
throw new Error("Must override _sendMessage");
}
_sendRequest(method, params, id) {
const request = {
jsonrpc: "2.0",
method,
params
};
if (id != null) {
request.id = id;
}
this._sendMessage(request);
}
_handleMessage(json) {
if (json.jsonrpc !== '2.0') {
throw new Error(`Bad or missing JSON-RPC version in message: ${stringify(json)}`);
}
if (json.hasOwnProperty('method')) {
this._handleRequest(json);
} else {
this._handleResponse(json);
}
}
_sendResponse(id, result, error) {
const response = {
jsonrpc: '2.0',
id
};
if (error != null) {
response.error = error;
} else {
response.result = result || null;
}
this._sendMessage(response);
}
_handleResponse(json) {
const { result, error, id } = json;
const openRequest = this._openRequests[id];
delete this._openRequests[id];
if (error) {
openRequest.reject(error);
} else {
openRequest.resolve(result);
}
}
_handleRequest(json) {
const { method, params, id } = json;
const rawResult = this.didReceiveCall(method, params);
if (id != null) {
Promise.resolve(rawResult).then(
result => {
this._sendResponse(id, result);
},
error => {
this._sendResponse(id, null, error);
}
);
}
}
}
class JSONRPCWebSocket extends JSONRPC {
constructor(webSocket) {
super();
this._ws = webSocket;
this._ws.onmessage = e => this._onSocketMessage(e);
this._ws.onopen = e => this._onSocketOpen(e);
this._ws.onclose = e => this._onSocketClose(e);
this._ws.onerror = e => this._onSocketError(e);
}
dispose() {
this._ws.close();
this._ws = null;
}
_onSocketOpen(e) {
addLine(`WS opened: ${stringify(e)}`);
}
_onSocketClose(e) {
addLine(`WS closed: ${stringify(e)}`);
}
_onSocketError(e) {
addLine(`WS error: ${stringify(e)}`);
}
_onSocketMessage(e) {
addLine(`Received message: ${e.data}`);
const json = JSON.parse(e.data);
this._handleMessage(json);
}
_sendMessage(message) {
const messageText = JSON.stringify(message);
addLine(`Sending message: ${messageText}`);
this._ws.send(messageText);
}
}
class ScratchBLE extends JSONRPCWebSocket {
constructor() {
super(new WebSocket('wss://device-manager.scratch.mit.edu:20110/scratch/ble'));
this.discoveredPeripheralId = null;
}
requestDevice(options) {
return this.sendRemoteRequest('discover', options);
}
didReceiveCall(method, params) {
switch (method) {
case 'didDiscoverPeripheral':
addLine(`Peripheral discovered: ${stringify(params)}`);
this.discoveredPeripheralId = params['peripheralId'];
break;
case 'ping':
return 42;
}
}
read(serviceId, characteristicId, optStartNotifications = false) {
const params = {
serviceId,
characteristicId
};
if (optStartNotifications) {
params.startNotifications = true;
}
return this.sendRemoteRequest('read', params);
}
write(serviceId, characteristicId, message, encoding = null, withResponse = null) {
const params = { serviceId, characteristicId, message };
if (encoding) {
params.encoding = encoding;
}
if (withResponse !== null) {
params.withResponse = withResponse;
}
return this.sendRemoteRequest('write', params);
}
}
class ScratchBT extends JSONRPCWebSocket {
constructor() {
super(new WebSocket('wss://device-manager.scratch.mit.edu:20110/scratch/bt'));
}
requestDevice(options) {
return this.sendRemoteRequest('discover', options);
}
connectDevice(options) {
return this.sendRemoteRequest('connect', options);
}
sendMessage(options) {
return this.sendRemoteRequest('send', options);
}
didReceiveCall(method, params) {
switch (method) {
case 'didDiscoverPeripheral':
addLine(`Peripheral discovered: ${stringify(params)}`);
break;
case 'didReceiveMessage':
addLine(`Message received from peripheral: ${stringify(params)}`);
break;
default:
return 'nah';
}
}
}
self.Scratch = self.Scratch || {};
function attachFunctionToButton(buttonId, func) {
const button = document.getElementById(buttonId);
button.onclick = () => {
try {
func();
} catch (e) {
addLine(`Button ${buttonId} caught exception: ${stringify(e)})`);
}
}
}
function getVersion(session) {
session.sendRemoteRequest('getVersion').then(
x => {
addLine(`Version request resolved with: ${stringify(x)}`);
},
e => {
addLine(`Version request rejected with: ${stringify(e)}`);
}
);
}
function initBLE() {
addLine('Connecting...');
self.Scratch.BLE = new ScratchBLE();
addLine('Connected.');
}
function pingBLE() {
Scratch.BLE.sendRemoteRequest('pingMe').then(
x => {
addLine(`Ping request resolved with: ${stringify(x)}`);
},
e => {
addLine(`Ping request rejected with: ${stringify(e)}`);
}
);
}
const filterInputsBLE = [];
function addFilterBLE() {
const filter = {};
filterInputsBLE.push(filter);
const fieldset = document.createElement('fieldset');
const legend = document.createElement('legend');
legend.appendChild(document.createTextNode('Filter ' + filterInputsBLE.length));
fieldset.appendChild(legend);
const exactNameDiv = document.createElement('div');
exactNameDiv.appendChild(document.createTextNode('Discover peripherals with exact name: '));
const exactNameInput = document.createElement('input');
exactNameInput.type = 'text';
exactNameInput.placeholder = 'Name';
exactNameDiv.appendChild(exactNameInput);
fieldset.appendChild(exactNameDiv);
const namePrefixDiv = document.createElement('div');
namePrefixDiv.appendChild(document.createTextNode('Discover peripherals with name prefix: '));
const namePrefixInput = document.createElement('input');
namePrefixInput.type = 'text';
namePrefixInput.placeholder = 'Name Prefix';
namePrefixDiv.appendChild(namePrefixInput);
fieldset.appendChild(namePrefixDiv);
const servicesDiv = document.createElement('div');
servicesDiv.appendChild(document.createTextNode('Discover peripherals with these services:'));
servicesDiv.appendChild(document.createElement('br'));
const servicesInput = document.createElement('textarea');
servicesInput.placeholder = 'Required services, if any, separated by whitespace';
servicesInput.style = 'width:20rem;height:3rem;';
servicesDiv.appendChild(servicesInput);
fieldset.appendChild(servicesDiv);
const manufacturerDataDiv = document.createElement('div');
manufacturerDataDiv.appendChild(document.createTextNode('Discover peripherals with this manufacturer data:'));
manufacturerDataDiv.appendChild(document.createElement('br'));
const addManufacturerDataFilterButton = document.createElement('button');
addManufacturerDataFilterButton.appendChild(document.createTextNode('Add data filter'));
const manufacturerDataFilterInputs = [];
addManufacturerDataFilterButton.onclick = () => {
const manufacturerDataFilter = {};
manufacturerDataFilterInputs.push(manufacturerDataFilter);
const manufacturerDataFilterFields = document.createElement('fieldset');
const manufacturerDataFilterLegend = document.createElement('legend');
manufacturerDataFilterLegend.appendChild(document.createTextNode('Manufacturer Data Filter ' + manufacturerDataFilterInputs.length));
manufacturerDataFilterFields.appendChild(manufacturerDataFilterLegend);
const manufacturerIdDiv = document.createElement('div');
manufacturerIdDiv.appendChild(document.createTextNode('Manufacturer ID: '));
const manufacturerIdInput = document.createElement('input');
manufacturerIdInput.type = 'number';
manufacturerIdInput.placeholder = '65535';
manufacturerIdDiv.appendChild(manufacturerIdInput);
manufacturerDataFilterFields.appendChild(manufacturerIdDiv);
const manufacturerDataPrefixDiv = document.createElement('div');
manufacturerDataPrefixDiv.appendChild(document.createTextNode('Data Prefix: '));
manufacturerDataPrefixInput = document.createElement('input');
manufacturerDataPrefixInput.type = 'text';
manufacturerDataPrefixInput.placeholder = '1 2 3';
manufacturerDataPrefixDiv.appendChild(manufacturerDataPrefixInput);
manufacturerDataFilterFields.appendChild(manufacturerDataPrefixDiv);
const manufacturerDataMaskDiv = document.createElement('div');
manufacturerDataMaskDiv.appendChild(document.createTextNode('Mask: '));
manufacturerDataMaskInput = document.createElement('input');
manufacturerDataMaskInput.type = 'text';
manufacturerDataMaskInput.placeholder = '255 15 255';
manufacturerDataMaskDiv.appendChild(manufacturerDataMaskInput);
manufacturerDataFilterFields.appendChild(manufacturerDataMaskDiv);
manufacturerDataFilter.idInput = manufacturerIdInput;
manufacturerDataFilter.prefixInput = manufacturerDataPrefixInput;
manufacturerDataFilter.maskInput = manufacturerDataMaskInput;
manufacturerDataDiv.appendChild(manufacturerDataFilterFields);
};
manufacturerDataDiv.appendChild(addManufacturerDataFilterButton);
fieldset.appendChild(manufacturerDataDiv);
filter.exactNameInput = exactNameInput;
filter.namePrefixInput = namePrefixInput;
filter.servicesInput = servicesInput;
filter.manufacturerDataFilterInputs = manufacturerDataFilterInputs;
const filtersParent = document.getElementById('filtersBLE');
filtersParent.appendChild(fieldset);
}
function discoverBLE() {
const filters = [];
for (const filterInputs of filterInputsBLE) {
const filter = {};
if (filterInputs.exactNameInput.value) filter.name = filterInputs.exactNameInput.value;
if (filterInputs.namePrefixInput.value) filter.namePrefix = filterInputs.namePrefixInput.value;
if (filterInputs.servicesInput.value.trim()) filter.services = filterInputs.servicesInput.value.trim().split(/\s+/);
if (filter.services) filter.services = filter.services.map(s => parseInt(s));
let hasManufacturerDataFilters = false;
const manufacturerDataFilters = {};
for (manufacturerDataFilterInputs of filterInputs.manufacturerDataFilterInputs) {
if (!manufacturerDataFilterInputs.idInput.value) continue;
const id = manufacturerDataFilterInputs.idInput.value.trim();
const manufacturerDataFilter = {};
manufacturerDataFilters[id] = manufacturerDataFilter;
hasManufacturerDataFilters = true;
if (manufacturerDataFilterInputs.prefixInput.value) manufacturerDataFilter.dataPrefix = manufacturerDataFilterInputs.prefixInput.value.trim().split(/\s+/).map(p => parseInt(p));
if (manufacturerDataFilterInputs.maskInput.value) manufacturerDataFilter.mask = manufacturerDataFilterInputs.maskInput.value.trim().split(/\s+/).map(m => parseInt(m));
}
if (hasManufacturerDataFilters) {
filter.manufacturerData = manufacturerDataFilters;
}
filters.push(filter);
}
const deviceDetails = {
filters: filters
};
const optionalServicesBLE = document.getElementById('optionalServicesBLE');
if (optionalServicesBLE.value.trim()) deviceDetails.optionalServices = optionalServicesBLE.value.trim().split(/\s+/);
Scratch.BLE.requestDevice(
deviceDetails
).then(
x => {
addLine(`requestDevice resolved to: ${stringify(x)}`);
},
e => {
addLine(`requestDevice rejected with: ${stringify(e)}`);
}
);
}
function connectBLE() {
// this should really be implicit in `requestDevice` but splitting it out helps with debugging
Scratch.BLE.sendRemoteRequest(
'connect',
{ peripheralId: Scratch.BLE.discoveredPeripheralId }
).then(
x => {
addLine(`connect resolved to: ${stringify(x)}`);
},
e => {
addLine(`connect rejected with: ${stringify(e)}`);
}
);
}
function getServicesBLE() {
Scratch.BLE.sendRemoteRequest (
'getServices'
).then(
x => {
addLine(`getServices resolved to: ${stringify(x)}`);
},
e => {
addLine(`getServices rejected with: ${stringify(e)}`);
}
);
}
function setServiceMicroBit() {
document.getElementById('serviceBLE').value = '0xf005';
}
function readMicroBit() {
Scratch.BLE.read(0xf005, '5261da01-fa7e-42ab-850b-7c80220097cc', true).then(
x => {
addLine(`read resolved to: ${stringify(x)}`);
},
e => {
addLine(`read rejected with: ${stringify(e)}`);
}
);
}
function writeMicroBit() {
const message = _encodeMessage('LINK');
Scratch.BLE.write(0xf005, '5261da02-fa7e-42ab-850b-7c80220097cc', message, 'base64').then(
x => {
addLine(`write resolved to: ${stringify(x)}`);
},
e => {
addLine(`write rejected with: ${stringify(e)}`);
}
);
}
function setServiceWeDo2() {
document.getElementById('serviceBLE').value = '00001523-1212-efde-1523-785feabcd123';
}
function setGDXFOR() {
if (filtersBLE.length < 1) addFilterBLE();
const optionalServicesBLE = document.getElementById('optionalServicesBLE');
optionalServicesBLE.value = 'd91714ef-28b9-4f91-ba16-f0d9a604f112';
filterInputsBLE[0].namePrefixInput.value = 'GDX';
filterInputsBLE[0].exactNameInput.value = null;
filterInputsBLE[0].servicesInput.value = null;
}
// micro:bit base64 encoding
// https://github.com/LLK/scratch-microbit-firmware/blob/master/protocol.md
function _encodeMessage(message) {
const output = new Uint8Array(message.length);
for (let i = 0; i < message.length; i++) {
output[i] = message.charCodeAt(i);
}
const output2 = new Uint8Array(output.length + 1);
output2[0] = 0x81; // CMD_DISPLAY_TEXT
for (let i = 0; i < output.length; i++) {
output2[i + 1] = output[i];
}
return base64 = window.btoa(String.fromCharCode.apply(null, output2));
}
attachFunctionToButton('initBLE', initBLE);
attachFunctionToButton('getVersionBLE', () => getVersion(self.Scratch.BLE));
attachFunctionToButton('pingBLE', pingBLE);
attachFunctionToButton('discoverBLE', discoverBLE);
attachFunctionToButton('connectBLE', connectBLE);
attachFunctionToButton('getServicesBLE', getServicesBLE);
attachFunctionToButton('setServiceMicroBit', setServiceMicroBit);
attachFunctionToButton('readMicroBit', readMicroBit);
attachFunctionToButton('writeMicroBit', writeMicroBit);
attachFunctionToButton('setServiceWeDo2', setServiceWeDo2);
attachFunctionToButton('setGDXFOR', setGDXFOR);
attachFunctionToButton('addFilterBLE', addFilterBLE);
addFilterBLE();
function initBT() {
addLine('Connecting...');
self.Scratch.BT = new ScratchBT();
addLine('Connected.');
}
function discoverBT() {
Scratch.BT.requestDevice({
majorDeviceClass: 8,
minorDeviceClass: 1
}).then(
x => {
addLine(`requestDevice resolved to: ${stringify(x)}`);
},
e => {
addLine(`requestDevice rejected with: ${stringify(e)}`);
}
);
}
function connectBT() {
Scratch.BT.connectDevice({
peripheralId: document.getElementById('peripheralId').value,
pin: "1234"
}).then(
x => {
addLine(`connectDevice resolved to: ${stringify(x)}`);
},
e => {
addLine(`connectDevice rejected with: ${stringify(e)}`);
}
);
}
function sendMessage(message) {
Scratch.BT.sendMessage({
message: document.getElementById('messageBody').value,
encoding: 'base64'
}).then(
x => {
addLine(`sendMessage resolved to: ${stringify(x)}`);
},
e => {
addLine(`sendMessage rejected with: ${stringify(e)}`);
}
);
}
function beep() {
Scratch.BT.sendMessage({
message: 'DwAAAIAAAJQBgQKC6AOC6AM=',
encoding: 'base64'
}).then(
x => {
addLine(`sendMessage resolved to: ${stringify(x)}`);
},
e => {
addLine(`sendMessage rejected with: ${stringify(e)}`);
}
);
}
function stringify(o) {
return JSON.stringify(o, o && Object.getOwnPropertyNames(o));
}
const follow = document.getElementById('follow');
const log = document.getElementById('log');
const closeButton = document.getElementById('closeBT');
closeButton.onclick = () => {
self.Scratch.BT.dispose();
};
attachFunctionToButton('initBT', initBT);
attachFunctionToButton('getVersionBT', () => getVersion(self.Scratch.BT));
attachFunctionToButton('discoverBT', discoverBT);
attachFunctionToButton('connectBT', connectBT);
attachFunctionToButton('send', sendMessage);
attachFunctionToButton('beep', beep);
class LogDisplay {
constructor (logElement, lineCount = 256) {
this._logElement = logElement;
this._lineCount = lineCount;
this._lines = [];
this._dirty = false;
this._follow = true;
}
addLine (text) {
this._lines.push(text);
if (!this._dirty) {
this._dirty = true;
requestAnimationFrame(() => {
this._trim();
this._logElement.textContent = this._lines.join('\n');
if (this._follow) {
this._logElement.scrollTop = this._logElement.scrollHeight;
}
this._dirty = false;
});
}
}
_trim () {
this._lines = this._lines.splice(-this._lineCount);
}
}
const logDisplay = new LogDisplay(log);
function addLine(text) {
logDisplay.addLine(text);
logDisplay._follow = follow.checked;
}
</script>
</body>
</html>