Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1509 lines (1356 loc) · 47.3 KB
/
Copy pathmain.cpp
File metadata and controls
1509 lines (1356 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* OpenSprinkler Unified Firmware
* Copyright (C) 2015 by Ray Wang (ray@opensprinkler.com)
*
* Main loop
* Feb 2015 @ OpenSprinkler.com
*
* This file is part of the OpenSprinkler Firmware
*
* 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 <limits.h>
#include "types.h"
#include "OpenSprinkler.h"
#include "core/bundle.h"
#include "core/program.h"
#include "platform/clock.h"
#include "services/weather.h"
#include "api/server.h"
#include "services/mqtt.h"
#include "core/scheduler.h"
#include "storage/logging.h"
#include "services/notifier.h"
#include "services/firmware_update.h"
#include "sensors/flow_rate.h"
#include "sensors/flow_rate_window.h"
#if defined(ESP8266)
#include <Arduino.h>
ESP8266WebServer *update_server = NULL;
DNSServer *dns = NULL;
ENC28J60lwIP enc28j60(PIN_ETHER_CS); // ENC28J60 lwip for wired Ether
OSWiznet5500lwIP w5500(PIN_ETHER_CS); // owned W5500 lwIP backend
lwipEth eth;
bool useEth = false; // tracks whether we are using WiFi or wired Ether connection
uint32_t getNtpTime();
#elif defined(ESP32)
#include <Arduino.h>
#include <WebServer.h>
WebServer *update_server = NULL;
DNSServer *dns = NULL;
bool useEth = false;
uint32_t getNtpTime();
#else // header and defs for RPI/Linux
#include <dirent.h>
#include <unistd.h>
bool useEth = false;
#endif
OTF::OpenThingsFramework *otf = NULL;
#if defined(ARDUINO)
static constexpr uint32_t OTC_BOOT_CONNECTION_DELAY_MS = 25000UL;
static constexpr uint32_t WIFI_BSSID_CONNECT_TIMEOUT_MS = 15000UL;
static constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 30000UL;
static uint16_t led_blink_ms = LED_FAST_BLINK;
#else
static uint16_t led_blink_ms = 0;
#endif
static inline bool firmware_update_display_active() {
#if defined(ARDUINO)
return firmware_update.display_active();
#else
return false;
#endif
}
#if defined(ARDUINO)
static bool otc_boot_delay_elapsed() {
static bool elapsed = false;
if (!elapsed && millis() >= OTC_BOOT_CONNECTION_DELAY_MS) elapsed = true;
return elapsed;
}
static inline void loop_otf(bool network_available = true) {
if (otf) otf->loop(network_available && otc_boot_delay_elapsed());
}
#endif
static uint16_t sys_led_blink_ms = LED_SLOW_BLINK;
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
const char *user_agent_string = "OpenSprinkler/" TOSTRING(OS_FW_VERSION) "#" TOSTRING(OS_FW_MINOR);
// Small variations have been added to the timing values below
// to minimize conflicting events
#define NTP_SYNC_INTERVAL 86413L // NTP sync interval (in seconds)
#define CHECK_NETWORK_INTERVAL 601 // Network checking timeout (in seconds)
#define CHECK_WEATHER_TIMEOUT 21613L // Weather check interval (in seconds)
#define LCD_BACKLIGHT_TIMEOUT 15 // LCD backlight timeout (in seconds))
#define PING_TIMEOUT 200 // Ping test timeout (in ms)
#define UI_STATE_MACHINE_INTERVAL 50 // how often does ui_state_machine run (in ms)
#define CLIENT_READ_TIMEOUT 5 // client read timeout (in seconds)
#define DHCP_CHECKLEASE_INTERVAL 3600L // DHCP check lease interval (in seconds)
#define FLOWPOLL_INTERVAL 5 // flow poll interval (in milli-seconds)
#define CURRPOLL_INTERVAL 20 // current poll interval (in milli-seconds)
#define SENSORPOLL_INTERVAL 5000 // sensor poll interval (in milli-seconds)
// Define buffers: need them to be sufficiently large to cover string option reading
char ether_buffer[ETHER_BUFFER_ALLOC_SIZE]; // HTTP client send/receive buffer
char tmp_buffer[TMP_BUFFER_ALLOC_SIZE]; // scratch buffer
// ====== Object defines ======
OpenSprinkler os; // OpenSprinkler object
ProgramData pd; // ProgramdData object
NotifQueue notif; // NotifQueue object
/* ====== Robert Hillman (RAH)'s implementation of flow sensor ======
* flow_start - first pulse of the station run
* flow_begin - first pulse after the 90-second settling period
* flow_stop - last falling edge pulse detected before the valve turns off
* flow_gallons - one sentinel plus pulses collected after the warm-up
* flow_last_gpm - last flow rate measured (averaged over flow_gallons) from last valve stopped (used to write to log file). */
uint32_t flow_begin, flow_start, flow_stop, flow_gallons;
uint32_t flow_count = 0;
unsigned char prev_flow_state = HIGH;
float flow_last_gpm = 0;
static FlowRateWindow flow_rate_window;
uint32_t reboot_timer = 0;
unsigned char curr_alert_sid = 0;
void flow_poll() {
uint32_t curr = monotonic_millis();
#if defined(ESP8266)
if(os.hw_rev>=2) {
pinMode(PIN_SENSOR1, INPUT); // Work-around for PIN_SENSOR1 on OS3.2 and above
pinMode(PIN_SENSOR1, INPUT_PULLUP);
}
#elif defined(ESP32)
if(os.hw_rev == 2) pinModeExt(PIN_SENSOR1, INPUT_PULLUP); // this seems necessary for OS 3.2
#endif
unsigned char curr_flow_state = digitalReadExt(PIN_SENSOR1);
if((!prev_flow_state) || curr_flow_state) { // only record on falling edge
prev_flow_state = curr_flow_state;
os.flowcount_rt = flow_rate_window.update(curr, flow_count, FLOWCOUNT_RT_WINDOW);
return;
}
prev_flow_state = curr_flow_state;
flow_count++;
/* RAH implementation of flow sensor */
if (flow_start == 0) {
flow_gallons = 0;
flow_start = curr;
} // if first pulse, record time
if ((curr-flow_start)<90000) {
flow_gallons=0;
} // wait 90 seconds before recording flow_begin
else {
if (flow_gallons==1) {
flow_begin = curr;
}
}
flow_stop = curr; // get time in ms for stop
flow_gallons++; // increment gallon count for each poll
/* End of RAH implementation of flow sensor */
os.flowcount_rt = flow_rate_window.update(curr, flow_count, FLOWCOUNT_RT_WINDOW);
}
#if defined(USE_DISPLAY)
// ====== UI defines ======
static char ui_anim_chars[3] = {'.', 'o', 'O'};
#define UI_STATE_DEFAULT 0
#define UI_STATE_DISP_IP 1
#define UI_STATE_DISP_GW 2
#define UI_STATE_RUNPROG 3
static unsigned char ui_state = UI_STATE_DEFAULT;
static unsigned char ui_state_runprog = 0;
bool ui_confirm(PGM_P str) {
os.lcd_print_line_clear_pgm(str, 0);
os.lcd_print_line_clear_pgm(PSTR("(B1:No, B3:Yes)"), 1);
unsigned char button;
uint32_t start = millis();
do {
button = os.button_read(BUTTON_WAIT_NONE);
if((button&BUTTON_MASK)==BUTTON_3 && (button&BUTTON_FLAG_DOWN)) return true;
if((button&BUTTON_MASK)==BUTTON_1 && (button&BUTTON_FLAG_DOWN)) return false;
delay(10);
} while(millis() - start < 2500);
return false;
}
void ui_state_machine() {
// to avoid ui_state_machine taking too much computation time
// we run it only every UI_STATE_MACHINE_INTERVAL ms
static uint32_t last_usm = 0;
if(millis() - last_usm <= UI_STATE_MACHINE_INTERVAL) { return; }
last_usm = millis();
// process screen led
static uint32_t led_toggle_prev = 0;
if(led_blink_ms) {
uint32_t tm = millis();
if(tm - led_toggle_prev > led_blink_ms) { // overflow proof timeout
os.toggle_screen_led();
os.toggle_sys_led();
led_toggle_prev = tm;
}
}
if (osboard::active().pins.system_led) {
static ulong sys_led_toggle_timeout = 0;
if(sys_led_blink_ms) {
if(millis()>sys_led_toggle_timeout) {
os.toggle_sys_led();
sys_led_toggle_timeout = millis() + sys_led_blink_ms;
}
}
}
if (!os.button_timeout) {
os.lcd_set_brightness(0);
ui_state = UI_STATE_DEFAULT; // also recover to default state
}
// read button, if something is pressed, wait till release
unsigned char button = os.button_read(BUTTON_WAIT_HOLD);
if (button & BUTTON_FLAG_DOWN) { // repond only to button down events
#if defined(ESP32)
os.lcd_dimmed = false;
#endif
os.button_timeout = LCD_BACKLIGHT_TIMEOUT;
os.lcd_set_brightness(1);
} else {
return;
}
switch(ui_state) {
case UI_STATE_DEFAULT:
switch (button & BUTTON_MASK) {
case BUTTON_1:
if (button & BUTTON_FLAG_HOLD) { // holding B1
if (digitalReadExt(PIN_BUTTON_3)==0) { // if B3 is pressed while holding B1, run a short test (internal test)
if(!ui_confirm(PSTR("Start 2s test?"))) {ui_state = UI_STATE_DEFAULT; break;}
manual_start_program(255, 0, QUEUE_OPTION_REPLACE);
} else if (digitalReadExt(PIN_BUTTON_2)==0) { // if B2 is pressed while holding B1, display gateway IP
#if defined(USE_SSD1306) || defined(USE_SH1106)
os.lcd.setAutoDisplay(false);
#endif
os.lcd.clear(0, 1);
os.lcd.setCursor(0, 0);
#if defined(ESP8266)
if (useEth) { os.lcd.print(eth.gatewayIP()); }
else { os.lcd.print(WiFi.gatewayIP()); }
#elif defined(ESP32)
if (useEth) { os.lcd.print(ETH.gatewayIP()); }
else { os.lcd.print(WiFi.gatewayIP()); }
#else
route_t route = get_route();
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(route.gateway), str, INET_ADDRSTRLEN);
os.lcd.print(str);
#endif
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(gwip)"));
ui_state = UI_STATE_DISP_IP;
os.lcd.display();
os.lcd.setAutoDisplay(true);
} else { // if no other button is clicked, stop all zones
if(!ui_confirm(PSTR("Stop all zones?"))) {ui_state = UI_STATE_DEFAULT; break;}
reset_all_stations();
}
} else { // clicking B1: display device IP and port
os.lcd.setAutoDisplay(false);
os.lcd.clear(0, 1);
os.lcd.setCursor(0, 0);
#if defined(ESP8266)
if (useEth) { os.lcd.print(eth.localIP()); }
else { os.lcd.print(WiFi.localIP()); }
#elif defined(ESP32)
if (useEth) { os.lcd.print(ETH.localIP()); }
else { os.lcd.print(WiFi.localIP()); }
#else
route_t route = get_route();
char str[INET_ADDRSTRLEN];
in_addr_t ip = get_ip_address(route.iface);
inet_ntop(AF_INET, &ip, str, INET_ADDRSTRLEN);
os.lcd.print(str);
#endif
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR(":"));
uint16_t httpport = (uint16_t)(os.iopts[IOPT_HTTPPORT_1]<<8) + (uint16_t)os.iopts[IOPT_HTTPPORT_0];
os.lcd.print(httpport);
os.lcd_print_pgm(PSTR(" (ip:port)"));
os.lcd.setCursor(0, 2);
os.lcd_print_pgm(PSTR("OTC:"));
switch(otf->getCloudStatus()) {
case OTF::NOT_ENABLED:
os.lcd_print_pgm(PSTR(" not enabled"));
break;
case OTF::UNABLE_TO_CONNECT:
os.lcd_print_pgm(PSTR("connecting.."));
break;
case OTF::DISCONNECTED:
os.lcd_print_pgm(PSTR("disconnected"));
break;
case OTF::CONNECTED:
os.lcd_print_pgm(PSTR(" Connected"));
break;
}
ui_state = UI_STATE_DISP_IP;
os.lcd.display();
os.lcd.setAutoDisplay(true);
}
break;
case BUTTON_2:
if (button & BUTTON_FLAG_HOLD) { // holding B2
if (digitalReadExt(PIN_BUTTON_1)==0) { // if B1 is pressed while holding B2, display external IP
os.lcd_print_ip((unsigned char*)(&os.nvdata.external_ip), 1);
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(eip)"));
ui_state = UI_STATE_DISP_IP;
} else if (digitalReadExt(PIN_BUTTON_3)==0) { // if B3 is pressed while holding B2, display last successful weather call
//os.lcd.clear(0, 1);
os.lcd_print_time(os.checkwt_success_lasttime);
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(lswc)"));
ui_state = UI_STATE_DISP_IP;
} else { // if no other button is clicked, reboot
if(!ui_confirm(PSTR("Reboot device?"))) {ui_state = UI_STATE_DEFAULT; break;}
os.reboot_dev(REBOOT_CAUSE_BUTTON);
}
} else { // clicking B2: display MAC
os.lcd.clear(0, 1);
unsigned char mac[6];
os.load_hardware_mac(mac, useEth);
os.lcd_print_mac(mac);
ui_state = UI_STATE_DISP_GW;
}
break;
case BUTTON_3:
if (button & BUTTON_FLAG_HOLD) { // holding B3
if (digitalReadExt(PIN_BUTTON_1)==0) { // if B1 is pressed while holding B3, display up time
os.lcd_print_time(os.powerup_lasttime);
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(lupt) cause:"));
os.lcd.print(os.last_reboot_cause);
ui_state = UI_STATE_DISP_IP;
} else if(digitalReadExt(PIN_BUTTON_2)==0) { // if B2 is pressed while holding B3, reset to AP and reboot
#if defined(ARDUINO)
if(!ui_confirm(PSTR("Reset to AP?"))) {ui_state = UI_STATE_DEFAULT; break;}
os.reset_to_ap();
#endif
} else { // if no other button is clicked, go to Run Program main menu
os.lcd_print_line_clear_pgm(PSTR("Run a Program:"), 0);
os.lcd_print_line_clear_pgm(PSTR("Click B3 to list"), 1);
ui_state = UI_STATE_RUNPROG;
}
} else { // clicking B3: switch board display (cycle through master and all extension boards)
os.status.display_board = (os.status.display_board + 1) % (os.nboards);
}
break;
}
break;
case UI_STATE_DISP_IP:
case UI_STATE_DISP_GW:
ui_state = UI_STATE_DEFAULT;
break;
case UI_STATE_RUNPROG:
if ((button & BUTTON_MASK)==BUTTON_3) {
if (button & BUTTON_FLAG_HOLD) {
// start
manual_start_program(ui_state_runprog, 0, QUEUE_OPTION_INSERT_FRONT);
ui_state = UI_STATE_DEFAULT;
} else {
ui_state_runprog = (ui_state_runprog+1) % (pd.nprograms+1);
os.lcd_print_line_clear_pgm(PSTR("Hold B3 to start"), 0);
if(ui_state_runprog > 0) {
ProgramStruct prog;
pd.read(ui_state_runprog-1, &prog);
os.lcd_print_line_clear_pgm(PSTR(" "), 1);
os.lcd.setCursor(0, 1);
os.lcd.print((int)ui_state_runprog);
os.lcd_print_pgm(PSTR(". "));
os.lcd.print(prog.name);
} else {
os.lcd_print_line_clear_pgm(PSTR("0. Test (1 min)"), 1);
}
}
}
break;
}
}
#endif
// ======================
// Setup Function
// ======================
#if defined(ARDUINO)
void do_setup() {
/* Clear WDT reset flag. */
WiFi.persistent(false);
led_blink_ms = LED_FAST_BLINK;
DEBUG_BEGIN(115200);
DEBUG_PRINT(F("Build timestamp: "));
DEBUG_PRINT(__DATE__);
DEBUG_PRINT(" ");
DEBUG_PRINTLN(__TIME__);
DEBUG_PRINTLN(F("--- Starting setup"));
os.begin(); // OpenSprinkler init
DEBUG_PRINTLN(F("--- Setting up options"));
os.options_setup(); // Setup options
#if defined(ARDUINO)
os.setup_pd_voltage();
#endif
#if defined(USE_DISPLAY)
os.lcd.clear();
os.lcd.setCursor(0, 0);
os.lcd_print_pgm(PSTR("Init sensors..."));
#endif
Sensor::load_all();
pd.init(); // ProgramData init
DEBUG_PRINTLN(F("--- Time setup"));
// set time using RTC if it exists
if(RTC.exists()) setTime(RTC.get());
os.lcd_print_time(os.now_tz()); // display time to LCD
os.powerup_lasttime = os.now_tz();
if (os.start_network()) { // initialize network
os.status.network_fails = 0;
} else {
os.status.network_fails = 1;
}
os.status.req_network = 0;
os.status.req_ntpsync = 1;
DEBUG_PRINTLN(F("--- MQTT Init"));
os.mqtt.init();
os.status.req_mqtt_restart = true;
os.apply_all_station_bits(); // reset station bits
// because at reboot we don't know if special stations
// are in OFF state, here we explicitly turn them off
for(unsigned char sid=0;sid<os.nstations;sid++) {
os.switch_special_station(sid, 0);
}
os.button_timeout = LCD_BACKLIGHT_TIMEOUT;
}
#else
void initialize_otf();
void do_setup() {
initialiseEpoch(); // initialize the Linux microsecond clock reference
os.begin(); // OpenSprinkler init
os.options_setup(); // Setup options
Sensor::load_all();
pd.init(); // ProgramData init
if (os.start_network()) { // initialize network
DEBUG_PRINTLN("network established.");
os.status.network_fails = 0;
} else {
DEBUG_PRINTLN("network failed.");
os.status.network_fails = 1;
}
os.status.req_network = 0;
// because at reboot we don't know if special stations
// are in OFF state, here we explicitly turn them off
for(unsigned char sid=0;sid<os.nstations;sid++) {
os.switch_special_station(sid, 0);
}
os.mqtt.init();
os.status.req_mqtt_restart = true;
initialize_otf();
}
#endif
static void check_network();
void check_weather();
static bool process_special_program_command(const char*, uint32_t curr_time);
static void perform_ntp_sync();
#if defined(ESP8266)
static void service_w5500_recovery();
#endif
#if defined(ARDUINO)
void start_server_ap();
void start_server_client();
#if defined(ESP8266)
static Ticker reboot_ticker;
#else
static uint32_t reboot_deadline = 0;
#endif
void reboot_in(uint32_t ms) {
if(os.state != OS_STATE_WAIT_REBOOT) {
os.state = OS_STATE_WAIT_REBOOT;
DEBUG_PRINTLN(F("Prepare to restart..."));
#if defined(ESP8266)
reboot_ticker.once_ms(ms, ESP.restart);
#else
reboot_deadline = millis() + ms;
#endif
}
}
#else
void handle_web_request(char *p);
#endif
uint32_t currpoll_timeout = 0;
#if defined(ARDUINO)
static unsigned char pending_overcurrent_sid = 0;
static uint16_t pending_overcurrent_value = 0;
#endif
void overcurrent_monitor() {
#if defined(ARDUINO)
// If a zone is turning on, do immediate overcurrent monitoring here for ~50ms
if (curr_alert_sid) {
int16_t imax = os.get_imax();
if(imax > 0) { // disable overcurrent checking if imax==0
imax += OVERCURRENT_INRUSH_EXTRA; // extra margin for inrush current
for(unsigned char i = 0; i < 10; i++) {
uint16_t curr = os.read_current();
if(curr > (uint16_t)imax) {
pending_overcurrent_sid = curr_alert_sid;
pending_overcurrent_value = curr;
os.set_output_rise_blocked(true);
break;
} else {
delay(5);
}
}
}
curr_alert_sid = 0;
}
#endif
}
#if defined(ARDUINO)
static void stop_output_owner(unsigned char sid, time_os_t curr_time) {
unsigned char qid = pd.station_qid[sid];
if (qid < pd.nqueue) turn_off_running_station_immediate(sid, curr_time);
else {
os.set_station_bit(sid, 0);
for (RuntimeQueueStruct* q = pd.queue; q < pd.queue + pd.nqueue; q++) {
if (q->sid == sid) q->dur = 0;
}
}
}
#if defined(ESP8266)
#define W5500_RECOVERY_WINDOW_MS 600000UL // recoveries are counted over 10 minutes
#define W5500_MAX_RECOVERIES 3 // recoveries allowed within that window
#define W5500_HEALTHY_QUALIFY_MS 60000UL // uninterrupted healthy time that re-arms rebooting
/* Schedule a controlled reboot after W5500 recovery has failed or repeated too
* often. Returns false when the reboot is deliberately suppressed.
*
* The first network-failure reboot is always allowed. After one, another is
* permitted only if this boot subsequently maintained a healthy connection for
* W5500_HEALTHY_QUALIFY_MS. A time-based cooldown would merely pace an endless
* reboot cycle on permanently faulty hardware; requiring a proven-healthy
* interval ends it, because a W5500 that never comes up can never re-arm the
* reboot. Such a controller keeps retrying the raw reset indefinitely instead,
* which costs nothing and leaves watering untouched.
*/
static bool request_w5500_reboot(bool network_was_healthy) {
if (os.last_reboot_cause == REBOOT_CAUSE_NETWORK_FAIL && !network_was_healthy)
return false;
os.nvdata.reboot_cause = REBOOT_CAUSE_NETWORK_FAIL;
os.status.safe_reboot = 1;
reboot_timer = os.now_tz();
#if defined(USE_DISPLAY)
if (!ui_state) {
os.lcd_print_line_clear_pgm(PSTR("Ethernet failed"), 1);
os.lcd_print_line_clear_pgm(PSTR("Reboot pending"), 2);
}
#endif
return true;
}
static void service_w5500_recovery() {
if (!useEth || !eth.isW5500) return;
static uint32_t next_health_check = 0;
static uint32_t recovery_window_started = 0;
static uint8_t recovery_attempts = 0;
static bool reboot_scheduled = false;
static uint32_t healthy_since = 0;
static bool sustained_healthy = false;
uint32_t now = millis();
if (!eth.fault_pending() && static_cast<int32_t>(now - next_health_check) >= 0) {
next_health_check = now + 1000UL;
if (eth.health_check() && eth.connected()) {
os.status.network_fails = 0;
// Track uninterrupted health so a fault later in this boot can
// still escalate to a reboot. The flag latches: once this boot has
// proven the interface works, a reboot remains a sane response.
if (!healthy_since) healthy_since = now ? now : 1;
else if (now - healthy_since >= W5500_HEALTHY_QUALIFY_MS) sustained_healthy = true;
} else {
healthy_since = 0;
}
}
if (!eth.fault_pending() || reboot_scheduled) return;
os.status.network_fails = 3;
// Escalate to a reboot once too many recoveries land inside one window. If
// the boot-loop guard suppresses that reboot, fall through to waiting the
// window out and retrying the raw reset rather than giving up entirely.
if (recovery_window_started && now - recovery_window_started < W5500_RECOVERY_WINDOW_MS &&
recovery_attempts >= W5500_MAX_RECOVERIES) {
reboot_scheduled = request_w5500_reboot(sustained_healthy);
return;
}
if (!recovery_window_started || now - recovery_window_started >= W5500_RECOVERY_WINDOW_MS) {
recovery_window_started = now;
recovery_attempts = 0;
}
recovery_attempts++;
#if defined(USE_DISPLAY)
if (!ui_state) {
os.lcd_print_line_clear_pgm(PSTR("Ethernet recovery"), 1);
os.lcd_print_line_clear_pgm(PSTR("Please wait..."), 2);
}
#endif
if (eth.raw_reinit()) {
os.status.network_fails = eth.connected() ? 0 : 1;
os.status.req_mqtt_restart = true;
next_health_check = now + 1000UL;
#if defined(USE_DISPLAY)
if (!ui_state) {
os.lcd_print_line_clear_pgm(PSTR("Ethernet restored"), 1);
os.lcd_print_line_clear_pgm(PSTR(""), 2);
}
#endif
return;
}
reboot_scheduled = request_w5500_reboot(sustained_healthy);
}
#endif
#endif
static void process_pending_overcurrent() {
#if defined(ARDUINO)
if (!pending_overcurrent_sid) return;
const unsigned char physical_sid = pending_overcurrent_sid - 1;
const uint16_t current = pending_overcurrent_value;
const time_os_t curr_time = os.now_tz();
pending_overcurrent_sid = 0;
pending_overcurrent_value = 0;
bool owner_found = false;
if (os.is_master_station(physical_sid)) {
reset_all_stations_immediate();
owner_found = true;
} else {
if (os.is_running(physical_sid)) {
owner_found = true;
stop_output_owner(physical_sid, curr_time);
}
for (unsigned char leader = 0; leader < os.nstations; leader++) {
if (!os.is_running(leader) || !bundle_claims_station(leader, physical_sid)) continue;
owner_found = true;
stop_output_owner(leader, curr_time);
}
}
if (!owner_found) reset_all_stations_immediate();
notif.add(NOTIFY_CURR_ALERT, physical_sid, current, CURR_ALERT_TYPE_OVER_STATION);
os.status.overcurrent_sid = physical_sid + 1;
currpoll_timeout += 1000;
os.apply_all_station_bits();
os.set_output_rise_blocked(false);
#endif
}
/** Main Loop */
void do_loop()
{
static uint32_t flowpoll_timeout = 0;
static bool flow_was_enabled = false;
bool flow_enabled = os.iopts[IOPT_SENSOR1_TYPE] == SENSOR_TYPE_FLOW;
if (flow_enabled != flow_was_enabled) {
flow_rate_window.reset();
os.flowcount_rt = 0;
prev_flow_state = digitalReadExt(PIN_SENSOR1);
flow_was_enabled = flow_enabled;
}
if(flow_enabled) {
// handle flow sensor using polling. Maximum freq is 1/(2*FLOWPOLL_INTERVAL)
// e.g. if FLOWPOLL_INTERVAL is 3ms, maximum freq is 166Hz
uint32_t tm = monotonic_millis();
if((int32_t)(tm-flowpoll_timeout) > 0) { // overflow proof timeout
flowpoll_timeout = tm+FLOWPOLL_INTERVAL;
flow_poll();
}
}
{
static uint32_t sensorpoll_timeout = 0;
uint32_t tm = millis();
if((int32_t)(tm-sensorpoll_timeout) > 0) {
sensorpoll_timeout = tm + SENSORPOLL_INTERVAL;
os.poll_sensors();
}
}
#if defined(ARDUINO)
{
uint32_t tn = millis();
if((int32_t)(tn-currpoll_timeout) > 0) { // overflow proof timeout
int16_t curr = (int16_t)os.read_current();
int16_t imax = os.get_imax();
if((imax > 0) && (curr > imax)) {
reset_all_stations_immediate(true);
notif.add(NOTIFY_CURR_ALERT, 0, curr, CURR_ALERT_TYPE_OVER_SYSTEM);
os.status.overcurrent_sid = 255; // 255 indicates system overcurrent
currpoll_timeout = tn+1000; // pause currpoll for a second to give time for solenoids to reset
} else {
currpoll_timeout = tn+CURRPOLL_INTERVAL;
}
}
}
#endif
static time_os_t last_time = 0;
static uint32_t last_minute = 0;
unsigned char bid, sid, s, pid, qid, gid, bitvalue;
ProgramStruct prog;
os.status.mas = os.iopts[IOPT_MASTER_STATION];
os.status.mas2= os.iopts[IOPT_MASTER_STATION_2];
os.status.mas3= os.iopts[IOPT_MASTER_STATION_3];
os.status.mas4= os.iopts[IOPT_MASTER_STATION_4];
time_os_t curr_time = os.now_tz();
#if defined(ESP8266)
service_w5500_recovery();
#endif
// ====== Process Ethernet packets ======
#if defined(ARDUINO) // Process Ethernet packets for Arduino
static uint32_t connecting_timeout;
static bool wifi_bssid_attempt_enabled = true;
static bool wifi_bssid_configured = false;
static bool connecting_with_bssid = false;
#if defined(ESP8266)
static uint32_t wifi_bssid_fallback_at = 0;
#endif
switch(os.state) {
case OS_STATE_INITIAL:
if(useEth) {
connecting_with_bssid = false;
led_blink_ms = 0;
os.set_screen_led(LOW);
os.lcd.clear();
os.save_wifi_ip();
start_server_client();
os.state = OS_STATE_CONNECTED;
connecting_timeout = 0;
} else if(os.get_wifi_mode()==OS_WIFI_MODE_AP) {
DEBUG_PRINTLN(F("Starting AP"));
connecting_with_bssid = false;
start_server_ap();
DEBUG_PRINTLN(F("AP started."));
dns->setErrorReplyCode(DNSReplyCode::NoError);
dns->start(53, "*", WiFi.softAPIP());
os.state = OS_STATE_CONNECTED;
connecting_timeout = 0;
if (osboard::active().pins.system_led) {
sys_led_blink_ms = 2000;
}
} else {
led_blink_ms = LED_SLOW_BLINK;
if ( osboard::active().pins.system_led ) {
sys_led_blink_ms = LED_SLOW_BLINK;
}
DEBUG_PRINTLN(F("Setting up WiFi client"));
#if defined(ESP32)
if(WiFi.getMode()!=WIFI_STA) WiFi.mode(WIFI_STA);
os.config_ip();
#endif
wifi_bssid_configured = os.sopt_load(SOPT_STA_BSSID_CHL).length()>0 &&
os.wifi_channel<255;
connecting_with_bssid = wifi_bssid_attempt_enabled && wifi_bssid_configured;
if(connecting_with_bssid) {
start_network_sta(os.wifi_ssid.c_str(), os.wifi_pass.c_str(), (int32_t)os.wifi_channel, os.wifi_bssid);
}
else
start_network_sta(os.wifi_ssid.c_str(), os.wifi_pass.c_str());
#if defined(ESP8266)
os.config_ip();
#endif
os.state = OS_STATE_CONNECTING;
connecting_timeout = millis() +
(connecting_with_bssid ? WIFI_BSSID_CONNECT_TIMEOUT_MS : WIFI_CONNECT_TIMEOUT_MS);
os.lcd.setCursor(0, -1);
os.lcd.print(F("Connecting to..."));
os.lcd.setCursor(0, 2);
os.lcd.print(os.wifi_ssid);
}
break;
case OS_STATE_TRY_CONNECT:
led_blink_ms = LED_SLOW_BLINK;
if ( osboard::active().pins.system_led) {
sys_led_blink_ms = LED_FAST_BLINK;
}
#if defined(ESP32)
if(WiFi.getMode()!=WIFI_AP_STA) WiFi.mode(WIFI_AP_STA);
os.config_ip();
#endif
if(os.sopt_load(SOPT_STA_BSSID_CHL).length()>0 && os.wifi_channel<255) {
start_network_sta_with_ap(os.wifi_ssid.c_str(), os.wifi_pass.c_str(), (int32_t)os.wifi_channel, os.wifi_bssid);
}
else
start_network_sta_with_ap(os.wifi_ssid.c_str(), os.wifi_pass.c_str());
#if defined(ESP8266)
os.config_ip();
#endif
os.state = OS_STATE_CONNECTED;
break;
case OS_STATE_CONNECTING:
if(WiFi.status() == WL_CONNECTED) {
connecting_with_bssid = false;
#if defined(ESP8266)
wifi_bssid_fallback_at = 0;
#endif
led_blink_ms = 0;
if ( osboard::active().pins.system_led ) {
sys_led_blink_ms = LED_SLOW_BLINK;
}
os.set_screen_led(LOW);
os.lcd.clear();
os.save_wifi_ip();
start_server_client();
os.state = OS_STATE_CONNECTED;
connecting_timeout = 0;
#if defined(ESP32)
if(MDNS.begin(MDNS_NAME))
DEBUG_PRINTLN("mDNS responder started");
#endif
} else {
if((int32_t)((uint32_t)millis()-connecting_timeout)>0) {
if(connecting_with_bssid) {
// A saved BSSID is only a fast-connect target. Fall back to
// an unrestricted SSID scan for the rest of this boot.
wifi_bssid_attempt_enabled = false;
}
connecting_with_bssid = false;
os.state = OS_STATE_INITIAL;
#if defined(ESP32)
WiFi.disconnect(false, false);
#else
WiFi.disconnect(true);
#endif
DEBUG_PRINTLN(F("timeout"));
}
}
break;
case OS_STATE_WAIT_REBOOT:
if(dns) dns->processNextRequest();
loop_otf();
if(update_server) update_server->handleClient();
#if defined(ESP32)
if(reboot_deadline && (int32_t)((uint32_t)millis() - reboot_deadline) >= 0) ESP.restart();
#endif
break;
case OS_STATE_CONNECTED:
if(os.get_wifi_mode() == OS_WIFI_MODE_AP) {
dns->processNextRequest();
if(update_server) update_server->handleClient();
loop_otf();
connecting_timeout = 0;
if(os.get_wifi_mode()==OS_WIFI_MODE_STA) {
// already in STA mode, waiting to reboot
break;
}
if(WiFi.status()==WL_CONNECTED && WiFi.localIP() && reboot_timer!=0) {
DEBUG_PRINTLN(F("STA connected, set up reboot timer"));
reboot_timer = os.now_tz() + 10;
//os.reboot_dev(REBOOT_CAUSE_WIFIDONE);
}
} else {
if(useEth || WiFi.status() == WL_CONNECTED) {
if(update_server) update_server->handleClient();
loop_otf(os.network_connected());
connecting_timeout = 0;
#if defined(ESP8266)
wifi_bssid_fallback_at = 0;
#endif
} else {
#if defined(ESP32)
static uint32_t reconnect_at = 0;
if ((int32_t)((uint32_t)millis() - reconnect_at) >= 0) {
reconnect_at = millis() + 30000UL;
os.state = OS_STATE_INITIAL;
}
#else
// The ESP8266 core normally handles reconnection. A configured
// BSSID can prevent failover, so retry without it after 30 seconds.
if(wifi_bssid_configured) {
if(!wifi_bssid_fallback_at) {
wifi_bssid_fallback_at = millis() + WIFI_CONNECT_TIMEOUT_MS;
} else if((int32_t)((uint32_t)millis() - wifi_bssid_fallback_at) >= 0) {
wifi_bssid_attempt_enabled = false;
wifi_bssid_fallback_at = 0;
os.state = OS_STATE_INITIAL;
}
}
#endif
}
}
break;
}
firmware_update.loop();
if (!firmware_update_display_active())
ui_state_machine();
#else // Process Ethernet packets for RPI/LINUX
if(otf) otf->loop();
#if defined(USE_DISPLAY)
ui_state_machine();
#endif
#endif // Process Ethernet packets
// Start up MQTT when we have a network connection
if (os.status.req_mqtt_restart && os.network_connected()) {
DEBUG_PRINTLN(F("req_mqtt_restart"));
os.mqtt.begin();
os.status.req_mqtt_restart = false;
os.mqtt.subscribe();
}
os.mqtt.loop();
os.apply_all_station_bits(overcurrent_monitor);
process_pending_overcurrent();
// The main control loop runs once every second
if (curr_time != last_time) {
#if defined(ESP8266) || defined(ESP32)
if(os.hw_rev>=2) {
pinModeExt(PIN_SENSOR1, INPUT_PULLUP); // this seems necessary for OS 3.2
pinModeExt(PIN_SENSOR2, INPUT_PULLUP);
}
#endif
last_time = curr_time;
if (os.button_timeout) os.button_timeout--;
#if defined(USE_DISPLAY)
if (!ui_state && !firmware_update_display_active())
os.lcd_print_time(curr_time); // print time
#endif