This repository has been archived by the owner on Jan 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdctt.ino
1580 lines (1372 loc) · 45.3 KB
/
dctt.ino
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
/*
Copyright (C) 2014 Axis Communications
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// Serial baudrate of the Arduino.
#define SERIAL_BAUD 57600
// Websocket heartbeats.
#define HEARTBEAT_INTERVAL 5
#define HEARTBEAT_TIMEOUT 15
// Webserver fail message.
#define WEBDUINO_FAIL_MESSAGE ""
// Buffer for sending files to client.
#define FILE_TX_BUFFER_SIZE 64
// Reserved pins.
#define ETHERNET_SELECT_PIN 10
#define SD_CARD_SELECT_PIN 4
#define SS_HARDWARE_PIN 53
#define RESET_PIN 40
// Favicon
#define WEBDUINO_FAVICON_DATA ""
//#define WEBDUINO_SERIAL_DEBUGGING 1
// Receiving larger door configuration files requires
// a longer timeout, 5 seconds has so far worked well
#define WEBDUINO_READ_TIMEOUT_IN_MS 5000
// Toggle bonjour/zeroconf functionality.
#undef BONJOUR_ENABLED
#include "SPI.h"
#include "avr/pgmspace.h"
#include "Ethernet.h"
#include "WebSocket.h"
#include "WebServer.h"
#include <EEPROM.h>
#include <SD.h>
#include "aJSON.h"
#include "SimpleTimer.h"
// STL stuff
#include <StandardCplusplus.h>
#include <vector>
#include <serstream>
// Door-specific files.
#include "PACSDoor.h"
#include "PACSReader.h"
#include "PACSPeripheral.h"
#include "PACSDoorManager.h"
#include "Network.h"
// For freemem.
#include "System.h"
#ifdef BONJOUR_ENABLED
#include "EthernetBonjour.h"
#endif
using namespace std;
// Cout pipes to serial.
namespace std {
ohserialstream cout(Serial);
}
System sys;
WebServer* webserver;
WebSocket websocketServer;
PACSDoorManager doorManager;
Network network;
// Pin mappings. Index is pin number.
char digitalPins[54][4];
char analogPins[16][4];
// Webserver filenames.
char* indexFilename = "index.htm";
// Configuration filenames.
const char* pinsConfigFilename = "config/pins.cfg";
const char* doorsConfigFilename = "config/doors.cfg";
int last_free_ram = 0;
/*
* Helper class for reading/writing aJSON to/from the WebServer
*/
class WebServeraJsonStream : public aJsonStream {
public:
WebServeraJsonStream(WebServer* webserver_): aJsonStream(NULL), webserver(webserver_) {}
virtual bool available() {
if (bucket != EOF)
return true;
return webserver->available();
}
private:
virtual size_t write(uint8_t ch) { return webserver->write(ch); }
virtual int getch() {
int retVal = bucket;
if (retVal != EOF) {
bucket = EOF;
}
else {
retVal = webserver->read();
if (retVal == -1)
retVal = EOF;
}
return retVal;
}
WebServer* webserver;
};
// API commands
typedef enum Command
{
SWIPECARD,
ENTERPIN,
OPENDOOR,
CLOSEDOOR,
PUSHREX,
ACTIVATEINPUT,
DEACTIVATEINPUT,
GETPERIPHERALSTATE,
UNDEFINED,
};
/*
* Mounts the SD card.
*/
void setupSDCard() {
// Disable ethernet shield SPI while setting up SD
pinMode(ETHERNET_SELECT_PIN, OUTPUT);
digitalWrite(ETHERNET_SELECT_PIN, HIGH);
cout << F("Mounting SD Card...");
if(!SD.begin(SD_CARD_SELECT_PIN)) {
cout << F(" failed.\n");
while (true) delay(100); // Don't continue if we fail.
}
else {
cout << F(" OK.\n");
} // SD.begin() returns with its SPI disabled, so no need to do it ourselves.
}
/*
* Help function to print out free mem (to check for mem-leaks).
*/
void freeMem() {
int freeRam = sys.ramFree();
if (last_free_ram != freeRam) {
cout << F("Free RAM: ") << freeRam << F(" bytes (")
<< sys.ramSize() << F(" total).") << endl;
last_free_ram = freeRam;
}
}
/*
* Sends a file on the SD card to the client.
*/
void sendFile(WebServer &server, const char* type, const char* filename)
{
byte txBuffer[FILE_TX_BUFFER_SIZE];
int bytesRead = 0;
P(could_not_open_file) = "Could not open file: ";
File fileStream = SD.open(filename);
if (!fileStream) {
server.httpFail();
server.printP(could_not_open_file);
server.print(filename);
return;
}
// Opening of file was successful, so send correct content
// type and start sending the file in "chunks".
server.httpSuccess(type);
while (fileStream.available())
{
txBuffer[bytesRead] = fileStream.read();
bytesRead++;
if(bytesRead == FILE_TX_BUFFER_SIZE)
{
server.write(txBuffer, FILE_TX_BUFFER_SIZE);
bytesRead = 0;
}
}
if(bytesRead > 0) {
server.write(txBuffer, bytesRead);
}
server.printCRLF();
fileStream.close();
}
/*
* Saves a file on the SD card from the client
*/
void receiveFile(WebServer &server, const char* filename)
{
byte txBuffer[FILE_TX_BUFFER_SIZE];
int bytesRead = 0;
P(could_not_open_file) = "Could not open file: ";
if (SD.exists((char*) filename))
SD.remove((char*) filename);
File fileStream = SD.open(filename, FILE_WRITE);
if (!fileStream) {
server.httpFail();
server.printP(could_not_open_file);
server.print(filename);
return;
}
int c = server.read();
// Opening of file was successful
while (c != -1)
{
fileStream.write(c);
c = server.read();
}
fileStream.close();
}
/* *****************************************************************************************************
*
* Configuration Section
*
***************************************************************************************************** */
/*
* Used by the functions that load the pin and door configuration. Waits for
* data to appear in the stream or timeout to occur, then returns.
*/
void waitForData(Stream& stream, int timeout) {
unsigned long i = millis() + timeout;
while ((!stream.available()) && (millis() < i)) /* spin with a timeout*/;
}
/*
* Find the next quotation-mark, and read all bytes until quotation-mark
* after that.
*/
bool getNextToken(Stream& stream, char* tokenBuffer, uint8_t length) {
stream.find("\"");
uint8_t bytesRead = stream.readBytesUntil('"', tokenBuffer, length);
tokenBuffer[bytesRead] = '\0';
if (bytesRead > 0)
return true;
else
return false;
}
// An enum to keep track of what we are parsing, when loading
// the door configuration file.
// We put the enum in its oown namespace to prevent poluting
// the global one.
namespace Cfg {
enum Pos {
NONE, DOOR, READER, DOOR_MONITOR, REX, LOCK, DIGITAL_INPUT, DIGITAL_OUTPUT, //Container
WIEGAND, GREEN_LED, BEEPER, //Subcontainer
ID, PIN, PIN_ZERO, PIN_ONE, ACTIVE //Property
};
enum PinType {DIGITAL, ANALOG};
};
/*
* This function is used to load the pin mappings from the configuration-
* file on the SD card. Each pin has a 3 character long id, which is stored
* in an array. This array is needed for lookup as the door configuration
* file references these id:s, instead of the actual pin numbers.
*
* A custom parser is needed as there is not enough memory to load the entire
* config file into memory.
*/
bool loadPinMappingsFromFile(const char* filename) {
Cfg::PinType cfgPinType = Cfg::DIGITAL;
const uint8_t tokenBufferLength = 4;
char tokenBuffer[tokenBufferLength] = "";
bool parsingSucceeded = false;
int i = 0;
uint8_t pin;
File fileStream;
if (!SD.exists((char*) filename)) {
// create a default pin mapping file
fileStream = SD.open(filename, FILE_WRITE);
if (!fileStream) {
cout << F("Error opening ") << filename << endl;
return false;
}
char buf[16];
for (i = 0; i < 70; i++) {
switch (i)
{
case 0:
strcpy(buf, "{\"0\":\"RSV\"");
break;
case 1:
case 4:
case 10:
case 50:
case 51:
case 52:
case 53:
sprintf(buf, ",\"%d\":\"RSV\"", i);
break;
default:
if (i < 54)
sprintf(buf, ",\"%d\":\"N/A\"", i);
else
sprintf(buf, ",\"A%d\":\"N/A\"", i - 54);
}
fileStream.write((uint8_t*) buf, strlen(buf));
}
fileStream.write('}');
fileStream.close();
}
// Open the file.
fileStream = SD.open(filename);
if (!fileStream) {
cout << F("Error opening ") << filename << endl;
return false;
}
while (true) {
if (cfgPinType == Cfg::DIGITAL) {
// Get the digital pin number.
getNextToken(fileStream, tokenBuffer, tokenBufferLength);
pin = (uint8_t)atoi(tokenBuffer);
// Make sure that the parsed pin is "correct", i.e. in numerical order.
if (pin != i) {
cout << F("Expected pin number ") << (int)i << ", got " << (int)pin << endl;
break;
}
// Get the pin id and save to array.
getNextToken(fileStream, tokenBuffer, tokenBufferLength);
strcpy(digitalPins[i], tokenBuffer);
digitalPins[i][3] = '\0';
}
else if (cfgPinType == Cfg::ANALOG) {
// Get the analog pin number.
getNextToken(fileStream, tokenBuffer, tokenBufferLength);
// Convert it to the actual analog pin number.
uint8_t parsedPin;
if (strcmp(tokenBuffer, "A0") == 0) parsedPin = A0;
else if (strcmp(tokenBuffer, "A1") == 0) parsedPin = A1;
else if (strcmp(tokenBuffer, "A2") == 0) parsedPin = A2;
else if (strcmp(tokenBuffer, "A3") == 0) parsedPin = A3;
else if (strcmp(tokenBuffer, "A4") == 0) parsedPin = A4;
else if (strcmp(tokenBuffer, "A5") == 0) parsedPin = A5;
else if (strcmp(tokenBuffer, "A6") == 0) parsedPin = A6;
else if (strcmp(tokenBuffer, "A7") == 0) parsedPin = A7;
else if (strcmp(tokenBuffer, "A8") == 0) parsedPin = A8;
else if (strcmp(tokenBuffer, "A9") == 0) parsedPin = A9;
else if (strcmp(tokenBuffer, "A10") == 0) parsedPin = A10;
else if (strcmp(tokenBuffer, "A11") == 0) parsedPin = A11;
else if (strcmp(tokenBuffer, "A12") == 0) parsedPin = A12;
else if (strcmp(tokenBuffer, "A13") == 0) parsedPin = A13;
else if (strcmp(tokenBuffer, "A14") == 0) parsedPin = A14;
else if (strcmp(tokenBuffer, "A15") == 0) parsedPin = A15;
else {
cout << F("Expected analog pin number, got ") << tokenBuffer << endl;
break;
}
// Get the pin id and save to array.
getNextToken(fileStream, tokenBuffer, tokenBufferLength);
strcpy(analogPins[i], tokenBuffer);
analogPins[i][3] = '\0';
}
// If we have parsed the last analog pin, we are finished!
if ((cfgPinType == Cfg::ANALOG) && (i == 15)) {
fileStream.close();
parsingSucceeded = true;
break;
}
// If we have parsed the last digital pin, switch to parsing the analog ones.
else if (i == 53) {
cfgPinType = Cfg::ANALOG;
i = 0;
}
// Otherwise, we are not finished. So just do the next one.
else {
i++;
}
}
// Close the file and return if we succeeded or not.
fileStream.close();
return (parsingSucceeded ? true : false);
}
/*
* Returns a pin number given the passed pin id.
*/
uint8_t getPinNumber(char* pinId) {
// Check for a match in the digital pins lookup table.
for (int i=0;i<=53;i++) {
if (strcmp(digitalPins[i], pinId) == 0) {
return i;
}
}
// If we didn't find a match there, we check the analog
// pins.
for (int i=0;i<=15;i++) {
if (strcmp(analogPins[i], pinId) == 0) {
switch (i) {
case 0: return A0;
case 1: return A1;
case 2: return A2;
case 3: return A3;
case 4: return A4;
case 5: return A5;
case 6: return A6;
case 7: return A7;
case 8: return A8;
case 9: return A9;
case 10: return A10;
case 11: return A11;
case 12: return A12;
case 13: return A13;
case 14: return A14;
case 15: return A15;
}
}
}
// If we find nothing...
cout << F("No matching pin number found for pin id ") << pinId << endl;
return 255;
}
/*
* Returns a pin number given the passed pin id.
*/
uint8_t isValidPin(int pinId) {
return (pinId != 255 ? true : false);
}
/*
* Parses a door "chunk" and using DoorManager, adds the doors and peripherals.
* This method is pretty brutal. Could be done much nicer.
*/
int parseDoor(Stream& stream, char* startToken, char* stopToken) {
// The passed stream points at the character after the door token,
// e.g. "DOOR2": { "blah": "blah" }
// ^---- points here
const uint8_t tokenLength = 16;
char token[tokenLength] = "";
uint8_t openBraces = 0;
Cfg::Pos cfgPos = Cfg::DOOR;
Cfg::Pos cfgParent = Cfg::NONE;
// Create temporary PACS-objects with rubbish values.
// These will receive proper values during parsing.
PACSDoor* tempDoor = doorManager.createDoor("temp");
PACSReader tempReader("temprdr", 255, 255);
PACSPeripheral tempPeripheral("tempper", GREENLED, 255, LOW);
// Keep parsing while there are more tokens in stream.
while(getNextToken(stream, token, tokenLength)) {
// Check if we've parsed the entire door.
if (strcmp(token, stopToken) == 0) {
// We return false to specify that there are more doors.
return 1;
}
//
// "CONTAINERS"
//
else if (strcmp(token, "Reader") == 0) {
cfgPos = Cfg::READER;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
else if (strcmp(token, "REX") == 0) {
cfgPos = Cfg::REX;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
else if (strcmp(token, "DoorMonitor") == 0) {
cfgPos = Cfg::DOOR_MONITOR;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
else if (strcmp(token, "Lock") == 0) {
cfgPos = Cfg::LOCK;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
else if (strcmp(token, "Input") == 0) {
cfgPos = Cfg::DIGITAL_INPUT;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
else if (strcmp(token, "Output") == 0) {
cfgPos = Cfg::DIGITAL_OUTPUT;
cfgParent = Cfg::DOOR;
openBraces = 0;
}
//
// "SUB-CONTAINERS"
//
else if (strcmp(token, "Wiegand") == 0) {
cfgPos = Cfg::WIEGAND;
cfgParent = Cfg::READER;
}
else if (strcmp(token, "GreenLED") == 0) {
cfgPos = Cfg::GREEN_LED;
cfgParent = Cfg::READER;
}
else if (strcmp(token, "Beeper") == 0) {
cfgPos = Cfg::BEEPER;
cfgParent = Cfg::READER;
}
//
// STRING/INT OBJECTS
//
else if (strcmp(token, "Id") == 0) {
getNextToken(stream, token, tokenLength);
switch (cfgPos) {
case Cfg::DOOR:
strcpy(tempDoor->id, token);
break;
case Cfg::WIEGAND:
strcpy(tempReader.id, token);
break;
case Cfg::GREEN_LED:
case Cfg::BEEPER:
case Cfg::DOOR_MONITOR:
case Cfg::REX:
case Cfg::LOCK:
case Cfg::DIGITAL_INPUT:
case Cfg::DIGITAL_OUTPUT:
strcpy(tempPeripheral.id, token);
}
}
else if (strcmp(token, "Pin") == 0) {
getNextToken(stream, token, tokenLength);
switch (cfgPos) {
case Cfg::GREEN_LED:
case Cfg::BEEPER:
case Cfg::DOOR_MONITOR:
case Cfg::REX:
case Cfg::LOCK:
case Cfg::DIGITAL_INPUT:
case Cfg::DIGITAL_OUTPUT:
tempPeripheral.pin = getPinNumber(token);
if (!isValidPin) {
return -1;
}
}
}
else if (strcmp(token, "Pin0") == 0) {
getNextToken(stream, token, tokenLength);
switch (cfgPos) {
case Cfg::WIEGAND:
tempReader.pin0 = getPinNumber(token);
if (!isValidPin) {
return -1;
}
}
}
else if (strcmp(token, "Pin1") == 0) {
getNextToken(stream, token, tokenLength);
switch (cfgPos) {
case Cfg::WIEGAND:
tempReader.pin1 = getPinNumber(token);
if (!isValidPin) {
return -1;
}
}
}
else if (strcmp(token, "ActiveLevel") == 0) {
getNextToken(stream, token, tokenLength);
switch (cfgPos) {
case Cfg::DOOR_MONITOR:
case Cfg::REX:
case Cfg::LOCK:
case Cfg::DIGITAL_INPUT:
case Cfg::DIGITAL_OUTPUT:
case Cfg::GREEN_LED:
case Cfg::BEEPER:
if (strcmp(token, "HIGH") == 0) {
tempPeripheral.activeLevel = HIGH;
}
else if (strcmp(token, "LOW") == 0) {
tempPeripheral.activeLevel = LOW;
}
}
}
// Token is parsed. Now we need to traverse the container.
while ((stream.available()) && (stream.peek() != '"')) {
switch (stream.read()) {
case ']':
cfgPos = Cfg::DOOR;
cfgParent = Cfg::NONE;
break;
case '{':
openBraces++;
break;
case '}':
openBraces--;
// Closing Curly brace means an object has "ended", which
// means we can save something.
if (cfgParent == Cfg::READER) {
switch (cfgPos) {
case Cfg::WIEGAND:
tempDoor->addReader(tempReader.id,
tempReader.pin0,
tempReader.pin1);
break;
case Cfg::GREEN_LED:
tempDoor->addPeripheral(tempPeripheral.id,
GREENLED,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
case Cfg::BEEPER:
tempDoor->addPeripheral(tempPeripheral.id,
BEEPER,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
}
// Move the parse position up a level.
cfgPos = Cfg::READER;
cfgParent = Cfg::DOOR;
}
else if (cfgParent == Cfg::DOOR) {
switch (cfgPos) {
case Cfg::DOOR_MONITOR:
tempDoor->addPeripheral(tempPeripheral.id,
DOORMONITOR,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
case Cfg::REX:
tempDoor->addPeripheral(tempPeripheral.id,
REX,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
case Cfg::LOCK:
tempDoor->addPeripheral(tempPeripheral.id,
LOCK,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
case Cfg::DIGITAL_INPUT:
tempDoor->addPeripheral(tempPeripheral.id,
DIGITAL_INPUT,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
case Cfg::DIGITAL_OUTPUT:
tempDoor->addPeripheral(tempPeripheral.id,
DIGITAL_OUTPUT,
tempPeripheral.pin,
tempPeripheral.activeLevel);
break;
}
}
else if (cfgParent == Cfg::NONE) {
//Do nothing
}
}
}
}
// If we got to this point, it means there was no stop token found, i.e.
// we have parsed the last door.
return 0;
}
/*
* Opens the door config file for reading and sends the doors it is comprised of
* for parsing, one at a time.
*/
bool parsDoorConfiguration(Stream& stream) {
const uint8_t MAX_NO_OF_DOORS = 16;
uint8_t currentDoor = 1;
char conversionBuffer[3];
bool doorsAvailable = true;
cout << F("Parsing door: ");
// Parse the door objects (as many as we can find, up
// to the defined maximum).
while(doorsAvailable == 1) {
// Construct the start/stop door-number string, e.g. "DOOR3", "DOOR4"
char currentDoorToken[10] = "DOOR";
char nextDoorToken[10] = "DOOR";
itoa(currentDoor, conversionBuffer, 10);
strcat(currentDoorToken, conversionBuffer);
itoa(currentDoor+1, conversionBuffer, 10);
strcat(nextDoorToken, conversionBuffer);
cout << (int)currentDoor << F(" ");
// Check if there's a door config entry for this door number.
// If there is, we create a door and start parsing it.
waitForData(stream, 1000);
// Do the actual parsing of the door.
doorsAvailable = parseDoor(stream, currentDoorToken, nextDoorToken);
// Check if there was an error while parsing.
if (doorsAvailable == -1) {
return false;
}
// Check if we have reached our door limit.
else if (currentDoor == MAX_NO_OF_DOORS) {
cout << F("Maximum number of doors reached.\n");
return false;
}
else {
currentDoor++;
}
}
cout << endl;
return true;
}
/*
* This function loads the door configuration, which should be in
* JSON format.
*
* It must be structured in a certain way, specified in the documentation.
* A custom parser is needed as there is not enough memory to load the entire
* config file into memory.
*/
bool loadDoorConfigurationFromFile(const char* filename) {
File doorCfgFile;
bool parsingSucceeded;
// Open the config file
doorCfgFile = SD.open(filename);
if (!doorCfgFile) {
cout << F("Error opening ") << filename << endl;
return false;
}
parsingSucceeded = parsDoorConfiguration(doorCfgFile);
doorCfgFile.close();
return (parsingSucceeded ? true : false);
}
/*
* Print a sumamry of the configured doors and peripherals to serial.
*/
void printDoorConfiguration() {
for (unsigned i=0; i < doorManager.doors.size(); i++) {
std::cout << "Door:" << std::endl
<< " Id: " << doorManager.doors[i].id << std::endl;
std::cout << "Wiegand:\n";
for (unsigned j=0; j < doorManager.doors[i].readers.size(); j++) {
std::cout << " Id: " << doorManager.doors[i].readers[j].id <<
" Pin0: " << (int)doorManager.doors[i].readers[j].pin0 <<
" Pin1: " << (int)doorManager.doors[i].readers[j].pin1
<< std::endl;
}
std::cout << "Peripherals:\n";
for (unsigned j=0; j < doorManager.doors[i].peripherals.size(); j++) {
std::cout << " Id: " << doorManager.doors[i].peripherals[j].id <<
" Pin: " << (int)doorManager.doors[i].peripherals[j].pin <<
" ActiveLevel: " << (int)doorManager.doors[i].peripherals[j].activeLevel
<< std::endl;
}
std::cout << std::endl;
}
}
/* *****************************************************************************************************
*
* Webserver Section
*
***************************************************************************************************** */
/*
* Called whenever a non extisting page is called.
*/
void errorHTML(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete)
{
server.httpFail();
if (type == WebServer::HEAD)
return;
server.print(F("<html><head><title>HTTP 400</title></head><body>\n"));
server.print(F("<h2>HTTP 400 - Bad Request</h2>\n"));
server.print(F("<p>The request cannot be fulfilled due to bad syntax.</p>\n"));
server.print(F("</body></html>"));
}
/*
* Called for default JSON extension file requests
*/
void webAppJsonFile(WebServer &server, WebServer::ConnectionType type, char **url_path, char *url_tail, bool tail_complete)
{
if (type == WebServer::GET)
cout << F("Client is GETting file: ");
else if (type == WebServer::POST)
cout << F("Client is POSTting file: ");
else
cout << F("Client is ???ing file: ");
cout << *url_path << endl;
if (strcmp(*url_path, "networksettings.json") == 0)
{
aJsonObject *root = NULL;
WebServeraJsonStream webstream(&server);
//doors.json
//pins.json
if (type == WebServer::GET) {
root = aJson.createObject();
network.settingsToJSON(root);
// send correct content type
server.httpSuccess("application/json");
aJson.print(root, &webstream);
server.printCRLF();
}
else if (type == WebServer::POST) {
root = aJson.parse(&webstream);
network.settingsFromJSON(root);
network.printConfiguration();
}
if (root != NULL) {
aJson.deleteItem(root);
}
}
else if (strcmp(*url_path, "doors.json") == 0)
{
if (type == WebServer::GET) {
sendFile(server, "application/json", doorsConfigFilename);
} else if (type == WebServer::POST) {
receiveFile(server, doorsConfigFilename);
}
}
else if (strcmp(*url_path, "pins.json") == 0)
{
if (type == WebServer::GET) {
sendFile(server, "application/json", pinsConfigFilename);
} else if (type == WebServer::POST) {
receiveFile(server, pinsConfigFilename);
}
}
else
{
server.print(F("<html><head><title>HTTP 404</title></head><body>\n"));
server.print(F("<h2>HTTP 404 - Not Found</h2>\n"));
server.print(F("<p>The requested object can not be found.</p>\n"));
server.print(F("</body></html>"));
}
}
/*
* Called for all the remaining cases. We need to check if the requested file is one we are servering,
* and if so, send it to the client.
*/
void webAppFile(WebServer &server, WebServer::ConnectionType type, char **url_path, char *url_tail, bool tail_complete)
{
// For a HEAD request, we just stop after outputting headers.
if (type == WebServer::HEAD)
return;
// Check if requested file is one we are serving on SD card.
if (strcmp(*url_path, "index.htm") == 0 || strcmp(*url_path, "app.js") == 0 ||
strcmp(*url_path, "keypad.mp3") == 0 || strcmp(*url_path, "favicon.ico") == 0)
{
cout << F("Client is requesting file: ") << *url_path << endl;
// Create a full filename path. 32 characters should be
// enough for 8+3 filenames and the folder structure we have.
char fullFilename[32];
sprintf(fullFilename, "web/%s", *url_path);
// It was successfully opened, so send the client a http 200 with correct
// content type depending on the file.
if (strcmp(*url_path, "app.js") == 0) {
sendFile(server, "text/javascript; charset=utf-8", fullFilename);
}
else if (strcmp(*url_path, "keypad.mp3") == 0) {
sendFile(server, "audio/mpeg", fullFilename);
}
else if (strcmp(*url_path, "favicon.ico") == 0) {
sendFile(server, "image/x-icon", fullFilename);
}
else {
sendFile(server, "text/html; charset=utf-8", fullFilename);
}
}
else if ((*url_path, ".json") != 0)
{
webAppJsonFile(server, type, url_path, url_tail, tail_complete);
}
// If we didn't get a match for any of the files we serve, we send the client
// a http 4xx error.
else {
errorHTML(server, type, url_tail, tail_complete);
}
}
/*
* Called when client requests the root url. We just redirect to our url-path function
* which handles all our web files (including the index.htm).
*/
void defaultHTML(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete)
{
webAppFile(server, type, &indexFilename, url_tail, tail_complete);
}
/*
* Returns a http fail message to the user in case of failed API command.
*/
void apiResponse(bool requestSuccessful, const unsigned char* message) {
if (requestSuccessful) {
webserver->httpFail();
}
else {
webserver->httpSuccess();
}
webserver->printP(message);
webserver->printCRLF();
}
/*
* This is the api route for sending http commands.
* Three post parameters need to be specified:
* cmd (the action to be performed, must come first!)
* doorId (id of the target door)
* id (id of the target peripheral)
* Alternatively, you can send in a json structure.
*/