forked from ClusterDuck-Protocol/ClusterDuck-Protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClusterDuck.cpp
More file actions
981 lines (786 loc) · 24.7 KB
/
Copy pathClusterDuck.cpp
File metadata and controls
981 lines (786 loc) · 24.7 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
#include "ClusterDuck.h"
U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ CDPCFG_PIN_OLED_CLOCK, /* data=*/ CDPCFG_PIN_OLED_DATA, /* reset=*/ CDPCFG_PIN_OLED_RESET);
IPAddress apIP(CDPCFG_AP_IP1, CDPCFG_AP_IP2, CDPCFG_AP_IP3, CDPCFG_AP_IP4);
AsyncWebServer webServer(CDPCFG_WEB_PORT);
SX1276 lora = new Module(CDPCFG_PIN_LORA_CS, CDPCFG_PIN_LORA_DIO0, CDPCFG_PIN_LORA_RST, CDPCFG_PIN_LORA_DIO1);
auto tymer = timer_create_default();
byte transmission[CDPCFG_CDP_BUFSIZE];
int packetIndex = 0;
String ssid = "";
String password = "";
String ClusterDuck::_deviceId = "";
bool restartRequired = false;
size_t content_len;
//Username and password for /update
const char* http_username = CDPCFG_UPDATE_USERNAME;
const char* http_password = CDPCFG_UPDATE_PASSWORD;
ClusterDuck::ClusterDuck() {
}
void ClusterDuck::setDeviceId(String deviceId) {
_deviceId = deviceId;
}
void ClusterDuck::begin(int baudRate) {
Serial.begin(baudRate);
Serial.print("Serial start ");
Serial.println(baudRate, DEC);
}
void ClusterDuck::setupDisplay(String deviceType) {
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.setCursor(0, 1);
u8x8.print(" ((>.<)) ");
u8x8.setCursor(0, 2);
u8x8.print(" Project OWL ");
u8x8.setCursor(0, 4);
u8x8.print("Device: " + deviceType);
u8x8.setCursor(0, 5);
u8x8.print("Status: Online");
u8x8.setCursor(0, 6);
u8x8.print("ID: " + _deviceId);
u8x8.setCursor(0, 7);
u8x8.print(duckMac(false));
}
// Initial LoRa settings
void ClusterDuck::setupLoRa(long BAND, int SS, int RST, int DI0, int DI1, int TxPower) {
//LoRa.setSignalBandwidth(62.5E3);
lora = new Module(SS, DI0, RST, DI1);
Serial.println("Starting LoRa......");
int state = lora.begin(); //TODO: Make more modular -> Bandwidth, Spreading factor
//Initialize LoRa
if (state == ERR_NONE) {
Serial.println("LoRa online, Quack!");
} else {
u8x8.clear();
u8x8.drawString(0, 0, "Starting LoRa failed!");
Serial.print("Starting LoRa Failed!!!");
Serial.println(state);
restartDuck();
}
if (lora.setFrequency(CDPCFG_RF_LORA_FREQ) == ERR_INVALID_FREQUENCY) {
Serial.println(F("Selected frequency is invalid for this module!"));
while (true);
}
if (lora.setBandwidth(CDPCFG_RF_LORA_BW) == ERR_INVALID_BANDWIDTH) {
Serial.println(F("Selected bandwidth is invalid for this module!"));
while (true);
}
if (lora.setSpreadingFactor(CDPCFG_RF_LORA_SF) == ERR_INVALID_SPREADING_FACTOR) {
Serial.println(F("Selected spreading factor is invalid for this module!"));
while (true);
}
if (lora.setOutputPower(CDPCFG_RF_LORA_TXPOW) == ERR_INVALID_OUTPUT_POWER) {
Serial.println(F("Selected output power is invalid for this module!"));
while (true);
}
if (lora.setGain(CDPCFG_RF_LORA_GAIN) == ERR_INVALID_GAIN) {
Serial.println(F("Selected gain is invalid for this module!"));
while (true);
}
lora.setDio0Action(setFlag);
state = lora.startReceive();
if (state == ERR_NONE) {
Serial.println("Listening for quacks");
} else {
Serial.print("failed, code ");
Serial.println(state);
restartDuck();
}
}
//============= Used for receiving LoRa packets ==========
volatile bool receivedFlag = false;
// disable interrupt when it's not needed
volatile bool enableInterrupt = true;
void ClusterDuck::setFlag(void) {
// check if the interrupt is enabled
if(!enableInterrupt) {
return;
}
// we got a packet, set the flag
receivedFlag = true;
}
// =====================================
// handle the upload of the firmware
void handleFirmwareUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t lenght, bool final){
// handle upload and update
if (!index) {
Serial.printf("Update: %s\n", filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
}
// flashing firmware to ESP
if (lenght){
Update.write(data, lenght);
}
if (final) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %ub written\nRebooting...\n", index+lenght);
} else {
Update.printError(Serial);
}
}
}
//Setup WebServer
void ClusterDuck::setupWebServer(bool createCaptivePortal) {
Serial.println("Setting up Web Server");
webServer.onNotFound([&](AsyncWebServerRequest *request) {
request->send(200, "text/html", portal);
});
webServer.on("/", HTTP_GET, [&](AsyncWebServerRequest *request) {
request->send(200, "text/html", portal);
});
// Update Firmware OTA
webServer.on("/update", HTTP_GET, [&](AsyncWebServerRequest *request){
if(!request->authenticate(http_username, http_password))
return request->requestAuthentication();
AsyncWebServerResponse *response = request->beginResponse(200, "text/html", update_page);
request->send(response);
});
webServer.on("/update", HTTP_POST, [&](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response = request->beginResponse((Update.hasError())?500:200, "text/plain", (Update.hasError())?"FAIL":"OK");
response->addHeader("Connection", "close");
response->addHeader("Access-Control-Allow-Origin", "*");
request->send(response);
restartRequired = true;
}, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
if (!index) {
lora.standby();
Serial.println("Pause Lora");
Serial.println("startint OTA update");
content_len = request->contentLength();
int cmd = (filename.indexOf("spiffs") > -1) ? U_SPIFFS : U_FLASH;
if (!Update.begin(UPDATE_SIZE_UNKNOWN, cmd)) {
Update.printError(Serial);
}
}
if (Update.write(data, len) != len) {
Update.printError(Serial);
lora.startReceive();
}
if (final) {
if (Update.end(true)) {
ESP.restart();
esp_task_wdt_init(1,true);
esp_task_wdt_add(NULL);
while(true);
}
}
});
// Captive Portal form submission
webServer.on("/formSubmit", HTTP_POST, [&](AsyncWebServerRequest *request) {
Serial.println("Submitting Form");
int paramsNumber = request->params();
String val = "";
for (int i = 0; i < paramsNumber; i++) {
AsyncWebParameter *p = request->getParam(i);
Serial.printf("%s: %s", p->name().c_str(), p->value().c_str());
Serial.println();
val = val + p->value().c_str() + "*";
}
sendPayloadStandard(val);
request->send(200, "text/html", portal);
});
webServer.on("/id", HTTP_GET, [&](AsyncWebServerRequest *request) {
request->send(200, "text/html", _deviceId);
});
webServer.on("/restart", HTTP_GET, [&](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Restarting...");
delay(1000);
restartDuck();
});
webServer.on("/mac", HTTP_GET, [&](AsyncWebServerRequest *request) {
String mac = duckMac(true);
request->send(200, "text/html", mac);
});
webServer.on("/wifi", HTTP_GET, [&](AsyncWebServerRequest *request) {
AsyncResponseStream *response = request->beginResponseStream("text/html");
response->print("<!DOCTYPE html><html><head><title>Update Wifi Credentials</title></head><body>");
response->print("<p>Use this page to update your Wifi credentials</p>");
response->print("<form action='/changeSSID' method='post'>");
response->print("<label for='ssid'>SSID:</label><br>");
response->print("<input name='ssid' type='text' placeholder='SSID' /><br><br>");
response->print("<label for='pass'>Password:</label><br>");
response->print("<input name='pass' type='text' placeholder='Password' /><br><br>");
response->print("<input type='submit' value='Submit' />");
response->print("</form>");
response->print("</body></html>");
request->send(response);
});
webServer.on("/changeSSID", HTTP_POST, [&](AsyncWebServerRequest *request) {
int paramsNumber = request->params();
String val = "";
String SSID = "";
String PASSWORD = "";
for (int i = 0; i < paramsNumber; i++) {
AsyncWebParameter *p = request->getParam(i);
String name = String(p->name());
String value = String(p->value());
if (name == "ssid") {
SSID = String(p->value());
} else if (name == "pass") {
PASSWORD = String(p->value());
}
}
if (SSID != "" && PASSWORD != "") {
setupInternet(SSID, PASSWORD);
request->send(200, "text/plain", "Success");
} else {
request->send(500, "text/plain", "There was an error");
}
});
webServer.begin();
}
void ClusterDuck::setupWifiAp(const char *AP) {
WiFi.mode(WIFI_AP);
WiFi.softAP(AP);
delay(200); // wait for 200ms for the access point to start before configuring
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
Serial.println("Created Wifi Access Point");
}
void ClusterDuck::setupDns() {
dnsServer.start(DNS_PORT, "*", apIP);
if (!MDNS.begin(DNS))
{
Serial.println("Error setting up MDNS responder!");
}
else
{
Serial.println("Created local DNS");
MDNS.addService("http", "tcp", CDPCFG_WEB_PORT);
}
}
void ClusterDuck::setupInternet(String SSID, String PASSWORD)
{
ssid = SSID;
password = PASSWORD;
Serial.println();
Serial.print("Connecting to ");
Serial.print(SSID);
if (SSID != "" && PASSWORD != "") {
// Connect to Access Point
WiFi.begin(SSID.c_str(), PASSWORD.c_str());
while (WiFi.status() != WL_CONNECTED)
{
tymer.tick(); //Advance timer to reboot after awhile
//TODO: Change this to make sure it is non-blocking for all other processes
}
// Connected to Access Point
Serial.println("");
Serial.println("DUCK CONNECTED TO INTERNET");
}
}
//Setup OTA
void ClusterDuck::setupOTA(){
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
}
//Setup premade DuckLink with default settings
void ClusterDuck::setupDuckLink() {
setupDisplay("Duck");
setupLoRa();
setupWifiAp();
setupDns();
setupWebServer(true);
setupOTA();
Serial.println("Duck Online");
}
void ClusterDuck::runDuckLink() {
ArduinoOTA.handle();
processPortalRequest();
}
void ClusterDuck::setupDetect() {
setupDisplay("Detector");
setupLoRa();
setupWifiAp();
setupDns();
setupWebServer(false);
setupOTA();
Serial.println("Detector Online");
}
int ClusterDuck::runDetect() {
ArduinoOTA.handle();
int val = 0;
if(receivedFlag) { //If LoRa packet received
receivedFlag = false;
enableInterrupt = false;
int pSize = handlePacket();
Serial.print("runDetect pSize ");
Serial.println(pSize);
if(pSize > 0) {
for(int i=0; i < pSize; i++) {
if(transmission[i] == iamhere_B) {
val = lora.getRSSI();
}
}
}
enableInterrupt = true;
Serial.println("runDetect startReceive");
startReceive();
}
return val;
}
void ClusterDuck::processPortalRequest() {
dnsServer.processNextRequest();
}
void ClusterDuck::setupMamaDuck() {
setupDisplay("Mama");
setupLoRa();
setupWifiAp();
setupDns();
setupWebServer(true);
setupOTA();
Serial.println("MamaDuck Online");
tymer.every(CDPCFG_MILLIS_ALIVE, imAlive);
tymer.every(CDPCFG_MILLIS_REBOOT, reboot);
}
void ClusterDuck::runMamaDuck() {
ArduinoOTA.handle();
tymer.tick();
if(receivedFlag) { //If LoRa packet received
receivedFlag = false;
enableInterrupt = false;
int pSize = handlePacket();
Serial.print("runMamaDuck pSize ");
Serial.println(pSize);
if(pSize > 0) {
String msg = getPacketData(pSize);
packetIndex = 0;
if(msg != "ping" && !idInPath(_lastPacket.path)) {
Serial.println("runMamaDuck relayPacket");
sendPayloadStandard(_lastPacket.payload, _lastPacket.senderId, _lastPacket.messageId, _lastPacket.path);
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE); //Reset transmission
packetIndex = 0;
}
} else {
// Serial.println("Byte code not recognized!");
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE); //Reset transmission
packetIndex = 0;
}
enableInterrupt = true;
Serial.println("runMamaDuck startReceive");
startReceive();
}
processPortalRequest();
}
String tohex(byte *data, int size) {
String buf = "";
buf.reserve(size*2);
const char *cs = "0123456789abcdef";
for (int i=0; i<size; i++) {
byte val = data[i];
buf += cs[(val>>4) & 0x0f];
buf += cs[ val & 0x0f];
}
return buf;
}
int ClusterDuck::handlePacket() {
int pSize = lora.getPacketLength();
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE); //Reset transmission
packetIndex = 0;
int state = lora.readData(transmission, pSize);
if (state == ERR_NONE) {
// packet was successfully received
Serial.print("handlePacket pSize ");
Serial.println(pSize);
// dump received packet stats+data
Serial.print("LORA RCV");
Serial.print(" millis:");
Serial.print(millis());
Serial.print(" rssi:");
Serial.print(lora.getRSSI());
Serial.print(" snr:");
Serial.print(lora.getSNR());
Serial.print(" fe:");
Serial.print(lora.getFrequencyError());
Serial.print(" size:");
Serial.print(pSize);
Serial.print(" data:");
Serial.println(tohex(transmission, pSize));
return pSize;
} else {
// some other error occurred
Serial.print("handlePacket Failed, code ");
Serial.println(state);
return -1;
}
}
void ClusterDuck::sendPayloadMessage(String msg) {
couple(senderId_B, _deviceId);
couple(messageId_B, uuidCreator());
couple(payload_B, msg);
couple(path_B, _deviceId);
Serial.print("sendPayloadMessage packetIndex ");
Serial.println(packetIndex);
startTransmit();
}
void ClusterDuck::sendPayloadStandard(String msg, String senderId, String messageId, String path) {
if(senderId == "") senderId = _deviceId;
if(messageId == "") messageId = uuidCreator();
if(path == "") {
path = _deviceId;
} else {
path = path + "," + _deviceId;
}
String total = senderId + messageId + path + msg;
if(total.length() + 4 > CDPCFG_CDP_BUFSIZE) {
Serial.println("Warning: message is too large!"); //TODO: do something
}
couple(senderId_B, senderId);
couple(messageId_B, messageId);
couple(payload_B, msg);
couple(path_B, path);
Serial.print("sendPayloadStandard packetIndex ");
Serial.println(packetIndex);
startTransmit();
}
void ClusterDuck::couple(byte byteCode, String outgoing) {
int outgoingLen = outgoing.length() + 1;
byte byteBuffer[outgoingLen];
outgoing.getBytes(byteBuffer, outgoingLen);
transmission[packetIndex] = byteCode; //add byte code
packetIndex++;
transmission[packetIndex] = (byte)outgoingLen; // add payload length
packetIndex++;
for(int i=0; i < outgoingLen; i++) { // add payload
transmission[packetIndex] = byteBuffer[i];
packetIndex++;
}
}
bool ClusterDuck::idInPath(String path) {
Serial.print("idInPath '");
Serial.print(path);
Serial.print("' ");
String temp = "";
int len = path.length() + 1;
char arr[len];
path.toCharArray(arr, len);
for (int i = 0; i < len; i++) {
if (arr[i] == ',' || i == len - 1) {
if (temp == _deviceId) {
Serial.println("true");
return true;
}
temp = "";
} else {
temp += arr[i];
}
}
Serial.println("false");
return false;
}
String ClusterDuck::getPacketData(int pSize) {
String packetData = "";
if(pSize == 0) {
Serial.println("getPacketData Packet is empty!");
return packetData;
}
packetIndex = 0;
int len = 0;
bool sId = false;
bool mId = false;
bool pLoad = false;
bool pth = false;
String msg = "";
bool gotLen = false;
for(int i=0; i < pSize; i++) {
if(i > 0 && len == 0) {
gotLen = false;
if(sId) {
_lastPacket.senderId = msg;
Serial.println("getPacketData User ID: " + _lastPacket.senderId);
msg = "";
sId = false;
} else if(mId) {
_lastPacket.messageId = msg;
Serial.println("getPacketData Message ID: " + _lastPacket.messageId);
msg = "";
mId = false;
} else if(pLoad) {
_lastPacket.payload = msg;
Serial.println("getPacketData Message: " + _lastPacket.payload);
msg = "";
pLoad = false;
} else if(pth) {
_lastPacket.path = msg;
Serial.println("getPacketData Path: " + _lastPacket.path);
msg = "";
pth = false;
}
}
if(transmission[i] == senderId_B){
//Serial.println(transmission[1+i]);
sId = true;
len = transmission[i+1];
Serial.println("getPacketData senderId_B Len = " + String(len));
} else if(transmission[i] == messageId_B) {
mId = true;
len = transmission[i+1];
Serial.println("getPacketData messageId_B Len = " + String(len));
} else if(transmission[i] == payload_B) {
pLoad = true;
len = transmission[i+1];
Serial.println("getPacketData payload_B Len = " + String(len));
} else if(transmission[i] == path_B) {
pth = true;
len = transmission[i+1];
Serial.println("getPacketData path_B Len = " + String(len));
} else if(transmission[i] == ping_B) {
if(_deviceId != "Det") {
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE);
packetIndex = 0;
couple(iamhere_B, "1");
startTransmit();
Serial.println("getPacketData pong sent");
packetData = "ping";
return packetData;
}
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE);
packetIndex = 0;
packetData = "ping";
} else if(transmission[i] == iamhere_B) {
Serial.println("getPacketData pong received");
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE);
packetIndex = 0;
packetData = "pong";
return packetData;
} else if(len > 0 && gotLen) {
msg = msg + String((char)transmission[i]);
len--;
} else {
gotLen = true;
}
packetIndex++;
}
if(len == 0) {
if(sId) {
_lastPacket.senderId = msg;
Serial.println("getPacketData len0 User ID: " + _lastPacket.senderId);
msg = "";
} else if(mId) {
_lastPacket.messageId = msg;
Serial.println("getPacketData len0 Message ID: " + _lastPacket.messageId);
msg = "";
} else if(pLoad) {
_lastPacket.payload = msg;
Serial.println("getPacketData len0 Message: " + _lastPacket.payload);
msg = "";
} else if(pth) {
_lastPacket.path = msg;
Serial.println("getPacketData len0 Path: " + _lastPacket.path);
msg = "";
}
}
return packetData;
}
/**
restart
Only restarts ESP
*/
void ClusterDuck::restartDuck()
{
Serial.println("Restarting Duck...");
ESP.restart();
}
//Timer reboot
bool ClusterDuck::reboot(void *) {
String reboot = "REBOOT";
Serial.println(reboot);
sendPayloadMessage(reboot);
restartDuck();
return true;
}
bool ClusterDuck::imAlive(void *) {
String alive = "Health Quack";
Serial.print("imAlive sending");
sendPayloadMessage(alive);
return true;
}
//Get Duck MAC address
String ClusterDuck::duckMac(boolean format)
{
char id1[15];
char id2[15];
uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
uint16_t chip = (uint16_t)(chipid >> 32);
snprintf(id1, 15, "%04X", chip);
snprintf(id2, 15, "%08X", (uint32_t)chipid);
String ID1 = id1;
String ID2 = id2;
String unformattedMac = ID1 + ID2;
if(format == true){
String formattedMac = "";
for(int i = 0; i < unformattedMac.length(); i++){
if(i % 2 == 0 && i != 0){
formattedMac += ":";
formattedMac += unformattedMac[i];
}
else {
formattedMac += unformattedMac[i];
}
}
return formattedMac;
} else {
return unformattedMac;
}
}
//Create a uuid
String ClusterDuck::uuidCreator() {
String msg = "";
int i;
for (i = 0; i < CDPCFG_UUID_LEN; i++) {
byte randomValue = random(0, 36);
if (randomValue < 26) {
msg = msg + char(randomValue + 'a');
} else {
msg = msg + char((randomValue - 26) + '0');
}
}
Serial.print("uuidCreator ");
Serial.println(msg);
return msg;
}
//Getters
String ClusterDuck::getDeviceId() {
return _deviceId;
}
Packet ClusterDuck::getLastPacket() {
Packet packet = _lastPacket;
_lastPacket = Packet();
return packet;
}
volatile bool ClusterDuck::getFlag() {
return receivedFlag;
}
volatile bool ClusterDuck::getInterrupt() {
return enableInterrupt;
}
int ClusterDuck::getRSSI() {
return lora.getRSSI();
}
String ClusterDuck::getSSID() {
return ssid;
}
String ClusterDuck::getPassword() {
return password;
}
//Setter
void ClusterDuck::flipFlag() {
if (receivedFlag == true) {
receivedFlag = false;
} else {
receivedFlag = true;
}
}
void ClusterDuck::flipInterrupt() {
if (enableInterrupt == true) {
enableInterrupt = false;
} else {
enableInterrupt = true;
}
}
void ClusterDuck::startReceive() {
int state = lora.startReceive();
if (state == ERR_NONE) {
} else {
Serial.print("startReceive failed, code ");
Serial.println(state);
restartDuck();
}
}
void ClusterDuck::startTransmit() {
bool oldEI = enableInterrupt;
enableInterrupt = false;
// dump send packet stats+data
Serial.print("LORA SND");
Serial.print(" millis:");
Serial.print(millis());
Serial.print(" size:");
Serial.print(packetIndex);
Serial.print(" data:");
Serial.println(tohex(transmission, packetIndex));
int state = lora.transmit(transmission, packetIndex);
memset(transmission, 0x00, CDPCFG_CDP_BUFSIZE); //Reset transmission
packetIndex = 0; //Reset packetIndex
if (state == ERR_NONE) {
// the packet was successfully transmitted
Serial.println("startTransmit Packet sent");
} else if (state == ERR_PACKET_TOO_LONG) {
// the supplied packet was longer than 256 bytes
Serial.println("startTransmit too long!");
} else if (state == ERR_TX_TIMEOUT) {
// timeout occured while transmitting packet
Serial.println("startTransmit timeout!");
} else {
// some other error occurred
Serial.print(F("startTransmit failed, code "));
Serial.println(state);
}
if (oldEI) {
enableInterrupt = true;
startReceive();
}
}
void ClusterDuck::ping() {
couple(ping_B, "0");
startTransmit();
}
// Setup LED
void ClusterDuck::setupLED() {
ledcAttachPin(ledR, 1); // assign RGB led pins to channels
ledcAttachPin(ledG, 2);
ledcAttachPin(ledB, 3);
// Initialize channels
// channels 0-15, resolution 1-16 bits, freq limits depend on resolution
// ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);
ledcSetup(1, 12000, 8); // 12 kHz PWM, 8-bit resolution
ledcSetup(2, 12000, 8);
ledcSetup(3, 12000, 8);
}
void ClusterDuck::setColor(int red, int green, int blue)
{
ledcWrite(1, red);
ledcWrite(2, green);
ledcWrite(3, blue);
}
DNSServer ClusterDuck::dnsServer;
const char * ClusterDuck::DNS = "duck";
const byte ClusterDuck::DNS_PORT = 53;
int ClusterDuck::_rssi = 0;
float ClusterDuck::_snr;
long ClusterDuck::_freqErr;
int ClusterDuck::_availableBytes;
int ClusterDuck::_packetSize = 0;
// LED
int ClusterDuck::ledR = CDPCFG_PIN_RGBLED_R;
int ClusterDuck::ledG = CDPCFG_PIN_RGBLED_G;
int ClusterDuck::ledB = CDPCFG_PIN_RGBLED_B;
Packet ClusterDuck::_lastPacket;
byte ClusterDuck::ping_B = 0xF4;
byte ClusterDuck::senderId_B = 0xF5;
byte ClusterDuck::messageId_B = 0xF6;
byte ClusterDuck::payload_B = 0xF7;
byte ClusterDuck::iamhere_B = 0xF8;
byte ClusterDuck::path_B = 0xF3;
String ClusterDuck::portal = MAIN_page;