forked from emsesp/EMS-ESP32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystem.cpp
1325 lines (1186 loc) · 51.5 KB
/
system.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
/*
* EMS-ESP - https://github.com/emsesp/EMS-ESP
* Copyright 2020 Paul Derbyshire
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "system.h"
#include "emsesp.h" // for send_raw_telegram() command
#if defined(EMSESP_DEBUG)
#include "test/test.h"
#endif
#ifndef EMSESP_STANDALONE
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "../esp32/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "../esp32s2/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "../esp32c3/rom/rtc.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "../rom/rtc.h"
#endif
#endif
namespace emsesp {
// Languages supported. Note: the order is important and must match locale_translations.h
const char * const languages[] = {EMSESP_LOCALE_EN, EMSESP_LOCALE_DE, EMSESP_LOCALE_NL, EMSESP_LOCALE_SE, EMSESP_LOCALE_PL, EMSESP_LOCALE_NO};
size_t num_languages = sizeof(languages) / sizeof(const char *);
uuid::log::Logger System::logger_{F_(system), uuid::log::Facility::KERN};
#ifndef EMSESP_STANDALONE
uuid::syslog::SyslogService System::syslog_;
#endif
// init statics
PButton System::myPButton_;
bool System::restart_requested_ = false;
// find the index of the language
// 0 = EN, 1 = DE, etc...
uint8_t System::language_index() {
for (uint8_t i = 0; i < num_languages; i++) {
if (languages[i] == locale()) {
return i;
}
}
return 0; // EN
}
// send raw to ems
bool System::command_send(const char * value, const int8_t id) {
return EMSESP::txservice_.send_raw(value); // ignore id
}
// fetch device values
bool System::command_fetch(const char * value, const int8_t id) {
std::string value_s;
if (Helpers::value2string(value, value_s)) {
if (value_s == "all") {
LOG_INFO(F("Requesting data from EMS devices"));
EMSESP::fetch_device_values();
return true;
} else if (value_s == read_flash_string(F_(boiler))) {
EMSESP::fetch_device_values_type(EMSdevice::DeviceType::BOILER);
return true;
} else if (value_s == read_flash_string(F_(thermostat))) {
EMSESP::fetch_device_values_type(EMSdevice::DeviceType::THERMOSTAT);
return true;
} else if (value_s == read_flash_string(F_(solar))) {
EMSESP::fetch_device_values_type(EMSdevice::DeviceType::SOLAR);
return true;
} else if (value_s == read_flash_string(F_(mixer))) {
EMSESP::fetch_device_values_type(EMSdevice::DeviceType::MIXER);
return true;
}
}
EMSESP::fetch_device_values(); // default if no name or id is given
return true;
}
// mqtt publish
bool System::command_publish(const char * value, const int8_t id) {
std::string value_s;
if (Helpers::value2string(value, value_s)) {
if (value_s == "ha") {
EMSESP::publish_all(true); // includes HA
LOG_INFO(F("Publishing all data to MQTT, including HA configs"));
return true;
} else if (value_s == read_flash_string(F_(boiler))) {
EMSESP::publish_device_values(EMSdevice::DeviceType::BOILER);
return true;
} else if (value_s == read_flash_string(F_(thermostat))) {
EMSESP::publish_device_values(EMSdevice::DeviceType::THERMOSTAT);
return true;
} else if (value_s == read_flash_string(F_(solar))) {
EMSESP::publish_device_values(EMSdevice::DeviceType::SOLAR);
return true;
} else if (value_s == read_flash_string(F_(mixer))) {
EMSESP::publish_device_values(EMSdevice::DeviceType::MIXER);
return true;
} else if (value_s == "other") {
EMSESP::publish_other_values(); // switch and heat pump
return true;
} else if ((value_s == read_flash_string(F_(dallassensor))) || (value_s == read_flash_string(F_(analogsensor)))) {
EMSESP::publish_sensor_values(true);
return true;
}
}
EMSESP::publish_all();
LOG_INFO(F("Publishing all data to MQTT"));
return true;
}
// syslog level
bool System::command_syslog_level(const char * value, const int8_t id) {
uint8_t s = 0xff;
if (Helpers::value2enum(value, s, FL_(list_syslog_level))) {
bool changed = false;
EMSESP::webSettingsService.update(
[&](WebSettings & settings) {
if (settings.syslog_level != (int8_t)s - 1) {
settings.syslog_level = (int8_t)s - 1;
changed = true;
}
return StateUpdateResult::CHANGED;
},
"local");
if (changed) {
EMSESP::system_.syslog_init();
}
return true;
}
return false;
}
// watch
bool System::command_watch(const char * value, const int8_t id) {
uint8_t w = 0xff;
uint16_t i = Helpers::hextoint(value);
if (Helpers::value2enum(value, w, FL_(list_watch))) {
if (w == 0 || EMSESP::watch() == EMSESP::Watch::WATCH_OFF) {
EMSESP::watch_id(0);
}
if (Mqtt::publish_single() && w != EMSESP::watch()) {
if (Mqtt::publish_single2cmd()) {
Mqtt::publish(F("system/watch"),
EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX ? Helpers::itoa(w) : read_flash_string(FL_(list_watch)[w]).c_str());
} else {
Mqtt::publish(F("system_data/watch"),
EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX ? Helpers::itoa(w) : read_flash_string(FL_(list_watch)[w]).c_str());
}
}
EMSESP::watch(w);
return true;
} else if (i) {
if (Mqtt::publish_single() && i != EMSESP::watch_id()) {
if (Mqtt::publish_single2cmd()) {
Mqtt::publish(F("system/watch"), Helpers::hextoa(i));
} else {
Mqtt::publish(F("system_data/watch"), Helpers::hextoa(i));
}
}
EMSESP::watch_id(i);
if (EMSESP::watch() == EMSESP::Watch::WATCH_OFF) {
EMSESP::watch(EMSESP::Watch::WATCH_ON);
}
return true;
}
return false;
}
// restart EMS-ESP
void System::system_restart() {
LOG_INFO(F("Restarting EMS-ESP..."));
Shell::loop_all();
delay(1000); // wait a second
#ifndef EMSESP_STANDALONE
ESP.restart();
#endif
}
// saves all settings
void System::wifi_reconnect() {
LOG_INFO(F("WiFi reconnecting..."));
Shell::loop_all();
EMSESP::console_.loop();
delay(1000); // wait a second
EMSESP::webSettingsService.save(); // local settings
EMSESP::esp8266React.getNetworkSettingsService()->callUpdateHandlers("local"); // in case we've changed ssid or password
}
// format the FS. Wipes everything.
void System::format(uuid::console::Shell & shell) {
auto msg = F("Formatting file system. This will reset all settings to their defaults");
shell.logger().warning(msg);
shell.flush();
EMSuart::stop();
#ifndef EMSESP_STANDALONE
LittleFS.format();
#endif
System::system_restart();
}
void System::syslog_init() {
#ifndef EMSESP_STANDALONE
bool was_enabled = syslog_enabled_;
#endif
EMSESP::webSettingsService.read([&](WebSettings & settings) {
syslog_enabled_ = settings.syslog_enabled;
syslog_level_ = settings.syslog_level;
syslog_mark_interval_ = settings.syslog_mark_interval;
syslog_host_ = settings.syslog_host;
syslog_port_ = settings.syslog_port;
});
#ifndef EMSESP_STANDALONE
if (syslog_enabled_) {
// start & configure syslog
if (!was_enabled) {
syslog_.start();
EMSESP::logger().info(F("Starting Syslog"));
}
syslog_.log_level((uuid::log::Level)syslog_level_);
syslog_.mark_interval(syslog_mark_interval_);
syslog_.destination(syslog_host_.c_str(), syslog_port_);
syslog_.hostname(hostname().c_str());
// register the command
// TODO translate this
Command::add(EMSdevice::DeviceType::SYSTEM, F_(syslog), System::command_syslog_level, F("change the syslog level"), CommandFlag::ADMIN_ONLY);
} else if (was_enabled) {
// in case service is still running, this flushes the queue
// https://github.com/emsesp/EMS-ESP/issues/496
EMSESP::logger().info(F("Stopping Syslog"));
syslog_.log_level((uuid::log::Level)-1);
syslog_.mark_interval(0);
syslog_.destination("");
}
if (Mqtt::publish_single()) {
if (Mqtt::publish_single2cmd()) {
Mqtt::publish(F("system/syslog"), syslog_enabled_ ? read_flash_string(FL_(list_syslog_level)[syslog_level_ + 1]).c_str() : "off");
if (EMSESP::watch_id() == 0 || EMSESP::watch() == 0) {
Mqtt::publish(F("system/watch"),
EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX ? Helpers::itoa(EMSESP::watch())
: read_flash_string(FL_(list_watch)[EMSESP::watch()]).c_str());
} else {
Mqtt::publish(F("system/watch"), Helpers::hextoa(EMSESP::watch_id()));
}
} else {
Mqtt::publish(F("system_data/syslog"), syslog_enabled_ ? read_flash_string(FL_(list_syslog_level)[syslog_level_ + 1]).c_str() : "off");
if (EMSESP::watch_id() == 0 || EMSESP::watch() == 0) {
Mqtt::publish(F("system_data/watch"),
EMSESP::system_.enum_format() == ENUM_FORMAT_INDEX ? Helpers::itoa(EMSESP::watch())
: read_flash_string(FL_(list_watch)[EMSESP::watch()]).c_str());
} else {
Mqtt::publish(F("system_data/watch"), Helpers::hextoa(EMSESP::watch_id()));
}
}
}
#endif
}
// read some specific system settings to store locally for faster access
void System::reload_settings() {
EMSESP::webSettingsService.read([&](WebSettings & settings) {
pbutton_gpio_ = settings.pbutton_gpio;
analog_enabled_ = settings.analog_enabled;
low_clock_ = settings.low_clock;
hide_led_ = settings.hide_led;
led_gpio_ = settings.led_gpio;
board_profile_ = settings.board_profile;
telnet_enabled_ = settings.telnet_enabled;
rx_gpio_ = settings.rx_gpio;
tx_gpio_ = settings.tx_gpio;
dallas_gpio_ = settings.dallas_gpio;
syslog_enabled_ = settings.syslog_enabled;
syslog_level_ = settings.syslog_level;
syslog_mark_interval_ = settings.syslog_mark_interval;
syslog_host_ = settings.syslog_host;
syslog_port_ = settings.syslog_port;
fahrenheit_ = settings.fahrenheit;
bool_format_ = settings.bool_format;
bool_dashboard_ = settings.bool_dashboard;
enum_format_ = settings.enum_format;
readonly_mode_ = settings.readonly_mode;
phy_type_ = settings.phy_type;
eth_power_ = settings.eth_power;
eth_phy_addr_ = settings.eth_phy_addr;
eth_clock_mode_ = settings.eth_clock_mode;
locale_ = settings.locale;
});
}
// adjust WiFi settings
// this for problem solving mesh and connection issues, and also get EMS bus-powered more stable by lowering power
void System::wifi_tweak() {
#if defined(EMSESP_WIFI_TWEAK)
// Default Tx Power is 80 = 20dBm <-- default
// WIFI_POWER_19_5dBm = 78,// 19.5dBm
// WIFI_POWER_19dBm = 76,// 19dBm
// WIFI_POWER_18_5dBm = 74,// 18.5dBm
// WIFI_POWER_17dBm = 68,// 17dBm
// WIFI_POWER_15dBm = 60,// 15dBm
// WIFI_POWER_13dBm = 52,// 13dBm
// WIFI_POWER_11dBm = 44,// 11dBm
// WIFI_POWER_8_5dBm = 34,// 8.5dBm
// WIFI_POWER_7dBm = 28,// 7dBm
// WIFI_POWER_5dBm = 20,// 5dBm
// WIFI_POWER_2dBm = 8,// 2dBm
// WIFI_POWER_MINUS_1dBm = -4// -1dBm
wifi_power_t p1 = WiFi.getTxPower();
(void)WiFi.setTxPower(WIFI_POWER_17dBm);
wifi_power_t p2 = WiFi.getTxPower();
bool s1 = WiFi.getSleep();
WiFi.setSleep(false); // turn off sleep - WIFI_PS_NONE
bool s2 = WiFi.getSleep();
#if defined(EMSESP_DEBUG)
LOG_DEBUG(F("[DEBUG] Adjusting WiFi - Tx power %d->%d, Sleep %d->%d"), p1, p2, s1, s2);
#endif
#endif
}
#ifdef ARDUINO_LOLIN_C3_MINI
// https://www.wemos.cc/en/latest/c3/c3_mini.html
bool System::is_valid_gpio(uint8_t pin) {
if ((pin >= 11 && pin <= 19) || (pin > 21)) {
return false; // bad pin
}
return true;
}
#else
// check for valid ESP32 pins. This is very dependent on which ESP32 board is being used.
// Typically you can't use 1, 6-11, 12, 14, 15, 20, 24, 28-31 and 40+
// we allow 0 as it has a special function on the NodeMCU apparently
// See https://diyprojects.io/esp32-how-to-use-gpio-digital-io-arduino-code/#.YFpVEq9KhjG
// and https://nodemcu.readthedocs.io/en/dev-esp32/modules/gpio/
bool System::is_valid_gpio(uint8_t pin) {
if ((pin == 1) || (pin >= 6 && pin <= 12) || (pin >= 14 && pin <= 15) || (pin == 20) || (pin == 24) || (pin >= 28 && pin <= 31) || (pin > 40)) {
return false; // bad pin
}
return true;
}
#endif
// Starts up the UART Serial bridge
void System::start() {
#ifndef EMSESP_STANDALONE
// disable bluetooth module
// periph_module_disable(PERIPH_BT_MODULE);
if (low_clock_) {
setCpuFrequencyMhz(160);
}
fstotal_ = LittleFS.totalBytes(); // read only once, it takes 500 ms to read
#endif
EMSESP::esp8266React.getNetworkSettingsService()->read([&](NetworkSettings & networkSettings) {
hostname(networkSettings.hostname.c_str()); // sets the hostname
});
commands_init(); // console & api commands
led_init(false); // init LED
button_init(false); // the special button
network_init(false); // network
syslog_init(); // start Syslog
EMSESP::uart_init(); // start UART
}
// button single click
void System::button_OnClick(PButton & b) {
LOG_DEBUG(F("Button pressed - single click"));
#ifdef EMSESP_DEBUG
#ifndef EMSESP_STANDALONE
Test::listDir(LittleFS, FS_CONFIG_DIRECTORY, 3);
#endif
#endif
}
// button double click
void System::button_OnDblClick(PButton & b) {
LOG_DEBUG(F("Button pressed - double click - reconnect"));
EMSESP::system_.wifi_reconnect();
}
// button long press
void System::button_OnLongPress(PButton & b) {
LOG_DEBUG(F("Button pressed - long press"));
}
// button indefinite press
void System::button_OnVLongPress(PButton & b) {
LOG_DEBUG(F("Button pressed - very long press"));
#ifndef EMSESP_STANDALONE
LOG_WARNING(F("Performing factory reset..."));
EMSESP::console_.loop();
EMSESP::esp8266React.factoryReset();
#endif
}
// push button
void System::button_init(bool refresh) {
if (refresh) {
reload_settings();
}
if (is_valid_gpio(pbutton_gpio_)) {
if (!myPButton_.init(pbutton_gpio_, HIGH)) {
LOG_DEBUG(F("Multi-functional button not detected"));
} else {
LOG_DEBUG(F("Multi-functional button enabled"));
}
} else {
LOG_WARNING(F("Invalid button GPIO. Check config."));
}
myPButton_.onClick(BUTTON_Debounce, button_OnClick);
myPButton_.onDblClick(BUTTON_DblClickDelay, button_OnDblClick);
myPButton_.onLongPress(BUTTON_LongPressDelay, button_OnLongPress);
myPButton_.onVLongPress(BUTTON_VLongPressDelay, button_OnVLongPress);
}
// set the LED to on or off when in normal operating mode
void System::led_init(bool refresh) {
if (refresh) {
reload_settings();
}
if ((led_gpio_ != 0) && is_valid_gpio(led_gpio_)) {
pinMode(led_gpio_, OUTPUT); // 0 means disabled
digitalWrite(led_gpio_, !LED_ON); // start with LED off
}
}
// returns true if OTA is uploading
bool System::upload_status() {
#if defined(EMSESP_STANDALONE)
return false;
#else
return upload_status_ || Update.isRunning();
#endif
}
void System::upload_status(bool in_progress) {
// if we've just started an upload
if (!upload_status_ && in_progress) {
EMSuart::stop();
}
upload_status_ = in_progress;
}
// checks system health and handles LED flashing wizardry
void System::loop() {
// check if we're supposed to do a reset/restart
if (restart_requested()) {
this->system_restart();
}
#ifndef EMSESP_STANDALONE
myPButton_.check(); // check button press
if (syslog_enabled_) {
syslog_.loop();
}
led_monitor(); // check status and report back using the LED
system_check(); // check system health
// send out heartbeat
uint32_t currentMillis = uuid::get_uptime();
if (!last_heartbeat_ || (currentMillis - last_heartbeat_ > SYSTEM_HEARTBEAT_INTERVAL)) {
last_heartbeat_ = currentMillis;
send_heartbeat();
}
#ifndef EMSESP_STANDALONE
#if defined(EMSESP_DEBUG)
/*
static uint32_t last_memcheck_ = 0;
if (currentMillis - last_memcheck_ > 10000) { // 10 seconds
last_memcheck_ = currentMillis;
show_mem("core");
}
*/
#endif
#endif
#endif
}
// create the json for heartbeat
bool System::heartbeat_json(JsonObject & output) {
uint8_t bus_status = EMSESP::bus_status();
if (bus_status == EMSESP::BUS_STATUS_TX_ERRORS) {
output["bus_status"] = FJSON("txerror");
} else if (bus_status == EMSESP::BUS_STATUS_CONNECTED) {
output["bus_status"] = FJSON("connected");
} else {
output["bus_status"] = FJSON("disconnected");
}
output["uptime"] = uuid::log::format_timestamp_ms(uuid::get_uptime_ms(), 3);
output["uptime_sec"] = uuid::get_uptime_sec();
bool value_b = EMSESP::system_.ntp_connected();
if (Mqtt::ha_enabled()) {
char s[7];
output["ntp_status"] = Helpers::render_boolean(s, value_b); // for HA always render as string
} else if (EMSESP::system_.bool_format() == BOOL_FORMAT_TRUEFALSE) {
output["ntp_status"] = value_b;
} else if (EMSESP::system_.bool_format() == BOOL_FORMAT_10) {
output["ntp_status"] = value_b ? 1 : 0;
} else {
char s[7];
output["ntp_status"] = Helpers::render_boolean(s, value_b);
}
output["rxreceived"] = EMSESP::rxservice_.telegram_count();
output["rxfails"] = EMSESP::rxservice_.telegram_error_count();
output["txreads"] = EMSESP::txservice_.telegram_read_count();
output["txwrites"] = EMSESP::txservice_.telegram_write_count();
output["txfails"] = EMSESP::txservice_.telegram_read_fail_count() + EMSESP::txservice_.telegram_write_fail_count();
if (Mqtt::enabled()) {
output["mqttcount"] = Mqtt::publish_count();
output["mqttfails"] = Mqtt::publish_fails();
}
output["apicalls"] = WebAPIService::api_count(); // + WebAPIService::api_fails();
output["apifails"] = WebAPIService::api_fails();
if (EMSESP::dallas_enabled() || EMSESP::analog_enabled()) {
output["sensorreads"] = EMSESP::dallassensor_.reads() + EMSESP::analogsensor_.reads();
output["sensorfails"] = EMSESP::dallassensor_.fails() + EMSESP::analogsensor_.fails();
}
#ifndef EMSESP_STANDALONE
output["freemem"] = ESP.getFreeHeap() / 1000L; // kilobytes
#endif
#ifndef EMSESP_STANDALONE
if (!ethernet_connected_) {
int8_t rssi = WiFi.RSSI();
output["rssi"] = rssi;
output["wifistrength"] = wifi_quality(rssi);
}
#endif
return true;
}
// send periodic MQTT message with system information
void System::send_heartbeat() {
// don't send heartbeat if WiFi or MQTT is not connected
if (!Mqtt::connected()) {
return;
}
StaticJsonDocument<EMSESP_JSON_SIZE_MEDIUM> doc;
JsonObject json = doc.to<JsonObject>();
if (heartbeat_json(json)) {
Mqtt::publish(F_(heartbeat), json); // send to MQTT with retain off. This will add to MQTT queue.
}
}
// initializes network
void System::network_init(bool refresh) {
if (refresh) {
reload_settings();
}
last_system_check_ = 0; // force the LED to go from fast flash to pulse
send_heartbeat();
if (phy_type_ == PHY_type::PHY_TYPE_NONE) {
return;
}
// configure Ethernet
int mdc = 23; // Pin# of the I²C clock signal for the Ethernet PHY - hardcoded
int mdio = 18; // Pin# of the I²C IO signal for the Ethernet PHY - hardcoded
uint8_t phy_addr = eth_phy_addr_; // I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110)
int8_t power = eth_power_; // Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source)
eth_phy_type_t type = (phy_type_ == PHY_type::PHY_TYPE_LAN8720) ? ETH_PHY_LAN8720 : ETH_PHY_TLK110; // Type of the Ethernet PHY (LAN8720 or TLK110)
// clock mode
// ETH_CLOCK_GPIO0_IN = 0 RMII clock input to GPIO0
// ETH_CLOCK_GPIO0_OUT = 1 RMII clock output from GPIO0
// ETH_CLOCK_GPIO16_OUT = 2 RMII clock output from GPIO16
// ETH_CLOCK_GPIO17_OUT = 3 RMII clock output from GPIO17, for 50hz inverted clock
auto clock_mode = (eth_clock_mode_t)eth_clock_mode_;
ETH.begin(phy_addr, power, mdc, mdio, type, clock_mode);
}
// check health of system, done every 5 seconds
void System::system_check() {
if (!last_system_check_ || ((uint32_t)(uuid::get_uptime() - last_system_check_) >= SYSTEM_CHECK_FREQUENCY)) {
last_system_check_ = uuid::get_uptime();
// check if we have a valid network connection
if (!ethernet_connected() && (WiFi.status() != WL_CONNECTED)) {
healthcheck_ |= HEALTHCHECK_NO_NETWORK;
} else {
healthcheck_ &= ~HEALTHCHECK_NO_NETWORK;
}
// check if we have a bus connection
if (!EMSbus::bus_connected()) {
healthcheck_ |= HEALTHCHECK_NO_BUS;
} else {
healthcheck_ &= ~HEALTHCHECK_NO_BUS;
}
// see if the healthcheck state has changed
static uint8_t last_healthcheck_ = 0;
if (healthcheck_ != last_healthcheck_) {
last_healthcheck_ = healthcheck_;
// see if we're better now
if (healthcheck_ == 0) {
// everything is healthy, show LED permanently on or off depending on setting
if (led_gpio_) {
digitalWrite(led_gpio_, hide_led_ ? !LED_ON : LED_ON);
}
send_heartbeat();
} else {
// turn off LED so we're ready to the flashes
if (led_gpio_) {
digitalWrite(led_gpio_, !LED_ON);
}
}
}
}
}
// commands - takes static function pointers
void System::commands_init() {
// TODO these should be translated too
Command::add(EMSdevice::DeviceType::SYSTEM, F_(send), System::command_send, F("send a telegram"), CommandFlag::ADMIN_ONLY);
Command::add(EMSdevice::DeviceType::SYSTEM, F_(fetch), System::command_fetch, F("refresh all EMS values"), CommandFlag::ADMIN_ONLY);
Command::add(EMSdevice::DeviceType::SYSTEM, F_(restart), System::command_restart, F("restart EMS-ESP"), CommandFlag::ADMIN_ONLY);
Command::add(EMSdevice::DeviceType::SYSTEM, F_(watch), System::command_watch, F("watch incoming telegrams"));
// register syslog command in syslog init
// Command::add(EMSdevice::DeviceType::SYSTEM, F_(syslog), System::command_syslog_level, F("set syslog level"), CommandFlag::ADMIN_ONLY);
if (Mqtt::enabled()) {
Command::add(EMSdevice::DeviceType::SYSTEM, F_(publish), System::command_publish, F("force a MQTT publish"));
}
// these commands will return data in JSON format
Command::add(EMSdevice::DeviceType::SYSTEM, F_(info), System::command_info, F("show system status"));
Command::add(EMSdevice::DeviceType::SYSTEM, F_(commands), System::command_commands, F("fetch system commands"));
#if defined(EMSESP_DEBUG)
Command::add(EMSdevice::DeviceType::SYSTEM, F("test"), System::command_test, F("run a specific test"));
#endif
// MQTT subscribe "ems-esp/system/#"
Mqtt::subscribe(EMSdevice::DeviceType::SYSTEM, "system/#", nullptr); // use empty function callback
}
// uses LED to show system health
void System::led_monitor() {
// we only need to run the LED healthcheck if there are errors
if (!healthcheck_) {
return; // all good
}
static uint32_t led_long_timer_ = 1; // 1 will kick it off immediately
static uint32_t led_short_timer_ = 0;
static uint8_t led_flash_step_ = 0; // 0 means we're not in the short flash timer
auto current_time = uuid::get_uptime();
// first long pause before we start flashing
if (led_long_timer_ && (uint32_t)(current_time - led_long_timer_) >= HEALTHCHECK_LED_LONG_DUARATION) {
// Serial.println("starting the flash check");
led_short_timer_ = current_time; // start the short timer
led_long_timer_ = 0; // stop long timer
led_flash_step_ = 1; // enable the short flash timer
}
// the flash timer which starts after the long pause
if (led_flash_step_ && (uint32_t)(current_time - led_short_timer_) >= HEALTHCHECK_LED_FLASH_DUARATION) {
led_long_timer_ = 0; // stop the long timer
led_short_timer_ = current_time;
static bool led_on_ = false;
if (++led_flash_step_ == 8) {
// reset the whole sequence
// Serial.println("resetting flash check");
led_long_timer_ = uuid::get_uptime();
led_flash_step_ = 0;
digitalWrite(led_gpio_, !LED_ON); // LED off
} else if (led_flash_step_ % 2) {
// handle the step events (on odd numbers 3,5,7,etc). see if we need to turn on a LED
// 1 flash is the EMS bus is not connected
// 2 flashes if the network (wifi or ethernet) is not connected
// 3 flashes is both the bus and the network are not connected. Then you know you're truly f*cked.
if ((led_flash_step_ == 3)
&& (((healthcheck_ & HEALTHCHECK_NO_NETWORK) == HEALTHCHECK_NO_NETWORK) || ((healthcheck_ & HEALTHCHECK_NO_BUS) == HEALTHCHECK_NO_BUS))) {
led_on_ = true;
}
if ((led_flash_step_ == 5) && ((healthcheck_ & HEALTHCHECK_NO_NETWORK) == HEALTHCHECK_NO_NETWORK)) {
led_on_ = true;
}
if ((led_flash_step_ == 7) && ((healthcheck_ & HEALTHCHECK_NO_NETWORK) == HEALTHCHECK_NO_NETWORK)
&& ((healthcheck_ & HEALTHCHECK_NO_BUS) == HEALTHCHECK_NO_BUS)) {
led_on_ = true;
}
if (led_on_ && led_gpio_) {
digitalWrite(led_gpio_, LED_ON);
}
} else {
// turn the led off after the flash, on even number count
if (led_on_ && led_gpio_) {
digitalWrite(led_gpio_, !LED_ON);
led_on_ = false;
}
}
}
}
// Return the quality (Received Signal Strength Indicator) of the WiFi network as a %
// High quality: 90% ~= -55dBm
// Medium quality: 50% ~= -75dBm
// Low quality: 30% ~= -85dBm
// Unusable quality: 8% ~= -96dBm
int8_t System::wifi_quality(int8_t dBm) {
if (dBm <= -100) {
return 0;
}
if (dBm >= -50) {
return 100;
}
return 2 * (dBm + 100);
}
// print users to console
void System::show_users(uuid::console::Shell & shell) {
shell.printfln(F("Users:"));
#ifndef EMSESP_STANDALONE
EMSESP::esp8266React.getSecuritySettingsService()->read([&](SecuritySettings & securitySettings) {
for (const User & user : securitySettings.users) {
shell.printfln(F(" username: %s, password: %s, is_admin: %s"), user.username.c_str(), user.password.c_str(), user.admin ? F("yes") : F("no"));
}
});
#endif
shell.println();
}
void System::show_system(uuid::console::Shell & shell) {
shell.println("System:");
shell.printfln(F(" Board profile: %s"), board_profile().c_str());
shell.printfln(F(" Uptime: %s"), uuid::log::format_timestamp_ms(uuid::get_uptime_ms(), 3).c_str());
#ifndef EMSESP_STANDALONE
shell.printfln(F(" SDK version: %s"), ESP.getSdkVersion());
shell.printfln(F(" CPU frequency: %lu MHz"), ESP.getCpuFreqMHz());
shell.printfln(F(" Free heap: %lu bytes"), (uint32_t)ESP.getFreeHeap());
shell.printfln(F(" FS used/total: %lu/%lu (bytes)"), LittleFS.usedBytes(), FStotal());
shell.println();
shell.println("Network:");
switch (WiFi.status()) {
case WL_IDLE_STATUS:
shell.printfln(F(" Network: Idle"));
break;
case WL_NO_SSID_AVAIL:
shell.printfln(F(" Network: Network not found"));
break;
case WL_SCAN_COMPLETED:
shell.printfln(F(" Network: Network scan complete"));
break;
case WL_CONNECTED:
shell.printfln(F(" Network: connected"));
shell.printfln(F(" SSID: %s"), WiFi.SSID().c_str());
shell.printfln(F(" BSSID: %s"), WiFi.BSSIDstr().c_str());
shell.printfln(F(" RSSI: %d dBm (%d %%)"), WiFi.RSSI(), wifi_quality(WiFi.RSSI()));
shell.printfln(F(" MAC address: %s"), WiFi.macAddress().c_str());
shell.printfln(F(" Hostname: %s"), WiFi.getHostname());
shell.printfln(F(" IPv4 address: %s/%s"), uuid::printable_to_string(WiFi.localIP()).c_str(), uuid::printable_to_string(WiFi.subnetMask()).c_str());
shell.printfln(F(" IPv4 gateway: %s"), uuid::printable_to_string(WiFi.gatewayIP()).c_str());
shell.printfln(F(" IPv4 nameserver: %s"), uuid::printable_to_string(WiFi.dnsIP()).c_str());
if (WiFi.localIPv6().toString() != "0000:0000:0000:0000:0000:0000:0000:0000") {
shell.printfln(F(" IPv6 address: %s"), uuid::printable_to_string(WiFi.localIPv6()).c_str());
}
break;
case WL_CONNECT_FAILED:
shell.printfln(F(" WiFi Network: Connection failed"));
break;
case WL_CONNECTION_LOST:
shell.printfln(F(" WiFi Network: Connection lost"));
break;
case WL_DISCONNECTED:
shell.printfln(F(" WiFi Network: Disconnected"));
break;
case WL_NO_SHIELD:
default:
shell.printfln(F(" WiFi Network: Unknown"));
break;
}
// show Ethernet if connected
if (ethernet_connected_) {
shell.println();
shell.printfln(F(" Ethernet Network: connected"));
shell.printfln(F(" MAC address: %s"), ETH.macAddress().c_str());
shell.printfln(F(" Hostname: %s"), ETH.getHostname());
shell.printfln(F(" IPv4 address: %s/%s"), uuid::printable_to_string(ETH.localIP()).c_str(), uuid::printable_to_string(ETH.subnetMask()).c_str());
shell.printfln(F(" IPv4 gateway: %s"), uuid::printable_to_string(ETH.gatewayIP()).c_str());
shell.printfln(F(" IPv4 nameserver: %s"), uuid::printable_to_string(ETH.dnsIP()).c_str());
if (ETH.localIPv6().toString() != "0000:0000:0000:0000:0000:0000:0000:0000") {
shell.printfln(F(" IPv6 address: %s"), uuid::printable_to_string(ETH.localIPv6()).c_str());
}
}
shell.println();
shell.println("Syslog:");
if (!syslog_enabled_) {
shell.printfln(F(" Syslog: disabled"));
} else {
shell.printfln(F(" Syslog: %s"), syslog_.started() ? "started" : "stopped");
shell.print(F(" "));
shell.printfln(F_(host_fmt), !syslog_host_.isEmpty() ? syslog_host_.c_str() : read_flash_string(F_(unset)).c_str());
shell.printfln(F(" IP: %s"), uuid::printable_to_string(syslog_.ip()).c_str());
shell.print(F(" "));
shell.printfln(F_(port_fmt), syslog_port_);
shell.print(F(" "));
shell.printfln(F_(log_level_fmt), uuid::log::format_level_lowercase(static_cast<uuid::log::Level>(syslog_level_)));
shell.print(F(" "));
shell.printfln(F_(mark_interval_fmt), syslog_mark_interval_);
shell.printfln(F(" Queued: %d"), syslog_.queued());
}
#endif
}
// handle upgrades from previous versions
// or managing an uploaded files to replace settings files
// returns true if we need a reboot
bool System::check_upgrade() {
bool reboot_required = false;
#ifndef EMSESP_STANDALONE
// see if we have a temp file, if so try and read it
File new_file = LittleFS.open(TEMP_FILENAME_PATH);
if (new_file) {
DynamicJsonDocument jsonDocument = DynamicJsonDocument(FS_BUFFER_SIZE);
DeserializationError error = deserializeJson(jsonDocument, new_file);
if (error == DeserializationError::Ok && jsonDocument.is<JsonObject>()) {
JsonObject input = jsonDocument.as<JsonObject>();
// see what type of file it is, either settings or customization. anything else is ignored
std::string settings_type = input["type"];
if (settings_type == "settings") {
// It's a settings file. Parse each section separately. If it's system related it will require a reboot
reboot_required = saveSettings(NETWORK_SETTINGS_FILE, "Network", input);
reboot_required |= saveSettings(AP_SETTINGS_FILE, "AP", input);
reboot_required |= saveSettings(MQTT_SETTINGS_FILE, "MQTT", input);
reboot_required |= saveSettings(NTP_SETTINGS_FILE, "NTP", input);
reboot_required |= saveSettings(SECURITY_SETTINGS_FILE, "Security", input);
reboot_required |= saveSettings(EMSESP_SETTINGS_FILE, "Settings", input);
} else if (settings_type == "customizations") {
// it's a customization file, just replace it and there's no need to reboot
saveSettings(EMSESP_CUSTOMIZATION_FILE, "Customizations", input);
} else {
LOG_ERROR(F("Unrecognized file uploaded"));
}
} else {
LOG_ERROR(F("Unrecognized file uploaded, not json"));
}
// close (just in case) and remove the temp file
new_file.close();
LittleFS.remove(TEMP_FILENAME_PATH);
}
#endif
return reboot_required;
}
// list commands
bool System::command_commands(const char * value, const int8_t id, JsonObject & output) {
return Command::list(EMSdevice::DeviceType::SYSTEM, output);
}
// convert settings file into json object
void System::extractSettings(const char * filename, const char * section, JsonObject & output) {
#ifndef EMSESP_STANDALONE
File settingsFile = LittleFS.open(filename);
if (settingsFile) {
DynamicJsonDocument jsonDocument = DynamicJsonDocument(FS_BUFFER_SIZE);
DeserializationError error = deserializeJson(jsonDocument, settingsFile);
if (error == DeserializationError::Ok && jsonDocument.is<JsonObject>()) {
JsonObject jsonObject = jsonDocument.as<JsonObject>();
JsonObject node = output.createNestedObject(section);
for (JsonPair kvp : jsonObject) {
node[kvp.key()] = kvp.value();
}
}
}
settingsFile.close();
#endif
}
// save settings file using input from a json object
bool System::saveSettings(const char * filename, const char * section, JsonObject & input) {
#ifndef EMSESP_STANDALONE
JsonObject section_json = input[section];
if (section_json) {
File section_file = LittleFS.open(filename, "w");
if (section_file) {
LOG_INFO(F("Applying new %s settings"), section);
serializeJson(section_json, section_file);
section_file.close();
return true; // reboot required
}
}
#endif
return false; // not found
}
// export status information including the device information
// http://ems-esp/api/system/info
bool System::command_info(const char * value, const int8_t id, JsonObject & output) {
JsonObject node;
// System
node = output.createNestedObject("System Status");
node["version"] = EMSESP_APP_VERSION;
node["uptime"] = uuid::log::format_timestamp_ms(uuid::get_uptime_ms(), 3);
// node["uptime (seconds)"] = uuid::get_uptime_sec();
#ifndef EMSESP_STANDALONE
node["freemem"] = ESP.getFreeHeap() / 1000L; // kilobytes
#endif
node["reset reason"] = EMSESP::system_.reset_reason(0) + " / " + EMSESP::system_.reset_reason(1);
#ifndef EMSESP_STANDALONE
// Network Status
node = output.createNestedObject("Network Status");
if (WiFi.status() == WL_CONNECTED) {
node["connection"] = F("WiFi");
node["hostname"] = WiFi.getHostname();
// node["SSID"] = WiFi.SSID();
// node["BSSID"] = WiFi.BSSIDstr();
node["RSSI"] = WiFi.RSSI();
// node["MAC"] = WiFi.macAddress();
node["IPv4 address"] = uuid::printable_to_string(WiFi.localIP()) + "/" + uuid::printable_to_string(WiFi.subnetMask());
node["IPv4 gateway"] = uuid::printable_to_string(WiFi.gatewayIP());
node["IPv4 nameserver"] = uuid::printable_to_string(WiFi.dnsIP());
if (WiFi.localIPv6().toString() != "0000:0000:0000:0000:0000:0000:0000:0000") {
node["IPv6 address"] = uuid::printable_to_string(WiFi.localIPv6());
}
} else if (EMSESP::system_.ethernet_connected()) {
node["connection"] = F("Ethernet");
node["hostname"] = ETH.getHostname();