forked from newrelic/futurestack14_badge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.nut
More file actions
1827 lines (1480 loc) · 55 KB
/
device.nut
File metadata and controls
1827 lines (1480 loc) · 55 KB
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
/*****************************************\
* FUTURESTACK 14 BADGE DEMO *
* (c) 2014 New Relic *
* *
* For more information, see: *
* github.com/newrelic/futurestack14_badge *
\*****************************************/
const SPICLK = 15000;
const CONNECT_TIMEOUT = 60; // 60 seconds
const RUNLOOP_INTERVAL = 3; // 3 seconds
// Semi-generic SPI Flash Driver
class SpiFlash {
// Clock up to 86 MHz (we go up to 15 MHz)
// device commands:
static WREN = "\x06"; // write enable
static WRDI = "\x04"; // write disable
static RDID = "\x9F"; // read identification
static RDSR = "\x05"; // read status register
static READ = "\x03"; // read data
static FASTREAD = "\x0B"; // fast read data
static RDSFDP = "\x5A"; // read SFDP
static RES = "\xAB"; // read electronic ID
static REMS = "\x90"; // read electronic mfg & device ID
static DREAD = "\x3B"; // double output mode, which we don't use
static SE = "\x20"; // sector erase (Any 4kbyte sector set to 0xff)
static BE = "\x52"; // block erase (Any 64kbyte sector set to 0xff)
static CE = "\x60"; // chip erase (full device set to 0xff)
static PP = "\x02"; // page program
static RDSCUR = "\x2B"; // read security register
static WRSCUR = "\x2F"; // write security register
static ENSO = "\xB1"; // enter secured OTP
static EXSO = "\xC1"; // exit secured OTP
static DP = "\xB9"; // deep power down
static RDP = "\xAB"; // release from deep power down
// offsets for the record and playback sectors in memory
// 64 blocks
// first 48 blocks: playback memory
// blocks 49 - 64: recording memory
static totalBlocks = 64;
static playbackBlocks = 48;
static recordOffset = 0x2FFFD0;
// manufacturer and device ID codes
mfgID = null;
devID = null;
// spi interface
spi = null;
cs_l = null;
booted = false;
// constructor takes in pre-configured spi interface object and chip select GPIO
constructor(spiBus, csPin) {
this.spi = spiBus;
this.cs_l = csPin;
spi.configure(MSB_FIRST | CLOCK_IDLE_LOW, SPICLK);
wake(); // In case we were sleeping
// read the manufacturer and device ID
cs_l.write(0);
spi.write(RDID);
local data = spi.readblob(3);
this.mfgID = data[0];
this.devID = (data[1] << 8) | data[2];
cs_l.write(1);
if (this.mfgID != 0x00) {
booted = true;
}
}
function wrenable() {
cs_l.write(0);
spi.write(WREN);
cs_l.write(1);
}
function wrdisable() {
cs_l.write(0);
spi.write(WRDI);
cs_l.write(1);
}
// pages should be pre-erased before writing
function write(addr, data) {
wrenable();
// check the status register's write enabled bit
if (!(getStatus() & 0x02)) {
server.error("Device: Flash Write not Enabled");
return 1;
}
cs_l.write(0);
// page program command goes first
spi.write(PP);
// followed by 24-bit address
spi.write(format("%c%c%c", (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF));
spi.write(data);
cs_l.write(1);
// wait for the status register to show write complete
// typical 1.4 ms, max 5 ms
local timeout = 50000; // time in us
local start = hardware.micros();
while (getStatus() & 0x01) {
if ((hardware.micros() - start) > timeout) {
server.error("Device: Timed out waiting for write to finish");
return 1;
}
}
return 0;
}
// allow data chunks greater than one flash page to be written in a single op
function writeChunk(addr, data) {
// separate the chunk into pages
data.seek(0,'b');
for (local i = 0; i < data.len(); i+=256) {
local leftInBuffer = data.len() - data.tell();
if ((addr+i % 256) + leftInBuffer >= 256) {
// Realign to the end of the page
local align = 256 - ((addr+i) % 256);
write((addr+i),data.readblob(align));
leftInBuffer -= align;
i += align;
if (leftInBuffer <= 0) break;
}
if (leftInBuffer < 256) {
write((addr+i),data.readblob(leftInBuffer));
} else {
write((addr+i),data.readblob(256));
}
}
}
function read(addr, bytes) {
cs_l.write(0);
// to read, send the read command and a 24-bit address
spi.write(READ);
spi.write(format("%c%c%c", (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF));
local readBlob = spi.readblob(bytes);
cs_l.write(1);
return readBlob;
}
function getStatus() {
cs_l.write(0);
spi.write(RDSR);
local status = spi.readblob(1);
cs_l.write(1);
return status[0];
}
function sleep() {
cs_l.write(0);
spi.write(DP);
cs_l.write(1);
spi.configure(CLOCK_IDLE_LOW | MSB_FIRST | CLOCK_2ND_EDGE, SPICLK);
}
function wake() {
spi.configure(MSB_FIRST | CLOCK_IDLE_LOW, SPICLK);
cs_l.write(0);
spi.write(RDP);
cs_l.write(1);
}
// erase any 4kbyte sector of flash
// takes a starting address, 24-bit, MSB-first
function sectorErase(addr) {
this.wrenable();
cs_l.write(0);
spi.write(SE);
spi.write(format("%c%c%c", (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF));
cs_l.write(1);
// wait for sector erase to complete
// typ = 60ms, max = 300ms
local timeout = 300000; // time in us
local start = hardware.micros();
while (getStatus() & 0x01) {
if ((hardware.micros() - start) > timeout) {
server.error("Device: Timed out waiting for write to finish");
return 1;
}
}
return 0;
}
// set any 64kbyte block of flash to all 0xff
// takes a starting address, 24-bit, MSB-first
function blockErase(addr) {
//server.log(format("Device: erasing 64kbyte SPI Flash block beginning at 0x%06x",addr));
this.wrenable();
cs_l.write(0);
spi.write(BE);
spi.write(format("%c%c%c", (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF));
cs_l.write(1);
// wait for sector erase to complete
// typ = 700ms, max = 2s
local timeout = 2000000; // time in us
local start = hardware.micros();
while (getStatus() & 0x01) {
if ((hardware.micros() - start) > timeout) {
server.error("Device: Timed out waiting for write to finish");
return 1;
}
}
return 0;
}
// clear the full flash to 0xFF
function chipErase() {
server.log("Device: Erasing SPI Flash");
this.wrenable();
cs_l.write(0);
spi.write(CE);
cs_l.write(1);
// chip erase takes a *while*
// typ = 25s, max = 50s
local timeout = 50000000; // time in us
local start = hardware.micros();
while (getStatus() & 0x01) {
if ((hardware.micros() - start) > timeout) {
server.error("Device: Timed out waiting for write to finish");
return 1;
}
}
server.log("Device: Done with chip erase");
return 0;
}
// erase the message portion of the SPI flash
// 2880000 bytes is 45 64-kbyte blocks
function erasePlayBlocks() {
server.log("Device: clearing playback flash sectors");
for(local i = 0; i < this.playbackBlocks; i++) {
if(this.blockErase(i*65535)) {
server.error(format("Device: SPI flash failed to erase block %d (addr 0x%06x)",
i, i*65535));
return 1;
}
}
return 0;
}
// erase the record buffer portion of the SPI flash
// this is a 960000-byte sector, beginning at block 46 and going to block 60
function eraseRecBlocks() {
server.log("Device: clearing recording flash sectors");
for (local i = this.playbackBlocks; i < this.totalBlocks; i++) {
if(this.blockErase(i*65535)) {
server.error(format("Device: SPI flash failed to erase block %d (addr 0x%06x)",
i, i*65535));
return 1;
}
}
return 0;
}
}
// IO Expander classes
class SX150x{
//Private variables
_i2c = null;
_addr = null;
_callbacks = null;
//Pass in pre-configured I2C since it may be used by other devices
constructor(i2c, address = 0x40) {
_i2c = i2c;
_addr = address; //8-bit address
_callbacks = [];
}
function readReg(register) {
local data = _i2c.read(_addr, format("%c", register), 1);
if (data == null) {
server.error("I2C Read Failure. Device: "+_addr+" Register: "+register);
return -1;
}
return data[0];
}
function writeReg(register, data) {
_i2c.write(_addr, format("%c%c", register, data));
}
function writeBit(register, bitn, level) {
local value = readReg(register);
value = (level == 0)?(value & ~(1<<bitn)):(value | (1<<bitn));
writeReg(register, value);
}
function writeMasked(register, data, mask) {
local value = readReg(register);
value = (value & ~mask) | (data & mask);
writeReg(register, value);
}
// set or clear a selected GPIO pin, 0-16
function setPin(gpio, level) {
writeBit(bank(gpio).REGDATA, gpio % 8, level ? 1 : 0);
}
// configure specified GPIO pin as input(0) or output(1)
function setDir(gpio, output) {
writeBit(bank(gpio).REGDIR, gpio % 8, output ? 0 : 1);
}
// enable or disable internal pull up resistor for specified GPIO
function setPullUp(gpio, enable) {
writeBit(bank(gpio).REGPULLUP, gpio % 8, enable ? 0 : 1);
}
// enable or disable internal pull down resistor for specified GPIO
function setPullDown(gpio, enable) {
writeBit(bank(gpio).REGPULLDN, gpio % 8, enable ? 0 : 1);
}
// configure whether specified GPIO will trigger an interrupt
function setIrqMask(gpio, enable) {
writeBit(bank(gpio).REGINTMASK, gpio % 8, enable ? 0 : 1);
}
// clear interrupt on specified GPIO
function clearIrq(gpio) {
writeBit(bank(gpio).REGINTMASK, gpio % 8, 1);
}
// get state of specified GPIO
function getPin(gpio) {
return ((readReg(bank(gpio).REGDATA) & (1<<(gpio%8))) ? 1 : 0);
}
//configure which callback should be called for each pin transition
function setCallback(gpio, callback){
_callbacks[gpio] = callback;
}
function callback(){
//server.log("Checking for callback...");
local irq = getIrq();
//server.log(format("IRQ = %08x",irq));
clearAllIrqs();
for (local i = 0; i < 16; i++){
if ( (irq & (1 << i)) && (typeof _callbacks[i] == "function")){
_callbacks[i]();
}
}
}
}
class SX1506 extends SX150x{
// I/O Expander internal registers
static BANK_A = { REGDATA = 0x01,
REGDIR = 0x03,
REGPULLUP = 0x05,
REGPULLDN = 0x07,
REGINTMASK = 0x09,
REGSNSHI = 0x0B,
REGSNSLO = 0x0D,
REGINTSRC = 0x0F}
static BANK_B = { REGDATA = 0x00,
REGDIR = 0x02,
REGPULLUP = 0x04,
REGPULLDN = 0x06,
REGINTMASK = 0x08,
REGSNSHI = 0x0A,
REGSNSLO = 0x0C,
REGINTSRC = 0x0E}
constructor(i2c, address=0x40){
base.constructor(i2c, address);
_callbacks.resize(16,null);
this.reset();
this.clearAllIrqs();
}
//Write registers to default values
function reset(){
writeReg(BANK_A.REGDIR, 0xFF);
writeReg(BANK_A.REGDATA, 0xFF);
writeReg(BANK_A.REGPULLUP, 0x00);
writeReg(BANK_A.REGPULLDN, 0x00);
writeReg(BANK_A.REGINTMASK, 0xFF);
writeReg(BANK_A.REGSNSHI, 0x00);
writeReg(BANK_A.REGSNSLO, 0x00);
writeReg(BANK_B.REGDIR, 0xFF);
writeReg(BANK_B.REGDATA, 0xFF);
writeReg(BANK_B.REGPULLUP, 0x00);
writeReg(BANK_B.REGPULLDN, 0x00);
writeReg(BANK_A.REGINTMASK, 0xFF);
writeReg(BANK_B.REGSNSHI, 0x00);
writeReg(BANK_B.REGSNSLO, 0x00);
}
function debug(){
server.log(format("A-DATA (0x%02X): 0x%02X",BANK_A.REGDATA, readReg(BANK_A.REGDATA)));
imp.sleep(0.1);
server.log(format("A-DIR (0x%02X): 0x%02X",BANK_A.REGDIR, readReg(BANK_A.REGDIR)));
imp.sleep(0.1);
server.log(format("A-PULLUP (0x%02X): 0x%02X",BANK_A.REGPULLUP, readReg(BANK_A.REGPULLUP)));
imp.sleep(0.1);
server.log(format("A-PULLDN (0x%02X): 0x%02X",BANK_A.REGPULLDN, readReg(BANK_A.REGPULLDN)));
imp.sleep(0.1);
server.log(format("A-INTMASK (0x%02X): 0x%02X",BANK_A.REGINTMASK, readReg(BANK_A.REGINTMASK)));
imp.sleep(0.1);
server.log(format("A-SNSHI (0x%02X): 0x%02X",BANK_A.REGSNSHI, readReg(BANK_A.REGSNSHI)));
imp.sleep(0.1);
server.log(format("A-SNSLO (0x%02X): 0x%02X",BANK_A.REGSNSLO, readReg(BANK_A.REGSNSLO)));
imp.sleep(0.1);
server.log(format("B-DATA (0x%02X): 0x%02X",BANK_B.REGDATA, readReg(BANK_B.REGDATA)));
imp.sleep(0.1);
server.log(format("B-DIR (0x%02X): 0x%02X",BANK_B.REGDIR, readReg(BANK_B.REGDIR)));
imp.sleep(0.1);
server.log(format("B-PULLUP (0x%02X): 0x%02X",BANK_B.REGPULLUP, readReg(BANK_B.REGPULLUP)));
imp.sleep(0.1);
server.log(format("B-PULLDN (0x%02X): 0x%02X",BANK_B.REGPULLDN, readReg(BANK_B.REGPULLDN)));
imp.sleep(0.1);
server.log(format("B-INTMASK (0x%02X): 0x%02X",BANK_B.REGINTMASK, readReg(BANK_B.REGINTMASK)));
imp.sleep(0.1);
server.log(format("B-SNSHI (0x%02X): 0x%02X",BANK_B.REGSNSHI, readReg(BANK_B.REGSNSHI)));
imp.sleep(0.1);
server.log(format("B-SNSLO (0x%02X): 0x%02X",BANK_B.REGSNSLO, readReg(BANK_B.REGSNSLO)));
// imp.sleep(0.1);
// foreach(idx,val in BANK_A){
// server.log(format("Bank A %s (0x%02X): 0x%02X", idx, val, readReg(val)));
// imp.sleep(0.1);
// }
// foreach(idx,val in BANK_B){
// server.log(format("Bank B %s (0x%02X): 0x%02X", idx, val, readReg(val)));
// imp.sleep(0.1);
// }
// for(local i =0; i < 0x2F; i++){
// server.log(format("0x%02X: 0x%02X", i, readReg(i)));
// }
}
function bank(gpio){
return (gpio > 7) ? BANK_B : BANK_A;
}
// configure whether edges trigger an interrupt for specified GPIO
function setIrqEdges( gpio, rising, falling) {
local bank = bank(gpio);
gpio = gpio % 8;
local mask = 0x03 << ((gpio & 3) << 1);
local data = (2*falling + rising) << ((gpio & 3) << 1);
writeMasked(gpio >= 4 ? bank.REGSNSHI : bank.REGSNSLO, data, mask);
}
function clearAllIrqs() {
writeReg(BANK_A.REGINTSRC,0xff);
writeReg(BANK_B.REGINTSRC,0xff);
}
function getIrq(){
return ((readReg(BANK_B.REGINTSRC) & 0xFF) << 8) | (readReg(BANK_A.REGINTSRC) & 0xFF);
}
}
class ExpGPIO{
_expander = null; //Instance of an Expander class
_gpio = null; //Pin number of this GPIO pin
constructor(expander, gpio) {
_expander = expander;
_gpio = gpio;
}
//Optional initial state (defaults to 0 just like the imp)
function configure(mode, callback = null, initialstate=0) {
// set the pin direction and configure the internal pullup resistor, if applicable
_expander.setPin(_gpio,initialstate);
if (mode == DIGITAL_OUT) {
_expander.setDir(_gpio,1);
_expander.setPullUp(_gpio,0);
} else if (mode == DIGITAL_IN) {
_expander.setDir(_gpio,0);
_expander.setPullUp(_gpio,0);
} else if (mode == DIGITAL_IN_PULLUP) {
_expander.setDir(_gpio,0);
_expander.setPullUp(_gpio,1);
}
// configure the pin to throw an interrupt, if necessary
if (callback) {
_expander.setIrqMask(_gpio,1);
_expander.setIrqEdges(_gpio,1,1);
_expander.setCallback(_gpio,callback);
} else {
_expander.setIrqMask(_gpio,0);
_expander.setIrqEdges(_gpio,0,0);
_expander.setCallback(_gpio,null);
}
}
function write(state) { _expander.setPin(_gpio,state); }
function read() { return _expander.getPin(_gpio); }
}
// PN532 Device Driver
const PN532_PREAMBLE = 0x00;
const PN532_STARTCODE2 = 0xFF;
const PN532_POSTAMBLE = 0x00;
const PN532_HOSTTOPN532 = 0xD4;
const PN532_FIRMWAREVERSION = 0x02;
const PN532_SAMCONFIGURATION = 0x14;
const PN532_RFCONFIGURATION = 0x32;
const PN532_SPI_STATREAD = 0x02;
const PN532_SPI_DATAWRITE = 0x01;
const PN532_SPI_DATAREAD = 0x03;
const PN532_SPI_READY = 0x01;
const PN532_MAX_RETRIES = 0x05;
class PN532 {
spi = null;
nfc_cs_l = null;
nfc_pd_l = null;
device_id = null;
device_id_a = null;
device_id_b = null;
device_id_c = null;
pn532_ack = [0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00];
pn532_firmware_version = [0x00, 0xFF, 0x06, 0xFA, 0xD5, 0x03];
response_buffer = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
booted = true;
constructor(_spi, _nfc_cs_l, _nfc_pd_l) {
device_id = hardware.getimpeeid().slice(10);
device_id_a = hex_to_i(device_id.slice(0,2));
device_id_b = hex_to_i(device_id.slice(2,4));
device_id_c = hex_to_i(device_id.slice(4,6));
spi = _spi;
nfc_cs_l = _nfc_cs_l;
nfc_pd_l = _nfc_pd_l;
}
///////////////////////////////////////
// NFC SPI Functions
function spi_start() {
// Configure SPI at about 4MHz
spi.configure(LSB_FIRST | CLOCK_IDLE_HIGH, 4000);
nfc_cs_l.configure(DIGITAL_OUT); // Configure the chip select pin
nfc_cs_l.write(1); // pull CS high
imp.sleep(0.1); // wait 100 ms
nfc_cs_l.write(0); // pull CS low to start the transmission of data
imp.sleep(0.1);
//server.log("SPI Init successful");
}
function spi_stop() {
spi.configure(CLOCK_IDLE_LOW | MSB_FIRST | CLOCK_2ND_EDGE, SPICLK);
}
function spi_read_ack() {
spi_read_data(6);
for (local i = 0; i < 6; i++) {
if (response_buffer[i] != pn532_ack[i])
return false;
}
return true;
}
function spi_read_data(length) {
nfc_cs_l.write(0); // pull CS low
imp.sleep(0.002);
spi_write(PN532_SPI_DATAREAD); // read leading byte DR and discard
local response = "";
for (local i = 0; i < length; i++) {
imp.sleep(0.001);
response_buffer[i] = spi_write(PN532_SPI_STATREAD);
response = response + response_buffer[i] + " ";
}
//server.log("spi_read_data: " + response);
nfc_cs_l.write(1); // pull CS high
}
function spi_read_status() {
nfc_cs_l.write(0); // pull CS low
imp.sleep(0.002);
// Send status command to PN532; ignore returned byte
spi_write(PN532_SPI_STATREAD);
// Collect status response, send junk 0x00 byte
local value = spi_write(0x00);
nfc_cs_l.write(1); // pull CS high
return value;
}
function spi_write_command(cmd, cmdlen) {
local checksum;
nfc_cs_l.write(0); // pull CS low
imp.sleep(0.002);
cmdlen++;
spi_write(PN532_SPI_DATAWRITE);
checksum = PN532_PREAMBLE + PN532_PREAMBLE + PN532_STARTCODE2;
spi_write(PN532_PREAMBLE);
spi_write(PN532_PREAMBLE);
spi_write(PN532_STARTCODE2);
spi_write(cmdlen);
local cmdlen_1 = 256 - cmdlen;
spi_write(cmdlen_1);
spi_write(PN532_HOSTTOPN532);
checksum += PN532_HOSTTOPN532;
for (local i = 0; i < cmdlen - 1; i++) {
spi_write(cmd[i]);
checksum += cmd[i];
}
checksum %= 256;
local checksum_1 = 255 - checksum;
spi_write(checksum_1);
spi_write(PN532_POSTAMBLE);
nfc_cs_l.write(1); // pull CS high
}
function spi_write(byte) {
// Write the single byte
spi.write(format("%c", byte));
// Collect the response from the holding register
local resp = spi.read(1);
// Show what we sent
//server.log(format("SPI tx %02x, rx %02x", byte, resp[0]));
// Return the byte
return resp[0];
}
////////////////////////////////////
// PN532 functions
function nfc_init() {
spi_start();
nfc_pd_l.write(1); // Power down high
nfc_cs_l.write(0); // pull CS low
imp.sleep(0.1);
// No need for this at the moment but it's useful for debugging.
if (!nfc_get_firmware_version()) {
server.log("Didn't find PN53x chip");
booted = false;
}
if (!nfc_SAM_config()) {
server.log("SAM config error");
booted = false;
}
spi_stop();
}
function nfc_get_firmware_version() {
//server.log("Getting firmware version");
if (!send_command_check_ready([PN532_FIRMWAREVERSION], 1,100))
return 0;
spi_read_data(12);
for (local i = 0; i < 6; i++) {
if (response_buffer[i] != pn532_firmware_version[i])
return false;
}
server.log(format("NFC chip: PN5%02x", response_buffer[6]));
//server.log("Firmware ver "+ response_buffer[7] + "." + response_buffer[8]);
//server.log(format("Supports %02x", response_buffer[9]));
return true;
}
function nfc_SAM_config() {
//server.log("SAM configuration");
if (!send_command_check_ready([PN532_SAMCONFIGURATION, 0x01, 0x14, 0x01], 4, 100))
return false;
spi_read_data(8);
if (response_buffer[5] == 0x15) return true;
else return false;
}
function nfc_scan() {
//server.log("nfc_p2p_scan");
send_command_check_ready([PN532_RFCONFIGURATION, PN532_MAX_RETRIES, 0xFF, 0x01, 0x14], 5, 100);
if (!send_command_check_ready([
0x4A, // InListPassivTargets
0x01, // Number of cards to init (if in field)
0x00, // Baud rate (106kbit/s)
], 3, 100)) {
error("Unknown error detected during nfc_p2p_scan");
return false;
}
spi_read_data(18);
if (response_buffer[7] > 0) {
local tag = format("%02x%02x%02x", response_buffer[14], response_buffer[15], response_buffer[16]);
return tag
}
return null;
}
function nfc_power_down() {
//server.log("nfc_power_down");
if (!send_command_check_ready([
0x16, // PowerDown
0x20, // Only wake on SPI
], 2, 100)) {
server.log("Unknown error detected during nfc_power_down");
return false;
}
spi_read_data(9);
}
// This command configures the NFC chip to act as a target, much like a standard
// dumb prox card. The ID sent depends on the baud rate. We're using 106kbit/s
// so the NFCID1 will be sent (3 bytes).
function nfc_p2p_target() {
//server.log("nfc_p2p_target");
if (!send_command([
0x8C, // TgInitAsTarget
0x00, // Accepted modes, 0 = all
0x08, 0x00, // SENS_RES
device_id_a, device_id_b, device_id_c, // NFCID1
0x40, // SEL_RES
0x01, 0xFE, 0xA2, 0xA3, // Parameters to build POL_RES (16 bytes)
0xA4, 0xA5, 0xA6, 0xA7,
0xC0, 0xC1, 0xC2, 0xC3,
0xC4, 0xC5, 0xC6, 0xC7,
0xFF, 0xFF,
0xAA, 0x99, 0x88, 0x77, // NFCID3t
0x66, 0x55, 0x44, 0x33,
0x22, 0x11,
0x00, // General bytes
0x00 // historical bytes
], 38, 100)) {
server.log("Unknown error detected during nfc_p2p_target");
return false;
}
}
function send_command_check_ready(cmd, cmdlen, timeout) {
return send_command(cmd, cmdlen, timeout) && check_ready(timeout);
}
function send_command(cmd, cmdlen, timeout) {
local timer = 0;
spi_write_command(cmd, cmdlen);
// Wait for chip to say its ready!
while (spi_read_status() != PN532_SPI_READY) {
if (timeout != 0) {
timer += 10;
if (timer > timeout) {
server.log("No response READY");
return false;
}
}
imp.sleep(0.01);
}
// read acknowledgement
if (!spi_read_ack()) {
server.log("Wrong ACK");
return false;
}
//server.log("read ack");
return true;
}
function check_ready(timeout) {
local timer = 0;
// Wait for chip to say its ready!
while (spi_read_status() != PN532_SPI_READY) {
if (timeout != 0) {
timer += 10;
if (timer > timeout) {
server.log("No response READY");
return false;
}
}
imp.sleep(0.01);
}
return true;
}
function hex_to_i(hex) {
local result = 0;
local shift = hex.len() * 4;
// For each digit..
for(local d = 0; d < hex.len(); d++) {
local digit;
// Convert from ASCII Hex to integer
if(hex[d] >= 0x61)
digit = hex[d] - 0x57;
else if(hex[d] >= 0x41)
digit = hex[d] - 0x37;
else
digit = hex[d] - 0x30;
// Accumulate digit
shift -= 4;
result += digit << shift;
}
return result;
}
function scan_and_sleep() {
if (booted) {
spi_start();
// Scan for nearby NFC devices
local tag_detected = nfc_scan();
// Enter target mode. This allows other readers to read our id.
nfc_p2p_target();
spi_stop();
return tag_detected;
} else {
server.error("PN532 could not be initialized, halting.");
return false;
}
}
}
const WIDTH = 264;
const HEIGHT = 176;
const PIXELS = 46464;
const BYTESPERSCREEN = 5808;
const BYTESPERLINE = 33;
const BYTESPERSCAN = 44;
const CHARCHAR = "%c%c";
const BYTE = 'b';
const SLOTS = 0;
const LINES = 1;
const WHITE_PIXEL = 0xaa;
const BLACK_PIXEL = 0xff;
const NOTHING_PIXEL = 0x00;
const INVERSE = 0xff;
const NORMAL = 0x00;
const REPEAT = 2;
const STEP = 4;
const BLOCK = 32;
class Epaper {
/*
* class to drive Pervasive Displays epaper display
* see http://repaper.org
*/
LINEHEADER = null;
spi = null;
epd_cs_l = null;
busy = null;
therm = null;
pwm = null;
rst_l = null;
pwr_en_l = null;
border = null;
discharge = null;
epd_cs_l_write = null;
spi_write = null;
line_data = null;
scan_line_data = null;
line_cache = null;
line_cache_ptr = null;
line_cache_slots = null;
line_cache_lines = null;
scan_table = null;
black_line = null;
white_line = null;
nothing_line = null;
writer = null;
booted = false;
constructor(width, height, spi, epd_cs_l, busy, therm, pwm, rst_l, pwr_en_l, discharge, border) {
this.LINEHEADER = format("%c%c", 0x70, 0x0A);
epd_cs_l_write = epd_cs_l.write.bindenv(epd_cs_l);
spi_write = spi.write.bindenv(spi);
// Initialize the various caches
local line_data_size = (width / 8) + (height / 4) + 2;
line_data = blob(line_data_size);
line_cache = array(32);
for (local i = 0; i < 32; i++ ) {
line_cache[i] = blob(line_data_size);
}
line_cache_ptr = 0;
line_cache_lines = {};
line_cache_slots = {};
scan_line_data = blob(BYTESPERSCAN);
white_line = junk_line(WHITE_PIXEL, BYTESPERLINE);
black_line = junk_line(BLACK_PIXEL, BYTESPERLINE);
nothing_line = junk_line(0x00, BYTESPERLINE);
writer = line_data.writen.bindenv(line_data);
// initialize the SPI bus
// this is tricky since we're likely sharing it with the SPI flash. Need to use a clock speed that both
// are ok with, or reconfigure the bus on every transaction
// As it turns out, the ePaper display is content with 4 MHz to 12 MHz, all of which are ok with the flash
// Furthermore, the display seems to work just fine at 15 MHz.
this.spi = spi;
//server.log("Display Running at: " + this.spiOff() + " kHz");
this.epd_cs_l = epd_cs_l;
this.epd_cs_l.configure(DIGITAL_OUT);
//this.epd_cs_l.write(0);
// initialize the other digital i/o needed by the display
this.busy = busy;
this.busy.configure(DIGITAL_IN);
this.therm = therm;
this.rst_l = rst_l;
this.rst_l.configure(DIGITAL_OUT);
//this.rst_l.write(1);
this.pwr_en_l = pwr_en_l;
this.pwr_en_l.configure(DIGITAL_OUT);
//this.pwr_en_l.write(1);
this.discharge = discharge;
this.discharge.configure(DIGITAL_OUT);
//this.discharge.write(0);
this.border = border;
this.border.configure(DIGITAL_OUT);
//this.border.write(0);
// must call this to release the spi bus
this.epd_cs_l.write(1);
}
// enable SPI
function spiOn() {
local freq = this.spi.configure(CLOCK_IDLE_HIGH | MSB_FIRST | CLOCK_2ND_EDGE, SPICLK);
this.spi.write("\x00");
imp.sleep(0.00001);
//server.log("running at " + freq);
return freq;
}