forked from OpenSprinkler/OpenSprinkler-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1928 lines (1766 loc) · 47.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 (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 "OpenSprinkler.h"
#include "program.h"
#include "weather.h"
#include "server.h"
#if defined(ARDUINO)
#include "Wire.h"
#ifdef ESP8266
#include <FS.h>
#include "gpio.h"
#include "espconnect.h"
char ether_buffer[ETHER_BUFFER_SIZE];
#else
#ifndef OSMICRO
#include <SdFat.h>
SdFat sd; // SD card object
#endif
byte Ethernet::buffer[ETHER_BUFFER_SIZE]; // Ethernet packet buffer
#endif
unsigned long getNtpTime();
#else // header and defs for RPI/BBB
#include <sys/stat.h>
#include <netdb.h>
#include "etherport.h"
#include "gpio.h"
char ether_buffer[ETHER_BUFFER_SIZE];
EthernetServer *m_server = 0;
EthernetClient *m_client = 0;
#endif
void reset_all_stations();
void reset_all_stations_immediate();
void push_message(byte type, uint32_t lval = 0, float fval = 0.f,
const char* sval = NULL);
void manual_start_program(byte, byte);
void httpget_callback(byte, uint16_t, uint16_t);
// Small variations have been added to the timing values below
// to minimize conflicting events
#define NTP_SYNC_INTERVAL 86403L // NYP sync interval, 24 hrs
#define RTC_SYNC_INTERVAL 60 // RTC sync interval, 60 secs
#define CHECK_NETWORK_INTERVAL 601 // Network checking timeout, 10 minutes
#define CHECK_WEATHER_TIMEOUT 3601 // Weather check interval: 1 hour
#define CHECK_WEATHER_SUCCESS_TIMEOUT 86433L // Weather check success interval: 24 hrs
#define LCD_BACKLIGHT_TIMEOUT 15 // LCD backlight timeout: 15 secs
#define PING_TIMEOUT 200 // Ping test timeout: 200 ms
extern char tmp_buffer[]; // scratch buffer
#ifdef ESP8266
ESP8266WebServer *wifi_server = NULL;
static uint16_t led_blink_ms = LED_FAST_BLINK;
ulong restart_timeout = 0;
#endif
// ====== Object defines ======
OpenSprinkler os; // OpenSprinkler object
ProgramData pd; // ProgramdData object
#ifndef OSMICRO
/* ====== 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). */
volatile ulong flow_begin, flow_start, flow_stop, flow_gallons;
volatile ulong flow_count = 0;
float flow_last_gpm=0;
/** Flow sensor interrupt service routine */
#ifdef ESP8266
ICACHE_RAM_ATTR void flow_isr() // for ESP8266, ISR must be marked ICACHE_RAM_ATTR
#else
void flow_isr()
#endif
{
if(os.options[OPTION_SENSOR_TYPE]!=SENSOR_TYPE_FLOW) return;
ulong curr = millis();
if(curr-os.flowcount_time_ms < 50) return; // debounce threshold: 50ms
flow_count++;
os.flowcount_time_ms = curr;
/* 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 interrupt
/* End of RAH implementation of flow sensor */
}
#endif
#if defined(ARDUINO)
// ====== UI defines ======
#ifndef OSMICRO
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;
void ui_state_machine()
{
#ifdef 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: stop all stations
if (digitalReadExt(PIN_BUTTON_3)==0)
{ // if B3 is pressed while holding B1, run a short test (internal test)
manual_start_program(255, 0);
}
else if (digitalReadExt(PIN_BUTTON_2)==0)
{ // if B2 is pressed while holding B1, display gateway IP
#ifdef ESP8266
os.lcd.clear(0, 1);
os.lcd.setCursor(0, 0);
os.lcd.print(WiFi.gatewayIP());
#else
os.lcd.clear();
os.lcd_print_ip(ether.gwip, 0);
#endif
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR("(gwip)"));
ui_state = UI_STATE_DISP_IP;
}
else
{
reset_all_stations();
}
}
else
{ // clicking B1: display device IP and port
#ifdef ESP8266
os.lcd.clear(0, 1);
os.lcd.setCursor(0, 0);
os.lcd.print(WiFi.localIP());
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR(":"));
uint16_t httpport = (uint16_t)(os.options[OPTION_HTTPPORT_1]<<8) + (uint16_t)os.options[OPTION_HTTPPORT_0];
os.lcd.print(httpport);
#else
os.lcd.clear();
os.lcd_print_ip(ether.myip, 0);
os.lcd.setCursor(0, 1);
os.lcd_print_pgm(PSTR(":"));
os.lcd.print(ether.hisport);
#endif
os.lcd_print_pgm(PSTR(" (ip:port)"));
ui_state = UI_STATE_DISP_IP;
}
break;
case BUTTON_2:
if (button & BUTTON_FLAG_HOLD)
{ // holding B2: reboot
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
{
os.reboot_dev();
}
}
else
{ // clicking B2: display MAC
#ifdef ESP8266
os.lcd.clear(0, 1);
byte mac[6];
WiFi.macAddress(mac);
os.lcd_print_mac(mac);
#else
os.lcd.clear();
os.lcd_print_mac(ether.mymac);
#endif
ui_state = UI_STATE_DISP_GW;
}
break;
case BUTTON_3:
if (button & BUTTON_FLAG_HOLD)
{ // holding B3: go to 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;
}
}
#endif
// ======================
// Setup Function
// ======================
void do_setup()
{
/* Clear WDT reset flag. */
#ifdef ESP8266
if(wifi_server)
{delete wifi_server; wifi_server = NULL;}
WiFi.persistent(false);
led_blink_ms = LED_FAST_BLINK;
#else
MCUSR &= ~(1 << WDRF);
#endif
DEBUG_BEGIN(115200);
delay(1000);
#ifdef OSMICRO
//Enable RTC
pinMode(PIN_RTC_VCC, OUTPUT);
digitalWrite(PIN_RTC_VCC, HIGH);
pinMode(PIN_RTC_GND, OUTPUT);
digitalWrite(PIN_RTC_GND, LOW);
byte stationPins[MAX_NUM_STATIONS] =
{
PIN_STATIONS_LIST
};
byte s;
for (s = 0; s < MAX_NUM_STATIONS; s++)
{
pinMode(stationPins[s], OUTPUT);
}
#endif
os.begin(); // OpenSprinkler init
os.options_setup(); // Setup options
pd.init(); // ProgramData init
setSyncInterval(RTC_SYNC_INTERVAL); // RTC sync interval
// if rtc exists, sets it as time sync source
setSyncProvider(RTC.get);
#ifndef OSMICRO
os.lcd_print_time(os.now_tz()); // display time to LCD
#endif
#ifndef 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.clear_all_station_bits();
os.apply_all_station_bits(); // reset station bits
#ifndef OSMICRO
os.button_timeout = LCD_BACKLIGHT_TIMEOUT;
#endif
}
// Arduino software reset function
void (*sysReset)(void) = 0;
#ifndef 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;
}
#endif
void write_log(byte type, ulong curr_time);
void schedule_all_stations(ulong curr_time);
void turn_off_station(byte sid, ulong curr_time);
void process_dynamic_events(ulong curr_time);
void check_network();
void check_weather();
void perform_ntp_sync();
void delete_log(char *name);
#ifdef ESP8266
void start_server_ap();
void start_server_client();
#else
void handle_web_request(char *p);
#endif
/** Main Loop */
void do_loop()
{
static ulong last_time = 0;
static ulong last_minute = 0;
byte bid, sid, s, pid, qid, bitvalue;
ProgramStruct prog;
os.status.mas = os.options[OPTION_MASTER_STATION];
os.status.mas2 = os.options[OPTION_MASTER_STATION_2];
time_t curr_time = os.now_tz();
// ====== Process Ethernet packets ======
#if defined(ARDUINO) // Process Ethernet packets for Arduino
#ifdef ESP8266
static ulong connecting_timeout;
switch(os.state)
{
case OS_STATE_INITIAL:
// ray todo: better handling
if(os.get_wifi_mode()==WIFI_MODE_AP)
{
start_server_ap();
os.state = OS_STATE_CONNECTED;
}
else
{
led_blink_ms = LED_SLOW_BLINK;
start_network_sta(os.wifi_config.ssid.c_str(), os.wifi_config.pass.c_str());
os.state = OS_STATE_CONNECTING;
connecting_timeout = millis() + 60000;
os.lcd.setCursor(0, -1);
os.lcd.print(F("Connecting to..."));
os.lcd.setCursor(0, 2);
os.lcd.print(os.wifi_config.ssid);
}
break;
case OS_STATE_TRY_CONNECT:
led_blink_ms = LED_SLOW_BLINK;
start_network_sta_with_ap(os.wifi_config.ssid.c_str(), os.wifi_config.pass.c_str());
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();
start_server_client();
os.state = OS_STATE_CONNECTED;
DEBUG_PRINTLN(WiFi.localIP());
}
else
{
if(millis()>connecting_timeout)
{
os.state = OS_STATE_INITIAL;
DEBUG_PRINTLN(F("timeout"));
}
}
break;
case OS_STATE_CONNECTED:
if(os.get_wifi_mode() == WIFI_MODE_AP)
wifi_server->handleClient();
else
{
if(WiFi.status() == WL_CONNECTED)
{
wifi_server->handleClient();
}
else
{
os.state = OS_STATE_INITIAL;
}
}
break;
case OS_STATE_RESTART:
wifi_server->handleClient();
if(millis() > restart_timeout)
{
os.state = OS_STATE_INITIAL;
os.reboot_dev();
}
break;
}
#else // AVR
uint16_t pos = ether.packetLoop(ether.packetReceive());
if (pos > 0)
{ // packet received
handle_web_request((char*) Ethernet::buffer + pos);
}
wdt_reset();
// reset watchdog timer
wdt_timeout = 0;
#endif
#ifndef OSMICRO
ui_state_machine();
#endif
#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
// if 1 second has passed
if (curr_time != last_time)
{
last_time = curr_time;
if (os.button_timeout)
os.button_timeout--;
#ifndef OSMICRO
#if defined(ARDUINO)
if (!ui_state)
os.lcd_print_time(os.now_tz()); // print time
#endif
#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_start_time = curr_time;
#ifndef OSMICRO
push_message(IFTTT_RAINSENSOR, LOGDATA_RAINDELAY, 1);
#endif
}
else
{
// rain delay stopped, write log
#ifndef OSMICRO
write_log(LOGDATA_RAINDELAY, curr_time);
push_message(IFTTT_RAINSENSOR, LOGDATA_RAINDELAY, 0);
#endif
}
os.old_status.rain_delayed = os.status.rain_delayed;
}
#ifndef OSMICRO
// ====== Check rain sensor status ======
if (os.options[OPTION_SENSOR_TYPE] == SENSOR_TYPE_RAIN)
{ // if a rain sensor is connected
os.rainsensor_status();
if (os.old_status.rain_sensed != os.status.rain_sensed)
{
if (os.status.rain_sensed)
{
// rain sensor on, record time
os.sensor_lasttime = curr_time;
push_message(IFTTT_RAINSENSOR, LOGDATA_RAINSENSE, 1);
}
else
{
// rain sensor off, write log
if (curr_time>os.sensor_lasttime+10)
{ // add a 10 second threshold
// to avoid faulty rain sensors generating
// too many log records
write_log(LOGDATA_RAINSENSE, curr_time);
push_message(IFTTT_RAINSENSOR, LOGDATA_RAINSENSE, 0);
}
}
os.old_status.rain_sensed = os.status.rain_sensed;
}
}
// ===== Check program switch status =====
if (os.programswitch_status(curr_time))
{
reset_all_stations_immediate(); // immediately stop all stations
if(pd.nprograms > 0) manual_start_program(1, 0);
}
#endif
// ====== 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;
// check through all programs
for (pid = 0; pid < pd.nprograms; pid++)
{
pd.read(pid, &prog);
if (prog.check_match(curr_time))
{
// program match found
// 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.station_attrib_bits_read(
ADDR_NVM_STNDISABLE + 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.options[OPTION_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(IFTTT_PROGRAM_SCHED, pid,
prog.use_weather ?
os.options[OPTION_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 station
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];
// check if this station is scheduled, either running or waiting to run
if (q->st > 0)
{
// if so, check if we should turn it off
if (curr_time >= q->st + q->dur)
{
turn_off_station(sid, curr_time);
}
}
// 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);
os.set_station_bit(sid, 1);
#ifndef OSMICRO
// RAH implementation of flow sensor
flow_start=0;
#endif
} //if curr_time > scheduled_start_time
} // if current station is not running
} //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->st + q->dur)
{
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
pd.last_seq_stop_time = 0;
ulong sst;
byte re = os.options[OPTION_REMOTE_EXT_MODE];
q = pd.queue;
for (; q < pd.queue + pd.nqueue; q++)
{
sid = q->sid;
bid = sid >> 3;
s = sid & 0x07;
// 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.station_attrib_bits_read(ADDR_NVM_STNSEQ + bid)
& (1 << s)) && !re)
{
pd.last_seq_stop_time =
(sst > pd.last_seq_stop_time) ?
sst : pd.last_seq_stop_time;
}
}
}
// 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();
// reset runtime
pd.reset_runtime();
// reset program busy bit
os.status.program_busy = 0;
#ifndef OSMICRO
// log flow sensor reading if flow sensor is used
if(os.options[OPTION_SENSOR_TYPE]==SENSOR_TYPE_FLOW)
{
write_log(LOGDATA_FLOWSENSE, curr_time);
push_message(IFTTT_FLOWSENSOR, (flow_count>os.flowcount_log_start)?(flow_count-os.flowcount_log_start):0);
}
#endif
// in case some options have changed while executing the program
os.status.mas = os.options[OPTION_MASTER_STATION]; // update master station
os.status.mas2 = os.options[OPTION_MASTER_STATION_2]; // update master2 station
}
} //if_some_program_is_running
// handle master
if (os.status.mas > 0)
{
int16_t mas_on_adj = water_time_decode_signed(
os.options[OPTION_MASTER_ON_ADJ]);
int16_t mas_off_adj = water_time_decode_signed(
os.options[OPTION_MASTER_OFF_ADJ]);
byte masbit = 0;
os.station_attrib_bits_load(ADDR_NVM_MAS_OP, (byte*) tmp_buffer); // tmp_buffer now stores masop_bits
for (sid = 0; sid < os.nstations; sid++)
{
// skip if this is the master station
if (os.status.mas == sid + 1)
continue;
bid = sid >> 3;
s = sid & 0x07;
// if this station is running and is set to activate master
if ((os.station_bits[bid] & (1 << s))
&& (tmp_buffer[bid] & (1 << s)))
{
q = pd.queue + pd.station_qid[sid];
// 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(os.status.mas - 1, masbit);
}
// handle master2
if (os.status.mas2 > 0)
{
int16_t mas_on_adj_2 = water_time_decode_signed(
os.options[OPTION_MASTER_ON_ADJ_2]);
int16_t mas_off_adj_2 = water_time_decode_signed(
os.options[OPTION_MASTER_OFF_ADJ_2]);
byte masbit2 = 0;
os.station_attrib_bits_load(ADDR_NVM_MAS_OP_2, (byte*) tmp_buffer); // tmp_buffer now stores masop2_bits
for (sid = 0; sid < os.nstations; sid++)
{
// skip if this is the master station
if (os.status.mas2 == sid + 1)
continue;
bid = sid >> 3;
s = sid & 0x07;
// if this station is running and is set to activate master
if ((os.station_bits[bid] & (1 << s))
&& (tmp_buffer[bid] & (1 << s)))
{
q = pd.queue + pd.station_qid[sid];
// check if timing is within the acceptable range
if (curr_time >= q->st + mas_on_adj_2
&& curr_time <= q->st + q->dur + mas_off_adj_2)
{
masbit2 = 1;
break;
}
}
}
os.set_station_bit(os.status.mas2 - 1, masbit2);
}
// process dynamic events
process_dynamic_events(curr_time);
// activate/deactivate valves
os.apply_all_station_bits();
#if defined(ARDUINO)
// process LCD display
#ifndef OSMICRO
if (!ui_state)
os.lcd_print_station(1, ui_anim_chars[curr_time%3]);
#endif
// check safe_reboot condition
if (os.status.safe_reboot)
{
// 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();
}
}
}
#endif
#ifndef OSMICRO
// real-time flow count
static ulong flowcount_rt_start = 0;