-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathtessel-export.js
1919 lines (1615 loc) · 49.9 KB
/
tessel-export.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';
// System Objects
const cp = require('child_process');
const Duplex = require('stream').Duplex;
const EventEmitter = require('events').EventEmitter;
const fs = require('fs');
const net = require('net');
const util = require('util');
const defOptions = {
ports: {
A: true,
B: true,
}
};
const pwmBankSettings = {
period: 0,
prescalarIndex: 0,
};
const reusableNoOp = () => {};
const enforceCallback = callback => typeof callback === 'function' ? callback : reusableNoOp;
// Port Name Constants
const A = 'A';
const B = 'B';
const ANALOG_RESOLUTION = 4096;
// Maximum number of ticks before period completes
const PWM_MAX_PERIOD = 0xFFFF;
// Actual lowest frequency is ~0.72Hz but 1Hz is easier to remember.
// 5000 is the max because any higher and the resolution drops
// below 7% (0xFFFF/5000 ~ 7.69) which is confusing
const PWM_MAX_FREQUENCY = 5000;
const PWM_MIN_FREQUENCY = 1;
const PWM_PRESCALARS = [1, 2, 4, 8, 16, 64, 256, 1024];
// Maximum number of unscaled ticks in a second (48 MHz)
const SAMD21_TICKS_PER_SECOND = 48000000;
// GPIO number of RESET pin
const SAMD21_RESET_GPIO = 39;
// Per pin capabilities
const ADC_PINS = [4, 7];
const INT_PINS = [2, 5, 6, 7];
const PULL_PINS = [2, 3, 4, 5, 6, 7];
const PWM_PINS = [5, 6];
const INT_MODES = {
rise: 1,
fall: 2,
change: 3,
high: 4,
low: 5,
};
const PULL_MODES = {
pulldown: 0,
pullup: 1,
none: 2,
};
const CMD = {
NOP: 0,
FLUSH: 1,
ECHO: 2,
GPIO_IN: 3,
GPIO_HIGH: 4,
GPIO_LOW: 5,
GPIO_TOGGLE: 21,
GPIO_CFG: 6,
GPIO_WAIT: 7,
GPIO_INT: 8,
GPIO_INPUT: 22,
GPIO_RAW_READ: 23,
GPIO_PULL: 26,
ANALOG_READ: 24,
ANALOG_WRITE: 25,
ENABLE_SPI: 10,
DISABLE_SPI: 11,
ENABLE_I2C: 12,
DISABLE_I2C: 13,
ENABLE_UART: 14,
DISABLE_UART: 15,
TX: 16,
RX: 17,
TXRX: 18,
START: 19,
STOP: 20,
PWM_DUTY_CYCLE: 27,
PWM_PERIOD: 28,
};
const REPLY = {
ACK: 0x80,
NACK: 0x81,
HIGH: 0x82,
LOW: 0x83,
DATA: 0x84,
MIN_ASYNC: 0xA0,
ASYNC_PIN_CHANGE_N: 0xC0, // c0 to c8 is all async pin assignments
ASYNC_UART_RX: 0xD0
};
class Tessel {
constructor(options) {
if (Tessel.instance) {
return Tessel.instance;
} else {
Tessel.instance = this;
}
// If the user program has provided a _valid_ options object, or use default
options = typeof options === 'object' && options !== null ? options : defOptions;
// If the user program has passed an options object that doesn't
// contain a `ports` property, or the value of the `ports` property
// is null or undefined: use the default.
if (options.ports == null) {
options.ports = defOptions.ports;
}
// For compatibility with T1 code, ensure that all ports are initialized by default.
// This means that only an explicit `A: false` or `B: false` will result in a
// port not being initialized. If the property is not present, null or undefined,
// it will be set to `true`.
//
// ONLY a value of `false` can prevent the port from being initialized!
//
if (options.ports.A == null) {
options.ports.A = true;
}
if (options.ports.B == null) {
options.ports.B = true;
}
this.ports = {
A: options.ports.A ? new Tessel.Port(A, Tessel.Port.PATH.A, this) : null,
B: options.ports.B ? new Tessel.Port(B, Tessel.Port.PATH.B, this) : null,
};
this.port = this.ports;
this.led = new Tessel.LEDs([{
color: 'red',
type: 'error'
}, {
color: 'amber',
type: 'wlan'
}, {
color: 'green',
type: 'user1'
}, {
color: 'blue',
type: 'user2'
}, ]);
this.leds = this.led;
this.network = {
wifi: new Tessel.Wifi(),
ap: new Tessel.AP(),
};
// tessel v1 does not have this version number
// this is useful for libraries to adapt to changes
// such as all pin reads/writes becoming async in version 2
this.version = 2;
}
close(portName) {
if (portName !== undefined) {
// This _could_ be combined with the above condition,
// but is separate since the open() method has a
// necessarily nested condition and this _may_ require
// further conditional restrictions in the future.
/* istanbul ignore else */
if (this.port[portName]) {
this.port[portName].close();
}
} else {
[A, B].forEach(name => this.close(name));
}
return this;
}
open(portName) {
if (portName !== undefined) {
// If there _is not_ a port created with this port name;
// Or there _is_, but the socket was previously destroyed...
if (!this.port[portName] ||
(this.port[portName] && this.port[portName].sock.destroyed)) {
this.port[portName] = new Tessel.Port(portName, Tessel.Port.PATH[portName], this);
}
} else {
[A, B].forEach(name => this.open(name));
}
return this;
}
reboot() {
this.close();
// When attempting to reboot, if the sockets
// are left open at the moment that `reboot`
// is executed, there will be a substantial
// delay before the actual reboot occurs.
// Polling for `destroyed` signals ensures
// that the sockets are closed before
// `reboot` is executed.
const pollUntilSocketsDestroyed = () => {
/* istanbul ignore else */
if (this.port.A.sock.destroyed &&
this.port.B.sock.destroyed) {
// Stop SPI communication between SAMD21 and MediaTek
cp.execSync('/etc/init.d/spid stop');
// Create a GPIO entry for the SAMD21 RESET pin
cp.execSync(`echo "${SAMD21_RESET_GPIO}" > /sys/class/gpio/export`);
// Make that GPIO an output
cp.execSync(`echo "out" > /sys/class/gpio/gpio${SAMD21_RESET_GPIO}/direction`);
// Pull the output low to reset the SAMD21
cp.execSync(`echo "0" > /sys/class/gpio/gpio${SAMD21_RESET_GPIO}/value`);
// Reboot the MediaTek
cp.execSync('reboot');
} else {
setImmediate(pollUntilSocketsDestroyed);
}
};
pollUntilSocketsDestroyed();
}
pwmFrequency(frequency, callback) {
if (frequency < PWM_MIN_FREQUENCY ||
frequency > PWM_MAX_FREQUENCY) {
throw new RangeError(`PWM Frequency value must be between ${PWM_MIN_FREQUENCY} and ${PWM_MAX_FREQUENCY}`);
}
const results = determineDutyCycleAndPrescalar(frequency);
pwmBankSettings.period = results.period;
pwmBankSettings.prescalarIndex = results.prescalarIndex;
// We are currently only using TCC Bank 0
// This may be expanded in the future to enable PWM on more pins
const TCC_ID = 0;
const packet = new Buffer(4);
// Write the command id first
packet.writeUInt8(CMD.PWM_PERIOD, 0);
// Write our prescalar to the top 4 bits and TCC id to the bottom 4 bits
packet.writeUInt8((pwmBankSettings.prescalarIndex << 4) | TCC_ID, 1);
// Write our period (16 bits)
packet.writeUInt16BE(pwmBankSettings.period, 2);
// Send the packet off to the samd21
// on the first available port object (regardless of name)
this.port[[A, B].find(name => this.ports[name] !== null)].sock.write(packet, callback);
}
}
const priv = new WeakMap();
class Port extends EventEmitter {
constructor(name, path, board) {
super();
const port = this;
let uart = null;
let spi = null;
priv.set(this, {
get uart() {
return uart;
},
set uart(value) {
uart = value;
},
get spi() {
return spi;
},
set spi(value) {
spi = value;
},
});
Object.defineProperties(this, {
spi: {
get() {
return spi;
},
},
uart: {
get() {
return uart;
},
},
});
this.name = name;
this.board = board;
// Connection to the SPI daemon
this.sock = net.createConnection({
path
}, error => {
/* istanbul ignore else */
if (error) {
throw error;
}
});
// Number of tasks occupying the socket
this.pending = 0;
// Unreference this socket so that the script will exit
// if nothing else is waiting in the event queue.
this.unref();
this.sock.on('error', error => {
console.log(`Socket: Error occurred: ${error.toString()}`);
});
this.sock.on('end', () => {
console.log('Socket: The other end sent FIN packet.');
});
this.sock.on('close', () => {
if (!this.sock.isAllowedToClose) {
throw new Error('Socket: The Port socket has closed.');
}
});
// Track whether the port should treat closing
// as an error. This will be set to true when `tessel.close()`
// is called, to indicate that the closing is intentional and
// therefore should be allow to proceed.
this.sock.isAllowedToClose = false;
let replyBuf = new Buffer(0);
this.sock.on('readable', () => {
let queued;
// This value can potentially be `null`.
const available = new Buffer(this.sock.read() || 0);
// Copy incoming data into the reply buffer
replyBuf = Buffer.concat([replyBuf, available]);
// While we still have data to process in the buffer
while (replyBuf.length !== 0) {
// Grab the next byte
const byte = replyBuf[0];
// If the next byte equals the marker for a uart incoming
if (byte === REPLY.ASYNC_UART_RX) {
// Get the next byte which is the number of bytes
const rxNum = replyBuf[1];
// As long as the number of bytes of rx buffer exists
// and we have at least the number of bytes needed for a uart rx packet
if (rxNum !== undefined && replyBuf.length >= 2 + rxNum) {
// Read the incoming data
const rxData = replyBuf.slice(2, 2 + rxNum);
// Cut those bytes out of the reply buf packet so we don't
// process them again
replyBuf = replyBuf.slice(2 + rxNum);
// If a uart port was instantiated
/* istanbul ignore else */
if (uart) {
// Push this data into the buffer
uart.push(rxData);
}
// Something went wrong and the packet is malformed
} else {
break;
}
// This is some other async transaction
} else if (byte >= REPLY.MIN_ASYNC) {
// If this is a pin change
if (byte >= REPLY.ASYNC_PIN_CHANGE_N && byte < REPLY.ASYNC_PIN_CHANGE_N + 16) {
// Pull out the pin number (requires clearing the value bit)
const pin = this.pin[(byte - REPLY.ASYNC_PIN_CHANGE_N) & ~(1 << 3)];
// Get the mode change
const mode = pin.interruptMode;
// Get the pin value
const pinValue = (byte >> 3) & 1;
// For one-time 'low' or 'high' event
if (mode === 'low' || mode === 'high') {
pin.emit(mode);
// Reset the pin interrupt state (prevent constant interrupts)
pin.interruptMode = null;
// Decrement the number of tasks waiting on the socket
this.unref();
} else {
// Emit the change and rise or fall
pin.emit('change', pinValue);
pin.emit(pinValue ? 'rise' : 'fall');
}
} else {
// Some other async event
this.emit('async-event', byte);
}
// Cut this byte off of the reply buffer
replyBuf = replyBuf.slice(1);
} else {
// If there are no commands awaiting a response
if (this.replyQueue.length === 0) {
// Throw an error... something went wrong
throw new Error(`Received unexpected response with no commands pending: ${byte}`);
}
// Get the size if the incoming packet
const size = this.replyQueue[0].size;
// If we have reply data
if (byte === REPLY.DATA) {
// Ensure that the packet size agrees
if (!size) {
throw new Error('Received unexpected data packet');
}
// The number of data bytes expected have been received.
if (replyBuf.length >= 1 + size) {
// Extract the data
const data = replyBuf.slice(1, 1 + size);
// Slice this data off of the buffer
replyBuf = replyBuf.slice(1 + size);
// Get the queued command
queued = this.dequeue();
// If there is a callback for th ecommand
/* istanbul ignore else */
if (queued.callback) {
// Return the data in the callback
queued.callback.call(this, null, data);
}
} else {
// The buffer does not have the correct number of
// date bytes to fulfill the requirements of the
// reply queue's next registered handler.
break;
}
// If it's just one byte being returned
} else {
/* istanbul ignore else */
if (byte === REPLY.HIGH || byte === REPLY.LOW) {
// Slice it off
replyBuf = replyBuf.slice(1);
// Get the callback in the queue
queued = this.dequeue();
// If a callback was provided
/* istanbul ignore else */
if (queued.callback) {
// Return the byte in the callback
queued.callback.call(this, null, byte);
}
}
}
}
}
});
// Active peripheral: 'none', 'i2c', 'spi', 'uart'
this.mode = 'none';
// Array of {size, callback} used to dispatch replies
this.replyQueue = [];
this.pin = [];
for (let i = 0; i < 8; i++) {
this.pin.push(new Tessel.Pin(i, this));
}
// Deprecated properties for Tessel 1 backwards compatibility:
this.pin.G1 = this.pin.g1 = this.pin[5];
this.pin.G2 = this.pin.g2 = this.pin[6];
this.pin.G3 = this.pin.g3 = this.pin[7];
this.digital = [this.pin[5], this.pin[6], this.pin[7]];
this.pwm = [this.pin[5], this.pin[6]];
// This are function expressions because
// they MUST be constructable (arrows disallow)
this.I2C = function(address) {
const options = {};
if (typeof address === 'object' && address != null) {
/*
{
addr: address,
freq: frequency,
port: port,
}
*/
Object.assign(options, address);
} else {
/*
(address)
*/
options.address = address;
}
/*
Always ensure that the options
object contains a port property
with this port as its value.
*/
if (!options.port) {
options.port = port;
} else {
/*
When receiving an object containing
options information, it's possible that
the calling code accidentally sends
a "port" that isn't this port.
*/
/* istanbul ignore else */
if (options.port !== port) {
options.port = port;
}
}
return new Tessel.I2C(options);
};
this.I2C.enabled = false;
// This are function expressions because
// they MUST be constructable (arrows disallow)
this.SPI = function(options) {
if (spi) {
spi.disable();
}
spi = new Tessel.SPI(options || {}, port);
return spi;
};
// This are function expressions because
// they MUST be constructable (arrows disallow)
this.UART = function(options) {
if (uart) {
uart.disable();
}
uart = new Tessel.UART(options || {}, port);
// Grab a reference to this socket so it doesn't close
// if we're waiting for UART data
port.ref();
return uart;
};
}
close() {
/* istanbul ignore else */
if (!this.sock.destroyed) {
this.sock.isAllowedToClose = true;
this.sock.destroy();
}
}
ref() {
// Increase the number of pending tasks
this.pending++;
// Ensure this socket stays open until unref'ed
this.sock.ref();
}
unref() {
// If we have pending tasks to complete
if (this.pending > 0) {
// Subtract the one that is being unref'ed
this.pending--;
}
// If this was the last task
if (this.pending === 0) {
// Unref the socket so the process doesn't hang open
this.sock.unref();
}
}
enqueue(reply) {
this.ref();
this.replyQueue.push(reply);
}
dequeue() {
this.unref();
return this.replyQueue.shift();
}
cork() {
this.sock.cork();
}
uncork() {
this.sock.uncork();
}
sync(callback) {
if (callback) {
this.sock.write(new Buffer([CMD.ECHO, 1, 0x88]));
this.enqueue({
size: 1,
callback
});
}
}
command(data, callback) {
this.cork();
this.sock.write(new Buffer(data));
this.sync(callback);
this.uncork();
}
status(data, callback) {
this.sock.write(new Buffer(data));
this.enqueue({
size: 0,
callback,
});
}
tx(data, callback) {
let offset = 0;
let chunk;
if (data.length === 0) {
throw new RangeError('Buffer size must be non-zero');
}
this.cork();
// The protocol only supports <256 byte transfers, chunk if data is bigger
while (offset < data.length) {
chunk = data.slice(offset, offset + 255);
this.sock.write(new Buffer([CMD.TX, chunk.length]));
this.sock.write(chunk);
offset += 255;
}
this.sync(callback);
this.uncork();
}
rx(len, callback) {
if (len === 0 || len > 255) {
throw new RangeError('Buffer size must be within 1-255');
}
this.sock.write(new Buffer([CMD.RX, len]));
this.enqueue({
size: len,
callback,
});
}
txrx(buf, callback) {
const len = buf.length;
if (len === 0 || len > 255) {
throw new RangeError('Buffer size must be within 1-255');
}
this.cork();
this.sock.write(new Buffer([CMD.TXRX, len]));
this.sock.write(buf);
this.enqueue({
size: len,
callback,
});
this.uncork();
}
}
Port.PATH = {
A: '/var/run/tessel/port_a',
B: '/var/run/tessel/port_b'
};
/*
Takes in a desired frequency setting and outputs the
necessary prescalar and duty cycle settings based on set period.
Outputs an object in the form of:
{
prescalar: number (0-7),
period: number (0-0xFFFF)
}
*/
function determineDutyCycleAndPrescalar(frequency) {
// Current setting for the prescalar
let prescalarIndex = 0;
// Current period setting
let period = 0;
// If the current frequency would require a period greater than the max
while ((period = Math.floor((SAMD21_TICKS_PER_SECOND / PWM_PRESCALARS[prescalarIndex]) / frequency)) > PWM_MAX_PERIOD) {
// Increase our clock prescalar
prescalarIndex++;
// If we have no higher prescalars
if (prescalarIndex === PWM_PRESCALARS.length) {
// Throw an error because this frequency is too low for our possible parameters
throw new Error('Unable to find prescalar/duty cycle parameter match for frequency');
}
}
// We have found a period inside a suitable prescalar, return results
return {
period,
prescalarIndex
};
}
class Pin extends EventEmitter {
constructor(pin, port) {
super();
this.pin = pin;
this.port = port;
this.isPWM = false;
this.supports = {
// These can be updated to use .includes()
// once > Node 6 is supported.
INT: INT_PINS.indexOf(pin) !== -1,
ADC: ADC_PINS.indexOf(pin) !== -1 || port.name === B,
PWM: PWM_PINS.indexOf(pin) !== -1,
PULL: PULL_PINS.indexOf(pin) !== -1,
};
let interruptMode = null;
Object.defineProperties(this, {
interruptMode: {
configurable: true,
get() {
return interruptMode;
},
set(mode) {
interruptMode = (mode === 'rise' || mode === 'fall') ? 'change' : mode;
port.command([CMD.GPIO_INT, pin | (mode ? INT_MODES[mode] << 4 : 0)]);
}
}
});
}
get resolution() {
return ANALOG_RESOLUTION;
}
removeListener(event, listener) {
// If it's an interrupt event, remove as necessary
super.removeListener(event, listener);
if (event === this.interruptMode && this.listenerCount(event) === 0) {
this.interruptMode = null;
}
return this;
}
removeAllListeners(event) {
/* istanbul ignore else */
if (!event || event === this.interruptMode) {
this.interruptMode = null;
}
super.removeAllListeners.apply(this, arguments);
return this;
}
addListener(mode, callback) {
// Check for valid pin event mode
if (typeof INT_MODES[mode] !== 'undefined') {
if (!this.supports.INT) {
throw new Error(`Interrupts are not supported on pin ${this.pin}. Pins 2, 5, 6, and 7 on either port support interrupts.`);
}
// For one-time 'low' or 'high' event
if ((mode === 'low' || mode === 'high') && !callback.listener) {
throw new Error('Cannot use "on" with level interrupts. You can only use "once".');
}
// Can't set multiple listeners when using 'low' or 'high'
if (this.interruptMode) {
const singleEventModes = ['low', 'high'];
if (singleEventModes.some(value => mode === value || this.interruptMode === value)) {
throw new Error(`Cannot set pin interrupt mode to "${mode}"; already listening for "${this.interruptMode}". Can only set multiple listeners with "change", "rise" & "fall".`);
}
}
// Set the socket reference so the script doesn't exit
this.port.ref();
this.interruptMode = mode;
// Add the event listener
super.on(mode, callback);
} else {
throw new Error(`Invalid pin event mode "${mode}". Valid modes are "change", "rise", "fall", "high" and "low".`);
}
}
high(callback) {
this.port.command([CMD.GPIO_HIGH, this.pin], callback);
return this;
}
low(callback) {
this.port.command([CMD.GPIO_LOW, this.pin], callback);
return this;
}
toggle(callback) {
this.port.command([CMD.GPIO_TOGGLE, this.pin], callback);
return this;
}
output(value, callback) {
if (value) {
this.high(callback);
} else {
this.low(callback);
}
return this;
}
write(value, callback) {
// same as .output
return this.output(value, callback);
}
rawDirection() {
throw new Error('pin.rawDirection is not supported on Tessel 2. Use .input() or .output()');
}
_readPin(cmd, callback) {
this.port.cork();
this.port.sock.write(new Buffer([cmd, this.pin]));
this.port.enqueue({
size: 0,
callback: (error, data) => callback(error, data === REPLY.HIGH ? 1 : 0),
});
this.port.uncork();
}
rawRead(callback) {
if (typeof callback !== 'function') {
throw new Error('pin.rawRead is async, pass in a callback to get the value');
}
this._readPin(CMD.GPIO_RAW_READ, callback);
return this;
}
input(callback) {
this.port.command([CMD.GPIO_INPUT, this.pin], callback);
return this;
}
read(callback) {
if (typeof callback !== 'function') {
throw new Error('pin.read is async, pass in a callback to get the value');
}
this._readPin(CMD.GPIO_IN, callback);
return this;
}
pull(pullType, callback) {
// Ensure this pin supports being pulled
if (!this.supports.PULL) {
throw new Error('Internal pull resistors are not available on this pin. Please use pins 2-7.');
}
// Set a default value to 'none';
if (pullType === undefined) {
pullType = 'none';
}
const mode = PULL_MODES[pullType];
// Ensure a valid mode was requested
if (mode === undefined) {
throw new Error('Invalid pull type. Must be one of: "pullup", "pulldown", or "none"');
}
// Send the command to the coprocessor
this.port.command([CMD.GPIO_PULL, (this.pin | (mode << 4))], callback);
}
readPulse() {
throw new Error('Pin.readPulse is not yet implemented');
}
analogRead(callback) {
if (!this.supports.ADC) {
throw new RangeError('pin.analogRead is not supported on this pin. Analog read is supported on port A pins 4 and 7 and on all pins on port B');
}
if (typeof callback !== 'function') {
throw new Error('analogPin.read is async, pass in a callback to get the value');
}
this.port.sock.write(new Buffer([CMD.ANALOG_READ, this.pin]));
this.port.enqueue({
size: 2,
callback(err, data) {
callback(err, (data[0] + (data[1] << 8)) / ANALOG_RESOLUTION);
},
});
return this;
}
analogWrite(val) {
// throw an error if this isn't the adc pin (port b, pin 7)
if (this.port.name !== 'B' || this.pin !== 7) {
throw new RangeError('Analog write can only be used on Pin 7 (G3) of Port B.');
}
const data = val * 0x3ff;
if (data > 0x3ff || data < 0) {
throw new RangeError('Analog write must be between 0 and 1');
}
this.port.sock.write(new Buffer([CMD.ANALOG_WRITE, data >> 8, data & 0xff]));
return this;
}
// Duty cycle should be a value between 0 and 1
pwmDutyCycle(dutyCycle, callback) {
// throw an error if this pin doesn't support PWM
if (!this.supports.PWM) {
throw new RangeError('PWM can only be used on TX (pin 5) and RX (pin 6) of either module port.');
}
if (typeof dutyCycle !== 'number' || dutyCycle < 0 || dutyCycle > 1) {
throw new RangeError('PWM duty cycle must be a number between 0 and 1');
}
// The frequency must be set prior to setting the duty cycle
if (pwmBankSettings.period === 0) {
throw new Error('PWM Frequency is not configured. You must call Tessel.pwmFrequency before setting duty cycle.');
}
// Calculate number of ticks for specified duty cycle
const dutyCycleTicks = Math.floor(dutyCycle * pwmBankSettings.period);
// Construct packet
const packet = new Buffer([CMD.PWM_DUTY_CYCLE, this.pin, dutyCycleTicks >> 8, dutyCycleTicks & 0xff]);
// Write it to the socket
this.port.sock.write(packet, callback);
return this;
}
}
Pin.prototype.rawWrite = util.deprecate(function(value) {
if (value) {
this.high();
} else {
this.low();
}
return this;
}, 'pin.rawWrite is deprecated. Use .high() or .low()');
Pin.prototype.on = Pin.prototype.addListener;
class I2C {
constructor(params) {
let frequency = 1e5;
if (params.address == null) {
throw new Error('I2C expected an address');
}
Object.defineProperties(this, {
frequency: {
get() {
return frequency;
},