-
Notifications
You must be signed in to change notification settings - Fork 0
/
nebulo.cpp
4123 lines (3619 loc) · 116 KB
/
nebulo.cpp
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
#include <WString.h>
#include <pgmspace.h>
#define SOFTWARE_VERSION_STR "Nebulo-V1-122021"
String SOFTWARE_VERSION(SOFTWARE_VERSION_STR);
#include <Arduino.h>
#include <arduino_lmic.h>
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
// includes ESP32 libraries
#define FORMAT_SPIFFS_IF_FAILED true
#include <FS.h>
#include <HTTPClient.h>
#include <SPIFFS.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <HardwareSerial.h>
#include <hwcrypto/sha.h>
#include <WebServer.h>
#include <ESPmDNS.h>
// includes external libraries
#include "./oledfont.h" // avoids including the default Arial font, needs to be included before SSD1306.h
#include <SSD1306Wire.h>
#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 0
#define ARDUINOJSON_ENABLE_ARDUINO_PRINT 0
#define ARDUINOJSON_DECODE_UNICODE 0
#include <ArduinoJson.h>
#include <DNSServer.h>
#include <StreamString.h>
#include <TinyGPS++.h>
#include "./bmx280_i2c.h"
// includes files
#include "./intl.h"
#include "./utils.h"
#include "defines.h"
#include "ext_def.h"
#include "html-content.h"
// configuration
namespace cfg
{
unsigned debug = DEBUG;
unsigned time_for_wifi_config = 600000;
unsigned sending_intervall_ms = 145000;
char current_lang[3];
// credentials for basic auth of internal web server
bool www_basicauth_enabled = WWW_BASICAUTH_ENABLED;
char www_username[LEN_WWW_USERNAME];
char www_password[LEN_CFG_PASSWORD];
// wifi credentials
char wlanssid[LEN_WLANSSID];
char wlanpwd[LEN_CFG_PASSWORD];
// credentials of the sensor in access point mode
char fs_ssid[LEN_FS_SSID] = FS_SSID;
char fs_pwd[LEN_CFG_PASSWORD] = FS_PWD;
// main config
bool has_wifi = HAS_WIFI;
bool has_lora = HAS_LORA;
char appeui[LEN_APPEUI];
char deveui[LEN_DEVEUI];
char appkey[LEN_APPKEY];
// (in)active sensors
bool sds_read = SDS_READ;
bool npm_read = NPM_READ;
bool npm_fulltime = NPM_FULLTIME;
bool bmx280_read = BMX280_READ;
char height_above_sealevel[8] = "0";
bool gps_read = GPS_READ;
// send to "APIs"
bool send2dusti = SEND2SENSORCOMMUNITY;
bool send2madavi = SEND2MADAVI;
bool send2custom = SEND2CUSTOM;
bool send2custom2 = SEND2CUSTOM2;
bool send2csv = SEND2CSV;
// (in)active displays
bool has_ssd1306 = HAS_SSD1306;
bool display_wifi_info = DISPLAY_WIFI_INFO;
bool display_lora_info = DISPLAY_LORA_INFO;
bool display_device_info = DISPLAY_DEVICE_INFO;
// API settings
bool ssl_madavi = SSL_MADAVI;
bool ssl_dusti = SSL_SENSORCOMMUNITY;
// API AirCarto
char host_custom[LEN_HOST_CUSTOM];
char url_custom[LEN_URL_CUSTOM];
bool ssl_custom = SSL_CUSTOM;
unsigned port_custom = PORT_CUSTOM;
char user_custom[LEN_USER_CUSTOM] = USER_CUSTOM;
char pwd_custom[LEN_CFG_PASSWORD] = PWD_CUSTOM;
// API AtmoSud
char host_custom2[LEN_HOST_CUSTOM2];
char url_custom2[LEN_URL_CUSTOM2];
bool ssl_custom2 = SSL_CUSTOM2;
unsigned port_custom2 = PORT_CUSTOM2;
char user_custom2[LEN_USER_CUSTOM2] = USER_CUSTOM2;
char pwd_custom2[LEN_CFG_PASSWORD] = PWD_CUSTOM2;
// First load
void initNonTrivials(const char *id)
{
strcpy(cfg::current_lang, CURRENT_LANG);
strcpy_P(appeui, APPEUI);
strcpy_P(deveui, DEVEUI);
strcpy_P(appkey, APPKEY);
strcpy_P(www_username, WWW_USERNAME);
strcpy_P(www_password, WWW_PASSWORD);
strcpy_P(wlanssid, WLANSSID);
strcpy_P(wlanpwd, WLANPWD);
strcpy_P(host_custom, HOST_CUSTOM);
strcpy_P(url_custom, URL_CUSTOM);
strcpy_P(host_custom2, HOST_CUSTOM2);
strcpy_P(url_custom2, URL_CUSTOM2);
// AJOUTER LORA ICI?
if (!*fs_ssid)
{
strcpy(fs_ssid, SSID_BASENAME);
strcat(fs_ssid, id);
}
}
}
// define size of the config JSON
#define JSON_BUFFER_SIZE 2300 // REVOIR LA TAILLE
LoggerConfig loggerConfigs[LoggerCount];
// test variables
long int sample_count = 0;
bool bmx280_init_failed = false;
bool gps_init_failed = false;
bool nebulo_selftest_failed = false;
WebServer server(80);
// include JSON config reader
#include "./nebulo-cfg.h"
/*****************************************************************
* Display definitions *
*****************************************************************/
SSD1306Wire *oled_ssd1306 = nullptr; // as pointer
/*****************************************************************
* Serial declarations *
*****************************************************************/
#define serialSDS (Serial1)
#define serialGPS (&(Serial2)) // as pointer
#define serialNPM (Serial1)
/*****************************************************************
* BMP/BME280 declaration *
*****************************************************************/
BMX280 bmx280;
/*****************************************************************
* GPS declaration *
*****************************************************************/
TinyGPSPlus gps;
// time management varialbles
bool send_now = false;
unsigned long starttime;
unsigned long time_point_device_start_ms;
unsigned long starttime_SDS;
unsigned long starttime_GPS;
unsigned long starttime_NPM;
unsigned long last_NPM;
unsigned long act_micro;
unsigned long act_milli;
unsigned long last_micro = 0;
unsigned long min_micro = 1000000000;
unsigned long max_micro = 0;
// bool is_SDS_running = true;
bool is_SDS_running;
// To read SDS responses
enum
{
SDS_REPLY_HDR = 10,
SDS_REPLY_BODY = 8
} SDS_waiting_for;
// To read NPM responses
enum
{
NPM_REPLY_HEADER_16 = 16,
NPM_REPLY_STATE_16 = 14,
NPM_REPLY_BODY_16 = 13,
NPM_REPLY_CHECKSUM_16 = 1
} NPM_waiting_for_16; // for concentration
enum
{
NPM_REPLY_HEADER_4 = 4,
NPM_REPLY_STATE_4 = 2,
NPM_REPLY_CHECKSUM_4 = 1
} NPM_waiting_for_4; // for change
enum
{
NPM_REPLY_HEADER_5 = 5,
NPM_REPLY_STATE_5 = 3,
NPM_REPLY_DATA_5 = 2,
NPM_REPLY_CHECKSUM_5 = 1
} NPM_waiting_for_5; // for fan speed
enum
{
NPM_REPLY_HEADER_6 = 6,
NPM_REPLY_STATE_6 = 4,
NPM_REPLY_DATA_6 = 3,
NPM_REPLY_CHECKSUM_6 = 1
} NPM_waiting_for_6; // for version
enum
{
NPM_REPLY_HEADER_8 = 8,
NPM_REPLY_STATE_8 = 6,
NPM_REPLY_BODY_8 = 5,
NPM_REPLY_CHECKSUM_8 = 1
} NPM_waiting_for_8; // for temperature/humidity
String current_state_npm;
String current_th_npm;
bool is_NPM_running = false;
unsigned long sending_time = 0;
unsigned long last_update_attempt;
int last_update_returncode;
int last_sendData_returncode;
// data variables
float last_value_BMX280_T = -128.0;
float last_value_BMX280_P = -1.0;
float last_value_BME280_H = -1.0;
uint32_t sds_pm10_sum = 0;
uint32_t sds_pm25_sum = 0;
uint32_t sds_val_count = 0;
uint32_t sds_pm10_max = 0;
uint32_t sds_pm10_min = 20000;
uint32_t sds_pm25_max = 0;
uint32_t sds_pm25_min = 20000;
uint32_t npm_pm1_sum = 0;
uint32_t npm_pm10_sum = 0;
uint32_t npm_pm25_sum = 0;
uint32_t npm_pm1_sum_pcs = 0;
uint32_t npm_pm10_sum_pcs = 0;
uint32_t npm_pm25_sum_pcs = 0;
uint16_t npm_val_count = 0;
uint16_t npm_pm1_max = 0;
uint16_t npm_pm1_min = 20000;
uint16_t npm_pm10_max = 0;
uint16_t npm_pm10_min = 20000;
uint16_t npm_pm25_max = 0;
uint16_t npm_pm25_min = 20000;
uint16_t npm_pm1_max_pcs = 0;
uint16_t npm_pm1_min_pcs = 60000;
uint16_t npm_pm10_max_pcs = 0;
uint16_t npm_pm10_min_pcs = 60000;
uint16_t npm_pm25_max_pcs = 0;
uint16_t npm_pm25_min_pcs = 60000;
float last_value_SDS_P1 = -1.0;
float last_value_SDS_P2 = -1.0;
float last_value_NPM_P0 = -1.0;
float last_value_NPM_P1 = -1.0;
float last_value_NPM_P2 = -1.0;
float last_value_NPM_N1 = -1.0;
float last_value_NPM_N10 = -1.0;
float last_value_NPM_N25 = -1.0;
float last_value_GPS_alt = -1000.0;
double last_value_GPS_lat = -200.0;
double last_value_GPS_lon = -200.0;
String last_value_GPS_timestamp;
String last_data_string;
int last_signal_strength;
int last_disconnect_reason;
// chipID variables
String esp_chipid;
// String esp_mac_id;
String last_value_SDS_version;
String last_value_NPM_version;
unsigned long SDS_error_count;
unsigned long NPM_error_count;
unsigned long WiFi_error_count;
unsigned long last_page_load = millis();
bool wificonfig_loop = false;
uint8_t sntp_time_set;
unsigned long count_sends = 0;
unsigned long last_display_millis = 0;
uint8_t next_display_count = 0;
// info
struct struct_wifiInfo
{
char ssid[LEN_WLANSSID];
uint8_t encryptionType;
int32_t RSSI;
int32_t channel;
};
struct struct_wifiInfo *wifiInfo;
uint8_t count_wifiInfo;
// IPAddress addr_static_ip;
// IPAddress addr_static_subnet;
// IPAddress addr_static_gateway;
// IPAddress addr_static_dns;
#define msSince(timestamp_before) (act_milli - (timestamp_before))
const char data_first_part[] PROGMEM = "{\"software_version\": \"" SOFTWARE_VERSION_STR "\", \"sensordatavalues\":[";
const char JSON_SENSOR_DATA_VALUES[] PROGMEM = "sensordatavalues";
static String displayGenerateFooter(unsigned int screen_count)
{
String display_footer;
for (unsigned int i = 0; i < screen_count; ++i)
{
display_footer += (i != (next_display_count % screen_count)) ? " . " : " o ";
}
return display_footer;
}
/*****************************************************************
* display values *
*****************************************************************/
static void display_debug(const String &text1, const String &text2)
{
debug_outln_info(F("output debug text to displays..."));
if (oled_ssd1306)
{
oled_ssd1306->clear();
oled_ssd1306->displayOn();
oled_ssd1306->setTextAlignment(TEXT_ALIGN_LEFT);
oled_ssd1306->drawString(0, 12, text1);
oled_ssd1306->drawString(0, 24, text2);
oled_ssd1306->display();
}
}
/*****************************************************************
* read SDS011 sensor serial and firmware date *
*****************************************************************/
static String SDS_version_date()
{
if (cfg::sds_read && !last_value_SDS_version.length())
{
debug_outln_verbose(FPSTR(DBG_TXT_START_READING), FPSTR(DBG_TXT_SDS011_VERSION_DATE));
is_SDS_running = SDS_cmd(PmSensorCmd::Start);
delay(250);
serialSDS.flush();
// Query Version/Date
SDS_rawcmd(0x07, 0x00, 0x00);
delay(400);
const constexpr uint8_t header_cmd_response[2] = {0xAA, 0xC5};
while (serialSDS.find(header_cmd_response, sizeof(header_cmd_response)))
{
uint8_t data[8];
unsigned r = serialSDS.readBytes(data, sizeof(data));
if (r == sizeof(data) && data[0] == 0x07 && SDS_checksum_valid(data))
{
char tmp[20];
snprintf_P(tmp, sizeof(tmp), PSTR("%02d-%02d-%02d(%02x%02x)"),
data[1], data[2], data[3], data[4], data[5]);
last_value_SDS_version = tmp;
break;
}
}
debug_outln_verbose(FPSTR(DBG_TXT_END_READING), FPSTR(DBG_TXT_SDS011_VERSION_DATE));
}
return last_value_SDS_version;
}
/*****************************************************************
* NPM functions *
*****************************************************************/
static uint8_t NPM_get_state()
{
uint8_t result;
NPM_waiting_for_4 = NPM_REPLY_HEADER_4;
debug_outln_info(F("State NPM..."));
NPM_cmd(PmSensorCmd2::State);
while (!serialNPM.available())
{
debug_outln("Wait for Serial...", DEBUG_MAX_INFO);
}
while (serialNPM.available() >= NPM_waiting_for_4)
{
const uint8_t constexpr header[2] = {0x81, 0x16};
uint8_t state[1];
uint8_t checksum[1];
uint8_t test[4];
switch (NPM_waiting_for_4)
{
case NPM_REPLY_HEADER_4:
if (serialNPM.find(header, sizeof(header)))
NPM_waiting_for_4 = NPM_REPLY_STATE_4;
break;
case NPM_REPLY_STATE_4:
serialNPM.readBytes(state, sizeof(state));
NPM_state(state[0]);
result = state[0];
NPM_waiting_for_4 = NPM_REPLY_CHECKSUM_4;
break;
case NPM_REPLY_CHECKSUM_4:
serialNPM.readBytes(checksum, sizeof(checksum));
memcpy(test, header, sizeof(header));
memcpy(&test[sizeof(header)], state, sizeof(state));
memcpy(&test[sizeof(header) + sizeof(state)], checksum, sizeof(checksum));
NPM_data_reader(test, 4);
NPM_waiting_for_4 = NPM_REPLY_HEADER_4;
if (NPM_checksum_valid_4(test))
{
debug_outln_info(F("Checksum OK..."));
}
break;
}
}
return result;
}
static bool NPM_start_stop()
{
bool result;
NPM_waiting_for_4 = NPM_REPLY_HEADER_4;
debug_outln_info(F("Switch start/stop NPM..."));
NPM_cmd(PmSensorCmd2::Change);
while (!serialNPM.available())
{
debug_outln("Wait for Serial...", DEBUG_MAX_INFO);
}
while (serialNPM.available() >= NPM_waiting_for_4)
{
const uint8_t constexpr header[2] = {0x81, 0x15};
uint8_t state[1];
uint8_t checksum[1];
uint8_t test[4];
switch (NPM_waiting_for_4)
{
case NPM_REPLY_HEADER_4:
if (serialNPM.find(header, sizeof(header)))
NPM_waiting_for_4 = NPM_REPLY_STATE_4;
break;
case NPM_REPLY_STATE_4:
serialNPM.readBytes(state, sizeof(state));
NPM_state(state[0]);
if (bitRead(state[0], 0) == 0)
{
debug_outln_info(F("NPM start..."));
result = true;
}
else if (bitRead(state[0], 0) == 1)
{
debug_outln_info(F("NPM stop..."));
result = false;
}
else
{
result = !is_NPM_running; //DANGER BECAUSE NON INITIALISED
}
NPM_waiting_for_4 = NPM_REPLY_CHECKSUM_4;
break;
case NPM_REPLY_CHECKSUM_4:
serialNPM.readBytes(checksum, sizeof(checksum));
memcpy(test, header, sizeof(header));
memcpy(&test[sizeof(header)], state, sizeof(state));
memcpy(&test[sizeof(header) + sizeof(state)], checksum, sizeof(checksum));
NPM_data_reader(test, 4);
NPM_waiting_for_4 = NPM_REPLY_HEADER_4;
if (NPM_checksum_valid_4(test))
{
debug_outln_info(F("Checksum OK..."));
}
break;
}
}
return result;
}
static String NPM_version_date()
{
// debug_outln_verbose(FPSTR(DBG_TXT_START_READING), FPSTR(DBG_TXT_NPM_VERSION_DATE));
delay(250);
NPM_waiting_for_6 = NPM_REPLY_HEADER_6;
debug_outln_info(F("Version NPM..."));
NPM_cmd(PmSensorCmd2::Version);
while (!serialNPM.available())
{
debug_outln("Wait for Serial...", DEBUG_MAX_INFO);
}
while (serialNPM.available() >= NPM_waiting_for_6)
{
const uint8_t constexpr header[2] = {0x81, 0x17};
uint8_t state[1];
uint8_t data[2];
uint8_t checksum[1];
uint8_t test[6];
switch (NPM_waiting_for_6)
{
case NPM_REPLY_HEADER_6:
if (serialNPM.find(header, sizeof(header)))
NPM_waiting_for_6 = NPM_REPLY_STATE_6;
break;
case NPM_REPLY_STATE_6:
serialNPM.readBytes(state, sizeof(state));
NPM_state(state[0]);
NPM_waiting_for_6 = NPM_REPLY_DATA_6;
break;
case NPM_REPLY_DATA_6:
if (serialNPM.readBytes(data, sizeof(data)) == sizeof(data))
{
NPM_data_reader(data, 2);
uint16_t NPMversion = word(data[0], data[1]);
last_value_NPM_version = String(NPMversion);
// debug_outln_verbose(FPSTR(DBG_TXT_END_READING), FPSTR(DBG_TXT_NPM_VERSION_DATE));
debug_outln_info(F("Next PM Firmware: "), last_value_NPM_version);
}
NPM_waiting_for_6 = NPM_REPLY_CHECKSUM_6;
break;
case NPM_REPLY_CHECKSUM_6:
serialNPM.readBytes(checksum, sizeof(checksum));
memcpy(test, header, sizeof(header));
memcpy(&test[sizeof(header)], state, sizeof(state));
memcpy(&test[sizeof(header) + sizeof(state)], data, sizeof(data));
memcpy(&test[sizeof(header) + sizeof(state) + sizeof(data)], checksum, sizeof(checksum));
NPM_data_reader(test, 6);
NPM_waiting_for_6 = NPM_REPLY_HEADER_6;
if (NPM_checksum_valid_6(test))
{
debug_outln_info(F("Checksum OK..."));
}
break;
}
}
return last_value_NPM_version;
}
static void NPM_fan_speed()
{
NPM_waiting_for_5 = NPM_REPLY_HEADER_5;
debug_outln_info(F("Set fan speed to 50 %..."));
NPM_cmd(PmSensorCmd2::Speed);
while (!serialNPM.available())
{
debug_outln("Wait for Serial...", DEBUG_MAX_INFO);
}
while (serialNPM.available() >= NPM_waiting_for_5)
{
const uint8_t constexpr header[2] = {0x81, 0x21};
uint8_t state[1];
uint8_t data[1];
uint8_t checksum[1];
uint8_t test[5];
switch (NPM_waiting_for_5)
{
case NPM_REPLY_HEADER_5:
if (serialNPM.find(header, sizeof(header)))
NPM_waiting_for_5 = NPM_REPLY_STATE_5;
break;
case NPM_REPLY_STATE_5:
serialNPM.readBytes(state, sizeof(state));
NPM_state(state[0]);
NPM_waiting_for_5 = NPM_REPLY_DATA_5;
break;
case NPM_REPLY_DATA_5:
if (serialNPM.readBytes(data, sizeof(data)) == sizeof(data))
{
NPM_data_reader(data, 1);
}
NPM_waiting_for_5 = NPM_REPLY_CHECKSUM_5;
break;
case NPM_REPLY_CHECKSUM_5:
serialNPM.readBytes(checksum, sizeof(checksum));
memcpy(test, header, sizeof(header));
memcpy(&test[sizeof(header)], state, sizeof(state));
memcpy(&test[sizeof(header) + sizeof(state)], data, sizeof(data));
memcpy(&test[sizeof(header) + sizeof(state) + sizeof(data)], checksum, sizeof(checksum));
NPM_data_reader(test, 5);
NPM_waiting_for_5 = NPM_REPLY_HEADER_5;
if (NPM_checksum_valid_5(test))
{
debug_outln_info(F("Checksum OK..."));
}
break;
}
}
}
static String NPM_temp_humi()
{
uint16_t NPM_temp;
uint16_t NPM_humi;
NPM_waiting_for_8 = NPM_REPLY_HEADER_8;
debug_outln_info(F("Temperature/Humidity in Next PM..."));
NPM_cmd(PmSensorCmd2::Temphumi);
while (!serialNPM.available())
{
debug_outln("Wait for Serial...", DEBUG_MAX_INFO);
}
while (serialNPM.available() >= NPM_waiting_for_8)
{
const uint8_t constexpr header[2] = {0x81, 0x14};
uint8_t state[1];
uint8_t data[4];
uint8_t checksum[1];
uint8_t test[8];
switch (NPM_waiting_for_8)
{
case NPM_REPLY_HEADER_8:
if (serialNPM.find(header, sizeof(header)))
NPM_waiting_for_8 = NPM_REPLY_STATE_8;
break;
case NPM_REPLY_STATE_8:
serialNPM.readBytes(state, sizeof(state));
NPM_state(state[0]);
NPM_waiting_for_8 = NPM_REPLY_BODY_8;
break;
case NPM_REPLY_BODY_8:
if (serialNPM.readBytes(data, sizeof(data)) == sizeof(data))
{
NPM_data_reader(data, 4);
NPM_temp = word(data[0], data[1]);
NPM_humi = word(data[2], data[3]);
debug_outln_verbose(F("Temperature (°C): "), String(NPM_temp / 100.0f));
debug_outln_verbose(F("Relative humidity (%): "), String(NPM_humi / 100.0f));
}
NPM_waiting_for_8 = NPM_REPLY_CHECKSUM_8;
break;
case NPM_REPLY_CHECKSUM_16:
serialNPM.readBytes(checksum, sizeof(checksum));
memcpy(test, header, sizeof(header));
memcpy(&test[sizeof(header)], state, sizeof(state));
memcpy(&test[sizeof(header) + sizeof(state)], data, sizeof(data));
memcpy(&test[sizeof(header) + sizeof(state) + sizeof(data)], checksum, sizeof(checksum));
NPM_data_reader(test, 8);
if (NPM_checksum_valid_8(test))
debug_outln_info(F("Checksum OK..."));
NPM_waiting_for_8 = NPM_REPLY_HEADER_8;
break;
}
}
return String(NPM_temp / 100.0f) + " / "+ String(NPM_humi / 100.0f);
}
/*****************************************************************
* disable unneeded NMEA sentences, TinyGPS++ needs GGA, RMC *
*****************************************************************/
static void disable_unneeded_nmea()
{
serialGPS->println(F("$PUBX,40,GLL,0,0,0,0*5C")); // Geographic position, latitude / longitude
// serialGPS->println(F("$PUBX,40,GGA,0,0,0,0*5A")); // Global Positioning System Fix Data
serialGPS->println(F("$PUBX,40,GSA,0,0,0,0*4E")); // GPS DOP and active satellites
// serialGPS->println(F("$PUBX,40,RMC,0,0,0,0*47")); // Recommended minimum specific GPS/Transit data
serialGPS->println(F("$PUBX,40,GSV,0,0,0,0*59")); // GNSS satellites in view
serialGPS->println(F("$PUBX,40,VTG,0,0,0,0*5E")); // Track made good and ground speed
}
/*****************************************************************
* write config to spiffs *
*****************************************************************/
static bool writeConfig()
{
DynamicJsonDocument json(JSON_BUFFER_SIZE);
debug_outln_info(F("Saving config..."));
json["SOFTWARE_VERSION"] = SOFTWARE_VERSION;
for (unsigned e = 0; e < sizeof(configShape) / sizeof(configShape[0]); ++e)
{
ConfigShapeEntry c;
memcpy_P(&c, &configShape[e], sizeof(ConfigShapeEntry));
switch (c.cfg_type)
{
case Config_Type_Bool:
json[c.cfg_key()].set(*c.cfg_val.as_bool);
break;
case Config_Type_UInt:
case Config_Type_Time:
json[c.cfg_key()].set(*c.cfg_val.as_uint);
break;
case Config_Type_Password:
case Config_Type_Hex:
case Config_Type_String:
json[c.cfg_key()].set(c.cfg_val.as_str);
break;
};
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
SPIFFS.remove(F("/config.json.old"));
SPIFFS.rename(F("/config.json"), F("/config.json.old"));
File configFile = SPIFFS.open(F("/config.json"), "w");
if (configFile)
{
serializeJson(json, configFile);
configFile.close();
debug_outln_info(F("Config written successfully."));
}
else
{
debug_outln_error(F("failed to open config file for writing"));
return false;
}
#pragma GCC diagnostic pop
return true;
}
/*****************************************************************
* read config from spiffs *
*****************************************************************/
/* backward compatibility for the times when we stored booleans as strings */
static bool boolFromJSON(const DynamicJsonDocument &json, const __FlashStringHelper *key)
{
if (json[key].is<const char *>())
{
return !strcmp_P(json[key].as<const char *>(), PSTR("true"));
}
return json[key].as<bool>();
}
static void readConfig(bool oldconfig = false)
{
bool rewriteConfig = false;
String cfgName(F("/config.json"));
if (oldconfig)
{
cfgName += F(".old");
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
File configFile = SPIFFS.open(cfgName, "r");
if (!configFile)
{
if (!oldconfig)
{
return readConfig(true /* oldconfig */);
}
debug_outln_error(F("failed to open config file."));
return;
}
debug_outln_info(F("opened config file..."));
DynamicJsonDocument json(JSON_BUFFER_SIZE);
DeserializationError err = deserializeJson(json, configFile.readString());
configFile.close();
#pragma GCC diagnostic pop
if (!err)
{
serializeJsonPretty(json, Debug);
debug_outln_info(F("parsed json..."));
for (unsigned e = 0; e < sizeof(configShape) / sizeof(configShape[0]); ++e)
{
ConfigShapeEntry c;
memcpy_P(&c, &configShape[e], sizeof(ConfigShapeEntry));
if (json[c.cfg_key()].isNull())
{
continue;
}
switch (c.cfg_type)
{
case Config_Type_Bool:
*(c.cfg_val.as_bool) = boolFromJSON(json, c.cfg_key());
break;
case Config_Type_UInt:
case Config_Type_Time:
*(c.cfg_val.as_uint) = json[c.cfg_key()].as<unsigned int>();
break;
case Config_Type_String:
case Config_Type_Hex:
case Config_Type_Password:
strncpy(c.cfg_val.as_str, json[c.cfg_key()].as<const char *>(), c.cfg_len);
c.cfg_val.as_str[c.cfg_len] = '\0';
break;
};
}
String writtenVersion(json["SOFTWARE_VERSION"].as<const char *>());
if (writtenVersion.length() && writtenVersion[0] == 'N' && SOFTWARE_VERSION != writtenVersion)
{
debug_outln_info(F("Rewriting old config from: "), writtenVersion);
// would like to do that, but this would wipe firmware.old which the two stage loader
// might still need
// SPIFFS.format();
rewriteConfig = true;
}
if (cfg::sending_intervall_ms < READINGTIME_SDS_MS)
{
cfg::sending_intervall_ms = READINGTIME_SDS_MS;
}
if (boolFromJSON(json, F("bmp280_read")) || boolFromJSON(json, F("bme280_read")))
{
cfg::bmx280_read = true;
rewriteConfig = true;
}
}
else
{
debug_outln_error(F("failed to load json config"));
if (!oldconfig)
{
return readConfig(true /* oldconfig */);
}
}
if (rewriteConfig)
{
writeConfig();
}
}
static void init_config()
{
debug_outln_info(F("mounting FS..."));
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
bool spiffs_begin_ok = SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED);
#pragma GCC diagnostic pop
if (!spiffs_begin_ok)
{
debug_outln_error(F("failed to mount FS"));
return;
}
readConfig();
}
/*****************************************************************
* Prepare information for data Loggers *
*****************************************************************/
static void createLoggerConfigs()
{
auto new_session = []()
{ return nullptr; };
if (cfg::send2dusti)
{
loggerConfigs[LoggerSensorCommunity].destport = 80;
if (cfg::ssl_dusti)
{
loggerConfigs[LoggerSensorCommunity].destport = 443;
loggerConfigs[LoggerSensorCommunity].session = new_session();
}
}
loggerConfigs[LoggerMadavi].destport = PORT_MADAVI;
if (cfg::send2madavi && cfg::ssl_madavi)
{
loggerConfigs[LoggerMadavi].destport = 443;
loggerConfigs[LoggerMadavi].session = new_session();
}
loggerConfigs[LoggerCustom].destport = cfg::port_custom;
if (cfg::send2custom && (cfg::ssl_custom || (cfg::port_custom == 443)))
{
loggerConfigs[LoggerCustom].session = new_session();
}
loggerConfigs[LoggerCustom2].destport = cfg::port_custom2;
if (cfg::send2custom2 && (cfg::ssl_custom2 || (cfg::port_custom2 == 443)))
{
loggerConfigs[LoggerCustom2].session = new_session();
}
}
/*****************************************************************
* dew point helper function *
*****************************************************************/
static float dew_point(const float temperature, const float humidity)
{
float dew_temp;
const float k2 = 17.62;
const float k3 = 243.12;
dew_temp = k3 * (((k2 * temperature) / (k3 + temperature)) + log(humidity / 100.0f)) / (((k2 * k3) / (k3 + temperature)) - log(humidity / 100.0f));
return dew_temp;
}
/*****************************************************************
* dew point helper function *
*****************************************************************/
static float pressure_at_sealevel(const float temperature, const float pressure)
{
float pressure_at_sealevel;
pressure_at_sealevel = pressure * pow(((temperature + 273.15f) / (temperature + 273.15f + (0.0065f * readCorrectionOffset(cfg::height_above_sealevel)))), -5.255f);
return pressure_at_sealevel;
}
/*****************************************************************
* html helper functions *
*****************************************************************/
static void start_html_page(String &page_content, const String &title)
{
last_page_load = millis();
RESERVE_STRING(s, LARGE_STR);
s = FPSTR(WEB_PAGE_HEADER);
s.replace("{t}", title);
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, FPSTR(TXT_CONTENT_TYPE_TEXT_HTML), s);
server.sendContent_P(WEB_PAGE_HEADER_HEAD);
s = FPSTR(WEB_PAGE_HEADER_BODY);
s.replace("{t}", title);
if (title != " ")
{
s.replace("{n}", F("»"));
}
else
{
s.replace("{n}", emptyString);
}
s.replace("{id}", esp_chipid);
// s.replace("{macid}", esp_mac_id);
// s.replace("{mac}", WiFi.macAddress());
page_content += s;
}
static void end_html_page(String &page_content)
{
if (page_content.length())
{
server.sendContent(page_content);
}
server.sendContent_P(WEB_PAGE_FOOTER);
}