-
Notifications
You must be signed in to change notification settings - Fork 14
/
ev3_scratch_v3.js
906 lines (758 loc) · 25.2 KB
/
ev3_scratch_v3.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
// EV3 ScratchX Plugin
// Copyright 2015 Ken Aspeslagh @massivevector
// Only tested on Mac. On Mac, ev3 brick must be named starting with "serial" if the plugin is to recognize it.
// Rename the brick before pairing it with the Mac or else the name gets cached and the serial port will have the old name
// My bricks are named serialBrick1 (etc)
// Turn off the iPod/iPhone/iPad checkbox on the EV3 Bluetooth settings after pairing or else it will not work at all
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
ext._getStatus = function()
{
if (!connected)
return { status:1, msg:'Disconnected' };
else
return { status:2, msg:'Connected' };
};
ext._deviceRemoved = function(dev)
{
console.log('Device removed');
// Not currently implemented with serial devices
};
var connected = false;
var connecting = false;
var notifyConnection = false;
var device = null;
var warnedAboutBattery = false;
var potentialDevices = [];
var deviceTimeout = 0;
ext._deviceConnected = function(dev) {
console.log(timeStamp() + '_deviceConnected: ' + dev.id);
// brick's serial port must be named like tty.serialBrick7-SerialPort
// this is how 10.10 is naming it automatically, the brick name being serialBrick7
// the Scratch plugin is only letting us know about serial ports with names that
// "begin with tty.usbmodem, tty.serial, or tty.usbserial" - according to khanning
if ((dev.id.indexOf('/dev/tty.serialBrick') === 0 && dev.id.indexOf('-SerialPort') != -1) || dev.id.indexOf('COM') === 0)
{
if (potentialDevices.filter(function(e) { return e.id == dev.id; }).length == 0) {
potentialDevices.push(dev); }
if (!deviceTimeout)
deviceTimeout = setTimeout(tryNextDevice, 1000);
}
};
var poller = null;
var pingTimeout = null;
var connectionTimeout = null;
var waitingForPing = false;
var waitingForInitialConnection = false;
var DEBUG_NO_EV3 = false;
var theDevice = null;
function clearSensorStatuses()
{
var numSensorBlocks = 9;
waitingQueries = [];
for (x = 0; x < numSensorBlocks; x++)
{
waitingCallbacks[x] = [];
global_touch_pressed[x] = false;
global_ir_button_pressed[x] = false;
global_sensor_queried[x] = 0;
}
}
var counter = 0;
function reconnect()
{
clearSensorStatuses();
counter = 0;
theDevice.open({ stopBits: 0, bitRate: 57600 /*115200*/, ctsFlowControl: 0}); //, parity:2, bufferSize:255 });
console.log(timeStamp() + ': Attempting connection with ' + theDevice.id);
theDevice.set_receive_handler(receive_handler);
connecting = true;
testTheConnection(startupBatteryCheckCallback);
waitingForInitialConnection = true;
connectionTimeout = setTimeout(connectionTimeOutCallback, 3000);
}
function startupBatteryCheckCallback(result)
{
console.log(timeStamp() + ": got battery level at connect: " + result);
waitingForInitialConnection = false;
connected = true;
connecting = false;
playStartUpTones();
// no watchdog right now. reconnection is too flakey so there is no point
// setupWatchdog();
}
function setupWatchdog()
{
if (poller)
clearInterval(poller);
poller = setInterval(pingBatteryWatchdog, 10000);
}
function timeStamp()
{
return (new Date).toISOString().replace(/z|t/gi,' ').trim();
}
function pingBatteryWatchdog()
{
console.log(timeStamp() + ": pingBatteryWatchdog");
testTheConnection(pingBatteryCheckCallback);
waitingForPing = true;
pingTimeout = setTimeout(pingTimeOutCallback, 3000);
}
function pingTimeOutCallback()
{
if (waitingForPing == true)
{
console.log(timeStamp() + ": Ping timed out");
if (poller)
clearInterval(poller);
connected = false;
alert("The connection to the brick was lost. Check your brick and refresh the page to reconnect. (Don't forget to save your project first!)");
/* if (r == true) {
reconnect();
} else {
// do nothing
}
*/
}
}
function connectionTimeOutCallback()
{
if (waitingForInitialConnection == true)
{
console.log(timeStamp() + ": Initial connection timed out");
connecting = false;
if (potentialDevices.length == 0)
{
alert("Failed to connect to a brick.\n\nMake sure your brick is:\n 1) powered on with Bluetooth On\n 2) named starting with serial (if on a Mac)\n 3) paired with this computer\n 4) the iPhone/iPad/iPod check box is NOT checked\n 5) Do not start a connection to or from the brick in any other way. Let the Scratch plug-in handle it!\n\nand then try reloading the webpage.");
/* if (r == true) {
reconnect();
} else {
// do nothing
}
*/
}
else
{
tryNextDevice();
}
}
}
function pingBatteryCheckCallback(result)
{
console.log(timeStamp() + ": pinged battery level: " + result);
if (pingTimeout)
clearTimeout(pingTimeout);
waitingForPing = false;
if (result < 11 && !warnedAboutBattery)
{
alert("Your battery is getting low.");
warnedAboutBattery = true;
}
}
function testTheConnection(theCallback)
{
window.setTimeout(function() {
readThatBatteryLevel(theCallback);
}, 500);
}
function playStartUpTones()
{
var tonedelay = 1000;
window.setTimeout(function() {
playFreqM2M(262, 100);
}, tonedelay);
window.setTimeout(function() {
playFreqM2M(392, 100);
}, tonedelay+150);
window.setTimeout(function() {
playFreqM2M(523, 100);
}, tonedelay+300);
}
function tryNextDevice()
{
potentialDevices.sort((function(a, b){return b.id.localeCompare(a.id)}));
console.log("devices: " + potentialDevices);
device = potentialDevices.shift();
if (!device)
return;
theDevice = device;
if (!DEBUG_NO_EV3)
{
reconnect();
}
/*
watchdog = setTimeout(function() {
clearInterval(poller);
poller = null;
device.set_receive_handler(null);
device.close();
device = null;
tryNextDevice();
}, 5000);
*/
}
ext._shutdown = function()
{
if (device && connected)
device.close();
if (poller)
clearInterval(poller);
device = null;
};
// create hex string from bytes
function createHexString(arr)
{
var result = "";
for (i in arr)
{
var str = arr[i].toString(16);
str = str.toUpperCase();
str = str.length == 0 ? "00" :
str.length == 1 ? "0" + str :
str.length == 2 ? str :
str.substring(str.length-2, str.length);
result += str;
}
return result;
}
var waitingCallbacks = [[],[],[],[],[],[],[],[], []];
var waitingQueries = [];
var global_touch_pressed = [false, false, false, false,false, false, false, false, false];
var global_ir_button_pressed = [false, false, false, false,false, false, false, false, false];
var global_sensor_queried = [0, 0, 0, 0, 0, 0, 0, 0, 0];
function receive_handler(data)
{
var inputData = new Uint8Array(data);
console.log("received: " + createHexString(inputData));
if (!(connected || connecting))
return;
var query_info = waitingQueries.shift();
var this_is_from_port = query_info[0];
var mode = query_info[1];
var modeType = query_info[2];
var theResult = "";
if (mode == TOUCH_SENSOR)
{
var result = inputData[5];
theResult = (result == 100);
}
else if (mode == COLOR_SENSOR)
{
var num = Math.floor(getFloatResult(inputData));
if (modeType == AMBIENT_INTENSITY || modeType == REFLECTED_INTENSITY)
{
theResult = num;
}
else if (modeType == COLOR_VALUE)
{
if (num >= 0 && num < 7)
theResult = colors[num];
else
theResult = "none";
}
/*
else if (modeType == COLOR_RAW_RGB) // is color_raw encoded as a string, hex, or number?
{
theResult = num; //maybe? probably not, but here's hoping it's this simple.
}
*/
}
else if (mode == IR_SENSOR)
{
if (modeType == IR_PROX)
theResult = getFloatResult(inputData);
else if (modeType == IR_REMOTE)
theResult = getIRButtonNameForCode(getFloatResult(inputData));
}
else if (mode == GYRO_SENSOR)
{
theResult = getFloatResult(inputData);
}
else if (mode == READ_FROM_MOTOR)
{
theResult = getFloatResult(inputData);
}
else if (mode == UIREAD)
{
if (modeType == UIREAD_BATTERY)
{
theResult = inputData[5];
}
}
global_touch_pressed[this_is_from_port] = theResult;
global_sensor_queried[this_is_from_port]--;
global_ir_button_pressed[this_is_from_port] = theResult;
while(callback = waitingCallbacks[this_is_from_port].shift())
{
console.log("result: " + theResult);
callback(theResult);
}
}
function getFloatResult(inputData)
{
var a = new ArrayBuffer(4);
var c = new Float32Array(a);
var arr = new Uint8Array(a);
arr[0] = inputData[5];
arr[1] = inputData[6];
arr[2] = inputData[7]
arr[3] = inputData[8]
return c[0];
}
function getIRButtonNameForCode(inButtonCode)
{
for (var i = 0; i < IRbuttonCodes.length; i++)
{
if (inButtonCode == IRbuttonCodes[i])
{
return IRbuttonNames[i];
}
}
return "";
}
// add counter and byte length encoding prefix. return Uint8Array of final message
function createMessage(str)
{
//console.log("message: " + str);
var length = ((str.length / 2) + 2);
var a = new ArrayBuffer(4);
var c = new Uint16Array(a);
var arr = new Uint8Array(a);
c[1] = counter;
c[0] = length;
counter++;
var mess = new Uint8Array((str.length / 2) + 4);
for (var i = 0; i < 4; i ++)
{
mess[i] = arr[i];
}
for (var i = 0; i < str.length; i += 2)
{
mess[(i / 2) + 4] = window.parseInt(str.substr(i, 2), 16);
}
console.log("sending: " + createHexString(mess));
return mess;
}
// motor port bit field from menu choice string
function getMotorBitsHexString(which)
{
if (which == "A")
return "01";
else if (which == "B")
return "02";
else if (which == "C")
return "04";
else if (which == "D")
return "08";
else if (which == "B+C")
return "06";
else if (which == "A+D")
return "09";
else if (which == "all")
return "0F";
return "00";
}
function getMotorIndex(which)
{
if (which == "A")
return 4;
else if (which == "B")
return 5;
else if (which == "C")
return 6;
else if (which == "D")
return 7;
}
// create 8 bit hex couplet
function hexcouplet(num)
{
var str = num.toString(16);
str = str.toUpperCase();
if (str.length == 1)
{
return "0" + str;
}
return str;
}
// int bytes using weird serialization method
function getPackedOutputHexString(num, lc)
{
// f-ed up nonsensical unsigned bit packing. see cOutputPackParam in c_output-c in EV3 firmware
var a = new ArrayBuffer(2);
var sarr = new Int8Array(a);
var uarr = new Uint8Array(a);
sarr[0] = num & 0x000000FF;
sarr[1] = (num >> 8) & 0x000000FF;
if (lc == 0)
{
var powerbits = uarr[0];
powerbits &= 0x0000003F;
return hexcouplet(powerbits);
}
else if (lc == 1)
{
return "81" + hexcouplet(uarr[0]);
}
else if (lc == 2)
{
return "82" + hexcouplet(uarr[0]) + hexcouplet(uarr[1]);
}
return "00";
}
var DIRECT_COMMAND_PREFIX = "800000";
var DIRECT_COMMAND_REPLY_PREFIX = "000100";
var DIRECT_COMMAND_REPLY_SENSOR_PREFIX = "000400";
var DIRECT_COMMAND_REPLY_MOTOR_PREFIX = "000500";
// direct command opcode/prefixes
var SET_MOTOR_SPEED = "A400";
var SET_MOTOR_STOP = "A300";
var SET_MOTOR_START = "A600";
var NOOP = "0201";
var PLAYTONE = "9401";
var INPUT_DEVICE_READY_SI = "991D";
var READ_SENSOR = "9A00";
var UIREAD = "81"; // opUI_READ
var UIREAD_BATTERY = "12"; // GET_LBATT
var mode0 = "00";
var TOUCH_SENSOR = "10";
var COLOR_SENSOR = "1D";
var ULTRASONIC_SENSOR = "1E";
var ULTRSONIC_CM = "00";
var ULTRSONIC_INCH = "01";
var ULTRSONIC_LISTEN = "02";
var ULTRSONIC_SI_CM = "03";
var ULTRSONIC_SI_INCH = "04";
var ULTRSONIC_DC_CM = "05";
var ULTRSONIC_DC_INCH = "06";
var GYRO_SENSOR = "20";
var GYRO_ANGLE = "00";
var GYRO_RATE = "01";
var GYRO_FAST = "02";
var GYRO_RATE_AND_ANGLE = "03";
var GYRO_CALIBRATION = "04";
var IR_SENSOR = "21";
var IR_PROX = "00";
var IR_SEEKER = "01";
var IR_REMOTE = "02"
var IR_REMOTE_ADVANCE = "03";
var IR_CALIBRATION = "05";
var REFLECTED_INTENSITY = "00";
var AMBIENT_INTENSITY = "01";
var COLOR_VALUE = "02";
var COLOR_RAW_RGB = "04";
var READ_FROM_MOTOR = "FOOBAR";
function sendCommand(commandArray)
{
if ((connected || connecting) && device)
device.send(commandArray.buffer);
}
ext.allMotorsOn = function(which, power)
{
clearDriveTimer();
console.log("motor " + which + " power: " + power);
motor(which, power);
}
function motor(which, power)
{
var motorBitField = getMotorBitsHexString(which);
var powerBits = getPackedOutputHexString(power, 1);
var motorsOnCommand = createMessage(DIRECT_COMMAND_PREFIX + SET_MOTOR_SPEED + motorBitField + powerBits + SET_MOTOR_START + motorBitField);
sendCommand(motorsOnCommand);
}
var frequencies = { "C4" : 262, "D4" : 294, "E4" : 330, "F4" : 349, "G4" : 392, "A4" : 440, "B4" : 494, "C5" : 523, "D5" : 587, "E5" : 659, "F5" : 698, "G5" : 784, "A5" : 880, "B5" : 988, "C6" : 1047, "D6" : 1175, "E6" : 1319, "F6" : 1397, "G6" : 1568, "A6" : 1760, "B6" : 1976, "C#4" : 277, "D#4" : 311, "F#4" : 370, "G#4" : 415, "A#4" : 466, "C#5" : 554, "D#5" : 622, "F#5" : 740, "G#5" : 831, "A#5" : 932, "C#6" : 1109, "D#6" : 1245, "F#6" : 1480, "G#6" : 1661, "A#6" : 1865 };
var colors = [ "none", "black", "blue", "green", "yellow", "red", "white"];
var IRbuttonNames = ['Top Left', 'Bottom Left', 'Top Right', 'Bottom Right', 'Top Bar'];
var IRbuttonCodes = [1, 2, 3, 4, 9];
ext.playTone = function(tone, duration, callback)
{
var freq = frequencies[tone];
console.log("playTone " + tone + " duration: " + duration + " freq: " + freq);
var volume = 100;
var volString = getPackedOutputHexString(volume, 1);
var freqString = getPackedOutputHexString(freq, 2);
var durString = getPackedOutputHexString(duration, 2);
var toneCommand = createMessage(DIRECT_COMMAND_PREFIX + PLAYTONE + volString + freqString + durString);
sendCommand(toneCommand);
window.setTimeout(function() {
driveTimer = 0;
callback();
}, duration);
}
ext.playFreq = function(freq, duration, callback)
{
console.log("playFreq duration: " + duration + " freq: " + freq);
var volume = 100;
var volString = getPackedOutputHexString(volume, 1);
var freqString = getPackedOutputHexString(freq, 2);
var durString = getPackedOutputHexString(duration, 2);
var toneCommand = createMessage(DIRECT_COMMAND_PREFIX + PLAYTONE + volString + freqString + durString);
sendCommand(toneCommand);
window.setTimeout(function() {
driveTimer = 0;
callback();
}, duration);
}
function playFreqM2M(freq, duration)
{
console.log("playFreqM2M duration: " + duration + " freq: " + freq);
var volume = 100;
var volString = getPackedOutputHexString(volume, 1);
var freqString = getPackedOutputHexString(freq, 2);
var durString = getPackedOutputHexString(duration, 2);
var toneCommand = createMessage(DIRECT_COMMAND_PREFIX + PLAYTONE + volString + freqString + durString);
sendCommand(toneCommand);
}
function clearDriveTimer()
{
if (driveTimer)
clearInterval(driveTimer);
driveTimer = 0;
if (driveCallback)
driveCallback();
driveCallback = 0;
}
ext.allMotorsOff = function(how)
{
clearDriveTimer();
motorsStop(how);
}
var driveTimer = 0;
driveCallback = 0;
function motorsStop(how)
{
console.log("motorsStop");
var motorBitField = getMotorBitsHexString("all");
var howHex = '00';
if (how == 'break')
howHex = '01';
var motorsOffCommand = createMessage(DIRECT_COMMAND_PREFIX + SET_MOTOR_STOP + motorBitField + howHex);
sendCommand(motorsOffCommand);
}
function sendNOP()
{
var nopCommand = createMessage(DIRECT_COMMAND_PREFIX + NOOP);
}
ext.steeringControl = function(ports, what, duration, callback)
{
clearDriveTimer();
var defaultPower = 50;
if (what == 'forward')
{
motor(ports, defaultPower);
}
else if (what == 'reverse')
{
motor(ports, -1 * defaultPower);
}
else
{
var p = ports.split("+");
if (what == 'left')
{
motor(p[0], -1 * defaultPower);
motor(p[1], defaultPower);
}
else if (what == 'right')
{
motor(p[1], -1 * defaultPower);
motor(p[0], defaultPower);
}
}
driveCallback = callback;
driveTimer = window.setTimeout(function()
{
if (duration > 0) // allow zero duration to run motors asynchronously
{
motorsStop('coast');
}
callback();
} , duration*1000);
}
function readTouchSensor(portInt)
{
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromSensor(portInt, TOUCH_SENSOR, mode0);
}
}
function readIRRemoteSensor(portInt)
{
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromSensor2(portInt, IR_SENSOR, IR_REMOTE);
}
}
ext.whenButtonPressed = function(port)
{
if (!device || !connected)
return false;
var portInt = parseInt(port) - 1;
readTouchSensor(portInt);
return global_touch_pressed[portInt];
}
ext.whenRemoteButtonPressed = function(IRbutton, port)
{
if (!device || !connected)
return false;
var portInt = parseInt(port) - 1;
readIRRemoteSensor(portInt);
return (global_ir_button_pressed[portInt] == IRbutton);
}
ext.readTouchSensorPort = function(port, callback)
{
var portInt = parseInt(port) - 1;
waitingCallbacks[portInt].push(callback);
readTouchSensor(portInt);
}
ext.readColorSensorPort = function(port, mode, callback)
{
var modeCode = AMBIENT_INTENSITY;
if (mode == 'reflected') { modeCode = REFLECTED_INTENSITY; }
if (mode == 'color') { modeCode = COLOR_VALUE; }
if (mode == 'RGBcolor') { modeCode = COLOR_RAW_RGB; }
var portInt = parseInt(port) - 1;
waitingCallbacks[portInt].push(callback);
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromSensor2(portInt, COLOR_SENSOR, modeCode);
}
}
ext.readGyroPort = function(mode, port, callback)
{
var modeCode = GYRO_ANGLE;
if (mode == 'rate') { modeCode = GYRO_RATE; }
var portInt = parseInt(port) - 1;
waitingCallbacks[portInt].push(callback);
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromSensor2(portInt, GYRO_SENSOR, modeCode);
}
}
ext.readDistanceSensorPort = function(port, callback)
{
var portInt = parseInt(port) - 1;
waitingCallbacks[portInt].push(callback);
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromSensor2(portInt, IR_SENSOR, IR_PROX);
}
}
ext.readRemoteButtonPort = function(port, callback)
{
var portInt = parseInt(port) - 1;
waitingCallbacks[portInt].push(callback);
readIRRemoteSensor(portInt);
}
function readFromSensor(port, type, mode)
{
waitingQueries.push([port, type, mode]);
var readCommand = createMessage(DIRECT_COMMAND_REPLY_PREFIX +
READ_SENSOR +
hexcouplet(port) +
type +
mode + "60");
sendCommand(readCommand);
}
function readFromSensor2(port, type, mode)
{
waitingQueries.push([port, type, mode]);
var readCommand = createMessage(DIRECT_COMMAND_REPLY_SENSOR_PREFIX +
INPUT_DEVICE_READY_SI + "00" + // layer
hexcouplet(port) + "00" + // type
mode +
"0160"); // result stuff
sendCommand(readCommand);
}
ext.readFromMotor = function(mmode, which, callback)
{
var portInt = getMotorIndex(which);
var mode = "01"; // position
if (mmode == 'speed')
mode = "02";
waitingCallbacks[portInt].push(callback);
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
readFromAMotor(portInt, READ_FROM_MOTOR, mode);
}
}
// this routine is awful similar to readFromSensor2...
function readFromAMotor(port, type, mode)
{
waitingQueries.push([port, type, mode]);
var readCommand = createMessage(DIRECT_COMMAND_REPLY_SENSOR_PREFIX +
INPUT_DEVICE_READY_SI + "00" + // layer
hexcouplet(port+12) + "00" + // type
mode +
"0160"); // result stuff
sendCommand(readCommand);
}
ext.readBatteryLevel = function(callback)
{
readThatBatteryLevel(callback);
}
function readThatBatteryLevel(callback)
{
var portInt = 8; // bogus port number
waitingCallbacks[portInt].push(callback);
if (global_sensor_queried[portInt] == 0)
{
global_sensor_queried[portInt]++;
UIRead(portInt, UIREAD_BATTERY);
}
}
ext.reconnectToDevice = function()
{
reconnect();
}
function UIRead(port, subtype)
{
waitingQueries.push([port, UIREAD, subtype]);
var readCommand = createMessage(DIRECT_COMMAND_REPLY_PREFIX +
UIREAD + subtype +
"60"); // result stuff
sendCommand(readCommand);
}
// Block and block menu descriptions
var descriptor = {
blocks: [
['w', 'drive %m.dualMotors %m.turnStyle %n seconds', 'steeringControl', 'B+C', 'forward', 3],
[' ', 'start motor %m.whichMotorPort speed %n', 'allMotorsOn', 'B+C', 100],
[' ', 'stop all motors %m.breakCoast', 'allMotorsOff', 'break'],
['h', 'when button pressed on port %m.whichInputPort', 'whenButtonPressed','1'],
['h', 'when IR remote %m.buttons pressed port %m.whichInputPort', 'whenRemoteButtonPressed','Top Left', '1'],
['R', 'button pressed %m.whichInputPort', 'readTouchSensorPort', '1'],
['w', 'play note %m.note duration %n ms', 'playTone', 'C5', 500],
['w', 'play frequency %n duration %n ms', 'playFreq', '262', 500],
['R', 'light sensor %m.whichInputPort %m.lightSensorMode', 'readColorSensorPort', '1', 'color'],
['R', 'measure distance %m.whichInputPort', 'readDistanceSensorPort', '1'],
['R', 'remote button %m.whichInputPort', 'readRemoteButtonPort', '1'],
// ['R', 'gyro %m.gyroMode %m.whichInputPort', 'readGyroPort', 'angle', '1'],
['R', 'motor %m.motorInputMode %m.whichMotorIndividual', 'readFromMotor', 'position', 'B'],
// ['R', 'battery level', 'readBatteryLevel'],
// [' ', 'reconnect', 'reconnectToDevice'],
],
menus: {
whichMotorPort: ['A', 'B', 'C', 'D', 'A+D', 'B+C'],
whichMotorIndividual: ['A', 'B', 'C', 'D'],
dualMotors: ['A+D', 'B+C'],
turnStyle: ['forward', 'reverse', 'right', 'left'],
breakCoast: ['break', 'coast'],
lightSensorMode: ['reflected', 'ambient', 'color'],
motorInputMode: ['position', 'speed'],
gyroMode: ['angle', 'rate'],
note:["C4","D4","E4","F4","G4","A4","B4","C5","D5","E5","F5","G5","A5","B5","C6","D6","E6","F6","G6","A6","B6","C#4","D#4","F#4","G#4","A#4","C#5","D#5","F#5","G#5","A#5","C#6","D#6","F#6","G#6","A#6"],
whichInputPort: ['1', '2', '3', '4'],
buttons: IRbuttonNames,
},
};
var serial_info = {type: 'serial'};
ScratchExtensions.register('EV3 Control', descriptor, ext, serial_info);
console.log('registered: ');
})({});