-
Notifications
You must be signed in to change notification settings - Fork 0
/
Receiver.ino
1225 lines (1058 loc) · 44.5 KB
/
Receiver.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
/*
* Project: Receiver (Ding9)
* Description:
* - receives sensor data by 433MHz ASK or LoRa signals
* - saves them to local csv files
* - forwards some sensor data to Blynk and ThingSpeak
* - displays some sensor data on a touch display
* - provides a webserver to show sensor data in a browser
*
* License: 2-Clause BSD License
* Copyright (c) 2024 codingABI
* For details see: License.txt
*
* External code parts of TFT_eSPI:
* Copyright (c) 2022 Bodmer (https://github.com/Bodmer), FreeBSD License
* Copyright Limor Fried/Ladyada for Adafruit Industries, The MIT License (MIT)
* Copyright (c) 2012 Adafruit Industries, BSD License
* For details see externalCode.ino and License TFT-eSPI.txt
*
* Used external libraries from Arduino IDE Library Manager
* - RCSwitch (by sui77,fingolfin)
* - LoRa (by Sandeep Mistry)
* - TFT_eSPI (by Bodmer)
* - Blynk (by Volodymyr Shymanskyy)
* - Adafruit Unified Sensor (by Adafruit)
* - Adafruit BME280 Library (by Adafruit)
*
* Hardware:
* - ESP-WROOM-32 NodeMCU (Arduino IDE Board manager: "ESP32 Dev Model")
* - ILI9341 TFT with XPT2046-Touch
* - PIR sensor AM312 to wakeup display from screensaver
* - Passive buzzer
* - RXB6 433MHz receiver (At the beginning I used a MX-RM-5V, but its reception was not good enough)
* - BME280 sensor for pressure, temperature and humidity
* - Lora SX1278 Ra-02
*
* Beep codes (short = 1 kHz for 100ms & 100ms quiet time, default = 500 Hz for 200ms & 100ms quiet time, long = 250 Hz for 400ms & 100ms quiet time):
* default, short, default = LittleFS semaphore error
* short, default, default = LittleFS mount error
* default, default, default = SPI semaphore error
* 1x short = Test sensor or a touch event
* 1x default = After device reset (in setup function)
* 1x long = When an error message is displayed
*
* History:
* 20210829, Initial version
* 20230120, Initial public version
* 20230122, Start Wifi every noon, if not already started as part ot the message of the day (for the case that the Wifi on signal was missed)
* 20230127, Add mini pie chart on web page for LittleFS usage
* 20230205, Speedup info web page, semaphore protection for LiffleFS in motd and info web page
* 20230223, Update Blynk from 1.1 to 1.2
* 20230311, Add missing "Bath OFF received" in display message
* 20230407, Update arduino-esp32 from 2.0.5 to 2.0.7 (IDF 4.4.4)
* 20230420, Add sensor 6 (wash maschine) for beeing notified, when washing has finished
* 20230505, Consolidate/rename Blynk events because Blynk in free plan limits to 5 events per device since 28.02.2023 (and reduces datastreams per template from 25 to 10)
* 20230508, Send LoRa XOR response back to sender
* 20230515, Add internal logfile on LittleFS partition
* 20230515, Add initial support for sending data to ThingSpeak
* 20230618, Remove unused column in CSV header
* 20230827, Delete oldest sn*.csv file when LittleFS has to less free space
* 20230906, Update code for Blynk 1.3.0
* 20230926, Add support for Emil Lux 315606 power outlets
* 20231007, Prevent delays while checking 433Mhz signals to avoid missed signals
* 20231007, Remove Blynk for SolarPoweredSender sensor because Blynk in free plan reduces datastreams per template from 10 to 5 at 16.10.2023 (Second reduction in 2023, not nice)
* 20231014, Add ISR for pir sensor
* 20231110, Improve web page to show only existing CSV files
* 20231111, Update arduino-esp32 from 2.0.7 to 2.0.14 (IDF 4.4.6), Update Blynk from 1.3.0 to 1.3.2
* 20240517, Update arduino-esp32 from 2.0.14 to 2.0.16 (IDF 4.4.7), Fix wrong "Sensor 6 duplicate received" debug message
* 20241002, Update arduino-esp32 from 2.0.16 to 3.0.5 (IDF 5.1.4), Changes for espnow&ledc, Update TFT_eSPI from 2.5.33
*/
#include "secrets.h"
#define DEBUG true // true for Serial.print
#define SERIALDEBUG if (DEBUG) Serial
// Blynk defines (must be defined before #include <BlynkSimpleEsp32.h>)
#if DEBUG == true
#define BLYNK_PRINT Serial
#endif
#define BLYNK_NO_BUILTIN
#define BLYNK_NO_FANCY_LOGO
// Includes
#include <esp_log.h>
#include <core_version.h>
#include <ESPmDNS.h>
#include <RCSwitch.h> // Without setting "const unsigned int RCSwitch::nSeparationLimit = 1500;" in RCSwitch.cpp the signal for my Emil Lux 315606 power outlets are not or wrongly detected as "32bit Protocol: 2".
#include <WiFi.h>
#include <EEPROM.h>
#include <ArduinoOTA.h>
#include <esp_now.h>
#include <LoRa.h>
#include <TFT_eSPI.h>
/* Dont forget to edit User_Setup.h from TFT_eSPI to define the pins:
// ###### EDIT THE PIN NUMBERS IN THE LINES FOLLOWING TO SUIT YOUR ESP32 SETUP ######
#define TFT_DC 17
#define TFT_CS 22
#define TFT_RST 5
#define TFT_MOSI 23
#define TFT_MISO 19
#define TFT_CLK 18
#define TOUCH_CS 14
*/
#include <LittleFS.h>
#include <FS.h>
#include <rom/rtc.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "sensordata.h"
#include <BlynkSimpleEsp32.h>
#include <HTTPClient.h>
#define RCSIGNATURE (0b00111UL << 27) // Signature for 32-bit 433MHz signals (only the first 5 bits are the signature)
#define SECS_PER_MIN 60
#define SECS_PER_HOUR 3600
#define SECS_PER_DAY 86400
#define LORAPROTOCOL 99 // Marks a signal as LoRa signal in checkSignal()
#define EEPROMADDR 10 // Startaddress in EEPROM
#define MAXSSIDLENGTH 30 // Maximum length of Wifi SSID
#define MAXPASSWORDLENGTH 30 // Maximum length of Wifi password
// Maximum number of consecutive notifications to Blynk in case of battery warning of a sensor
#define MAXLOWBATTERYNOTIFICATIONS 3
// I/O-PINs
#define BEEPER_PIN 27
#define PIR_PIN 4
#define RCSWITCH_PIN GPIO_NUM_35
// I2C
#define SDA_PIN 32
#define SCL_PIN 33
// LoRa (SPI MOSI=23, MISO=19, CLK=18, same pins as the TFT)
#define LORA_NSS 26
#define LORA_RST 21
#define LORA_IRQ 34
// TFT (Pins definitions for TFT see User_Setup.h in TFT_eSPI)
#define TFT_LED 16
#define TIRQ_PIN 25
// Message IDs for display task
#define ID_ALERT 1 // Power on display and show message
#define ID_INFO 2 // Show message
#define ID_DISPLAYON 3 // Power on display
#define ID_REFESHBUTTONS 4 // Refresh button display
#define ID_RESET 5 // Reset graph, battery states, min/max values
#define ID_BEEP 6 // Beep
// Time in MS, after the display will be blanked because of inactivity
#define SCREENSAVERMS 20000
#define TIMEZONE "CET-1CEST,M3.5.0/02,M10.5.0/03" // Timezone for Germany
#define NTPSERVER "pool.ntp.org" // Configured NTP server
// Use only one cpu for our tasks to simplify interrupts and keeps CPU0 free for OS, Wifi ...
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t g_appCpu = 0;
#else
static const BaseType_t g_appCpu = 1;
#endif
#define FORMAT_LittleFS_IF_FAILED false // set to true if you want to format LitteFS on a new device
#define MINFREESPACE_LittleFS (200*1024)
// Internal logfile on LittleFS partition
#define LOGFILE "/logfile.csv"
#define BACKUPLOGFILE "/backuplogfile.csv"
#define MAXLOGFILESIZE (32*1024)
// CSV data files
#define CSVBASEFOLDER "/"
#define CSVFILEPREFIX "sn"
#define CSVLASTFILE "/sn999999.csv"
// Global variables
RCSwitch g_433MHzRCSwitch = RCSwitch(); // 433MHz Receiver
bool g_ScreenSaverEnabled = true; // Screensaver on/off
volatile bool g_SoundDisabled = false; // Buzzer on/off
volatile bool g_PIREnabled = true; // PIR sensor on/off
bool g_wifiEnabled = false; // Current Wifi status
bool g_wifiSwitch = true; // Wifi switch on/off
bool g_demoModeEnabled = false; // Demo mode status
bool g_demoModeSwitch = false; // Demo mode switch on/off
bool g_mailAlert = false; // Alert from my mail box
enum pendingStates { none, alert, clear };
pendingStates g_pendingBlynkMailAlert = none; // pending events
time_t g_lastStorageTime = -SECS_PER_HOUR;
unsigned long g_lastNTPSyncMS = -SECS_PER_HOUR * 1000;
time_t g_lastNTPTime = 0; // Last NTP-Sync
time_t g_firstNTPTime = 0; // First NTP-Sync
unsigned long g_lastPIRChangeMS = 0;
unsigned long g_lastWIFICheckMS = -SECS_PER_MIN * 1000;
unsigned long g_lastBME280MS = -SECS_PER_MIN * 1000;
time_t g_nextWifiOn = 0; // Delayed Wifi start
unsigned long g_lastMotDCheckMS = 0;
bool g_motdShown = false; // Daily message at noon displayed?
bool g_timeSet = false; // Is time valid?
volatile bool v_touchedTFT = false; // Touch screen IRQ fired?
volatile bool v_detectedPIR = false; // PIR sensor IRQ fired?
Adafruit_BME280 bme; // BME280 I2C module
bool g_BME280ready = false; // BME280 found?
volatile bool v_loraReceived = false; // Lora IRQ triggered?
bool g_LORAready = false;
// Wifi credentials
char g_wifiSSID[MAXSSIDLENGTH+1];
char g_wifiPassword[MAXPASSWORDLENGTH+1];
bool g_wifiAPMode = false; // AP-mode will be used, if no Wifi credentials are found in EEPROM or the the device is powered on and Wifi fails
WiFiServer g_server(80); // Webserver on port 80
byte g_buffer[1400]; // // Buffer for webserver to improve low speed due TCP_NODELAY & Nagle's Algorithm
TFT_eSPI g_tft = TFT_eSPI();
/*
* Definitions for scrolling area at the lower end of the screen
* The scrolling area must be a integral multiple of TEXT_HEIGHT
*/
#define TOP_FIXED_AREA 272 // Linenumbers of the non scrolling area on top of screen
#define TEXT_HEIGHT 8 // Height of a text line in scrolled area
// Handles for tasks
TaskHandle_t g_handleTaskWebServer = NULL;
TaskHandle_t g_handleTaskDisplay = NULL;
// Semaphores
SemaphoreHandle_t g_semaphoreSPIBus; // for SPI-Bus
SemaphoreHandle_t g_semaphoreLittleFS; // for LittleFS
SemaphoreHandle_t g_semaphoreBeep; // for buzzer
// Structure for a message to the display task
#define MAXMSGLENGTH 40
typedef struct {
byte id;
char strData[ MAXMSGLENGTH+1 ];
} DisplayMessage;
// Queues for the display
QueueHandle_t displayMsgQueue; // Messages
QueueHandle_t displayDatQueue; // Data sets
// List of last saved sensor data for internal purposes (e.g. debugging)
SensorDataBuffer dataHistoryBuffer;
// Newest sensor data
sensorData g_pendingSensorData;
// Timestamp for other received known 433 MHz signals
time_t g_last433MhzBathOn = 0;
time_t g_last433MhzBathOff = 0;
time_t g_last433MhzCafeOn = 0;
time_t g_last433MhzCafeOff = 0;
time_t g_last433MhzWifiOff = 0;
time_t g_last433MhzWifiOn = 0;
// ISR for Touch-Interrupt (Primarily to reliably exit screensaver after touch)
void IRAM_ATTR TouchISR() {
v_touchedTFT = true;
}
// ISR for pir sensor
void IRAM_ATTR PirISR() {
v_detectedPIR = true;
}
// Callback for LoRa receiver
void callbackLoraReceived(int packetSize) {
if (packetSize == 0) return;
v_loraReceived = true;
}
// Send data to ThingSpeak
void sendToThingSpeak(float data,int field) {
#define THINGSPEAKBASEURL "http://api.thingspeak.com/update"
#define MAXSTRDATALENGTH 127
char strData[MAXSTRDATALENGTH+1];
HTTPClient http;
WiFiClient client;
if (!g_wifiEnabled) return;
snprintf(strData,MAXSTRDATALENGTH+1,"api_key=%s&field%i=%.2f",THINGSPEAKAPIKEY,field,data);
http.begin(client, THINGSPEAKBASEURL);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Send HTTP POST request
int httpResponseCode = http.POST(strData);
http.end();
}
// Read Wifi config from EEPROM
void getWifiConnecitonDataFromEEPROM() {
g_wifiSSID[0] = '\0';
g_wifiPassword[0] = '\0';
if ( (EEPROM.read(EEPROMADDR) == 15) && (EEPROM.read(EEPROMADDR+1) == 43) ) { // Check signature
for (int i=0;i<=MAXSSIDLENGTH;i++) {
g_wifiSSID[i] = EEPROM.read(EEPROMADDR+2+i)-g_eepromenc[i%(strlen(g_eepromenc))];
}
g_wifiSSID[MAXSSIDLENGTH] = '\0';
for (int i=0;i<=MAXPASSWORDLENGTH;i++) {
g_wifiPassword[i] = EEPROM.read(EEPROMADDR+2+MAXSSIDLENGTH+1+i)-g_eepromenc[i%(strlen(g_eepromenc))];
}
g_wifiPassword[MAXPASSWORDLENGTH] = '\0';
}
}
// Write Wifi config to EEPROM
void storeWifiConnectionDataToEEPROM() {
EEPROM.write(EEPROMADDR,15);
EEPROM.write(EEPROMADDR+1,43);
for (int i=0;i<=MAXSSIDLENGTH;i++) {
EEPROM.write(EEPROMADDR+2+i,g_wifiSSID[i]+g_eepromenc[i%(strlen(g_eepromenc))]);
}
for (int i=0;i<=MAXPASSWORDLENGTH;i++) {
EEPROM.write(EEPROMADDR+2+MAXSSIDLENGTH+1+i,g_wifiPassword[i]+g_eepromenc[i%(strlen(g_eepromenc))]);
}
EEPROM.commit();
}
// callback when Blynk established a connection
BLYNK_CONNECTED() {
DisplayMessage msg;
SERIALDEBUG.println("Connected to Blynk");
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Connected to Blynk");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
// Start Wifi in AP-mode to configure Wifi
void startAPMode() {
#define RANDOMPASSWORDLENGTH 8
char randomPassword[RANDOMPASSWORDLENGTH+1];
const char *passwordChars="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
DisplayMessage msg;
// Generate password
for (int i=0;i<RANDOMPASSWORDLENGTH;i++) {
randomPassword[i]=passwordChars[random(strlen(passwordChars))];
}
randomPassword[RANDOMPASSWORDLENGTH] = '\0';
// start AP
WiFi.mode(WIFI_AP);
WiFi.softAP(HOSTNAME,randomPassword);
delay(1000);
// Show AP connection data on display
IPAddress IP = WiFi.softAPIP();
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Please connect to AP:");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
snprintf(msg.strData,MAXMSGLENGTH+1,"SSID %s", HOSTNAME);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
snprintf(msg.strData,MAXMSGLENGTH+1,"Password %s", randomPassword);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
snprintf(msg.strData,MAXMSGLENGTH+1,"URL http://%d.%d.%d.%d/cfg",IP[0],IP[1],IP[2],IP[3]);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
g_wifiAPMode = true; // Enable /cfg-Site on webserver
// Start webserver
g_server.begin();
// Loop because device will be reset by webserver
for (;;) {
if ((v_detectedPIR) && (g_PIREnabled)) {
if (millis() - g_lastPIRChangeMS > 1000) {
msg.id = ID_DISPLAYON;
msg.strData[0]='\0';
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
g_lastPIRChangeMS = millis();
}
}
v_detectedPIR = false;
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
// Beep with passive buzzer
void beep(int type=0) {
// User PWM to improve quality
#define SHORTBEEP 1
#define LONGBEEP 2
if (!g_SoundDisabled) {
if (xSemaphoreTake( g_semaphoreBeep, 10000 / portTICK_PERIOD_MS) == pdTRUE) {
switch(type) {
case 0: // 500 Hz for 200ms
ledcAttach(BEEPER_PIN,500,8);
ledcWrite(BEEPER_PIN, 128);
delay(200);
ledcWrite(BEEPER_PIN, 0);
ledcDetach(BEEPER_PIN);
break;
case SHORTBEEP: // 1 kHz for 100ms
ledcAttach(BEEPER_PIN,1000,8);
ledcWrite(BEEPER_PIN, 128);
delay(100);
ledcWrite(BEEPER_PIN, 0);
ledcDetach(BEEPER_PIN);
break;
case LONGBEEP: // 250 Hz for 400ms
ledcAttach(BEEPER_PIN,250,8);
ledcWrite(BEEPER_PIN, 128);
delay(400);
ledcWrite(BEEPER_PIN, 0);
ledcDetach(BEEPER_PIN);
break;
}
}
delay(100);
xSemaphoreGive( g_semaphoreBeep );
} else {
SERIALDEBUG.println("Error: beep Semaphore Timeout");
}
}
// Append line to file (write header, if file is not existing)
byte appendToFile(char strFile[], char strData[], char strHeader[]) {
bool newFile = false;
int RC=0;
if (xSemaphoreTake( g_semaphoreLittleFS, 10000 / portTICK_PERIOD_MS) == pdTRUE) {
if (!LittleFS.exists(strFile)) newFile = true;
fs::File file = LittleFS.open(strFile, "a");
if (!file) {
RC=2;
} else {
if (newFile) {
if (!file.println(strHeader)) RC=3;
}
if ((RC==0) && (!file.println(strData))) RC=4;
file.close();
}
xSemaphoreGive( g_semaphoreLittleFS );
} else {
SERIALDEBUG.println("Error: LittleFS Semaphore Timeout");
beep();
beep(SHORTBEEP);
beep();
RC=6;
}
return RC;
}
// Check if filename is valid for a CSV data file
bool isValidCSVFilename(const char *filename) {
#define MAXSTRDATALENGTH 50
char strData[MAXSTRDATALENGTH+1];
int pos, i;
// Check basics
if (filename == NULL) return false;
if (strlen(filename) != strlen(CSVLASTFILE)) return false;
// Check root
snprintf(strData,MAXSTRDATALENGTH+1,"%s",CSVBASEFOLDER);
for (i=0;i<strlen(strData);i++) {
if (toupper(filename[i]) != toupper(strData[i])) return false;
}
pos = i;
// Check prefix
snprintf(strData,MAXSTRDATALENGTH+1,"%s",CSVFILEPREFIX);
for (i=0;i<strlen(strData);i++) {
if (toupper(filename[pos+i]) != toupper(strData[i])) return false;
}
pos +=i;
// Check numbers
snprintf(strData,MAXSTRDATALENGTH+1,"%s",CSVLASTFILE);
for (i=0;i<strlen(CSVLASTFILE)-strlen(CSVFILEPREFIX)-strlen(CSVBASEFOLDER)-4;i++) {
if (filename[pos+i] < '0') return false;
if (filename[pos+i] > '9') return false;
}
// Check extension
for (i=strlen(strData)-4;i<strlen(strData);i++) {
if (toupper(filename[i]) != toupper(strData[i])) return false;
}
return true;
}
// Reset ESP
void reset() {
SERIALDEBUG.println("Reset...");
delay(2000);
ESP.restart();
}
// callback function for reveived ESPNOW packages
void OnDataRecv(const esp_now_recv_info_t *info, const uint8_t *incomingData, int len) {
#define MAXMACLENGTH 17
char strMac[MAXMACLENGTH+1];
DisplayMessage msg;
const uint8_t* mac_addr = info->src_addr;
snprintf(strMac, MAXMACLENGTH+1, "%02x:%02x:%02x:%02x:%02x:%02x",mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
msg.id= ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"ESPNOW from %s",strMac);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
// Check free space and delete oldest CSV file, if free space is too low
void checkFreeSpace() {
DisplayMessage msg;
String filename, oldestFilename;
fs::File dir;
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
if (xSemaphoreTake( g_semaphoreLittleFS, 1000 / portTICK_PERIOD_MS) == pdTRUE) {
unsigned long usedBytes = LittleFS.usedBytes();
unsigned long totalBytes = LittleFS.totalBytes();
if (LittleFS.totalBytes() == 0) {
SERIALDEBUG.println("Alert: 0 bytes total LittleFS");
xSemaphoreGive( g_semaphoreLittleFS );
return;
}
snprintf(msg.strData,MAXMSGLENGTH+1,"%d%% disk used",100 *usedBytes/totalBytes);
msg.id= ID_INFO;
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
if (totalBytes - usedBytes >= MINFREESPACE_LittleFS) { // Nothing to do
SERIALDEBUG.println("Freespace is OK");
xSemaphoreGive( g_semaphoreLittleFS );
return;
}
dir = LittleFS.open(CSVBASEFOLDER);
if(!dir){
SERIALDEBUG.println("Alert: Failed to open root directory");
xSemaphoreGive( g_semaphoreLittleFS );
return;
}
if(!dir.isDirectory()){
SERIALDEBUG.println("Alert: root is not a directory");
xSemaphoreGive( g_semaphoreLittleFS );
return;
}
oldestFilename = CSVLASTFILE;
filename = dir.getNextFileName();
while (filename != "") {
if (isValidCSVFilename(filename.c_str())) {
if (filename < oldestFilename) { // Older file found?
oldestFilename = filename;
}
}
filename = dir.getNextFileName();
}
if (oldestFilename != CSVLASTFILE) { // At least one matching CSV file found?
msg.id= ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Remove %s",oldestFilename.c_str());
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
LittleFS.remove(oldestFilename); // Delete file
}
xSemaphoreGive( g_semaphoreLittleFS );
} else {
SERIALDEBUG.println("Skip checking free space because could not get semaphore in 1 second");
}
}
// Enable Wifi
void WiFiOn() {
byte wifiRetry=0;
byte mac[6];
#define MAXMACLENGTH 17
char strMac[MAXMACLENGTH+1];
DisplayMessage msg;
IPAddress ip;
getWifiConnecitonDataFromEEPROM();
if (strlen(g_wifiSSID)==0) { // No Wifi config found in EEPROM
SERIALDEBUG.println("Alert: no ssid configured");
msg.id = ID_ALERT;
snprintf(msg.strData,MAXMSGLENGTH+1,"No Wifi SSID configured");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
startAPMode();
// This line will never be reached, because the configuration waits for a reset by the webserver (exception would be a semaphore timeout for display or button)
} else {
msg.id= ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Startup Wifi to %s",g_wifiSSID);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); // Fix to make setHostname working without delay
WiFi.persistent(false);
WiFi.begin(g_wifiSSID, g_wifiPassword);
WiFi.setHostname(HOSTNAME);
SERIALDEBUG.print("WIFI to ");
SERIALDEBUG.print(g_wifiSSID);
while ((WiFi.status() != WL_CONNECTED) && (wifiRetry <= 20)) {
wifiRetry++;
delay(500);
SERIALDEBUG.print(".");
}
if (WiFi.status() != WL_CONNECTED) { // Connection failed
if (g_demoModeSwitch) return; // Demo modus switch was touched during Wifi connection => do nothing
if ((!g_timeSet)) { // If time is not valid
if (rtc_get_reset_reason(0)==12) { // SW_CPU_RESET => Reset
SERIALDEBUG.println("Alert: Wifi timeout => Reset");
msg.id = ID_ALERT;
snprintf(msg.strData,MAXMSGLENGTH+1,"Wifi timeout => reset");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
vTaskDelay(2000 / portTICK_PERIOD_MS);
reset();
} else {
// powered on and no Wifi is working => Goto AP-mode to configure Wifi
msg.id = ID_ALERT;
snprintf(msg.strData,MAXMSGLENGTH+1,"Wifi timeout => reconfig");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
startAPMode();
// This line will never be reached, because the configuration waits for a reset by the webserver (exception would be a semaphore timeout for display or button)
}
} else {
msg.id = ID_ALERT;
snprintf(msg.strData,MAXMSGLENGTH+1,"Wifi timeout => continue");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
} else {
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
msg.id = ID_ALERT;
snprintf(msg.strData,MAXMSGLENGTH+1,"ESP-NOW failed");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
} else {
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
}
// Show ip config
SERIALDEBUG.println();
SERIALDEBUG.print("Hostname: ");
SERIALDEBUG.println(HOSTNAME);
SERIALDEBUG.print("NTP-Server: ");
SERIALDEBUG.println(NTPSERVER);
SERIALDEBUG.print("IP: ");
SERIALDEBUG.println(WiFi.localIP());
SERIALDEBUG.print("Subnetmask: ");
SERIALDEBUG.println(WiFi.subnetMask());
SERIALDEBUG.print("Gateway: ");
SERIALDEBUG.println(WiFi.gatewayIP());
SERIALDEBUG.print("DNS: ");
SERIALDEBUG.println(WiFi.dnsIP());
WiFi.macAddress(mac);
SERIALDEBUG.print("MAC: ");
snprintf(strMac,MAXMACLENGTH+1,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
SERIALDEBUG.println(strMac);
g_wifiEnabled = true;
g_wifiSwitch = true;
msg.id = ID_REFESHBUTTONS;
msg.strData[0]='\0';
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Hostname %s",HOSTNAME);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
ip = WiFi.localIP();
snprintf(msg.strData,MAXMSGLENGTH+1,"IP %i.%i.%i.%i",ip[0],ip[1],ip[2],ip[3]);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
snprintf(msg.strData,MAXMSGLENGTH+1,"MAC %s",strMac);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
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()
SERIALDEBUG.println("Start updating " + type);
})
.onEnd([]() {
SERIALDEBUG.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
SERIALDEBUG.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
SERIALDEBUG.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) SERIALDEBUG.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) SERIALDEBUG.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) SERIALDEBUG.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) SERIALDEBUG.println("Receive Failed");
else if (error == OTA_END_ERROR) SERIALDEBUG.println("End Failed");
});
ArduinoOTA.setPassword(OTAPASSWORD);
ArduinoOTA.begin();
if(!MDNS.begin(HOSTNAME)) { // mDNS after OTA, to avoid problems
SERIALDEBUG.println("Error starting mDNS");
} else {
SERIALDEBUG.print("MDNS: ");
SERIALDEBUG.print(HOSTNAME);
SERIALDEBUG.println(".local");
}
Blynk.connect();
}
}
}
// Disable Wifi
void WiFiOff() {
DisplayMessage msg;
msg.id=ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Shutdown Wifi");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
Blynk.disconnect();
ArduinoOTA.end();
SERIALDEBUG.println("Shutdown WIFI");
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
g_wifiEnabled = false;
g_wifiSwitch = false;
msg.id = ID_REFESHBUTTONS;
msg.strData[0]='\0';
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
// Daily status message
void showMotD() {
DisplayMessage msg;
time_t now;
struct tm * ptrTimeinfo;
if (g_timeSet) {
time(&now);
ptrTimeinfo = localtime ( &now );
if (ptrTimeinfo->tm_hour == 12) { // Only at noon
if (g_motdShown == false) {
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Uptime %lld days",esp_timer_get_time()/1000/1000/SECS_PER_DAY);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
// Check free space
checkFreeSpace();
// Start WiFi every noon, if not already started
if ((WiFi.status() != WL_CONNECTED) && (g_nextWifiOn==0)) {
SERIALDEBUG.println("It is noon and wifi is not enabled => enable");
g_nextWifiOn = now + SECS_PER_MIN * 5; // Power on wifi in 5 minutes to give access point enough time for booting
ptrTimeinfo = localtime(&g_nextWifiOn);
msg.id=ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Wifi start at %02d:%02d",ptrTimeinfo->tm_hour,ptrTimeinfo->tm_min);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
g_motdShown = true;
}
} else g_motdShown = false;
}
}
void setup() {
sensorData emptySensorData;
DisplayMessage msg;
SERIALDEBUG.begin(115200);
SERIALDEBUG.print("ESP32 SDK: ");
SERIALDEBUG.println(ESP.getSdkVersion());
SERIALDEBUG.print("Compile time: ");
SERIALDEBUG.println(__DATE__ " " __TIME__);
EEPROM.begin(512);
g_semaphoreBeep = xSemaphoreCreateBinary();
configASSERT( g_semaphoreBeep );
xSemaphoreGive( g_semaphoreBeep );
pinMode(BEEPER_PIN,OUTPUT);
beep();
pinMode(TIRQ_PIN,INPUT);
pinMode(TFT_LED,OUTPUT);
digitalWrite(TFT_LED,HIGH);
setupPIR();
setupASKReceiver();
// Set timezone to prevent wrong time after OTA resets until first NTP sync
setenv("TZ", TIMEZONE, 1);
tzset();
displayMsgQueue = xQueueCreate(50,sizeof( DisplayMessage ) );
configASSERT( displayMsgQueue );
displayDatQueue = xQueueCreate(5,sizeof( sensorData ) );
configASSERT( displayDatQueue );
// Reset reason
for (int i=0;i<ESP.getChipCores();i++) {
switch (rtc_get_reset_reason(i))
{
case 1 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d POWERON_RESET",i);break; /**<1, Vbat power on reset*/ // Normaler Einschaltvorgang durch Stromzufuhr
case 3 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d SW_RESET",i);break; /**<3, Software reset digital core*/
case 4 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d OWDT_RESET",i);break; /**<4, Legacy watch dog reset digital core*/
case 5 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d DEEPSLEEP_RESET",i);break; /**<5, Deep Sleep reset digital core*/
case 6 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d SDIO_RESET",i);break; /**<6, Reset by SLC module, reset digital core*/
case 7 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d TG0WDT_SYS_RESET",i);break; /**<7, Timer Group0 Watch dog reset digital core*/
case 8 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d TG1WDT_SYS_RESET",i);break; /**<8, Timer Group1 Watch dog reset digital core*/
case 9 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d RTCWDT_SYS_RESET",i);break; /**<9, RTC Watch dog Reset digital core*/
case 10 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d INTRUSION_RESET",i);break; /**<10, Intrusion tested to reset CPU*/
case 11 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d TGWDT_CPU_RESET",i);break; /**<11, Time Group reset CPU*/
case 12 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d SW_CPU_RESET",i);break; /**<12, Software reset CPU*/ // z.B. nach einem Flashvorgang
case 13 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d RTCWDT_CPU_RESET",i);break; /**<13, RTC Watch dog Reset CPU*/
case 14 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d EXT_CPU_RESET",i);break; /**<14, for APP CPU, reseted by PRO CPU*/
case 15 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d RTCWDT_BROWN_OUT_RESET",i);break;/**<15, Reset when the vdd voltage is not stable*/
case 16 : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d RTCWDT_RTC_RESET",i);break; /**<16, RTC Watch dog reset digital core and rtc module*/
default : snprintf(msg.strData,MAXMSGLENGTH+1,"CPU%d NO_MEAN",i);
}
msg.id = ID_INFO;
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
setupBME280();
setupLoRa();
if (!LittleFS.begin(FORMAT_LittleFS_IF_FAILED)) {
SERIALDEBUG.println("LittleFS mount failed");
beep(SHORTBEEP);
beep();
beep(SHORTBEEP);
reset();
} else {
SERIALDEBUG.println("LittleFS OK");
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Disk %dk from %dk used",LittleFS.usedBytes() / 1024, LittleFS.totalBytes() / 1024);
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
g_semaphoreLittleFS = xSemaphoreCreateBinary();
configASSERT( g_semaphoreLittleFS );
xSemaphoreGive( g_semaphoreLittleFS );
// TFT
g_tft.init();
// Blynk
Blynk.config(BLYNK_AUTH_TOKEN);
g_semaphoreSPIBus = xSemaphoreCreateBinary();
configASSERT( g_semaphoreSPIBus );
xSemaphoreGive( g_semaphoreSPIBus );
xTaskCreatePinnedToCore(
taskWebServer , // Function that should be called
"taskWebServer", // Name of the task (for debugging)
3250, // Stack size (bytes)
NULL, // Parameter to pass
1, // Task priority (Prio 0 would reduce webserver performance to ~50%)
&g_handleTaskWebServer // Task handle
, g_appCpu
);
configASSERT( g_handleTaskWebServer );
xTaskCreatePinnedToCore(
taskDisplay , // Function that should be called
"taskDisplay", // Name of the task (for debugging)
4400, // Stack size (bytes)
NULL, // Parameter to pass
0, // Task priority
&g_handleTaskDisplay // Task handle
, g_appCpu
);
configASSERT( g_handleTaskDisplay );
// Define empty sensor set data
emptySensorData.time = 0;
emptySensorData.sensor1LowBattery = NOVALIDLOWBATTERY;
emptySensorData.sensor1Temperature = NOVALIDTEMPERATUREDATA;
emptySensorData.sensor1Humidity= NOVALIDHUMIDITYDATA;
emptySensorData.sensor1Vcc = NOVALIDVCCDATA;
emptySensorData.sensor2Temperature = NOVALIDTEMPERATUREDATA;
emptySensorData.sensor2Humidity= NOVALIDHUMIDITYDATA;
emptySensorData.sensor2Pressure = NOVALIDPRESSUREDATA;
emptySensorData.sensor3LowBattery = NOVALIDLOWBATTERY;
emptySensorData.sensor3Switch1 = NOVALIDSWITCHDATA;
emptySensorData.sensor3Switch2 = NOVALIDSWITCHDATA;
emptySensorData.sensor3Vcc = NOVALIDVCCDATA;
emptySensorData.sensor3Temperature = NOVALIDTEMPERATUREDATA;
emptySensorData.sensor3Humidity= NOVALIDHUMIDITYDATA;
emptySensorData.sensor4LowBattery = NOVALIDLOWBATTERY;
emptySensorData.sensor4Vcc = NOVALIDVCCDATA;
emptySensorData.sensor4Runtime = NOVALIDRUNTIME;
emptySensorData.sensor5LowBattery = NOVALIDLOWBATTERY;
emptySensorData.sensor5Vcc = NOVALIDVCCDATA;
emptySensorData.sensor5Switch1 = NOVALIDSWITCHDATA;
emptySensorData.sensor5PCI1 = NOVALIDPCI;
emptySensorData.sensor6LowBattery = NOVALIDLOWBATTERY;
emptySensorData.sensor6Vcc = NOVALIDVCCDATA;
// Send empty data to display
xQueueSend( displayDatQueue, ( void * ) &emptySensorData, portMAX_DELAY );
msg.id = ID_INFO;
snprintf(msg.strData,MAXMSGLENGTH+1,"Setup finished");
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
}
void loop() {
DisplayMessage msg;
sensorData newSensorData, emptySensorData;
#define MAXSTRDATALENGTH 127
char strTempData[MAXSTRDATALENGTH+1];
char strData[MAXSTRDATALENGTH+1];
#define MAXFILENAMELENGHT 13
char strFile[MAXFILENAMELENGHT+1];
byte RC;
struct tm timeinfo;
time_t now;
struct tm * ptrTimeinfo;
byte maxLoops;
ArduinoOTA.handle();
// Turn demo mode on/off, if changed by gui button
if ((g_demoModeSwitch && !g_demoModeEnabled) || (!g_demoModeSwitch && g_demoModeEnabled)) {
g_demoModeEnabled = !g_demoModeEnabled; // Invert mode
msg.id = ID_INFO;
if (g_demoModeEnabled) {
snprintf(msg.strData,MAXMSGLENGTH+1,"Enter demo mode");
} else {
snprintf(msg.strData,MAXMSGLENGTH+1,"Exit demo mode");
}
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
msg.strData[0]='\0';
// Reset graph, battery states, min/max values on display
msg.id = ID_RESET;
xQueueSend( displayMsgQueue, ( void * ) &msg, portMAX_DELAY );
// Send empty data to display
xQueueSend( displayDatQueue, ( void * ) &newSensorData, portMAX_DELAY );
}
// Read PIR sensor
readPIR();
// Daily status message at noon
if (millis() - g_lastMotDCheckMS > SECS_PER_MIN * 1000) {
showMotD();
g_lastMotDCheckMS = millis();
}
if (!g_demoModeEnabled) {
if(Blynk.connected()){ // Blynk, if only if connected, because the connection phase can block loop for several seconds
Blynk.run();
if (Blynk.connected()) {
switch (g_pendingBlynkMailAlert) {
case none:break;
// resolveAllEvents and resolveEvent from v1.2.0 (formerly clearEvent in 1.1.0) worked until ~02/2023 and stopped working (perhaps part of "Essential changes to FREE plan!")
// case clear:Blynk.resolveAllEvents("mailalert");break; // resolveAllEvents is only allowed every 15 minutes
case alert:
if (g_pendingSensorData.sensor5Vcc != NOVALIDVCCDATA)
snprintf(strData,MAXSTRDATALENGTH+1,"Du hast Post... (Vcc=%.1fV)",g_pendingSensorData.sensor5Vcc/10.0f);
else snprintf(strData,MAXSTRDATALENGTH+1,"Du hast Post...");
Blynk.logEvent("info",strData); // Send to Blynk
break;