forked from OpenSprinkler/OpenSprinkler-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1903 lines (1692 loc) · 56.9 KB
/
main.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
/* OpenSprinkler Unified (AVR/RPI/BBB/LINUX) Firmware
* Copyright (C) 2015 by Ray Wang ([email protected])
*
* 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 "program.h"
#include "weather.h"
#include "opensprinkler_server.h"
#include "mqtt.h"
#include "main.h"
#if defined(ARDUINO)
#if defined(ESP8266)
ESP8266WebServer *update_server = NULL;
OTF::OpenThingsFramework *otf = NULL;
DNSServer *dns = NULL;
ENC28J60lwIP enc28j60(PIN_ETHER_CS); // ENC28J60 lwip for wired Ether
Wiznet5500lwIP w5500(PIN_ETHER_CS); // W5500 lwip for wired Ether
lwipEth eth;
bool useEth = false; // tracks whether we are using WiFi or wired Ether connection
static uint16_t led_blink_ms = LED_FAST_BLINK;
#else
EthernetServer *m_server = NULL;
EthernetClient *m_client = NULL;
SdFat sd; // SD card object
bool useEth = true;
#endif
unsigned long getNtpTime();
#else // header and defs for RPI/BBB
EthernetServer *m_server = 0;
EthernetClient *m_client = 0;
#endif
void push_message(int type, uint32_t lval=0, float fval=0.f, const char* sval=NULL);
void manual_start_program(byte, byte);
void remote_http_callback(char*);
// 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 CHECK_WEATHER_SUCCESS_TIMEOUT 86400L // Weather check success 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 buffers: need them to be sufficiently large to cover string option reading
char ether_buffer[ETHER_BUFFER_SIZE*2]; // ethernet buffer, make it twice as large to allow overflow
char tmp_buffer[TMP_BUFFER_SIZE*2]; // scratch buffer, make it twice as large to allow overflow
// ====== Object defines ======
OpenSprinkler os; // OpenSprinkler object
ProgramData pd; // ProgramdData object
/* ====== Robert Hillman (RAH)'s implementation of flow sensor ======
* flow_begin - time when valve turns on
* flow_start - time when flow starts being measured (i.e. 2 mins after flow_begin approx
* flow_stop - time when valve turns off (last rising edge pulse detected before off)
* flow_gallons - total # of gallons+1 from flow_start to flow_stop
* flow_last_gpm - last flow rate measured (averaged over flow_gallons) from last valve stopped (used to write to log file). */
ulong flow_begin, flow_start, flow_stop, flow_gallons;
ulong flow_count = 0;
byte prev_flow_state = HIGH;
float flow_last_gpm=0;
uint32_t reboot_timer = 0;
void flow_poll() {
#if defined(ESP8266)
if(os.hw_rev>=2) pinModeExt(PIN_SENSOR1, INPUT_PULLUP); // this seems necessary for OS 3.2
#endif
byte curr_flow_state = digitalReadExt(PIN_SENSOR1);
if(!(prev_flow_state==HIGH && curr_flow_state==LOW)) { // only record on falling edge
prev_flow_state = curr_flow_state;
return;
}
prev_flow_state = curr_flow_state;
ulong curr = millis();
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 */
}
#if defined(ARDUINO)
// ====== 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 byte ui_state = UI_STATE_DEFAULT;
static byte 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);
byte button;
ulong 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();
#if defined(ESP8266)
// process screen led
static ulong led_toggle_timeout = 0;
if(led_blink_ms) {
if(millis()>led_toggle_timeout) {
os.toggle_screen_led();
led_toggle_timeout = millis() + led_blink_ms;
}
}
#endif
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
byte button = os.button_read(BUTTON_WAIT_HOLD);
if (button & BUTTON_FLAG_DOWN) { // repond only to button down events
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);
} else if (digitalReadExt(PIN_BUTTON_2)==0) { // if B2 is pressed while holding B1, display gateway IP
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()); }
#else
{ os.lcd.print(Ethernet.gatewayIP()); }
#endif
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(gwip)"));
ui_state = UI_STATE_DISP_IP;
} 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.clear(0, 1);
os.lcd.setCursor(0, 0);
#if defined(ESP8266)
if (useEth) { os.lcd.print(eth.localIP()); }
else { os.lcd.print(WiFi.localIP()); }
#else
{ os.lcd.print(Ethernet.localIP()); }
#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)"));
ui_state = UI_STATE_DISP_IP;
}
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((byte*)(&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);
byte 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(ESP8266)
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);
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;
}
}
// ======================
// Setup Function
// ======================
void do_setup() {
/* Clear WDT reset flag. */
#if defined(ESP8266)
WiFi.persistent(false);
led_blink_ms = LED_FAST_BLINK;
#else
MCUSR &= ~(1<<WDRF);
#endif
DEBUG_BEGIN(115200);
DEBUG_PRINTLN(F("started"));
os.begin(); // OpenSprinkler init
os.options_setup(); // Setup options
pd.init(); // ProgramData init
// 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 !defined(ESP8266)
// enable WDT
/* In order to change WDE or the prescaler, we need to
* set WDCE (This will allow updates for 4 clock cycles).
*/
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* set new watchdog timeout prescaler value */
WDTCSR = 1<<WDP3 | 1<<WDP0; // 8.0 seconds
/* Enable the WD interrupt (note no reset). */
WDTCSR |= _BV(WDIE);
#endif
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;
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(byte sid=0;sid<os.nstations;sid++) {
os.switch_special_station(sid, 0);
}
os.button_timeout = LCD_BACKLIGHT_TIMEOUT;
}
// Arduino software reset function
void(* sysReset) (void) = 0;
#if !defined(ESP8266)
volatile byte wdt_timeout = 0;
/** WDT interrupt service routine */
ISR(WDT_vect)
{
wdt_timeout += 1;
// this isr is called every 8 seconds
if (wdt_timeout > 15) {
// reset after 120 seconds of timeout
sysReset();
}
}
#endif
#else
void do_setup() {
initialiseEpoch(); // initialize time reference for millis() and micros()
os.begin(); // OpenSprinkler init
os.options_setup(); // Setup options
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(byte sid=0;sid<os.nstations;sid++) {
os.switch_special_station(sid, 0);
}
os.mqtt.init();
os.status.req_mqtt_restart = true;
}
#endif
void turn_on_station(byte sid, ulong duration);
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)
bool delete_log_oldest();
void start_server_ap();
void start_server_client();
static Ticker reboot_ticker;
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..."));
reboot_ticker.once_ms(ms, ESP.restart);
}
}
#else
void handle_web_request(char *p);
#endif
/** Main Loop */
void do_loop()
{
// handle flow sensor using polling every 1ms (maximum freq 1/(2*1ms)=500Hz)
static ulong flowpoll_timeout=0;
if(os.iopts[IOPT_SENSOR1_TYPE]==SENSOR_TYPE_FLOW) {
ulong curr = millis();
if(curr!=flowpoll_timeout) {
flowpoll_timeout = curr;
flow_poll();
}
}
static time_os_t last_time = 0;
static ulong last_minute = 0;
byte 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];
time_os_t curr_time = os.now_tz();
// ====== Process Ethernet packets ======
#if defined(ARDUINO) // Process Ethernet packets for Arduino
#if defined(ESP8266)
static ulong connecting_timeout;
switch(os.state) {
case OS_STATE_INITIAL:
if(useEth) {
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()==WIFI_MODE_AP) {
start_server_ap();
dns->setErrorReplyCode(DNSReplyCode::NoError);
dns->start(53, "*", WiFi.softAPIP());
os.state = OS_STATE_CONNECTED;
connecting_timeout = 0;
} else {
led_blink_ms = LED_SLOW_BLINK;
if(os.sopt_load(SOPT_STA_BSSID_CHL).length()>0 && os.wifi_channel<255) {
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());
os.config_ip();
os.state = OS_STATE_CONNECTING;
connecting_timeout = millis() + 120000L;
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(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());
os.config_ip();
os.state = OS_STATE_CONNECTED;
break;
case OS_STATE_CONNECTING:
if(WiFi.status() == WL_CONNECTED) {
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(millis()>connecting_timeout) {
os.state = OS_STATE_INITIAL;
WiFi.disconnect(true);
DEBUG_PRINTLN(F("timeout"));
}
}
break;
case OS_STATE_WAIT_REBOOT:
if(dns) dns->processNextRequest();
if(otf) otf->loop();
if(update_server) update_server->handleClient();
break;
case OS_STATE_CONNECTED:
if(os.get_wifi_mode() == WIFI_MODE_AP) {
dns->processNextRequest();
update_server->handleClient();
otf->loop();
connecting_timeout = 0;
if(os.get_wifi_mode()==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) {
update_server->handleClient();
otf->loop();
connecting_timeout = 0;
} else {
// todo: better handling of WiFi disconnection
DEBUG_PRINTLN(F("WiFi disconnected, going back to initial"));
os.state = OS_STATE_INITIAL;
WiFi.disconnect(true);
}
}
break;
}
#else // AVR
static unsigned long dhcp_timeout = 0;
if(curr_time > dhcp_timeout) {
Ethernet.maintain();
dhcp_timeout = curr_time + DHCP_CHECKLEASE_INTERVAL;
}
EthernetClient client = m_server->available();
if (client) {
ulong cli_timeout = now() + CLIENT_READ_TIMEOUT;
while(client.connected() && now() < cli_timeout) {
size_t size = client.available();
if(size>0) {
if(size>ETHER_BUFFER_SIZE) size=ETHER_BUFFER_SIZE;
int len = client.read((uint8_t*) ether_buffer, size);
if(len>0) {
m_client = &client;
ether_buffer[len] = 0; // properly end the buffer
handle_web_request(ether_buffer);
m_client = NULL;
break;
}
}
}
client.stop();
}
wdt_reset(); // reset watchdog timer
wdt_timeout = 0;
#endif
ui_state_machine();
#else // Process Ethernet packets for RPI/BBB
EthernetClient client = m_server->available();
if (client) {
while(true) {
int len = client.read((uint8_t*) ether_buffer, ETHER_BUFFER_SIZE);
if (len <=0) {
if(!client.connected()) {
break;
} else {
continue;
}
} else {
m_client = &client;
ether_buffer[len] = 0; // put a zero at the end of the packet
handle_web_request(ether_buffer);
m_client = 0;
break;
}
}
}
#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.loop();
// The main control loop runs once every second
if (curr_time != last_time) {
#if defined(ESP8266)
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(ARDUINO)
if (!ui_state)
os.lcd_print_time(curr_time); // print time
#endif
// ====== Check raindelay status ======
if (os.status.rain_delayed) {
if (curr_time >= os.nvdata.rd_stop_time) { // rain delay is over
os.raindelay_stop();
}
} else {
if (os.nvdata.rd_stop_time > curr_time) { // rain delay starts now
os.raindelay_start();
}
}
// ====== Check controller status changes and write log ======
if (os.old_status.rain_delayed != os.status.rain_delayed) {
if (os.status.rain_delayed) {
// rain delay started, record time
os.raindelay_on_lasttime = curr_time;
push_message(NOTIFY_RAINDELAY, LOGDATA_RAINDELAY, 1);
} else {
// rain delay stopped, write log
write_log(LOGDATA_RAINDELAY, curr_time);
push_message(NOTIFY_RAINDELAY, LOGDATA_RAINDELAY, 0);
}
os.old_status.rain_delayed = os.status.rain_delayed;
}
// ====== Check binary (i.e. rain or soil) sensor status ======
os.detect_binarysensor_status(curr_time);
if(os.old_status.sensor1_active != os.status.sensor1_active) {
// send notification when sensor1 becomes active
if(os.status.sensor1_active) {
os.sensor1_active_lasttime = curr_time;
push_message(NOTIFY_SENSOR1, LOGDATA_SENSOR1, 1);
} else {
write_log(LOGDATA_SENSOR1, curr_time);
push_message(NOTIFY_SENSOR1, LOGDATA_SENSOR1, 0);
}
}
os.old_status.sensor1_active = os.status.sensor1_active;
if(os.old_status.sensor2_active != os.status.sensor2_active) {
// send notification when sensor1 becomes active
if(os.status.sensor2_active) {
os.sensor2_active_lasttime = curr_time;
push_message(NOTIFY_SENSOR2, LOGDATA_SENSOR2, 1);
} else {
write_log(LOGDATA_SENSOR2, curr_time);
push_message(NOTIFY_SENSOR2, LOGDATA_SENSOR2, 0);
}
}
os.old_status.sensor2_active = os.status.sensor2_active;
// ===== Check program switch status =====
byte pswitch = os.detect_programswitch_status(curr_time);
if(pswitch > 0) {
reset_all_stations_immediate(); // immediately stop all stations
}
if (pswitch & 0x01) {
if(pd.nprograms > 0) manual_start_program(1, 0);
}
if (pswitch & 0x02) {
if(pd.nprograms > 1) manual_start_program(2, 0);
}
// ====== Schedule program data ======
ulong curr_minute = curr_time / 60;
boolean match_found = false;
RuntimeQueueStruct *q;
// since the granularity of start time is minute
// we only need to check once every minute
if (curr_minute != last_minute) {
last_minute = curr_minute;
apply_monthly_adjustment(curr_time); // check and apply monthly adjustment here, if it's selected
// check through all programs
for(pid=0; pid<pd.nprograms; pid++) {
pd.read(pid, &prog); // todo future: reduce load time
if(prog.check_match(curr_time)) {
// program match found
// check and process special program command
if(process_special_program_command(prog.name, curr_time)) continue;
// process all selected stations
for(sid=0;sid<os.nstations;sid++) {
bid=sid>>3;
s=sid&0x07;
// skip if the station is a master station (because master cannot be scheduled independently
if ((os.status.mas==sid+1) || (os.status.mas2==sid+1))
continue;
// if station has non-zero water time and the station is not disabled
if (prog.durations[sid] && !(os.attrib_dis[bid]&(1<<s))) {
// water time is scaled by watering percentage
ulong water_time = water_time_resolve(prog.durations[sid]);
// if the program is set to use weather scaling
if (prog.use_weather) {
byte wl = os.iopts[IOPT_WATER_PERCENTAGE];
water_time = water_time * wl / 100;
if (wl < 20 && water_time < 10) // if water_percentage is less than 20% and water_time is less than 10 seconds
// do not water
water_time = 0;
}
if (water_time) {
// check if water time is still valid
// because it may end up being zero after scaling
q = pd.enqueue();
if (q) {
q->st = 0;
q->dur = water_time;
q->sid = sid;
q->pid = pid+1;
match_found = true;
} else {
// queue is full
}
}// if water_time
}// if prog.durations[sid]
}// for sid
if(match_found) {
push_message(NOTIFY_PROGRAM_SCHED, pid, prog.use_weather?os.iopts[IOPT_WATER_PERCENTAGE]:100);
}
}// if check_match
}// for pid
// calculate start and end time
if (match_found) {
schedule_all_stations(curr_time);
// For debugging: print out queued elements
/*DEBUG_PRINT("en:");
for(q=pd.queue;q<pd.queue+pd.nqueue;q++) {
DEBUG_PRINT("[");
DEBUG_PRINT(q->sid);
DEBUG_PRINT(",");
DEBUG_PRINT(q->dur);
DEBUG_PRINT(",");
DEBUG_PRINT(q->st);
DEBUG_PRINT("]");
}
DEBUG_PRINTLN("");*/
}
}//if_check_current_minute
// ====== Run program data ======
// Check if a program is running currently
// If so, do station run-time keeping
if (os.status.program_busy){
// first, go through run time queue to assign queue elements to stations
q = pd.queue;
qid=0;
for(;q<pd.queue+pd.nqueue;q++,qid++) {
sid=q->sid;
byte sqi=pd.station_qid[sid];
// skip if station is already assigned a queue element
// and that queue element has an earlier start time
if(sqi<255 && pd.queue[sqi].st<q->st) continue;
// otherwise assign the queue element to station
pd.station_qid[sid]=qid;
}
// next, go through the stations and perform time keeping
for(bid=0;bid<os.nboards; bid++) {
bitvalue = os.station_bits[bid];
for(s=0;s<8;s++) {
byte sid = bid*8+s;
// skip master stations and any station that's not in the queue
if (os.status.mas == sid+1) continue;
if (os.status.mas2== sid+1) continue;
if (pd.station_qid[sid]==255) continue;
q = pd.queue + pd.station_qid[sid];
// if current station is not running, check if we should turn it on
if(!((bitvalue >> s) & 1)) {
if (curr_time >= q->st && curr_time < q->st+q->dur) {
turn_on_station(sid, q->st+q->dur-curr_time); // the last parameter is expected run time
} //if curr_time > scheduled_start_time
} // if current station is not running
// check if this station should be turned off
if (q->st > 0) {
if (curr_time >= q->st+q->dur) {
turn_off_station(sid, curr_time);
}
}
}//end_s
}//end_bid
// finally, go through the queue again and clear up elements marked for removal
int qi;
for(qi=pd.nqueue-1;qi>=0;qi--) {
q=pd.queue+qi;
if(!q->dur || curr_time >= q->deque_time) {
pd.dequeue(qi);
}
}
// process dynamic events
process_dynamic_events(curr_time);
// activate / deactivate valves
os.apply_all_station_bits();
// check through runtime queue, calculate the last stop time of sequential stations
memset(pd.last_seq_stop_times, 0, sizeof(ulong)*NUM_SEQ_GROUPS);
time_os_t sst;
byte re=os.iopts[IOPT_REMOTE_EXT_MODE];
q = pd.queue;
for(;q<pd.queue+pd.nqueue;q++) {
sid = q->sid;
bid = sid>>3;
s = sid&0x07;
gid = os.get_station_gid(sid);
// check if any sequential station has a valid stop time
// and the stop time must be larger than curr_time
sst = q->st + q->dur;
if (sst>curr_time) {
// only need to update last_seq_stop_time for sequential stations
if (os.is_sequential_station(sid) && !re) {
pd.last_seq_stop_times[gid] = (sst > pd.last_seq_stop_times[gid]) ? sst : pd.last_seq_stop_times[gid];
}
}
}
// if the runtime queue is empty
// reset all stations
if (!pd.nqueue) {
// turn off all stations
os.clear_all_station_bits();
os.apply_all_station_bits();
pd.reset_runtime(); // reset runtime
os.status.program_busy = 0; // reset program busy bit
pd.clear_pause(); // TODO: what if pause hasn't expired and a new program is scheduled to run?
// log flow sensor reading if flow sensor is used
if(os.iopts[IOPT_SENSOR1_TYPE]==SENSOR_TYPE_FLOW) {
write_log(LOGDATA_FLOWSENSE, curr_time);
push_message(NOTIFY_FLOWSENSOR, (flow_count>os.flowcount_log_start)?(flow_count-os.flowcount_log_start):0);
}
// in case some options have changed while executing the program
os.status.mas = os.iopts[IOPT_MASTER_STATION]; // update master station
os.status.mas2= os.iopts[IOPT_MASTER_STATION_2]; // update master2 station
}
}//if_some_program_is_running
// handle master
for (byte mas = MASTER_1; mas < NUM_MASTER_ZONES; mas++) {
byte mas_id = os.masters[mas][MASOPT_SID];
if (mas_id) { // if this master station is set
int16_t mas_on_adj = os.get_on_adj(mas);
int16_t mas_off_adj = os.get_off_adj(mas);
byte masbit = 0;
for(sid = 0; sid < os.nstations; sid++) {
// skip if this is the master station
if (mas_id == sid + 1) continue;
if(pd.station_qid[sid]==255) continue; // skip if station is not in the queue
q = pd.queue + pd.station_qid[sid];
if (os.bound_to_master(q->sid, mas)) {
// check if timing is within the acceptable range
if (curr_time >= q->st + mas_on_adj &&
curr_time <= q->st + q->dur + mas_off_adj) {
masbit = 1;
break;
}
}
}
os.set_station_bit(mas_id - 1, masbit);
}
}
if (os.status.pause_state) {
if (os.pause_timer > 0) {
os.pause_timer--;
} else {
os.clear_all_station_bits();
pd.clear_pause();
}
}
// process dynamic events
process_dynamic_events(curr_time);
// activate/deactivate valves
os.apply_all_station_bits();
#if defined(ARDUINO)
// process LCD display
if (!ui_state) { os.lcd_print_screen(ui_anim_chars[(unsigned long)curr_time%3]); }
#endif
// handle reboot request
// check safe_reboot condition
if (os.status.safe_reboot && (curr_time > reboot_timer)) {
// if no program is running at the moment
if (!os.status.program_busy) {
// and if no program is scheduled to run in the next minute
bool willrun = false;
for(pid=0; pid<pd.nprograms; pid++) {
pd.read(pid, &prog);
if(prog.check_match(curr_time+60)) {
willrun = true;
break;
}
}
if (!willrun) {
os.reboot_dev(os.nvdata.reboot_cause);
}
}
} else if(reboot_timer && (curr_time > reboot_timer)) {
os.reboot_dev(REBOOT_CAUSE_TIMER);
}
// real-time flow count
static ulong flowcount_rt_start = 0;
if (os.iopts[IOPT_SENSOR1_TYPE]==SENSOR_TYPE_FLOW) {
if (curr_time % FLOWCOUNT_RT_WINDOW == 0) {
os.flowcount_rt = (flow_count > flowcount_rt_start) ? flow_count - flowcount_rt_start: 0;
flowcount_rt_start = flow_count;
}
}
// perform ntp sync
// instead of using curr_time, which may change due to NTP sync itself
// we use Arduino's millis() method
if (curr_time % NTP_SYNC_INTERVAL == 0) os.status.req_ntpsync = 1;
//if((millis()/1000) % NTP_SYNC_INTERVAL==15) os.status.req_ntpsync = 1;
perform_ntp_sync();
// check network connection
if (curr_time && (curr_time % CHECK_NETWORK_INTERVAL==0)) os.status.req_network = 1;
check_network();
// check weather
check_weather();
if(os.weather_update_flag & WEATHER_UPDATE_WL) {
// at the moment, we only send notification if water level changed
// the other changes, such as sunrise, sunset changes are ignored for notification
push_message(NOTIFY_WEATHER_UPDATE, 0, os.iopts[IOPT_WATER_PERCENTAGE]);
os.weather_update_flag = 0;
}
static byte reboot_notification = 1;
if(reboot_notification) {
reboot_notification = 0;
push_message(NOTIFY_REBOOT);
}
}
#if !defined(ARDUINO)
delay(1); // For OSPI/OSBO/LINUX, sleep 1 ms to minimize CPU usage
#endif
}
/** Check and process special program command */
static bool process_special_program_command(const char* pname, uint32_t curr_time) {
if(pname[0]==':') { // special command start with :
if(strncmp(pname, ":>reboot_now", 12) == 0) {
os.status.safe_reboot = 0; // reboot regardless of program status
reboot_timer = curr_time + 65; // set a timer to reboot in 65 seconds
// this is to avoid the same command being executed again right after reboot
return true;
} else if(strncmp(pname, ":>reboot", 8) == 0) {