-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmicroBitBLE.js
executable file
·1524 lines (1395 loc) · 57.9 KB
/
microBitBLE.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
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
micro:bit BLE I2C and GPIO and sensors driver for Chromium / WebBluetooth or WebUSB
Through Web Bluetooth, you can easily use micro:bit I2C , GPIO I/F from Chromium|Chrome which supported bluetooth.
Supports WebI2C and WebGPIO APIs, so this is one of the CHIRIMEN implementation ;)
Also Supports micro:bit's embedded Buttons, matrixLEDs, Accelerometer, Magnetometer, Thermometer, Lightmeter with special APIs
=======================================================================================================
Programmed by Satoru Takagi
Copyright 2019 by Satoru Takagi All Rights Reserved
=======================================================================================================
License: (GPL v3)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=======================================================================================================
History:
(このドライバの更新履歴)
2019.03.07: Rev6: micro:bitのファームをリファクタリング(結局メモリが足りなくなる・・・)、それに伴いこちらのコードもリファクタリング・・
2019.06.18: Rev7: ついにファームメモリオーバーフロー解消? GPIOもサポート あとはonChange系と終了時処理系
2019.06.21: GPIO analog INをサポートする、pullModeを設定可能に・・
2019.06.25: onchangeを実装。 ただしこのドライバがBLE経由でポーリングしている・・・
2019.07.12: 外的要因によるonDisconnectedでnotificationsが出なくなる問題があるようなので、そのエラー処理をしました
2019.07.16: readBytes(<9bytes)をサポート ( for S11059.... )
2019.07.19: readBytes(<33bytes)をサポート
2019.08.09: キューを実装 Now sending command....エラーを出さなくした
2019.08.20: 例外処理を少し強化(processNextQueue()周り)
2019.08.20: showIconLED()
2019.08.30: sendCmd2MicroBit()タイムアウト処理 を実装中 (テスト用ファーム(エラーをあえて出すので実用は×):https://makecode.microbit.org/_Uf7d6eL1WYDb)
2020.07.13: AB両押しに対応/非対応環境向けエラーメッセージをより詳細にする/エラーハンドリングプロセスの整理など by @kou029w
2020.08.17: readByte()サポート ( for VEML6070 driver )
2020.09.07: webUSB経由でも接続できる機能の実装を行った! connect(true)でUSB経由・・もうちょっときれいにしたいね
=======================================================================================================
FirmWares on micro:bit:
for Bluetooth Connection:
(以下の中の最新リビジョンのファームとのペアで本ドライバは動作するようになっています)
この版では、完全にリファクタリングした・・
https://makecode.microbit.org/_8PsJJmh5F1W3 "W"コマンドのみ
https://makecode.microbit.org/_C30W7EP3shUP "W"及び"R"サポート: だいぶ進んだがまだ不安定、readとwriteを混在させるとおかしくなったり、動かしつつけるとconnection切れたりする。
https://makecode.microbit.org/_cmbD852LJ4Wv 2019/5/27 リファクタリング ほとんどをcustom ns下に移動し buffer関連のメモリリーク?エラーを解決しようとしてる
https://makecode.microbit.org/_cKR1R7M9ee4w 2019/5/28 内蔵センサをイネーブルに ただし、一度でも内蔵センサを使うと、これでNeopixel I2Cで LED 64個を併用するとERR020が必ず起きる メモリーが足りない... 打つ手はないような気がする 192バイトBufferが取れない。micro:bit側のi2cwritebufferでcontinueを入れても分割送信は無理だった・・
==ここでようやくメモリオーバーフローの長いトンネルを抜けました・・・
2019.06.18: Rev11 : WebGPIO https://makecode.microbit.org/_Uuxca6Mp0Cr2 ついに結構安定板ができた!!!
2019.06.19: https://makecode.microbit.org/_XrUF6yJbg6Fp 少し綺麗に?
2019.06.21: https://makecode.microbit.org/_9uyik75iiXMF GPIOの動作をチェック pullModeの指定を可能にしてanalogIn動くように・・
2019.06.25: https://makecode.microbit.org/_d4hA9cWMz5rC 少しきれいにした程度 本当はネイティブonchangeを入れようとしたが020ERR...
2019.07.02: https://makecode.microbit.org/_gozVrxVwyUhf micro:bitのinput.lightLevelとpins.analogReadPinはコンフリクトしてる。 led.setDisplayMode(DisplayMode.BlackAndWhite)とpins.digitalWritePin(DigitalPin.P2, 0)を双方呼ぶとなんとかリセットされるので"P"にそれを入れた ( test: https://makecode.microbit.org/_YLeAM8JDAF5x )
2019.07.16: https://makecode.microbit.org/_DEy9fTMpreEu readBytes(<9bytes)をサポート
2019.07.19: https://makecode.microbit.org/_chw6fvg6KW2m readBytes(<33bytes)をサポート
2019.08.20: https://makecode.microbit.org/_0jhPcA3iX0gC showIconLEDサポート
2020.07.13: https://makecode.microbit.org/_Jh51P7beW6Kb コード整理 AB両押し対応 by @kou029w
for USB Connection:
2020.09.07: https://makecode.microbit.org/_FCyPDq5kUhzr
2020.09.08: https://makecode.microbit.org/_gmeAtmHXJ1yP すこし・・
2020.09.09: https://makecode.microbit.org/_XPuM8WFsKR2E ビットレートを明記(不要だと思うんだけど)
=======================================================================================================
References:
Customを使わないとヒープ減らせないか作戦・・https://makecode.microbit.org/_iXdKFUieAWFz
https://github.com/lancaster-university/microbit-dal/issues/390 これは参考になる 2.1.0はほとんどBLE使い物にならないらしい https://github.com/lancaster-university/microbit-dal/issues/390#issuecomment-426156052 はいろいろdisableにすると使える!
BT省メモリ化可能な開発(コンパイル)環境:https://makecode.microbit.org/app/ceebbcc016c631523a6f1ea8d5ba9523b0e5c213-c728c358f3
上のツールで設定される値をpxt.jsonに直接書けばうまく動くようになる?
https://makecode.microbit.org/_Te0UcjJDRVfR rev8はこれをやってるだけ ->うまく動くかんじ!!!
see also
https://lancaster-university.github.io/microbit-docs/ble/profile/
https://lancaster-university.github.io/microbit-docs/resources/bluetooth/bluetooth_profile.html
https://relativelayout.hatenablog.com/entry/2018/02/03/013251
https://github.com/edrosten/bluez/blob/master/monitor/uuid.c (Huge Dicts!)
https://tknc.jp/tp_detail.php?id=360
https://makecode.microbit.org/v0/06016-09825-51608-35581
micro:bitでADT7410
https://yamamoto-works.hatenablog.com/entry/2018/12/23/233953
i2cWriteNumber
i2cReadNumber
i2cWriteBuffer (ブロックとしてはない)
i2cReadBuffer (ブロックとしてはない)
https://makecode.microbit.org/reference/pins/i2c-write-buffer
https://github.com/Microsoft/pxt-microbit/blob/master/libs/core/pins.ts
https://github.com/adafruit/pxt-seesaw/blob/master/seesaw.ts
I2Cのwriteはなんかi2cWriteNumberをtrue,false連続で送る方法は効かない感じがする・・
8bitなら、これで送る感じ?
http://robert-fromm.info/?post=elec_i2c_calliope
pins.i2cWriteNumber(addr, reg * 256 + value, NumberFormat.UInt16BE)
I2Cについて
http://www.picfun.com/f1/f06.html 基本
http://s-ajisaka.hatenablog.com/entry/2017/06/29/003636 レジスタについて
micro:bit UART側がこちらに一度に送れる文字列長は20文字!!
I2Cはこのへん
https://makecode.microbit.org/reference/pins/i2c-read-number
https://yamamoto-works.hatenablog.com/entry/2018/12/23/233953
これも使えるはず
https://makecode.microbit.org/reference/pins/i2c-write-buffer
https://makecode.microbit.org/reference/pins/i2c-read-buffer
USBはこれをすごく参考にさせてもらいました
https://github.com/bsiever/microbit-webusb
**/
(function (window) {
var navigator = window.navigator;
var usbMode = false;
var prevConnectedDevices = [];
var debugLog = false;
var microBitBleFactory = (function () {
var pollingInterval = 250;
var microBitUUIDs = {
//micro:bit BLE UUID
/* BBC micro:bit Bluetooth Profiles */
"MicroBit Accelerometer Service": "e95d0753-251d-470a-a062-fa1922dfa9a8",
"MicroBit Accelerometer Data": "e95dca4b-251d-470a-a062-fa1922dfa9a8",
"MicroBit Accelerometer Period": "e95dfb24-251d-470a-a062-fa1922dfa9a8",
"MicroBit Magnetometer Service": "e95df2d8-251d-470a-a062-fa1922dfa9a8",
"MicroBit Magnetometer Data": "e95dfb11-251d-470a-a062-fa1922dfa9a8",
"MicroBit Magnetometer Period": "e95d386c-251d-470a-a062-fa1922dfa9a8",
"MicroBit Magnetometer Bearing": "e95d9715-251d-470a-a062-fa1922dfa9a8",
"MicroBit Button Service": "e95d9882-251d-470a-a062-fa1922dfa9a8",
"MicroBit Button A State": "e95dda90-251d-470a-a062-fa1922dfa9a8",
"MicroBit Button B State": "e95dda91-251d-470a-a062-fa1922dfa9a8",
"MicroBit IO PIN Service": "e95d127b-251d-470a-a062-fa1922dfa9a8",
"MicroBit PIN Data": "e95d8d00-251d-470a-a062-fa1922dfa9a8", // e95d8d00251d470aa062fa1922dfa9a8
"MicroBit PIN AD Configuration": "e95d5899-251d-470a-a062-fa1922dfa9a8", // e95d5899251d470aa062fa1922dfa9a8
"MicroBit PIN IO Configuration": "e95db9fe-251d-470a-a062-fa1922dfa9a8", // e95db9fe251d470aa062fa1922dfa9a8
"MicroBit PWM Control": "e95dd822-251d-470a-a062-fa1922dfa9a8", // e95dd822251d470aa062fa1922dfa9a8
"MicroBit LED Service": "e95dd91d-251d-470a-a062-fa1922dfa9a8",
"MicroBit LED Matrix state": "e95d7b77-251d-470a-a062-fa1922dfa9a8",
"MicroBit LED Text": "e95d93ee-251d-470a-a062-fa1922dfa9a8",
"MicroBit Scrolling Delay": "e95d0d2d-251d-470a-a062-fa1922dfa9a8",
"MicroBit Event Service": "e95d93af-251d-470a-a062-fa1922dfa9a8",
"MicroBit Requirements": "e95db84c-251d-470a-a062-fa1922dfa9a8",
"MicroBit Event Data": "e95d9775-251d-470a-a062-fa1922dfa9a8",
"MicroBit Client Requirements": "e95d23c4-251d-470a-a062-fa1922dfa9a8",
"MicroBit Client Events": "e95d5404-251d-470a-a062-fa1922dfa9a8",
"MicroBit DFU Control Service": "e95d93b0-251d-470a-a062-fa1922dfa9a8",
"MicroBit DFU Control": "e95d93b1-251d-470a-a062-fa1922dfa9a8",
"MicroBit Temperature Service": "e95d6100-251d-470a-a062-fa1922dfa9a8",
"MicroBit Temperature Data": "e95d9250-251d-470a-a062-fa1922dfa9a8",
"MicroBit Temperature Period": "e95d1b25-251d-470a-a062-fa1922dfa9a8",
/* Nordic UART Port Emulation */
"Nordic UART Service": "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
"Nordic UART TX": "6e400002-b5a3-f393-e0a9-e50e24dcca9e",
"Nordic UART RX": "6e400003-b5a3-f393-e0a9-e50e24dcca9e",
};
async function connectBluetooth() {
return connect();
}
async function connectUSB() {
return connect(true);
}
async function connect(isUsbMode) {
usbMode = isUsbMode;
var primaryDevice = false; // navigator.*に登録されてたらtrure
var dt = new Date();
console.log("mbBLE connect");
function pinCallBack() {
console.log("called pinCallBack", this);
}
/**
function uartCallBack(e){
console.log("called uartCallBack",this);
var str_arr=[];
for(var i=0;i<this.value.byteLength;i++){
str_arr[i]=this.value.getUint8(i);
}
var str= String.fromCharCode.apply(null,str_arr);
console.log("uartCallBack:",str);
}
**/
var uartCallBackObj = {
cmdQueue: [], // ここには、処理待ちの、cbFunc:func、blmsg:stringを入れる 2019/8/9
uartCallBack: null,
sending: false,
mbCmdReturnValue: [],
conn: false,
};
async function onCharacteristicValueChanged(e) {
// Data Receive Func for Bluetooth
// console.log("onCharacteristicValueChanged: DT:",dt,this.value);
var str_arr = [];
if (this.value && this.value.byteLength) {
for (var i = 0; i < this.value.byteLength; i++) {
str_arr[i] = this.value.getUint8(i);
}
var str = String.fromCharCode.apply(null, str_arr);
if (debugLog) {
console.log("btStr:", str);
}
uartCallBackObj.mbCmdReturnValue.push(str);
if (str.startsWith("END")) {
clearTimeout(uartCallBackObj.timoutTimer);
uartCallBackObj.sending = false;
uartCallBackObj.uartCallBack(uartCallBackObj.mbCmdReturnValue);
uartCallBackObj.mbCmdReturnValue = [];
if (uartCallBackObj.cmdQueue.length > 0) {
// キューにたまっている場合、次のコマンドを処理
mbBleUart.processNextQueue();
}
} else {
// uartCallBackObj.mbCmdReturnValue.push(str);
}
}
}
function usbDataRecieved(rcv) {
var str = rcv;
uartCallBackObj.mbCmdReturnValue.push(str);
if (str.startsWith("END")) {
clearTimeout(uartCallBackObj.timoutTimer);
uartCallBackObj.sending = false;
uartCallBackObj.uartCallBack(uartCallBackObj.mbCmdReturnValue);
uartCallBackObj.mbCmdReturnValue = [];
if (uartCallBackObj.cmdQueue.length > 0) {
// キューにたまっている場合、次のコマンドを処理
mbBleUart.processNextQueue();
}
} else {
// uartCallBackObj.mbCmdReturnValue.push(str);
}
}
// onCharacteristicValueChanged(null);
console.log("prev mbBLE:", mbBLE);
var mbBLE, mbUSB, mbBleUart;
if (usbMode) {
mbUSB = await connectMicroBitUSB(usbDataRecieved);
await sleep(2000);
// mbBLE = cu.device;
// DAPOutReportRequest = cu.DAPOutReportRequest;
uartCallBackObj.conn = true;
mbBleUart = getMbUsbService(mbUSB, uartCallBackObj);
// 接続完了したらLEDを◇表示にする
// 最初のコマンドはうまく返答が来ないことがあり、ちょっと冗長に入れている
await sleep(100);
await showIconLED("36"); // 小さい◇
await sleep(100);
await showIconLED("31"); // 中が半分埋まった◇
await sleep(100);
await showIconLED("35"); // ◇
} else {
mbBLE = await connectMicroBit(
pinCallBack,
onCharacteristicValueChanged
);
var conn = mbBLE != null;
if (!conn) {
const message = [
"接続に失敗しました。",
"Web Bluetooth APIに対応していないか、Bluetoothデバイスへのアクセスが許可されていない可能性があります。",
" https://caniuse.com/#feat=web-bluetooth ",
"デスクトップ環境のChrome/Chromiumの場合、試験的なWebプラットフォーム機能を有効化してください。",
" chrome://flags/#enable-experimental-web-platform-features",
].join("");
console.error(message);
alert(message);
return {
connected: conn,
disconnect: () => Promise.reject(),
requestI2CAccess: () => Promise.reject(),
requestGPIOAccess: () => Promise.reject(),
readSensor: () => Promise.reject(),
printLED: () => Promise.reject(),
showIconLED: () => Promise.reject(),
};
}
console.log("connected MicroBit mbBLE:", mbBLE);
var mbBleDevice = mbBLE.device;
// var mbBlePin ...... // for WebGPIO and switches? err020....
// for WebI2C and embedded sendors,LEDs
var mbBleUartTx = mbBLE.characteristics[0];
var mbBleUartRx = mbBLE.characteristics[1];
var mbBleUart = getMbUartService(
mbBleDevice,
uartCallBackObj,
mbBleUartRx
);
mbBleDevice.addEventListener("gattserverdisconnected", onDisconnected);
if (
prevConnectedDevices[mbBleDevice.id] &&
prevConnectedDevices[mbBleDevice.id] == "diconnectFromDevice"
) {
// このwebAppsのライフサイクル中で、過去に接続したことがあり、しかも何かデバイス側から切られたことがある。
// この場合にChromeのバグらしきものが出る・・ see onDisconnected() 2019/7/12
prevConnectedDevices[mbBleDevice.id] = "diconnectFromWebApps";
await mbBleDevice.gatt.disconnect();
alert(
"残念ながら、うまくNotificationが出ないので一度切断します・・・・・\nもう一度繋ぐとうまく使えると思います\nそれでも失敗する時は chrome://bluetooth-internals/#devices でデバイスをForgetしてみてください。"
);
throw Error("Please re connect because of Chrome's issue....");
}
prevConnectedDevices[mbBleDevice.id] = "yes";
}
uartCallBackObj.conn = conn;
console.log("uartCallBackObj:", uartCallBackObj);
async function readSensor() {
return await readSensorInt(mbBleUart);
}
async function printLED(ptext) {
return await printLedInt(mbBleUart, ptext);
}
async function showIconLED(iconNumber) {
return await showIconLedInt(mbBleUart, iconNumber);
}
var requestI2CAccess = requestI2CAccessGenerator(mbBleUart);
var requestGPIOAccess = requestGPIOAccessGenerator(mbBleUart);
async function onDisconnected() {
mbBleDevice.removeEventListener(
"gattserverdisconnected",
onDisconnected
);
conn = false;
if (primaryDevice) {
delete navigator.requestI2CAccess;
delete navigator.requestGPIOAccess;
primaryDevice = false;
}
if (prevConnectedDevices[mbBleDevice.id] != "diconnectFromWebApps") {
prevConnectedDevices[mbBleDevice.id] = "diconnectFromDevice";
}
console.log(
"DISCONNECTED",
dt,
" by WebApps?:",
prevConnectedDevices[mbBleDevice.id]
);
uartCallBackObj.conn = conn;
uartCallBackObj.sending = false;
console.log("mbBLE:", mbBLE);
var charas = mbBLE.characteristics;
console.log("charas:", charas);
for (var i = 0; i < charas.length; i++) {
// await charas[i].stopNotifications();
// BTデバイス側が強制切断時・・
// 再接続してもNotificationsがやってこないという問題を抱えてしまっている。
// 多分これができれば良いはずだと思うが、切断しているのでもうできない・・(Exeptionになる)
//
// ただし、一度繋げて、再度切断・接続すれば復帰するようです・・
// また、強制切断後、chrome://bluetooth-internals/#devices でinspect forgotしてから接続してもOK
// バグ踏んでるかも 参考:(https://stackoverflow.com/questions/45577219/web-bluetooth-notification-only-few-response)
}
console.log("mbBleDevice.gatt:", mbBleDevice.gatt);
// await mbBleDevice.gatt.disconnect(); // これはさすがに意味がなかった
console.log("DISCONNECTED", dt);
}
async function disconnect() {
conn = false;
uartCallBackObj.conn = conn;
if (usbMode) {
var device = mbUSB.device;
if (device && device.opened) {
device.close();
}
} else {
console.log("mbBLE:", mbBLE);
if (mbBleDevice && mbBleDevice.gatt.connected) {
var charas = mbBLE.characteristics;
for (var i = 0; i < charas.length; i++) {
try {
console.log("notify:", charas[i].properties.notify);
await charas[i].stopNotifications(); // これを動かさないと、いつまでもイベントリスナが残ったままになってしまう挙動??? そうでもない感じもするが・・ 2019.7.12
} catch (e) {
console.log("Fail..");
}
}
prevConnectedDevices[mbBleDevice.id] = "diconnectFromWebApps";
await mbBleDevice.gatt.disconnect();
console.log("charas:", charas);
}
}
}
if (!navigator.requestI2CAccess) {
primaryDevice = true;
console.log("set navigator.requestI2CAccess");
navigator.requestI2CAccess = requestI2CAccess;
console.log("set navigator.requestGPIOAccess");
navigator.requestGPIOAccess = requestGPIOAccess;
}
return {
get connected() {
return conn;
},
disconnect: disconnect,
// reConnect: reConnect,
requestI2CAccess: requestI2CAccess,
requestGPIOAccess: requestGPIOAccess,
readSensor: readSensor,
printLED: printLED,
showIconLED: showIconLED,
};
}
async function connectMicroBitUSB(usbDataRecieved) {
// based on https://bsiever.github.io/microbit-webusb/ubitwebusb.js
var MICROBIT_VENDOR_ID = 0x0d28;
var MICROBIT_PRODUCT_ID = 0x0204;
var MICROBIT_DAP_INTERFACE = 4;
var controlTransferGetReport = 0x01;
var controlTransferSetReport = 0x09;
var controlTransferOutReport = 0x200;
var controlTransferInReport = 0x100;
var DAPOutReportRequest = {
requestType: "class",
recipient: "interface",
request: controlTransferSetReport,
value: controlTransferOutReport,
index: MICROBIT_DAP_INTERFACE,
};
var DAPInReportRequest = {
requestType: "class",
recipient: "interface",
request: controlTransferGetReport,
value: controlTransferInReport,
index: MICROBIT_DAP_INTERFACE,
};
var uBitBadMessageDelay = 500; // Delay if message failed
var uBitIncompleteMessageDelay = 150; // Delay if no message ready now
// var uBitGoodMessageDelay = 20; // Time to try again if message was good
var uBitGoodMessageDelay = 30; // Time to try again if message was good
var md = await navigator.usb.requestDevice({
filters: [
{ vendorId: MICROBIT_VENDOR_ID, productId: MICROBIT_PRODUCT_ID },
],
});
await md.open();
await md.selectConfiguration(1);
await md.claimInterface(4);
if (true) {
await doMbitUSBinitSeq(md, DAPOutReportRequest, DAPInReportRequest);
} else {
// Connect in default mode: https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__Connect.html
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from([2, 0])
);
// Set Clock: 0x989680 = 10MHz : https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__SWJ__Clock.html
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from([0x11, 0x80, 0x96, 0x98, 0])
);
// SWD Configure (1 clock turn around; no wait/fault): https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__SWD__Configure.html
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from([0x13, 0])
);
// Vendor Specific command 2 (ID_DAP_Vendor2): https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c ; 0x0001c200 = 115,200kBps
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from([0x82, 0x00, 0xc2, 0x01, 0x00])
// Uint8Array.from([0x82, 0x00, 0xe1, 0x00, 0x00])
);
//115200 1C200
// Uint8Array.from([0x82, 0x00, 0xc2, 0x01, 0x00])
//57600 E100
// Uint8Array.from([0x82, 0x00, 0xe1, 0x00, 0x00])
}
var decoder = new TextDecoder("utf-8");
// var transmitting=false; // これはさすがに不要かな・・・
async function dataRecieveLoop() {
var rs = "";
while (md.opened) {
if (readBufferClearFlg) {
rs = "";
readBufferClearFlg = false;
}
/**
if ( transmitting ){
await sleep(uBitGoodMessageDelay);
continue;
}
**/
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from([0x83])
);
var data;
if (md.opened) {
// transmitting=true;
data = await md.controlTransferIn(DAPInReportRequest, 64);
// console.log("data:",data.status," msg:",new Uint8Array(data.data.buffer));
// transmitting=false;
}
if (data.status == "ok") {
var arr = new Uint8Array(data.data.buffer);
var len = arr[1];
// if ( len > 0 ){console.log("data:",data.status," msg:",arr);}
var msg = arr.slice(2, 2 + len);
var string = decoder.decode(msg);
var len0 = string.length;
if (msg.length > 0) {
// なんかlength==1の奴は怪しい。原因不明・・
rs += string;
// console.log("msg:",msg," str:",string);
if (msg[msg.length - 1] == 10) {
// console.log("received:",new TextEncoder().encode(rs));
rs = rs.split("\n");
for (var i = 0; i < rs.length; i++) {
if (rs[i] != "") {
// console.log("recv:",rs[i].trim());
usbDataRecieved(rs[i].trim());
}
}
rs = "";
}
}
}
await sleep(uBitGoodMessageDelay);
}
}
var readBufferClearFlg = false;
function clearReadBuffer() {
// なんかゴミが出る感じなので・・・・
readBufferClearFlg = true;
}
setTimeout(dataRecieveLoop, 50);
return {
device: md,
DAPOutReportRequest: DAPOutReportRequest,
clearReadBuffer: clearReadBuffer,
// transmitting: transmitting
};
}
async function doMbitUSBinitSeq(
md,
DAPOutReportRequest,
DAPInReportRequest
) {
// Makecode本家の初期化手順をそのまま倣ったものを用意してみ
// prettier-ignore
var initCmd = [
[0, 254],
[17, 128, 150, 152, 0],
[2, 0],
[17, 128, 150, 152, 0],
[4, 0, 80, 0, 0, 0],
[19, 0],
[18, 56, 255, 255, 255, 255, 255, 255, 255],
[18, 16, 158, 231],
[18, 56, 255, 255, 255, 255, 255, 255, 255],
[18, 8, 0],
[5, 0, 1, 2],
[5, 0, 4, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 4, 0, 0, 0, 80, 6],
[5, 0, 4, 4, 0, 15, 0, 80, 8, 0, 0, 0, 0, 8, 240, 0, 0, 0, 15],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 0, 32, 0, 224, 15],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 0, 32, 0, 224, 13, 2, 0, 0, 0],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 8, 32, 0, 224, 13, 0, 0, 0, 0],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 12, 32, 0, 224, 13, 0, 0, 0, 0],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 16, 32, 0, 224, 13, 0, 0, 0, 0],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 20, 32, 0, 224, 13, 0, 0, 0, 0],
[5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 0, 237, 0, 224, 15],
[128],
[5, 0, 3, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 16, 0, 0, 16],
[5, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15],
[130, 0, 194, 1, 0]
];
for (var i = 0; i < initCmd.length; i++) {
await md.controlTransferOut(
DAPOutReportRequest,
Uint8Array.from(initCmd[i])
);
var data = await md.controlTransferIn(DAPInReportRequest, 64);
// console.log("data:",data.status," msg:",new Uint8Array(data.data.buffer));
await sleep(20);
}
}
async function connectMicroBit(pinGate, uartTxGate) {
var characteristicSet = [];
// Pin Services Characteristics[0:UART_TX,1:UART_RX,2:data,3:ADconf,4:IOconf,5:PWMconf]
characteristicSet.push({
serviceUUID: microBitUUIDs["Nordic UART Service"],
dataUUID: microBitUUIDs["Nordic UART TX"],
callback: uartTxGate,
});
characteristicSet.push({
serviceUUID: microBitUUIDs["Nordic UART Service"],
dataUUID: microBitUUIDs["Nordic UART RX"],
});
var mbBLE = await connectBLE(characteristicSet);
return mbBLE;
}
async function connectBLE(characteristicSet) {
// characteristicSet = [{serviceUUID:serviceUUID, dataUUID:dataUUID, callBack:callBackFunc},...]
// というデータ構造を作って、投入する。
// 生成された.deviceおよび、上記に対応するcharacteristicが入った.characteristics配列が、返却される
// If requestDevice() is called without HM interaction (input button event etc) then throw exception
// If you already get device then set device option , for bypassing requestDevice()
// console.log("navigator.bluetooth:",navigator.bluetooth);
var optionalServicesArray = [];
for (var i = 0; i < characteristicSet.length; i++) {
optionalServicesArray.push(characteristicSet[i].serviceUUID);
}
try {
var device = await navigator.bluetooth.requestDevice({
filters: [
{
namePrefix: "BBC micro:bit",
},
],
optionalServices: optionalServicesArray, // Trap!!!: This option is mandatory
});
// console.log("Get micro:bit device : ", device);
if (device.gatt.connected) {
console.log("Already connected");
return false;
}
var server = await (async function (device) {
return device.gatt.connect();
})(device);
console.log("Get micro:bit server : ", server);
var characteristics = [];
for (var i = 0; i < characteristicSet.length; i++) {
var service = await (async function (server) {
return server.getPrimaryService(characteristicSet[i].serviceUUID);
})(server);
// console.log("service No:",i," : ", service)
var chara = await (async function (service) {
return service.getCharacteristic(characteristicSet[i].dataUUID);
})(service);
// console.log("chara:", chara)
await (async function (chara) {
// alert("BLE接続が完了しました。");
// console.log("callBack?:",characteristicSet[i].callback, characteristicSet[i]);
if (characteristicSet[i].callback) {
// chara.stopNotifications();
// console.log("SET CALLBACK : : : ",characteristicSet[i].callback, await characteristicSet[i].callback(null) );
chara.startNotifications();
chara.addEventListener(
"characteristicvaluechanged",
characteristicSet[i].callback
);
// chara.oncharacteristicvaluechanged =characteristicSet[i].callback;
} else {
// console.log("NO CALLBACK, no NOTIFICATION");
// chara.addEventListener('characteristicvaluechanged',function(ev){console.log("no NOTIF:",ev)});
}
})(chara);
characteristics.push(chara);
}
console.log("OK: ", device, characteristics);
return {
device: device,
characteristics: characteristics,
};
} catch (error) {
console.error(error);
}
}
function getMbUsbService(mbUSB, uartCallBackObj) {
// mbUSB { device: md, DAPOutReportRequest: DAPOutReportRequest }
var conn = uartCallBackObj.conn;
var firstTime = 3;
console.log("getMbUsbService: conn:", conn);
async function sendCmd2MicroBit(sendValue) {
return new Promise(async function (resolve) {
await sendCmd2MicroBitS2(sendValue, resolve);
});
}
async function sendCmd2MicroBitS2(sendValue, cbFunc) {
if (debugLog) {
console.log("sendVal:", sendValue);
}
var timeOutMsec = 500;
if (sendValue.charAt(0) == "L") {
timeOutMsec = 20000;
} // LEDにtextを出す場合はスクロール完了までの時間がかかるのでtimeOutを長くする・・・(TBD)
// var blmsg = string_to_buffer(sendValue + "\n");
var blmsg = sendValue;
uartCallBackObj.cmdQueue.push({
blmsg: blmsg,
cbFunc: cbFunc,
timeOutMsec: timeOutMsec,
});
// console.log(uartCallBackObj.cmdQueue.length);
if (uartCallBackObj.cmdQueue.length == 1 && !uartCallBackObj.sending) {
await processNextQueue();
} else {
if (debugLog) {
console.log(
"ADD QUEUE:",
sendValue,
" queueL:",
uartCallBackObj.cmdQueue.length,
" sending:",
uartCallBackObj.sending
);
}
}
}
async function processNextQueue() {
if (conn) {
if (firstTime > 0) {
--firstTime;
}
const nextCmd = uartCallBackObj.cmdQueue.shift();
uartCallBackObj.mbCmdReturnValue = [];
uartCallBackObj.uartCallBack = nextCmd.cbFunc;
uartCallBackObj.sending = true;
uartCallBackObj.timoutTimer = setTimeout(
checkCmdCompleted,
nextCmd.timeOutMsec
);
try {
// console.log("sendCmd:",nextCmd);
await uBitSend(
nextCmd.blmsg,
mbUSB.device,
mbUSB.DAPOutReportRequest
);
// この後、microBitから返事が返ると、onCharacteristicValueChanged()がn回連続で呼び出され、最後に"END"の値が返ったものが来る
} catch (err) {
// まだ原因がよくわからないがエラーが起きる時があるので、その時はそのコマンド処理をスキップしnullを返す・・・(console.log出し過ぎが問題だった???出さなくしたらそもそもエラーが出なくなった感がある・・・) 2019/8/20
console.error("[[[ERROR]]] on calling uBitSend : ", err);
uartCallBackObj.sending = false;
uartCallBackObj.uartCallBack(null);
uartCallBackObj.mbCmdReturnValue = [];
if (uartCallBackObj.cmdQueue.length > 0) {
processNextQueue();
}
}
} else {
console.log("uartCallBackObj:", uartCallBackObj);
throw Error("Bluetooth is not connected..");
}
}
function checkCmdCompleted() {
console.log("called checkCmdCompleted", uartCallBackObj.sending);
if (uartCallBackObj.sending == true) {
uartCallBackObj.sending = false;
uartCallBackObj.mbCmdReturnValue = [];
uartCallBackObj.cmdQueue = [];
if (firstTime > 0) {
// 電源投入直後の最初の1-2回だけ、ちゃんとレスポンスが返ってこない挙動がある?
//(最初の一回目のリクエストはLEDを◇表示する命令なので放置する)
uartCallBackObj.uartCallBack(true);
console.log("firstTime ERR BUT SKIP");
} else {
console.error("[[[ERROR]]] No micro:bit response.");
uartCallBackObj.uartCallBack(null);
}
}
}
async function uBitSend(data, md, DAPOutReportRequest) {
if (!md.opened) {
return;
}
// Need to send 0x84 (command), length (including newline), data's characters, newline
var fullLine = data + "\n";
var encoded = new TextEncoder("utf-8").encode(fullLine);
var message = new Uint8Array(1 + 1 + fullLine.length);
message[0] = 0x84;
message[1] = encoded.length;
message.set(encoded, 2);
// console.log("uBitSend:", message," data:",data);
// DAP ID_DAP_Vendor3: https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c
mbUSB.clearReadBuffer(); //コマンド出す前に帰って来ているデータは何かゴミのデータという前提
await md.controlTransferOut(DAPOutReportRequest, message);
}
return {
sendCmd2MicroBit: sendCmd2MicroBit,
processNextQueue: processNextQueue,
};
}
function getMbUartService(mbBleDevice, uartCallBackObj, mbBleUartRx) {
async function sendCmd2MicroBit(sendValue) {
// if ( uartCallBackObj.sending ){
// throw Error("Now sending command....");
// }
// uartCallBackObj.sending = true;
return new Promise(async function (resolve) {
await sendCmd2MicroBitS2(sendValue, resolve);
});
}
async function sendCmd2MicroBitS2(sendValue, cbFunc) {
if (debugLog) {
console.log("sendVal:", sendValue);
}
var timeOutMsec = 500;
if (sendValue.charAt(0) == "L") {
timeOutMsec = 20000;
} // LEDにtextを出す場合はスクロール完了までの時間がかかるのでtimeOutを長くする・・・(TBD)
var blmsg = string_to_buffer(sendValue + "\n");
uartCallBackObj.cmdQueue.push({
blmsg: blmsg,
cbFunc: cbFunc,
timeOutMsec: timeOutMsec,
});
// console.log(uartCallBackObj.cmdQueue.length);
if (uartCallBackObj.cmdQueue.length == 1 && !uartCallBackObj.sending) {
await processNextQueue();
} else {
if (debugLog) {
console.log(
"ADD QUEUE:",
sendValue,
" queueL:",
uartCallBackObj.cmdQueue.length,
" sending:",
uartCallBackObj.sending
);
}
}
}
async function processNextQueue() {
if (uartCallBackObj.conn) {
const nextCmd = uartCallBackObj.cmdQueue.shift();
uartCallBackObj.mbCmdReturnValue = [];
uartCallBackObj.uartCallBack = nextCmd.cbFunc;
uartCallBackObj.sending = true;
uartCallBackObj.timoutTimer = setTimeout(
checkCmdCompleted,
nextCmd.timeOutMsec
);
try {
await mbBleUartRx.writeValue(nextCmd.blmsg);
// この後、microBitから返事が返ると、onCharacteristicValueChanged()がn回連続で呼び出され、最後に"END"の値が返ったものが来る
} catch (err) {
// まだ原因がよくわからないがエラーが起きる時があるので、その時はそのコマンド処理をスキップしnullを返す・・・(console.log出し過ぎが問題だった???出さなくしたらそもそもエラーが出なくなった感がある・・・) 2019/8/20
console.error(
"[[[ERROR]]] on calling mbBleUartRx.writeValue : ",
err
);
uartCallBackObj.sending = false;
uartCallBackObj.uartCallBack(null);
uartCallBackObj.mbCmdReturnValue = [];
if (uartCallBackObj.cmdQueue.length > 0) {
processNextQueue();
}
}
} else {
console.log("uartCallBackObj:", uartCallBackObj);
throw Error("Bluetooth is not connected..");
}
}
function checkCmdCompleted() {
console.log("called checkCmdCompleted", uartCallBackObj.sending);
if (uartCallBackObj.sending == true) {
console.error("[[[ERROR]]] No micro:bit response.");
uartCallBackObj.sending = false;
uartCallBackObj.uartCallBack(null);
uartCallBackObj.mbCmdReturnValue = [];
uartCallBackObj.cmdQueue = [];
}
}
return {
sendCmd2MicroBit: sendCmd2MicroBit,
processNextQueue: processNextQueue,
};
}
// webGPIOimpl
var availablePorts = [1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1]; // LED matrix ports are unavailable
var canOutPorts = [1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1]; //
var canAnalogInPorts = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //
var pullModeEnum = { none: 0, down: 1, up: 2 };
function requestGPIOAccessGenerator(mbBleUart) {
async function requestGPIOAccess() {
var GPIOports = new Map();
for (var i = 0; i < availablePorts.length; i++) {
GPIOports.set(i, getGPIOPort(mbBleUart, i));
}
return {
ports: GPIOports,
unexportAll: async function () {},
};
}
return requestGPIOAccess;
}
function getGPIOPort(mbBleUart, portNumb) {
var direction = "";
var exported = false;
var pNumber = portNumb;
var out = true;
var ain = false;
async function export_port(mode, pullMode) {
// mode: "in", "out", "analogin", "analogout", (TBD"pwmout") case insensitive
// pullModeは、ポートやモードごとに決め打ちにするのがいいのかもしれません analoginはnoneでないとうまく動かない
// console.log("export_port",mode);
if (exported) {
throw Error("Already exported. Use unexport().");
}
direction = mode.toLowerCase();
exported = true;
switch (direction) {
case "in":
out = false;
ain = false;
if (!pullMode) {
pullMode = "up"; // CHIRIMEN for RPi3はしばしばpull upのサンプルがあるため・・
}
break;
case "out":
if (canOutPorts[pNumber] == 0) {
throw Error("This port is not supported digital out");
}
out = true;
ain = false;
break;
case "analogin":
if (canAnalogInPorts[pNumber] == 0) {
throw Error("This port is not supported analog in");
}
out = false;
ain = true;