/
index.js
984 lines (906 loc) · 35 KB
/
index.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
const ArgumentType = require('../../extension-support/argument-type');
const BlockType = require('../../extension-support/block-type');
const log = require('../../util/log');
const cast = require('../../util/cast');
const formatMessage = require('format-message');
const BLE = require('../../io/ble');
const Base64Util = require('../../util/base64-util');
/**
* Icon png to be displayed at the left edge of each extension block, encoded as a data URI.
* @type {string}
*/
// eslint-disable-next-line max-len
const blockIconURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAACXBIWXMAABYlAAAWJQFJUiTwAAAKcElEQVR42u2cfXAU9RnHv7u3L3d7l9yR5PIGXO7MkQKaYiCUWqJhFGvRMk4JZXSc8aXVaSmiYlthVHQEW99FxiIdrVY6teiMdoa+ICqhIqgQAsjwMgYDOQKXl7uY17u9293b3f5x5JKYe8+FJGSfvzbP/n77e/azz+95nt9v90KoqgpN0hdSQ6AB1ABqADWAmmgANYAaQA2gJhpADeBEE2q8GPLaWzu/CslyiY4k9dOn5uijtXGd7+jWkaReVpT3Hrhv6d0awEFC07rgD+ZeYYnXprhwigUAvjj0zbjxQCLebozT7iDzK1ZUWCru2K7L//6MVC8ue45Blz8n6rlQ815QtuohOlXiEdy/AUqPa6y59Mkh6Q1345GNja6m7pHEQKNl3t0704EXat4L6fSOmOeEI1vHKzwAyNJR9MPFpRUPOu0ONm2A0xatWaTLm5WfDrzvAppA8AbiG03fC8CQNkDKZK2YrPAuRrhpifJERsuYywveJc7CqcIDMAyeLm82dEXzw39I/qjXkpr3QuW9lxfAdOABGAKPslWDnbsy7Jl8BxTeM3SqmO0gaA5U6c3jymup0YSn9JyLee67wpTfBQAQjmyF3HFqiJcRtDECjy5dAmbmcgQPvjjxl3Lx4IVjnD/5cE1zkWtyP34VBGcdKLJnLgc9cznk1kMXFdzEn8KJ4KUqqsSHvcxWDf7j1UM8UPr6/YgHhhX8xAaYaXgAIB7fBnbuSrBzV8aNgarEQ/z6/YkLcDTg9V9XlXjQtuqoU1TpcUHlvZDOfDiuyh5qPMCLrJ1bDw3EuUtx81N/BH3pjQBJQ2HMF5V6iKfeRchVm9kkMtrwxmSdobeA9daBde8GwV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D1dSDuxbsGQIymmz48DbwIguOESJOcce8XaO3oVpZ8k3Em5KVVAAMFnuOB9as1MbimCBunn04vBmR40ls29Wfgxf1KMn1gBdY+MXUCvK4ANvPndpLzrLzALjBN2VPwrDBksgLYkn1jBMp90nVY2++8vAw3RlPeLNYVZSPAEgjKWP6ZCn4lF+gMdnE08spQb73RQB9aXtgo6tJcNodf8rWz3L//Br340UW3sExEkXrFFKSSUVHqkRfkJZ8QSZk5gS6hw9H+GyDQAclSs41BVmSUIn+toAKIUTJskKoQUknCxKlkISKb/sM0NMyyVAhXW+AlYosfgOgQlUJVadTSUWBKoQoudvPioPbenq5oIUTaRUqenhWKi3oyVIUqKpKREoLggDhF6hQb4CV9LRM9rctMPN6glChp2SdTqeSskwoAECSKnG61fzFR/XsGu+FhmONriYl7TImsjoYKJyZSeB8CoBQo6spqU8TCO1fgE7gDVUNoCYaQA2gBlADqAHURAOoAdQAagA10QCOgfwfNp/hXbfBMCAAAAAASUVORK5CYII=';
/**
* Enum for micro:bit BLE command protocol.
* https://github.com/scratchfoundation/scratch-microbit-firmware/blob/master/protocol.md
* @readonly
* @enum {number}
*/
const BLECommand = {
CMD_PIN_CONFIG: 0x80,
CMD_DISPLAY_TEXT: 0x81,
CMD_DISPLAY_LED: 0x82
};
/**
* A time interval to wait (in milliseconds) before reporting to the BLE socket
* that data has stopped coming from the peripheral.
*/
const BLETimeout = 4500;
/**
* A time interval to wait (in milliseconds) while a block that sends a BLE message is running.
* @type {number}
*/
const BLESendInterval = 100;
/**
* A string to report to the BLE socket when the micro:bit has stopped receiving data.
* @type {string}
*/
const BLEDataStoppedError = 'micro:bit extension stopped receiving data';
/**
* Enum for micro:bit protocol.
* https://github.com/scratchfoundation/scratch-microbit-firmware/blob/master/protocol.md
* @readonly
* @enum {string}
*/
const BLEUUID = {
service: 0xf005,
rxChar: '5261da01-fa7e-42ab-850b-7c80220097cc',
txChar: '5261da02-fa7e-42ab-850b-7c80220097cc'
};
/**
* Manage communication with a MicroBit peripheral over a Scrath Link client socket.
*/
class MicroBit {
/**
* Construct a MicroBit communication object.
* @param {Runtime} runtime - the Scratch 3.0 runtime
* @param {string} extensionId - the id of the extension
*/
constructor (runtime, extensionId) {
/**
* The Scratch 3.0 runtime used to trigger the green flag button.
* @type {Runtime}
* @private
*/
this._runtime = runtime;
/**
* The BluetoothLowEnergy connection socket for reading/writing peripheral data.
* @type {BLE}
* @private
*/
this._ble = null;
this._runtime.registerPeripheralExtension(extensionId, this);
/**
* The id of the extension this peripheral belongs to.
*/
this._extensionId = extensionId;
/**
* The most recently received value for each sensor.
* @type {Object.<string, number>}
* @private
*/
this._sensors = {
tiltX: 0,
tiltY: 0,
buttonA: 0,
buttonB: 0,
touchPins: [0, 0, 0],
gestureState: 0,
ledMatrixState: new Uint8Array(5)
};
/**
* The most recently received value for each gesture.
* @type {Object.<string, Object>}
* @private
*/
this._gestures = {
moving: false,
move: {
active: false,
timeout: false
},
shake: {
active: false,
timeout: false
},
jump: {
active: false,
timeout: false
}
};
/**
* Interval ID for data reading timeout.
* @type {number}
* @private
*/
this._timeoutID = null;
/**
* A flag that is true while we are busy sending data to the BLE socket.
* @type {boolean}
* @private
*/
this._busy = false;
/**
* ID for a timeout which is used to clear the busy flag if it has been
* true for a long time.
*/
this._busyTimeoutID = null;
this.reset = this.reset.bind(this);
this._onConnect = this._onConnect.bind(this);
this._onMessage = this._onMessage.bind(this);
}
/**
* @param {string} text - the text to display.
* @return {Promise} - a Promise that resolves when writing to peripheral.
*/
displayText (text) {
const output = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
output[i] = text.charCodeAt(i);
}
return this.send(BLECommand.CMD_DISPLAY_TEXT, output);
}
/**
* @param {Uint8Array} matrix - the matrix to display.
* @return {Promise} - a Promise that resolves when writing to peripheral.
*/
displayMatrix (matrix) {
return this.send(BLECommand.CMD_DISPLAY_LED, matrix);
}
/**
* @return {number} - the latest value received for the tilt sensor's tilt about the X axis.
*/
get tiltX () {
return this._sensors.tiltX;
}
/**
* @return {number} - the latest value received for the tilt sensor's tilt about the Y axis.
*/
get tiltY () {
return this._sensors.tiltY;
}
/**
* @return {boolean} - the latest value received for the A button.
*/
get buttonA () {
return this._sensors.buttonA;
}
/**
* @return {boolean} - the latest value received for the B button.
*/
get buttonB () {
return this._sensors.buttonB;
}
/**
* @return {number} - the latest value received for the motion gesture states.
*/
get gestureState () {
return this._sensors.gestureState;
}
/**
* @return {Uint8Array} - the current state of the 5x5 LED matrix.
*/
get ledMatrixState () {
return this._sensors.ledMatrixState;
}
/**
* Called by the runtime when user wants to scan for a peripheral.
*/
scan () {
if (this._ble) {
this._ble.disconnect();
}
this._ble = new BLE(this._runtime, this._extensionId, {
filters: [
{services: [BLEUUID.service]}
]
}, this._onConnect, this.reset);
}
/**
* Called by the runtime when user wants to connect to a certain peripheral.
* @param {number} id - the id of the peripheral to connect to.
*/
connect (id) {
if (this._ble) {
this._ble.connectPeripheral(id);
}
}
/**
* Disconnect from the micro:bit.
*/
disconnect () {
if (this._ble) {
this._ble.disconnect();
}
this.reset();
}
/**
* Reset all the state and timeout/interval ids.
*/
reset () {
if (this._timeoutID) {
window.clearTimeout(this._timeoutID);
this._timeoutID = null;
}
}
/**
* Return true if connected to the micro:bit.
* @return {boolean} - whether the micro:bit is connected.
*/
isConnected () {
let connected = false;
if (this._ble) {
connected = this._ble.isConnected();
}
return connected;
}
/**
* Send a message to the peripheral BLE socket.
* @param {number} command - the BLE command hex.
* @param {Uint8Array} message - the message to write
*/
send (command, message) {
if (!this.isConnected()) return;
if (this._busy) return;
// Set a busy flag so that while we are sending a message and waiting for
// the response, additional messages are ignored.
this._busy = true;
// Set a timeout after which to reset the busy flag. This is used in case
// a BLE message was sent for which we never received a response, because
// e.g. the peripheral was turned off after the message was sent. We reset
// the busy flag after a while so that it is possible to try again later.
this._busyTimeoutID = window.setTimeout(() => {
this._busy = false;
}, 5000);
const output = new Uint8Array(message.length + 1);
output[0] = command; // attach command to beginning of message
for (let i = 0; i < message.length; i++) {
output[i + 1] = message[i];
}
const data = Base64Util.uint8ArrayToBase64(output);
this._ble.write(BLEUUID.service, BLEUUID.txChar, data, 'base64', true).then(
() => {
this._busy = false;
window.clearTimeout(this._busyTimeoutID);
}
);
}
/**
* Starts reading data from peripheral after BLE has connected to it.
* @private
*/
_onConnect () {
this._ble.read(BLEUUID.service, BLEUUID.rxChar, true, this._onMessage);
this._timeoutID = window.setTimeout(
() => this._ble.handleDisconnectError(BLEDataStoppedError),
BLETimeout
);
}
/**
* Process the sensor data from the incoming BLE characteristic.
* @param {object} base64 - the incoming BLE data.
* @private
*/
_onMessage (base64) {
// parse data
const data = Base64Util.base64ToUint8Array(base64);
this._sensors.tiltX = data[1] | (data[0] << 8);
if (this._sensors.tiltX > (1 << 15)) this._sensors.tiltX -= (1 << 16);
this._sensors.tiltY = data[3] | (data[2] << 8);
if (this._sensors.tiltY > (1 << 15)) this._sensors.tiltY -= (1 << 16);
this._sensors.buttonA = data[4];
this._sensors.buttonB = data[5];
this._sensors.touchPins[0] = data[6];
this._sensors.touchPins[1] = data[7];
this._sensors.touchPins[2] = data[8];
this._sensors.gestureState = data[9];
// cancel disconnect timeout and start a new one
window.clearTimeout(this._timeoutID);
this._timeoutID = window.setTimeout(
() => this._ble.handleDisconnectError(BLEDataStoppedError),
BLETimeout
);
}
/**
* @param {number} pin - the pin to check touch state.
* @return {number} - the latest value received for the touch pin states.
* @private
*/
_checkPinState (pin) {
return this._sensors.touchPins[pin];
}
}
/**
* Enum for tilt sensor direction.
* @readonly
* @enum {string}
*/
const MicroBitTiltDirection = {
FRONT: 'front',
BACK: 'back',
LEFT: 'left',
RIGHT: 'right',
ANY: 'any'
};
/**
* Enum for micro:bit gestures.
* @readonly
* @enum {string}
*/
const MicroBitGestures = {
MOVED: 'moved',
SHAKEN: 'shaken',
JUMPED: 'jumped'
};
/**
* Enum for micro:bit buttons.
* @readonly
* @enum {string}
*/
const MicroBitButtons = {
A: 'A',
B: 'B',
ANY: 'any'
};
/**
* Enum for micro:bit pin states.
* @readonly
* @enum {string}
*/
const MicroBitPinState = {
ON: 'on',
OFF: 'off'
};
/**
* Scratch 3.0 blocks to interact with a MicroBit peripheral.
*/
class Scratch3MicroBitBlocks {
/**
* @return {string} - the name of this extension.
*/
static get EXTENSION_NAME () {
return 'micro:bit';
}
/**
* @return {string} - the ID of this extension.
*/
static get EXTENSION_ID () {
return 'microbit';
}
/**
* @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold.
*/
static get TILT_THRESHOLD () {
return 15;
}
/**
* @return {array} - text and values for each buttons menu element
*/
get BUTTONS_MENU () {
return [
{
text: 'A',
value: MicroBitButtons.A
},
{
text: 'B',
value: MicroBitButtons.B
},
{
text: formatMessage({
id: 'microbit.buttonsMenu.any',
default: 'any',
description: 'label for "any" element in button picker for micro:bit extension'
}),
value: MicroBitButtons.ANY
}
];
}
/**
* @return {array} - text and values for each gestures menu element
*/
get GESTURES_MENU () {
return [
{
text: formatMessage({
id: 'microbit.gesturesMenu.moved',
default: 'moved',
description: 'label for moved gesture in gesture picker for micro:bit extension'
}),
value: MicroBitGestures.MOVED
},
{
text: formatMessage({
id: 'microbit.gesturesMenu.shaken',
default: 'shaken',
description: 'label for shaken gesture in gesture picker for micro:bit extension'
}),
value: MicroBitGestures.SHAKEN
},
{
text: formatMessage({
id: 'microbit.gesturesMenu.jumped',
default: 'jumped',
description: 'label for jumped gesture in gesture picker for micro:bit extension'
}),
value: MicroBitGestures.JUMPED
}
];
}
/**
* @return {array} - text and values for each pin state menu element
*/
get PIN_STATE_MENU () {
return [
{
text: formatMessage({
id: 'microbit.pinStateMenu.on',
default: 'on',
description: 'label for on element in pin state picker for micro:bit extension'
}),
value: MicroBitPinState.ON
},
{
text: formatMessage({
id: 'microbit.pinStateMenu.off',
default: 'off',
description: 'label for off element in pin state picker for micro:bit extension'
}),
value: MicroBitPinState.OFF
}
];
}
/**
* @return {array} - text and values for each tilt direction menu element
*/
get TILT_DIRECTION_MENU () {
return [
{
text: formatMessage({
id: 'microbit.tiltDirectionMenu.front',
default: 'front',
description: 'label for front element in tilt direction picker for micro:bit extension'
}),
value: MicroBitTiltDirection.FRONT
},
{
text: formatMessage({
id: 'microbit.tiltDirectionMenu.back',
default: 'back',
description: 'label for back element in tilt direction picker for micro:bit extension'
}),
value: MicroBitTiltDirection.BACK
},
{
text: formatMessage({
id: 'microbit.tiltDirectionMenu.left',
default: 'left',
description: 'label for left element in tilt direction picker for micro:bit extension'
}),
value: MicroBitTiltDirection.LEFT
},
{
text: formatMessage({
id: 'microbit.tiltDirectionMenu.right',
default: 'right',
description: 'label for right element in tilt direction picker for micro:bit extension'
}),
value: MicroBitTiltDirection.RIGHT
}
];
}
/**
* @return {array} - text and values for each tilt direction (plus "any") menu element
*/
get TILT_DIRECTION_ANY_MENU () {
return [
...this.TILT_DIRECTION_MENU,
{
text: formatMessage({
id: 'microbit.tiltDirectionMenu.any',
default: 'any',
description: 'label for any direction element in tilt direction picker for micro:bit extension'
}),
value: MicroBitTiltDirection.ANY
}
];
}
/**
* Construct a set of MicroBit blocks.
* @param {Runtime} runtime - the Scratch 3.0 runtime.
*/
constructor (runtime) {
/**
* The Scratch 3.0 runtime.
* @type {Runtime}
*/
this.runtime = runtime;
// Create a new MicroBit peripheral instance
this._peripheral = new MicroBit(this.runtime, Scratch3MicroBitBlocks.EXTENSION_ID);
}
/**
* @returns {object} metadata for this extension and its blocks.
*/
getInfo () {
return {
id: Scratch3MicroBitBlocks.EXTENSION_ID,
name: Scratch3MicroBitBlocks.EXTENSION_NAME,
blockIconURI: blockIconURI,
showStatusButton: true,
blocks: [
{
opcode: 'whenButtonPressed',
text: formatMessage({
id: 'microbit.whenButtonPressed',
default: 'when [BTN] button pressed',
description: 'when the selected button on the micro:bit is pressed'
}),
blockType: BlockType.HAT,
arguments: {
BTN: {
type: ArgumentType.STRING,
menu: 'buttons',
defaultValue: MicroBitButtons.A
}
}
},
{
opcode: 'isButtonPressed',
text: formatMessage({
id: 'microbit.isButtonPressed',
default: '[BTN] button pressed?',
description: 'is the selected button on the micro:bit pressed?'
}),
blockType: BlockType.BOOLEAN,
arguments: {
BTN: {
type: ArgumentType.STRING,
menu: 'buttons',
defaultValue: MicroBitButtons.A
}
}
},
'---',
{
opcode: 'whenGesture',
text: formatMessage({
id: 'microbit.whenGesture',
default: 'when [GESTURE]',
description: 'when the selected gesture is detected by the micro:bit'
}),
blockType: BlockType.HAT,
arguments: {
GESTURE: {
type: ArgumentType.STRING,
menu: 'gestures',
defaultValue: MicroBitGestures.MOVED
}
}
},
'---',
{
opcode: 'displaySymbol',
text: formatMessage({
id: 'microbit.displaySymbol',
default: 'display [MATRIX]',
description: 'display a pattern on the micro:bit display'
}),
blockType: BlockType.COMMAND,
arguments: {
MATRIX: {
type: ArgumentType.MATRIX,
defaultValue: '0101010101100010101000100'
}
}
},
{
opcode: 'displayText',
text: formatMessage({
id: 'microbit.displayText',
default: 'display text [TEXT]',
description: 'display text on the micro:bit display'
}),
blockType: BlockType.COMMAND,
arguments: {
TEXT: {
type: ArgumentType.STRING,
defaultValue: formatMessage({
id: 'microbit.defaultTextToDisplay',
default: 'Hello!',
description: `default text to display.
IMPORTANT - the micro:bit only supports letters a-z, A-Z.
Please substitute a default word in your language
that can be written with those characters,
substitute non-accented characters or leave it as "Hello!".
Check the micro:bit site documentation for details`
})
}
}
},
{
opcode: 'displayClear',
text: formatMessage({
id: 'microbit.clearDisplay',
default: 'clear display',
description: 'display nothing on the micro:bit display'
}),
blockType: BlockType.COMMAND
},
'---',
{
opcode: 'whenTilted',
text: formatMessage({
id: 'microbit.whenTilted',
default: 'when tilted [DIRECTION]',
description: 'when the micro:bit is tilted in a direction'
}),
blockType: BlockType.HAT,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirectionAny',
defaultValue: MicroBitTiltDirection.ANY
}
}
},
{
opcode: 'isTilted',
text: formatMessage({
id: 'microbit.isTilted',
default: 'tilted [DIRECTION]?',
description: 'is the micro:bit is tilted in a direction?'
}),
blockType: BlockType.BOOLEAN,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirectionAny',
defaultValue: MicroBitTiltDirection.ANY
}
}
},
{
opcode: 'getTiltAngle',
text: formatMessage({
id: 'microbit.tiltAngle',
default: 'tilt angle [DIRECTION]',
description: 'how much the micro:bit is tilted in a direction'
}),
blockType: BlockType.REPORTER,
arguments: {
DIRECTION: {
type: ArgumentType.STRING,
menu: 'tiltDirection',
defaultValue: MicroBitTiltDirection.FRONT
}
}
},
'---',
{
opcode: 'whenPinConnected',
text: formatMessage({
id: 'microbit.whenPinConnected',
default: 'when pin [PIN] connected',
description: 'when the pin detects a connection to Earth/Ground'
}),
blockType: BlockType.HAT,
arguments: {
PIN: {
type: ArgumentType.STRING,
menu: 'touchPins',
defaultValue: '0'
}
}
}
],
menus: {
buttons: {
acceptReporters: true,
items: this.BUTTONS_MENU
},
gestures: {
acceptReporters: true,
items: this.GESTURES_MENU
},
pinState: {
acceptReporters: true,
items: this.PIN_STATE_MENU
},
tiltDirection: {
acceptReporters: true,
items: this.TILT_DIRECTION_MENU
},
tiltDirectionAny: {
acceptReporters: true,
items: this.TILT_DIRECTION_ANY_MENU
},
touchPins: {
acceptReporters: true,
items: ['0', '1', '2']
}
}
};
}
/**
* Test whether the A or B button is pressed
* @param {object} args - the block's arguments.
* @return {boolean} - true if the button is pressed.
*/
whenButtonPressed (args) {
if (args.BTN === 'any') {
return this._peripheral.buttonA | this._peripheral.buttonB;
} else if (args.BTN === 'A') {
return this._peripheral.buttonA;
} else if (args.BTN === 'B') {
return this._peripheral.buttonB;
}
return false;
}
/**
* Test whether the A or B button is pressed
* @param {object} args - the block's arguments.
* @return {boolean} - true if the button is pressed.
*/
isButtonPressed (args) {
if (args.BTN === 'any') {
return (this._peripheral.buttonA | this._peripheral.buttonB) !== 0;
} else if (args.BTN === 'A') {
return this._peripheral.buttonA !== 0;
} else if (args.BTN === 'B') {
return this._peripheral.buttonB !== 0;
}
return false;
}
/**
* Test whether the micro:bit is moving
* @param {object} args - the block's arguments.
* @return {boolean} - true if the micro:bit is moving.
*/
whenGesture (args) {
const gesture = cast.toString(args.GESTURE);
if (gesture === 'moved') {
return (this._peripheral.gestureState >> 2) & 1;
} else if (gesture === 'shaken') {
return this._peripheral.gestureState & 1;
} else if (gesture === 'jumped') {
return (this._peripheral.gestureState >> 1) & 1;
}
return false;
}
/**
* Display a predefined symbol on the 5x5 LED matrix.
* @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves after a tick.
*/
displaySymbol (args) {
const symbol = cast.toString(args.MATRIX).replace(/\s/g, '');
const reducer = (accumulator, c, index) => {
const value = (c === '0') ? accumulator : accumulator + Math.pow(2, index);
return value;
};
const hex = symbol.split('').reduce(reducer, 0);
if (hex !== null) {
this._peripheral.ledMatrixState[0] = hex & 0x1F;
this._peripheral.ledMatrixState[1] = (hex >> 5) & 0x1F;
this._peripheral.ledMatrixState[2] = (hex >> 10) & 0x1F;
this._peripheral.ledMatrixState[3] = (hex >> 15) & 0x1F;
this._peripheral.ledMatrixState[4] = (hex >> 20) & 0x1F;
this._peripheral.displayMatrix(this._peripheral.ledMatrixState);
}
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, BLESendInterval);
});
}
/**
* Display text on the 5x5 LED matrix.
* @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves after the text is done printing.
* Note the limit is 19 characters
* The print time is calculated by multiplying the number of horizontal pixels
* by the default scroll delay of 120ms.
* The number of horizontal pixels = 6px for each character in the string,
* 1px before the string, and 5px after the string.
*/
displayText (args) {
const text = String(args.TEXT).substring(0, 19);
if (text.length > 0) this._peripheral.displayText(text);
const yieldDelay = 120 * ((6 * text.length) + 6);
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, yieldDelay);
});
}
/**
* Turn all 5x5 matrix LEDs off.
* @return {Promise} - a Promise that resolves after a tick.
*/
displayClear () {
for (let i = 0; i < 5; i++) {
this._peripheral.ledMatrixState[i] = 0;
}
this._peripheral.displayMatrix(this._peripheral.ledMatrixState);
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, BLESendInterval);
});
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
*/
whenTilted (args) {
return this._isTilted(args.DIRECTION);
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
*/
isTilted (args) {
return this._isTilted(args.DIRECTION);
}
/**
* @param {object} args - the block's arguments.
* @property {TiltDirection} DIRECTION - the direction (front, back, left, right) to check.
* @return {number} - the tilt sensor's angle in the specified direction.
* Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right).
*/
getTiltAngle (args) {
return this._getTiltAngle(args.DIRECTION);
}
/**
* Test whether the tilt sensor is currently tilted.
* @param {TiltDirection} direction - the tilt direction to test (front, back, left, right, or any).
* @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction.
* @private
*/
_isTilted (direction) {
switch (direction) {
case MicroBitTiltDirection.ANY:
return (Math.abs(this._peripheral.tiltX / 10) >= Scratch3MicroBitBlocks.TILT_THRESHOLD) ||
(Math.abs(this._peripheral.tiltY / 10) >= Scratch3MicroBitBlocks.TILT_THRESHOLD);
default:
return this._getTiltAngle(direction) >= Scratch3MicroBitBlocks.TILT_THRESHOLD;
}
}
/**
* @param {TiltDirection} direction - the direction (front, back, left, right) to check.
* @return {number} - the tilt sensor's angle in the specified direction.
* Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right).
* @private
*/
_getTiltAngle (direction) {
switch (direction) {
case MicroBitTiltDirection.FRONT:
return Math.round(this._peripheral.tiltY / -10);
case MicroBitTiltDirection.BACK:
return Math.round(this._peripheral.tiltY / 10);
case MicroBitTiltDirection.LEFT:
return Math.round(this._peripheral.tiltX / -10);
case MicroBitTiltDirection.RIGHT:
return Math.round(this._peripheral.tiltX / 10);
default:
log.warn(`Unknown tilt direction in _getTiltAngle: ${direction}`);
}
}
/**
* @param {object} args - the block's arguments.
* @return {boolean} - the touch pin state.
* @private
*/
whenPinConnected (args) {
const pin = parseInt(args.PIN, 10);
if (isNaN(pin)) return;
if (pin < 0 || pin > 2) return false;
return this._peripheral._checkPinState(pin);
}
}
module.exports = Scratch3MicroBitBlocks;