-
Notifications
You must be signed in to change notification settings - Fork 147
/
firmata.js
2098 lines (1776 loc) · 56.6 KB
/
firmata.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
"use strict";
// Global Environment Dependencies
/* istanbul ignore if */
/* jshint -W079 */
if (!Object.assign || !Map) {
require("es6-shim");
}
// Built-in Dependencies
var Emitter = require("events").EventEmitter;
// Internal Dependencies
var Encoder7Bit = require("./encoder7bit");
var OneWireUtils = require("./onewireutils");
var com = require("./com");
// Program specifics
var i2cActive = new Map();
/**
* constants
*/
var ANALOG_MAPPING_QUERY = 0x69;
var ANALOG_MAPPING_RESPONSE = 0x6A;
var ANALOG_MESSAGE = 0xE0;
var CAPABILITY_QUERY = 0x6B;
var CAPABILITY_RESPONSE = 0x6C;
var DIGITAL_MESSAGE = 0x90;
var END_SYSEX = 0xF7;
var EXTENDED_ANALOG = 0x6F;
var I2C_CONFIG = 0x78;
var I2C_REPLY = 0x77;
var I2C_REQUEST = 0x76;
var I2C_READ_MASK = 0x18; // 0b00011000
var I2C_END_TX_MASK = 0x40; // 0b01000000
var ONEWIRE_CONFIG_REQUEST = 0x41;
var ONEWIRE_DATA = 0x73;
var ONEWIRE_DELAY_REQUEST_BIT = 0x10;
var ONEWIRE_READ_REPLY = 0x43;
var ONEWIRE_READ_REQUEST_BIT = 0x08;
var ONEWIRE_RESET_REQUEST_BIT = 0x01;
var ONEWIRE_SEARCH_ALARMS_REPLY = 0x45;
var ONEWIRE_SEARCH_ALARMS_REQUEST = 0x44;
var ONEWIRE_SEARCH_REPLY = 0x42;
var ONEWIRE_SEARCH_REQUEST = 0x40;
var ONEWIRE_WITHDATA_REQUEST_BITS = 0x3C;
var ONEWIRE_WRITE_REQUEST_BIT = 0x20;
var PIN_MODE = 0xF4;
var PIN_STATE_QUERY = 0x6D;
var PIN_STATE_RESPONSE = 0x6E;
var PING_READ = 0x75;
var PULSE_IN = 0x74;
var PULSE_OUT = 0x73;
var QUERY_FIRMWARE = 0x79;
var REPORT_ANALOG = 0xC0;
var REPORT_DIGITAL = 0xD0;
var REPORT_VERSION = 0xF9;
var SAMPLING_INTERVAL = 0x7A;
var SERVO_CONFIG = 0x70;
var SERIAL_MESSAGE = 0x60;
var SERIAL_CONFIG = 0x10;
var SERIAL_WRITE = 0x20;
var SERIAL_READ = 0x30;
var SERIAL_REPLY = 0x40;
var SERIAL_CLOSE = 0x50;
var SERIAL_FLUSH = 0x60;
var SERIAL_LISTEN = 0x70;
var START_SYSEX = 0xF0;
var STEPPER = 0x72;
var STRING_DATA = 0x71;
var SYSTEM_RESET = 0xFF;
var MAX_PIN_COUNT = 128;
/**
* MIDI_RESPONSE contains functions to be called when we receive a MIDI message from the arduino.
* used as a switch object as seen here http://james.padolsey.com/javascript/how-to-avoid-switch-case-syndrome/
* @private
*/
var MIDI_RESPONSE = {};
/**
* Handles a REPORT_VERSION response and emits the reportversion event.
* @private
* @param {Board} board the current arduino board we are working with.
*/
MIDI_RESPONSE[REPORT_VERSION] = function(board) {
board.version.major = board.currentBuffer[1];
board.version.minor = board.currentBuffer[2];
board.emit("reportversion");
};
/**
* Handles a ANALOG_MESSAGE response and emits "analog-read" and "analog-read-"+n events where n is the pin number.
* @private
* @param {Board} board the current arduino board we are working with.
*/
MIDI_RESPONSE[ANALOG_MESSAGE] = function(board) {
var pin = board.currentBuffer[0] & 0x0F;
var value = board.currentBuffer[1] | (board.currentBuffer[2] << 7);
/* istanbul ignore else */
if (board.pins[board.analogPins[pin]]) {
board.pins[board.analogPins[pin]].value = value;
}
board.emit("analog-read-" + pin, value);
board.emit("analog-read", {
pin: pin,
value: value,
});
};
/**
* Handles a DIGITAL_MESSAGE response and emits:
* "digital-read"
* "digital-read-"+n
*
* Where n is the pin number.
*
* @private
* @param {Board} board the current arduino board we are working with.
*/
MIDI_RESPONSE[DIGITAL_MESSAGE] = function(board) {
var port = (board.currentBuffer[0] & 0x0F);
var portValue = board.currentBuffer[1] | (board.currentBuffer[2] << 7);
for (var i = 0; i < 8; i++) {
var pinNumber = 8 * port + i;
var pin = board.pins[pinNumber];
var bit = 1 << i;
if (pin && (pin.mode === board.MODES.INPUT || pin.mode === board.MODES.PULLUP)) {
pin.value = (portValue >> (i & 0x07)) & 0x01;
if (pin.value) {
board.ports[port] |= bit;
} else {
board.ports[port] &= ~bit;
}
board.emit("digital-read-" + pinNumber, pin.value);
board.emit("digital-read", {
pin: pinNumber,
value: pin.value,
});
}
}
};
/**
* SYSEX_RESPONSE contains functions to be called when we receive a SYSEX message from the arduino.
* used as a switch object as seen here http://james.padolsey.com/javascript/how-to-avoid-switch-case-syndrome/
* @private
*/
var SYSEX_RESPONSE = {};
/**
* Handles a QUERY_FIRMWARE response and emits the "queryfirmware" event
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[QUERY_FIRMWARE] = function(board) {
var length = board.currentBuffer.length - 2;
var buffer = new Buffer(Math.round((length - 4) / 2));
var byte = 0;
var offset = 0;
for (var i = 4; i < length; i += 2) {
byte = ((board.currentBuffer[i] & 0x7F) | ((board.currentBuffer[i + 1] & 0x7F) << 7)) & 0xFF;
buffer.writeUInt8(byte, offset++);
}
board.firmware = {
name: buffer.toString(),
version: {
major: board.currentBuffer[2],
minor: board.currentBuffer[3],
},
};
board.emit("queryfirmware");
};
/**
* Handles a CAPABILITY_RESPONSE response and emits the "capability-query" event
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[CAPABILITY_RESPONSE] = function(board) {
var mode, resolution;
var modes = Object.keys(board.MODES).map(function(key) {
return board.MODES[key];
});
var capability = 0;
function supportedModes(capability) {
return modes.reduce(function(accum, mode, index) {
if (capability & (1 << mode)) {
accum.push(mode);
}
return accum;
}, []);
}
// Only create pins if none have been previously created on the instance.
if (!board.pins.length) {
for (var i = 2, n = 0; i < board.currentBuffer.length - 1; i++) {
if (board.currentBuffer[i] === 127) {
board.pins.push({
supportedModes: supportedModes(capability),
mode: undefined,
value: 0,
report: 1,
});
capability = 0;
n = 0;
continue;
}
if (n === 0) {
mode = board.currentBuffer[i];
resolution = (1 << board.currentBuffer[i + 1]) - 1;
capability |= (1 << mode);
// ADC Resolution of Analog Inputs
if (mode === board.MODES.ANALOG && board.RESOLUTION.ADC === null) {
board.RESOLUTION.ADC = resolution;
}
// PWM Resolution of PWM Outputs
if (mode === board.MODES.PWM && board.RESOLUTION.PWM === null) {
board.RESOLUTION.PWM = resolution;
}
// DAC Resolution of DAC Outputs
// if (mode === board.MODES.DAC && board.RESOLUTION.DAC === null) {
// board.RESOLUTION.DAC = resolution;
// }
}
n ^= 1;
}
}
board.emit("capability-query");
};
/**
* Handles a PIN_STATE response and emits the 'pin-state-'+n event where n is the pin number.
*
* Note about pin state: For output modes, the state is any value that has been
* previously written to the pin. For input modes, the state is the status of
* the pullup resistor.
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[PIN_STATE_RESPONSE] = function (board) {
var pin = board.currentBuffer[2];
board.pins[pin].mode = board.currentBuffer[3];
board.pins[pin].state = board.currentBuffer[4];
if (board.currentBuffer.length > 6) {
board.pins[pin].state |= (board.currentBuffer[5] << 7);
}
if (board.currentBuffer.length > 7) {
board.pins[pin].state |= (board.currentBuffer[6] << 14);
}
board.emit("pin-state-" + pin);
};
/**
* Handles a ANALOG_MAPPING_RESPONSE response and emits the "analog-mapping-query" event.
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[ANALOG_MAPPING_RESPONSE] = function(board) {
var pin = 0;
var currentValue;
for (var i = 2; i < board.currentBuffer.length - 1; i++) {
currentValue = board.currentBuffer[i];
board.pins[pin].analogChannel = currentValue;
if (currentValue !== 127) {
board.analogPins.push(pin);
}
pin++;
}
board.emit("analog-mapping-query");
};
/**
* Handles a I2C_REPLY response and emits the "I2C-reply-"+n event where n is the slave address of the I2C device.
* The event is passed the buffer of data sent from the I2C Device
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[I2C_REPLY] = function(board) {
var reply = [];
var address = (board.currentBuffer[2] & 0x7F) | ((board.currentBuffer[3] & 0x7F) << 7);
var register = (board.currentBuffer[4] & 0x7F) | ((board.currentBuffer[5] & 0x7F) << 7);
for (var i = 6, length = board.currentBuffer.length - 1; i < length; i += 2) {
reply.push(board.currentBuffer[i] | (board.currentBuffer[i + 1] << 7));
}
board.emit("I2C-reply-" + address + "-" + register, reply);
};
SYSEX_RESPONSE[ONEWIRE_DATA] = function(board) {
var subCommand = board.currentBuffer[2];
if (!SYSEX_RESPONSE[subCommand]) {
return;
}
SYSEX_RESPONSE[subCommand](board);
};
SYSEX_RESPONSE[ONEWIRE_SEARCH_REPLY] = function(board) {
var pin = board.currentBuffer[3];
var replyBuffer = board.currentBuffer.slice(4, board.currentBuffer.length - 1);
board.emit("1-wire-search-reply-" + pin, OneWireUtils.readDevices(replyBuffer));
};
SYSEX_RESPONSE[ONEWIRE_SEARCH_ALARMS_REPLY] = function(board) {
var pin = board.currentBuffer[3];
var replyBuffer = board.currentBuffer.slice(4, board.currentBuffer.length - 1);
board.emit("1-wire-search-alarms-reply-" + pin, OneWireUtils.readDevices(replyBuffer));
};
SYSEX_RESPONSE[ONEWIRE_READ_REPLY] = function(board) {
var encoded = board.currentBuffer.slice(4, board.currentBuffer.length - 1);
var decoded = Encoder7Bit.from7BitArray(encoded);
var correlationId = (decoded[1] << 8) | decoded[0];
board.emit("1-wire-read-reply-" + correlationId, decoded.slice(2));
};
/**
* Handles a STRING_DATA response and logs the string to the console.
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[STRING_DATA] = function(board) {
var string = new Buffer(board.currentBuffer.slice(2, -1)).toString("utf8").replace(/\0/g, "");
board.emit("string", string);
};
/**
* Response from pingRead
*/
SYSEX_RESPONSE[PING_READ] = function(board) {
var pin = (board.currentBuffer[2] & 0x7F) | ((board.currentBuffer[3] & 0x7F) << 7);
var durationBuffer = [
(board.currentBuffer[4] & 0x7F) | ((board.currentBuffer[5] & 0x7F) << 7),
(board.currentBuffer[6] & 0x7F) | ((board.currentBuffer[7] & 0x7F) << 7),
(board.currentBuffer[8] & 0x7F) | ((board.currentBuffer[9] & 0x7F) << 7),
(board.currentBuffer[10] & 0x7F) | ((board.currentBuffer[11] & 0x7F) << 7),
];
var duration = ((durationBuffer[0] << 24) +
(durationBuffer[1] << 16) +
(durationBuffer[2] << 8) +
(durationBuffer[3]));
board.emit("ping-read-" + pin, duration);
};
/**
* Handles the message from a stepper completing move
* @param {Board} board
*/
SYSEX_RESPONSE[STEPPER] = function(board) {
var deviceNum = board.currentBuffer[2];
board.emit("stepper-done-" + deviceNum, true);
};
/**
* Handles a SERIAL_REPLY response and emits the "serial-data-"+n event where n is the id of the
* serial port.
* The event is passed the buffer of data sent from the serial device
* @private
* @param {Board} board the current arduino board we are working with.
*/
SYSEX_RESPONSE[SERIAL_MESSAGE] = function(board) {
var command = board.currentBuffer[2] & 0xF0;
var portId = board.currentBuffer[2] & 0x0F;
var reply = [];
/* istanbul ignore else */
if (command === SERIAL_REPLY) {
for (var i = 3, len = board.currentBuffer.length; i < len - 1; i += 2) {
reply.push((board.currentBuffer[i + 1] << 7) | board.currentBuffer[i]);
}
board.emit("serial-data-" + portId, reply);
}
};
/**
* @class The Board object represents an arduino board.
* @augments EventEmitter
* @param {String} port This is the serial port the arduino is connected to.
* @param {function} function A function to be called when the arduino is ready to communicate.
* @property MODES All the modes available for pins on this arduino board.
* @property I2C_MODES All the I2C modes available.
* @property SERIAL_MODES All the Serial modes available.
* @property SERIAL_PORT_ID ID values to pass as the portId parameter when calling serialConfig.
* @property HIGH A constant to set a pins value to HIGH when the pin is set to an output.
* @property LOW A constant to set a pins value to LOW when the pin is set to an output.
* @property pins An array of pin object literals.
* @property analogPins An array of analog pins and their corresponding indexes in the pins array.
* @property version An object indicating the major and minor version of the firmware currently running.
* @property firmware An object indicateon the name, major and minor version of the firmware currently running.
* @property currentBuffer An array holding the current bytes received from the arduino.
* @property {SerialPort} sp The serial port object used to communicate with the arduino.
*/
function Board(port, options, callback) {
if (typeof options === "function" || typeof options === "undefined") {
callback = options;
options = {};
}
if (!(this instanceof Board)) {
return new Board(port, options, callback);
}
Emitter.call(this);
var board = this;
var defaults = {
reportVersionTimeout: 5000,
samplingInterval: 19,
serialport: {
baudRate: 57600,
// https://github.com/node-serialport/node-serialport/blob/5.0.0/UPGRADE_GUIDE.md#open-options
highWaterMark: 256,
},
};
if (options.bufferSize) {
options.highWaterMark = options.bufferSize;
}
var settings = Object.assign({}, defaults, options);
this.isReady = false;
this.MODES = {
INPUT: 0x00,
OUTPUT: 0x01,
ANALOG: 0x02,
PWM: 0x03,
SERVO: 0x04,
SHIFT: 0x05,
I2C: 0x06,
ONEWIRE: 0x07,
STEPPER: 0x08,
SERIAL: 0x0A,
PULLUP: 0x0B,
IGNORE: 0x7F,
PING_READ: 0x75,
UNKOWN: 0x10,
};
this.I2C_MODES = {
WRITE: 0,
READ: 1,
CONTINUOUS_READ: 2,
STOP_READING: 3,
};
this.STEPPER = {
TYPE: {
DRIVER: 1,
TWO_WIRE: 2,
FOUR_WIRE: 4,
},
RUNSTATE: {
STOP: 0,
ACCEL: 1,
DECEL: 2,
RUN: 3,
},
DIRECTION: {
CCW: 0,
CW: 1,
},
};
this.SERIAL_MODES = {
CONTINUOUS_READ: 0x00,
STOP_READING: 0x01,
};
// ids for hardware and software serial ports on the board
this.SERIAL_PORT_IDs = {
HW_SERIAL0: 0x00,
HW_SERIAL1: 0x01,
HW_SERIAL2: 0x02,
HW_SERIAL3: 0x03,
SW_SERIAL0: 0x08,
SW_SERIAL1: 0x09,
SW_SERIAL2: 0x10,
SW_SERIAL3: 0x11,
// Default can be used by depender libraries to key on a
// single property name when negotiating ports.
//
// Firmata elects SW_SERIAL0: 0x08 as its DEFAULT
DEFAULT: 0x08,
};
// map to the pin resolution value in the capability query response
this.SERIAL_PIN_TYPES = {
RES_RX0: 0x00,
RES_TX0: 0x01,
RES_RX1: 0x02,
RES_TX1: 0x03,
RES_RX2: 0x04,
RES_TX2: 0x05,
RES_RX3: 0x06,
RES_TX3: 0x07,
};
this.RESOLUTION = {
ADC: null,
DAC: null,
PWM: null,
};
this.HIGH = 1;
this.LOW = 0;
this.pins = [];
this.ports = Array(16).fill(0);
this.analogPins = [];
this.version = {};
this.firmware = {};
this.currentBuffer = [];
this.versionReceived = false;
this.name = "Firmata";
this.settings = settings;
this.pending = 0;
if (typeof port === "object") {
this.transport = port;
} else {
this.transport = new com.SerialPort(port, settings.serialport);
}
// For backward compat
this.sp = this.transport;
this.transport.on("close", function(event) {
// https://github.com/node-serialport/node-serialport/blob/5.0.0/UPGRADE_GUIDE.md#opening-and-closing
if (event && event.disconnect && event.disconnected) {
this.emit("disconnect");
return;
}
this.emit("close");
}.bind(this));
this.transport.on("open", function(event) {
this.emit("open", event);
// Legacy
this.emit("connect", event);
}.bind(this));
this.transport.on("error", function(error) {
if (!this.isReady && typeof callback === "function") {
callback(error);
} else {
this.emit("error", error);
}
}.bind(this));
this.transport.on("data", function(data) {
var byte, currByte, response, first, last, handler;
for (var i = 0; i < data.length; i++) {
byte = data[i];
// we dont want to push 0 as the first byte on our buffer
if (this.currentBuffer.length === 0 && byte === 0) {
continue;
} else {
this.currentBuffer.push(byte);
first = this.currentBuffer[0];
last = this.currentBuffer[this.currentBuffer.length - 1];
// [START_SYSEX, ... END_SYSEX]
if (first === START_SYSEX && last === END_SYSEX) {
handler = SYSEX_RESPONSE[this.currentBuffer[1]];
// Ensure a valid SYSEX_RESPONSE handler exists
// Only process these AFTER the REPORT_VERSION
// message has been received and processed.
if (handler && this.versionReceived) {
handler(this);
}
// It is possible for the board to have
// existing activity from a previous run
// that will leave any of the following
// active:
//
// - ANALOG_MESSAGE
// - SERIAL_READ
// - I2C_REQUEST, CONTINUOUS_READ
//
// This means that we will receive these
// messages on transport "open", before any
// handshake can occur. We MUST assert
// that we will only process this buffer
// AFTER the REPORT_VERSION message has
// been received. Not doing so will result
// in the appearance of the program "hanging".
//
// Since we cannot do anything with this data
// until _after_ REPORT_VERSION, discard it.
//
this.currentBuffer.length = 0;
} else if (first === START_SYSEX && (this.currentBuffer.length > 0)) {
// we have a new command after an incomplete sysex command
currByte = data[i];
if (currByte > 0x7F) {
this.currentBuffer.length = 0;
this.currentBuffer.push(currByte);
}
} else {
/* istanbul ignore else */
if (first !== START_SYSEX) {
// Check if data gets out of sync: first byte in buffer
// must be a valid response if not START_SYSEX
// Identify response on first byte
response = first < START_SYSEX ? (first & START_SYSEX) : first;
// Check if the first byte is possibly
// a valid MIDI_RESPONSE (handler)
/* istanbul ignore else */
if (response !== REPORT_VERSION &&
response !== ANALOG_MESSAGE &&
response !== DIGITAL_MESSAGE) {
// If not valid, then we received garbage and can discard
// whatever bytes have been been queued.
this.currentBuffer.length = 0;
}
}
}
// There are 3 bytes in the buffer and the first is not START_SYSEX:
// Might have a MIDI Command
if (this.currentBuffer.length === 3 && first !== START_SYSEX) {
// response bytes under 0xF0 we have a multi byte operation
response = first < START_SYSEX ? (first & START_SYSEX) : first;
/* istanbul ignore else */
if (MIDI_RESPONSE[response]) {
// It's ok that this.versionReceived will be set to
// true every time a valid MIDI_RESPONSE is received.
// This condition is necessary to ensure that REPORT_VERSION
// is called first.
if (this.versionReceived || first === REPORT_VERSION) {
this.versionReceived = true;
MIDI_RESPONSE[response](this);
}
this.currentBuffer.length = 0;
} else {
// A bad serial read must have happened.
// Reseting the buffer will allow recovery.
this.currentBuffer.length = 0;
}
}
}
}
}.bind(this));
// if we have not received the version within the alotted
// time specified by the reportVersionTimeout (user or default),
// then send an explicit request for it.
this.reportVersionTimeoutId = setTimeout(function() {
/* istanbul ignore else */
if (this.versionReceived === false) {
this.reportVersion(function() {});
this.queryFirmware(function() {});
}
}.bind(this), settings.reportVersionTimeout);
function ready() {
board.isReady = true;
board.emit("ready");
/* istanbul ignore else */
if (typeof callback === "function") {
callback();
}
}
// Await the reported version.
this.once("reportversion", function() {
clearTimeout(this.reportVersionTimeoutId);
this.versionReceived = true;
this.once("queryfirmware", function() {
// Only preemptively set the sampling interval if `samplingInterval`
// property was _explicitly_ set as a constructor option.
if (options.samplingInterval !== undefined) {
this.setSamplingInterval(options.samplingInterval);
}
if (settings.skipCapabilities) {
this.analogPins = settings.analogPins || this.analogPins;
this.pins = settings.pins || this.pins;
/* istanbul ignore else */
if (!this.pins.length) {
for (var i = 0; i < (settings.pinCount || MAX_PIN_COUNT); i++) {
var analogChannel = this.analogPins.indexOf(i);
if (analogChannel < 0) {
analogChannel = 127;
}
this.pins.push({supportedModes: [], analogChannel: analogChannel});
}
}
// If the capabilities query is skipped,
// default resolution values will be used.
//
// Based on ATmega328/P
//
this.RESOLUTION.ADC = 0x3FF;
this.RESOLUTION.PWM = 0x0FF;
ready();
} else {
this.queryCapabilities(function() {
this.queryAnalogMapping(ready);
});
}
});
});
}
Board.prototype = Object.create(Emitter.prototype, {
constructor: {
value: Board,
},
});
/**
* writeToTransport Due to the non-blocking behaviour of transport write
* operations, dependent programs need a way to know
* when all writes are complete. Every write increments
* a `pending` value, when the write operation has
* completed, the `pending` value is decremented.
*
* @param {Board} board An active Board instance
* @param {Array} data An array of 8 and 7 bit values that will be
* wrapped in a Buffer and written to the transport.
*/
function writeToTransport(board, data) {
board.pending++;
board.transport.write(new Buffer(data), function() {
board.pending--;
});
}
/**
* Asks the arduino to tell us its version.
* @param {function} callback A function to be called when the arduino has reported its version.
*/
Board.prototype.reportVersion = function(callback) {
this.once("reportversion", callback);
writeToTransport(this, [REPORT_VERSION]);
};
/**
* Asks the arduino to tell us its firmware version.
* @param {function} callback A function to be called when the arduino has reported its firmware version.
*/
Board.prototype.queryFirmware = function(callback) {
this.once("queryfirmware", callback);
writeToTransport(this, [START_SYSEX, QUERY_FIRMWARE, END_SYSEX]);
};
/**
* Asks the arduino to read analog data. Turn on reporting for this pin.
* @param {number} pin The pin to read analog data
* @param {function} callback A function to call when we have the analag data.
*/
Board.prototype.analogRead = function(pin, callback) {
this.reportAnalogPin(pin, 1);
this.addListener("analog-read-" + pin, callback);
};
/**
* Write a PWM value Asks the arduino to write an analog message.
* @param {number} pin The pin to write analog data to.
* @param {nubmer} value The data to write to the pin between 0 and this.RESOLUTION.PWM.
*/
Board.prototype.pwmWrite = function(pin, value) {
var data = [];
this.pins[pin].value = value;
if (pin > 15) {
data[0] = START_SYSEX;
data[1] = EXTENDED_ANALOG;
data[2] = pin;
data[3] = value & 0x7F;
data[4] = (value >> 7) & 0x7F;
if (value > 0x00004000) {
data[data.length] = (value >> 14) & 0x7F;
}
if (value > 0x00200000) {
data[data.length] = (value >> 21) & 0x7F;
}
if (value > 0x10000000) {
data[data.length] = (value >> 28) & 0x7F;
}
data[data.length] = END_SYSEX;
} else {
data.push(ANALOG_MESSAGE | pin, value & 0x7F, (value >> 7) & 0x7F);
}
writeToTransport(this, data);
};
Board.prototype.analogWrite = Board.prototype.pwmWrite;
/**
* Set a pin to SERVO mode with an explicit PWM range.
*
* @param {number} pin The pin the servo is connected to
* @param {number} min A 14-bit signed int.
* @param {number} max A 14-bit signed int.
*/
Board.prototype.servoConfig = function(pin, min, max) {
var temp;
if (typeof pin === "object" && pin !== null) {
temp = pin;
pin = temp.pin;
min = temp.min;
max = temp.max;
}
if (typeof pin === "undefined") {
throw new Error("servoConfig: pin must be specified");
}
if (typeof min === "undefined") {
throw new Error("servoConfig: min must be specified");
}
if (typeof max === "undefined") {
throw new Error("servoConfig: max must be specified");
}
// [0] START_SYSEX (0xF0)
// [1] SERVO_CONFIG (0x70)
// [2] pin number (0-127)
// [3] minPulse LSB (0-6)
// [4] minPulse MSB (7-13)
// [5] maxPulse LSB (0-6)
// [6] maxPulse MSB (7-13)
// [7] END_SYSEX (0xF7)
this.pins[pin].mode = this.MODES.SERVO;
writeToTransport(this, [
START_SYSEX,
SERVO_CONFIG,
pin,
min & 0x7F,
(min >> 7) & 0x7F,
max & 0x7F,
(max >> 7) & 0x7F,
END_SYSEX,
]);
};
/**
* Asks the arduino to move a servo
* @param {number} pin The pin the servo is connected to
* @param {number} value The degrees to move the servo to.
*/
Board.prototype.servoWrite = function(pin, value) {
// Values less than 544 will be treated as angles in degrees
// (valid values in microseconds are handled as microseconds)
this.analogWrite.apply(this, arguments);
};
/**
* Asks the arduino to set the pin to a certain mode.
* @param {number} pin The pin you want to change the mode of.
* @param {number} mode The mode you want to set. Must be one of board.MODES
*/
Board.prototype.pinMode = function(pin, mode) {
this.pins[pin].mode = mode;
writeToTransport(this, [PIN_MODE, pin, mode]);
};
/**
* Asks the arduino to write a value to a digital pin
* @param {number} pin The pin you want to write a value to.
* @param {number} value The value you want to write. Must be board.HIGH or board.LOW
*/
Board.prototype.digitalWrite = function(pin, value) {
var port = pin >> 3;
var bit = 1 << (pin & 0x07);
this.pins[pin].value = value;
if (value) {
this.ports[port] |= bit;
} else {
this.ports[port] &= ~bit;
}
writeToTransport(this, [
DIGITAL_MESSAGE | port,
this.ports[port] & 0x7F,
(this.ports[port] >> 7) & 0x7F
]);
};
/**
* Asks the arduino to read digital data. Turn on reporting for this pin's port.
*
* @param {number} pin The pin to read data from
* @param {function} callback The function to call when data has been received
*/
Board.prototype.digitalRead = function(pin, callback) {
this.reportDigitalPin(pin, 1);
this.addListener("digital-read-" + pin, callback);
};
/**
* Asks the arduino to tell us its capabilities
* @param {function} callback A function to call when we receive the capabilities
*/
Board.prototype.queryCapabilities = function(callback) {
this.once("capability-query", callback);
writeToTransport(this, [START_SYSEX, CAPABILITY_QUERY, END_SYSEX]);
};
/**
* Asks the arduino to tell us its analog pin mapping
* @param {function} callback A function to call when we receive the pin mappings.
*/
Board.prototype.queryAnalogMapping = function(callback) {
this.once("analog-mapping-query", callback);
writeToTransport(this, [START_SYSEX, ANALOG_MAPPING_QUERY, END_SYSEX]);
};
/**
* Asks the arduino to tell us the current state of a pin
* @param {number} pin The pin we want to the know the state of
* @param {function} callback A function to call when we receive the pin state.
*/
Board.prototype.queryPinState = function(pin, callback) {
this.once("pin-state-" + pin, callback);
writeToTransport(this, [START_SYSEX, PIN_STATE_QUERY, pin, END_SYSEX]);
};
/**
* Sends a string to the arduino
* @param {String} string to send to the device
*/