forked from OpenSprinkler/OpenSprinkler-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.cpp
1770 lines (1562 loc) · 49.3 KB
/
server.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)
*
* Server functions
* Feb 2015 @ OpenSprinkler.com
*
* This file is part of the OpenSprinkler library
*
* 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 "OpenSprinkler.h"
#include "program.h"
#include "server.h"
// External variables defined in main ion file
#include <FS.h>
#include "espconnect.h"
#define INSERT_DELAY(x) {}
#include <time.h>
extern ESP8266WebServer *wifi_server;
extern char ether_buffer[];
#define handle_return(x) {if(x==HTML_OK) server_send_html(ether_buffer); else server_send_result(x); return;}
extern char tmp_buffer[];
extern OpenSprinkler os;
extern ProgramData pd;
extern ulong flow_count;
static byte return_code;
static char* get_buffer = NULL;
BufferFiller bfill;
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(time_t curr_time);
void check_weather(time_t curr_time);
void perform_ntp_sync(time_t curr_time);
void log_statistics(time_t curr_time);
void delete_log(char *name);
void reset_all_stations_immediate();
void reset_all_stations();
void make_logfile_name(char *name);
/* Check available space (number of bytes) in the Ethernet buffer */
int available_ether_buffer() {
return ETHER_BUFFER_SIZE - (int)bfill.position();
}
// Define return error code
#define HTML_OK 0x00
#define HTML_SUCCESS 0x01
#define HTML_UNAUTHORIZED 0x02
#define HTML_MISMATCH 0x03
#define HTML_DATA_MISSING 0x10
#define HTML_DATA_OUTOFBOUND 0x11
#define HTML_DATA_FORMATERROR 0x12
#define HTML_RFCODE_ERROR 0x13
#define HTML_PAGE_NOT_FOUND 0x20
#define HTML_NOT_PERMITTED 0x30
#define HTML_UPLOAD_FAILED 0x40
#define HTML_REDIRECT_HOME 0xFF
static const char html200OK[] PROGMEM =
"HTTP/1.1 200 OK\r\n"
;
static const char htmlCacheCtrl[] PROGMEM =
"Cache-Control: max-age=604800, public\r\n"
;
static const char htmlNoCache[] PROGMEM =
"Cache-Control: max-age=0, no-cache, no-store, must-revalidate\r\n"
;
static const char htmlContentHTML[] PROGMEM =
"Content-Type: text/html\r\n"
;
static const char htmlAccessControl[] PROGMEM =
"Access-Control-Allow-Origin: *\r\n"
;
static const char htmlContentJSON[] PROGMEM =
"Content-Type: application/json\r\n"
"Connection: close\r\n"
;
static const char htmlMobileHeader[] PROGMEM =
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no\">\r\n"
;
static const char htmlReturnHome[] PROGMEM =
"<script>window.location=\"/\";</script>\n"
;
void print_html_standard_header() {
wifi_server->sendHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
wifi_server->sendHeader("Access-Control-Allow-Origin", "*");
}
void print_json_header(bool bracket=true) {
wifi_server->sendHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
wifi_server->sendHeader("Content-Type", "application/json");
wifi_server->sendHeader("Access-Control-Allow-Origin", "*");
if(bracket) bfill.emit_p(PSTR("{"));
}
byte findKeyVal (const char *str,char *strbuf, uint8_t maxlen,const char *key,bool key_in_pgm=false,uint8_t *keyfound=NULL)
{
uint8_t found=0;
// for ESP8266: there are two cases:
// case 1: if str is NULL, we assume the key-val to search is already parsed in wifi_server
if(str==NULL) {
char _key[10];
if(key_in_pgm) strcpy_P(_key, key);
else strcpy(_key, key);
if(wifi_server->hasArg(_key)) {
// copy value to buffer, and make sure it ends properly
strncpy(strbuf, wifi_server->arg(_key).c_str(), maxlen);
strbuf[maxlen-1]=0;
found=1;
} else {
strbuf[0]=0;
}
if (keyfound) *keyfound = found;
return strlen(strbuf);
}
// case 2: otherwise, assume the key-val is stored in str
uint8_t i=0;
const char *kp;
kp=key;
if (key_in_pgm) {
// key is in program memory space
while(*str && *str!=' ' && *str!='\n' && found==0){
if (*str == pgm_read_byte(kp)){
kp++;
if (pgm_read_byte(kp) == '\0'){
str++;
kp=key;
if (*str == '='){
found=1;
}
}
} else {
kp=key;
}
str++;
}
} else {
while(*str && *str!=' ' && *str!='\n' && found==0){
if (*str == *kp){
kp++;
if (*kp == '\0'){
str++;
kp=key;
if (*str == '='){
found=1;
}
}
} else {
kp=key;
}
str++;
}
}
if (found==1){
// copy the value to a buffer and terminate it with '\0'
while(*str && *str!=' ' && *str!='\n' && *str!='&' && i<maxlen-1){
*strbuf=*str;
i++;
str++;
strbuf++;
}
if (!(*str) || *str == ' ' || *str == '\n' || *str == '&') {
*strbuf = '\0';
} else {
found = 0; // Ignore partial values i.e. value length is larger than maxlen
i = 0;
}
}
// return the length of the value
if (keyfound) *keyfound = found;
return(i);
}
void rewind_ether_buffer() {
bfill = ether_buffer;
}
void send_packet(bool final=false) {
if(final || available_ether_buffer()<250) {
wifi_server->sendContent(ether_buffer);
if(final)
wifi_server->client().stop();
else
rewind_ether_buffer();
}
}
/** Convert a single hex digit character to its integer value */
unsigned char h2int(char c)
{
if (c >= '0' && c <='9'){
return((unsigned char)c - '0');
}
if (c >= 'a' && c <='f'){
return((unsigned char)c - 'a' + 10);
}
if (c >= 'A' && c <='F'){
return((unsigned char)c - 'A' + 10);
}
return(0);
}
/** Decode a url string e.g "hello%20joe" or "hello+joe" becomes "hello joe" */
void urlDecode (char *urlbuf)
{
if(!urlbuf) return;
char c;
char *dst = urlbuf;
while ((c = *urlbuf) != 0) {
if (c == '+') c = ' ';
if (c == '%') {
c = *++urlbuf;
c = (h2int(c) << 4) | h2int(*++urlbuf);
}
*dst++ = c;
urlbuf++;
}
*dst = '\0';
}
String two_digits(uint8_t x) {
return String(x/10) + (x%10);
}
String toHMS(ulong t) {
return two_digits(t/3600)+":"+two_digits((t/60)%60)+":"+two_digits(t%60);
}
void server_send_html(String html) {
wifi_server->send(200, "text/html", html);
}
void server_send_json(String json) {
wifi_server->send(200, "application/json", json);
}
void server_send_result(byte code) {
String html = F("{\"result\":");
html += code;
html += "}";
print_html_standard_header();
server_send_json(html);
}
void server_send_result(byte code, const char* item) {
String html = F("{\"result\":");
html += code;
html += F(",\"item\":\"");
if(item) html += item;
html += "\"";
html += "}";
print_json_header();
server_send_json(html);
}
bool get_value_by_key(const char* key, long& val) {
if(wifi_server->hasArg(key)) {
val = wifi_server->arg(key).toInt();
return true;
} else {
return false;
}
}
bool get_value_by_key(const char* key, String& val) {
if(wifi_server->hasArg(key)) {
val = wifi_server->arg(key);
return true;
} else {
return false;
}
}
void append_key_value(String& html, const char* key, const ulong value) {
html += "\"";
html += key;
html += "\":";
html += value;
html += ",";
}
void append_key_value(String& html, const char* key, const int16_t value) {
html += "\"";
html += key;
html += "\":";
html += value;
html += ",";
}
void append_key_value(String& html, const char* key, const String& value) {
html += "\"";
html += key;
html += "\":\"";
html += value;
html += "\",";
}
char dec2hexchar(byte dec) {
if(dec<10) return '0'+dec;
else return 'A'+(dec-10);
}
String get_mac() {
static String hex;
if(!hex.length()) {
byte mac[6];
WiFi.macAddress(mac);
for(byte i=0;i<6;i++) {
hex += dec2hexchar((mac[i]>>4)&0x0F);
hex += dec2hexchar(mac[i]&0x0F);
}
}
return hex;
}
String get_ap_ssid() {
static String ap_ssid;
if(!ap_ssid.length()) {
byte mac[6];
WiFi.macAddress(mac);
ap_ssid += "OS_";
for(byte i=3;i<6;i++) {
ap_ssid += dec2hexchar((mac[i]>>4)&0x0F);
ap_ssid += dec2hexchar(mac[i]&0x0F);
}
}
return ap_ssid;
}
static String scanned_ssids;
void on_ap_home() {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
server_send_html(FPSTR(ap_home_html));
}
void on_ap_scan() {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
server_send_html(scanned_ssids);
}
void on_ap_change_config() {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
if(wifi_server->hasArg("ssid")&&wifi_server->arg("ssid").length()!=0) {
os.wifi_config.ssid = wifi_server->arg("ssid");
os.wifi_config.pass = wifi_server->arg("pass");
os.options_save(true);
server_send_result(HTML_SUCCESS);
os.state = OS_STATE_TRY_CONNECT;
//os.lcd.setCursor(0, 2);
//os.lcd.print(F("Connecting..."));
} else {
server_send_result(HTML_DATA_MISSING, "ssid");
}
}
void on_ap_try_connect() {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
String html = "{";
ulong ip = (WiFi.status()==WL_CONNECTED)?(uint32_t)WiFi.localIP():0;
append_key_value(html, "ip", ip);
html.remove(html.length()-1);
html += "}";
server_send_html(html);
if(WiFi.status() == WL_CONNECTED && WiFi.localIP()) {
// IP received by client, restart
os.reboot_dev();
}
}
/** Check and verify password */
boolean process_password(boolean fwv_on_fail=false, char *p = NULL)
{
if (os.options[OPTION_IGNORE_PASSWORD]) return true;
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pw"), true)) {
urlDecode(tmp_buffer);
if (os.password_verify(tmp_buffer))
return true;
}
/* some pages will output fwv if password check has failed */
if(fwv_on_fail) {
rewind_ether_buffer();
print_json_header();
bfill.emit_p(PSTR("\"$F\":$D}"), op_json_names+0, os.options[0]);
server_send_html(ether_buffer);
} else {
server_send_result(HTML_UNAUTHORIZED);
}
return false;
}
void server_json_stations_attrib(const char* name, int addr)
{
byte *attrib = (byte*)tmp_buffer;
os.station_attrib_bits_load(addr, attrib);
bfill.emit_p(PSTR("\"$F\":["), name);
for(byte i=0;i<os.nboards;i++) {
bfill.emit_p(PSTR("$D"), attrib[i]);
if(i!=os.nboards-1)
bfill.emit_p(PSTR(","));
}
bfill.emit_p(PSTR("],"));
}
void server_json_stations_main()
{
server_json_stations_attrib(PSTR("masop"), ADDR_NVM_MAS_OP);
server_json_stations_attrib(PSTR("ignore_rain"), ADDR_NVM_IGNRAIN);
server_json_stations_attrib(PSTR("masop2"), ADDR_NVM_MAS_OP_2);
server_json_stations_attrib(PSTR("stn_dis"), ADDR_NVM_STNDISABLE);
server_json_stations_attrib(PSTR("stn_seq"), ADDR_NVM_STNSEQ);
// only output stn_spe if it's supported
if (os.status.has_sd) {
server_json_stations_attrib(PSTR("stn_spe"), ADDR_NVM_STNSPE);
}
bfill.emit_p(PSTR("\"snames\":["));
byte sid;
for(sid=0;sid<os.nstations;sid++) {
os.get_station_name(sid, tmp_buffer);
bfill.emit_p(PSTR("\"$S\""), tmp_buffer);
if(sid!=os.nstations-1)
bfill.emit_p(PSTR(","));
if (available_ether_buffer()<80) {
send_packet();
}
}
bfill.emit_p(PSTR("],\"maxlen\":$D}"), STATION_NAME_SIZE);
INSERT_DELAY(1);
}
/** Output stations data */
void server_json_stations() {
if(!process_password()) return;
rewind_ether_buffer();
print_json_header();
server_json_stations_main();
handle_return(HTML_OK);
}
/** Output station special attribute */
void server_json_station_special() {
// if no sd card, return false
if (!os.status.has_sd) handle_return(HTML_PAGE_NOT_FOUND);
if(!process_password()) return;
rewind_ether_buffer();
byte sid;
byte comma=0;
int stepsize=sizeof(StationSpecialData);
StationSpecialData *stn = (StationSpecialData *)tmp_buffer;
print_json_header();
for(sid=0;sid<os.nstations;sid++) {
if(os.station_attrib_bits_read(ADDR_NVM_STNSPE+(sid>>3))&(1<<(sid&0x07))) {
read_from_file(stns_filename, (char*)stn, stepsize, sid*stepsize);
if (comma) bfill.emit_p(PSTR(","));
else {comma=1;}
bfill.emit_p(PSTR("\"$D\":{\"st\":$D,\"sd\":\"$S\"}"), sid, stn->type, stn->data);
}
}
bfill.emit_p(PSTR("}"));
INSERT_DELAY(1);
handle_return(HTML_OK);
}
void server_change_stations_attrib(char *p, char header, int addr)
{
byte attrib[MAX_EXT_BOARDS+1];
os.station_attrib_bits_load(addr, attrib);
char tbuf2[3] = {0, 0, 0};
byte bid;
tbuf2[0]=header;
for(bid=0;bid<os.nboards;bid++) {
itoa(bid, tbuf2+1, 10);
if(findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, tbuf2)) {
attrib[bid] = atoi(tmp_buffer);
}
}
os.station_attrib_bits_save(addr, attrib);
}
/**
* Change Station Name and Attributes
* Command: /cs?pw=xxx&s?=x&m?=x&i?=x&n?=x&d?=x
*
* pw: password
* s?: station name (? is station index, starting from 0)
* m?: master operation bit field (? is board index, starting from 0)
* i?: ignore rain bit field
* n?: master2 operation bit field
* d?: disable sation bit field
* q?: station sequeitnal bit field
* p?: station special flag bit field
*/
void server_change_stations() {
char* p = NULL;
if(!process_password()) return;
byte sid;
char tbuf2[4] = {'s', 0, 0, 0};
// process station names
for(sid=0;sid<os.nstations;sid++) {
itoa(sid, tbuf2+1, 10);
if(findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, tbuf2)) {
urlDecode(tmp_buffer);
os.set_station_name(sid, tmp_buffer);
}
}
server_change_stations_attrib(p, 'm', ADDR_NVM_MAS_OP); // master1
server_change_stations_attrib(p, 'i', ADDR_NVM_IGNRAIN); // ignore rain
server_change_stations_attrib(p, 'n', ADDR_NVM_MAS_OP_2); // master2
server_change_stations_attrib(p, 'd', ADDR_NVM_STNDISABLE); // disable
server_change_stations_attrib(p, 'q', ADDR_NVM_STNSEQ); // sequential
// only parse station special bits if it's supported
if(os.status.has_sd) {
server_change_stations_attrib(p, 'p', ADDR_NVM_STNSPE); // special
}
/* handle special data */
if(findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("sid"), true)) {
sid = atoi(tmp_buffer);
if(sid<0 || sid>os.nstations) handle_return(HTML_DATA_OUTOFBOUND);
if(findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("st"), true) &&
findKeyVal(p, tmp_buffer+1, TMP_BUFFER_SIZE-1, PSTR("sd"), true)) {
int stepsize=sizeof(StationSpecialData);
tmp_buffer[0]-='0';
tmp_buffer[stepsize-1] = 0;
// only process GPIO and HTTP stations for OS 2.3, above, and OSPi
if(tmp_buffer[0] == STN_TYPE_GPIO) {
// check that pin does not clash with OSPi pins
byte gpio = (tmp_buffer[1] - '0') * 10 + tmp_buffer[2] - '0';
byte activeState = tmp_buffer[3] - '0';
byte gpioList[] = PIN_FREE_LIST;
bool found = false;
for (int i = 0; i < sizeof(gpioList) && found == false; i++) {
// if (gpioList[i] == gpio) found = true;
}
if (!found || activeState > 1) handle_return(HTML_DATA_OUTOFBOUND);
} else if (tmp_buffer[0] == STN_TYPE_HTTP) {
if (strlen(tmp_buffer+1) > sizeof(HTTPStationData)) {
handle_return(HTML_DATA_OUTOFBOUND);
}
}
write_to_file(stns_filename, tmp_buffer, strlen(tmp_buffer)+1, stepsize*sid, false);
} else {
handle_return(HTML_DATA_MISSING);
}
}
handle_return(HTML_SUCCESS);
}
/** Parse one number from a comma separate list */
uint16_t parse_listdata(char **p) {
char* pv;
int i=0;
tmp_buffer[i]=0;
// copy to tmp_buffer until a non-number is encountered
for(pv=(*p);pv<(*p)+10;pv++) {
if ((*pv)=='-' || (*pv)=='+' || ((*pv)>='0'&&(*pv)<='9'))
tmp_buffer[i++] = (*pv);
else
break;
}
tmp_buffer[i]=0;
*p = pv+1;
return (uint16_t)atol(tmp_buffer);
}
void manual_start_program(byte, byte);
/** Manual start program
* Command: /mp?pw=xxx&pid=xxx&uwt=xxx
*
* pw: password
* pid: program index (0 refers to the first program)
* uwt: use weather (i.e. watering percentage)
*/
void server_manual_program() {
char* p = NULL;
if(!process_password()) return;
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true))
handle_return(HTML_DATA_MISSING);
int pid=atoi(tmp_buffer);
if (pid < 0 || pid >= pd.nprograms) {
handle_return(HTML_DATA_OUTOFBOUND);
}
byte uwt = 0;
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("uwt"), true)) {
if(tmp_buffer[0]=='1') uwt = 1;
}
// reset all stations and prepare to run one-time program
reset_all_stations_immediate();
manual_start_program(pid+1, uwt);
handle_return(HTML_SUCCESS);
}
/**
* Change run-once program
* Command: /cr?pw=xxx&t=[x,x,x...]
*
* pw: password
* t: station water time
*/
void server_change_runonce() {
char* p = NULL;
if(!process_password()) return;
if(!findKeyVal(p,tmp_buffer,TMP_BUFFER_SIZE, "t",false)) handle_return(HTML_DATA_MISSING);
char *pv = tmp_buffer+1;
// reset all stations and prepare to run one-time program
reset_all_stations_immediate();
byte sid, bid, s;
uint16_t dur;
boolean match_found = false;
for(sid=0;sid<os.nstations;sid++) {
dur=parse_listdata(&pv);
bid=sid>>3;
s=sid&0x07;
// if non-zero duration is given
// and if the station has not been disabled
if (dur>0 && !(os.station_attrib_bits_read(ADDR_NVM_STNDISABLE+bid)&(1<<s))) {
RuntimeQueueStruct *q = pd.enqueue();
if (q) {
q->st = 0;
q->dur = water_time_resolve(dur);
q->pid = 254;
q->sid = sid;
match_found = true;
}
}
}
if(match_found) {
schedule_all_stations(os.now_tz());
handle_return(HTML_SUCCESS);
}
handle_return(HTML_DATA_MISSING);
}
/**
* Delete a program
* Command: /dp?pw=xxx&pid=xxx
*
* pw: password
* pid:program index (-1 will delete all programs)
*/
void server_delete_program() {
char* p = NULL;
if(!process_password()) return;
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true))
handle_return(HTML_DATA_MISSING);
int pid=atoi(tmp_buffer);
if (pid == -1) {
pd.eraseall();
} else if (pid < pd.nprograms) {
pd.del(pid);
} else {
handle_return(HTML_DATA_OUTOFBOUND);
}
handle_return(HTML_SUCCESS);
}
/**
* Move up a program
* Command: /up?pw=xxx&pid=xxx
*
* pw: password
* pid: program index (must be 1 or larger, because we can't move up program 0)
*/
void server_moveup_program() {
char* p = NULL;
if(!process_password()) return;
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true))
handle_return(HTML_DATA_MISSING);
int pid=atoi(tmp_buffer);
if (!(pid>=1 && pid< pd.nprograms))
handle_return(HTML_DATA_OUTOFBOUND);
pd.moveup(pid);
handle_return(HTML_SUCCESS);
}
/**
* Change a program
* Command: /cp?pw=xxx&pid=x&v=[flag,days0,days1,[start0,start1,start2,start3],[dur0,dur1,dur2..]]&name=x
*
* pw: password
* pid: program index
* flag: program flag
* start?:up to 4 start times
* dur?: station water time
* name: program name
*/
const char _str_program[] PROGMEM = "Program ";
void server_change_program() {
char* p = NULL;
if(!process_password()) return;
byte i;
ProgramStruct prog;
// parse program index
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true)) handle_return(HTML_DATA_MISSING);
int pid=atoi(tmp_buffer);
if (!(pid>=-1 && pid< pd.nprograms)) handle_return(HTML_DATA_OUTOFBOUND);
// check if "en" parameter is present
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("en"), true)) {
if(pid<0) handle_return(HTML_DATA_OUTOFBOUND);
pd.set_flagbit(pid, PROGRAMSTRUCT_EN_BIT, (tmp_buffer[0]=='0')?0:1);
handle_return(HTML_SUCCESS);
}
// check if "uwt" parameter is present
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("uwt"), true)) {
if(pid<0) handle_return(HTML_DATA_OUTOFBOUND);
pd.set_flagbit(pid, PROGRAMSTRUCT_UWT_BIT, (tmp_buffer[0]=='0')?0:1);
handle_return(HTML_SUCCESS);
}
// parse program name
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("name"), true)) {
urlDecode(tmp_buffer);
strncpy(prog.name, tmp_buffer, PROGRAM_NAME_SIZE);
} else {
strcpy_P(prog.name, _str_program);
itoa((pid==-1)? (pd.nprograms+1): (pid+1), prog.name+8, 10);
}
// do a full string decoding
if(p) urlDecode(p);
if(!findKeyVal(p,tmp_buffer,TMP_BUFFER_SIZE, "v",false)) handle_return(HTML_DATA_MISSING);
char *pv = tmp_buffer+1;
// parse headers
*(char*)(&prog) = parse_listdata(&pv);
prog.days[0]= parse_listdata(&pv);
prog.days[1]= parse_listdata(&pv);
// parse start times
pv++; // this should be a '['
for (i=0;i<MAX_NUM_STARTTIMES;i++) {
prog.starttimes[i] = parse_listdata(&pv);
}
pv++; // this should be a ','
pv++; // this should be a '['
for (i=0;i<os.nstations;i++) {
uint16_t pre = parse_listdata(&pv);
prog.durations[i] = pre;
}
pv++; // this should be a ']'
pv++; // this should be a ']'
// parse program name
// i should be equal to os.nstations at this point
for(;i<MAX_NUM_STATIONS;i++) {
prog.durations[i] = 0; // clear unused field
}
// process interval day remainder (relative-> absolute)
if (prog.type == PROGRAM_TYPE_INTERVAL && prog.days[1] > 1) {
pd.drem_to_absolute(prog.days);
}
if (pid==-1) {
if(!pd.add(&prog)) handle_return(HTML_DATA_OUTOFBOUND);
} else {
if(!pd.modify(pid, &prog)) handle_return(HTML_DATA_OUTOFBOUND);
}
handle_return(HTML_SUCCESS);
}
void server_json_options_main() {
byte oid;
for(oid=0;oid<NUM_OPTIONS;oid++) {
int32_t v=os.options[oid];
if (oid==OPTION_MASTER_OFF_ADJ || oid==OPTION_MASTER_OFF_ADJ_2 ||
oid==OPTION_MASTER_ON_ADJ || oid==OPTION_MASTER_ON_ADJ_2 ||
oid==OPTION_STATION_DELAY_TIME) {
v=water_time_decode_signed(v);
}
if (oid==OPTION_BOOST_TIME) {
if (os.hw_type==HW_TYPE_AC || os.hw_type==HW_TYPE_UNKNOWN) continue;
else v<<=2;
}
if (oid==OPTION_SEQUENTIAL_RETIRED) continue;
if (oid==OPTION_DEVICE_ID && os.status.has_hwmac) continue; // do not send DEVICE ID if hardware MAC exists
if(oid==OPTION_LCD_CONTRAST || oid==OPTION_LCD_BACKLIGHT || oid==OPTION_LCD_DIMMING) continue;
// each json name takes 5 characters
strncpy_P0(tmp_buffer, op_json_names+oid*5, 5);
bfill.emit_p(PSTR("\"$S\":$D"), tmp_buffer, v);
if(oid!=NUM_OPTIONS-1)
bfill.emit_p(PSTR(","));
}
bfill.emit_p(PSTR(",\"dexp\":$D,\"mexp\":$D,\"hwt\":$D}"), MAX_EXT_BOARDS, MAX_EXT_BOARDS, os.hw_type);
INSERT_DELAY(1);
}
/** Output Options */
void server_json_options() {
if(!process_password(true)) return;
rewind_ether_buffer();
print_json_header();
server_json_options_main();
handle_return(HTML_OK);
}
void server_json_programs_main() {
bfill.emit_p(PSTR("\"nprogs\":$D,\"nboards\":$D,\"mnp\":$D,\"mnst\":$D,\"pnsize\":$D,\"pd\":["),
pd.nprograms, os.nboards, MAX_NUMBER_PROGRAMS, MAX_NUM_STARTTIMES, PROGRAM_NAME_SIZE);
byte pid, i;
ProgramStruct prog;
for(pid=0;pid<pd.nprograms;pid++) {
pd.read(pid, &prog);
if (prog.type == PROGRAM_TYPE_INTERVAL && prog.days[1] > 1) {
pd.drem_to_relative(prog.days);
}
byte bytedata = *(char*)(&prog);
bfill.emit_p(PSTR("[$D,$D,$D,["), bytedata, prog.days[0], prog.days[1]);
// start times data
for (i=0;i<(MAX_NUM_STARTTIMES-1);i++) {
bfill.emit_p(PSTR("$D,"), prog.starttimes[i]);
}
bfill.emit_p(PSTR("$D],["), prog.starttimes[i]); // this is the last element
// station water time
for (i=0; i<os.nstations-1; i++) {
bfill.emit_p(PSTR("$L,"),(unsigned long)prog.durations[i]);
}
bfill.emit_p(PSTR("$L],\""),(unsigned long)prog.durations[i]); // this is the last element
// program name
strncpy(tmp_buffer, prog.name, PROGRAM_NAME_SIZE);
tmp_buffer[PROGRAM_NAME_SIZE] = 0; // make sure the string ends
bfill.emit_p(PSTR("$S"), tmp_buffer);
if(pid!=pd.nprograms-1) {
bfill.emit_p(PSTR("\"],"));
} else {
bfill.emit_p(PSTR("\"]"));
}
// push out a packet if available
// buffer size is getting small
if (available_ether_buffer() < 250) {
send_packet();
}
}
bfill.emit_p(PSTR("]}"));
INSERT_DELAY(1);
}
/** Output program data */
void server_json_programs() {
if(!process_password()) return;
rewind_ether_buffer();
print_json_header();
server_json_programs_main();
handle_return(HTML_OK);
}
/** Output script url form */
void server_view_scripturl() {
// no authenticaion needed
rewind_ether_buffer();
print_html_standard_header();
bfill.emit_p(PSTR("<form name=of action=cu method=get><table cellspacing=\"12\"><tr><td><b>JavaScript</b>:</td><td><input type=text size=40 maxlength=40 value=\"$E\" name=jsp></td></tr><tr><td>Default:</td><td>$S</td></tr><tr><td><b>Weather</b>:</td><td><input type=text size=40 maxlength=40 value=\"$E\" name=wsp></td></tr><tr><td>Default:</td><td>$S</td></tr><tr><td><b>Password</b>:</td><td><input type=password size=32 name=pw> <input type=submit></td></tr></table></form><script src=https://ui.opensprinkler.com/js/hasher.js></script>"), ADDR_NVM_JAVASCRIPTURL, DEFAULT_JAVASCRIPT_URL, ADDR_NVM_WEATHERURL, DEFAULT_WEATHER_URL);
handle_return(HTML_OK);
}
void server_json_controller_main() {
byte bid, sid;
ulong curr_time = os.now_tz();
//os.nvm_string_get(ADDR_NVM_LOCATION, tmp_buffer);
bfill.emit_p(PSTR("\"devt\":$L,\"nbrd\":$D,\"en\":$D,\"rd\":$D,\"rs\":$D,\"rdst\":$L,"
"\"loc\":\"$E\",\"wtkey\":\"$E\",\"sunrise\":$D,\"sunset\":$D,\"eip\":$L,\"lwc\":$L,\"lswc\":$L,"
"\"lupt\":$L,\"lrun\":[$D,$D,$D,$L],"),
curr_time,
os.nboards,
os.status.enabled,
os.status.rain_delayed,
os.status.rain_sensed,
os.nvdata.rd_stop_time,
ADDR_NVM_LOCATION,
ADDR_NVM_WEATHER_KEY,
os.nvdata.sunrise_time,
os.nvdata.sunset_time,
os.nvdata.external_ip,
os.checkwt_lasttime,
os.checkwt_success_lasttime,
os.powerup_lasttime,
pd.lastrun.station,
pd.lastrun.program,
pd.lastrun.duration,
pd.lastrun.endtime);
if(os.options[OPTION_SENSOR2_TYPE]==SENSOR_TYPE_FLOW) {
bfill.emit_p(PSTR("\"flcrt\":$L,\"flwrt\":$D,"), os.flowcount_rt, FLOWCOUNT_RT_WINDOW);
}
bfill.emit_p(PSTR("\"sbits\":["));
// print sbits
for(bid=0;bid<os.nboards;bid++)
bfill.emit_p(PSTR("$D,"), os.station_bits[bid]);
bfill.emit_p(PSTR("0],\"ps\":["));
// print ps
for(sid=0;sid<os.nstations;sid++) {
unsigned long rem = 0;
byte qid = pd.station_qid[sid];
RuntimeQueueStruct *q = pd.queue + qid;
if (qid<255) {
rem = (curr_time >= q->st) ? (q->st+q->dur-curr_time) : q->dur;
if(rem>65535) rem = 0;
}
bfill.emit_p(PSTR("[$D,$L,$L]"), (qid<255)?q->pid:0, rem, (qid<255)?q->st:0);
bfill.emit_p((sid<os.nstations-1)?PSTR(","):PSTR("]"));
// if available ether buffer is getting small
// send out a packet
if(available_ether_buffer() < 80) {
send_packet();
}
}
if(read_from_file(wtopts_filename, tmp_buffer)) {
bfill.emit_p(PSTR(",\"wto\":{$S}"), tmp_buffer);
}
if(read_from_file(ifkey_filename, tmp_buffer)) {
bfill.emit_p(PSTR(",\"ifkey\":\"$S\""), tmp_buffer);
}
bfill.emit_p(PSTR(",\"RSSI\":$D"), (int16_t)WiFi.RSSI());
bfill.emit_p(PSTR("}"));
INSERT_DELAY(1);
}
/** Output controller variables in json */
void server_json_controller() {
if(!process_password()) return;
rewind_ether_buffer();
print_json_header();
server_json_controller_main();