forked from OpenSprinkler/OpenSprinkler-Firmware
-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.cpp
2305 lines (2060 loc) · 58.9 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"
#include "weather.h"
// External variables defined in main ion file
#if defined(ARDUINO)
#if defined(ESP8266)
#include <FS.h>
#include "espconnect.h"
extern ESP8266WebServer *wifi_server;
extern EthernetServer *m_server;
extern EthernetClient *m_client;
#define handle_return(x) {if(m_client) {return_code=x; return;} else {if(x==HTML_OK) server_send_html(ether_buffer); else server_send_result(x); return;}}
#else
#include "SdFat.h"
extern SdFat sd;
extern EthernetClient *m_client;
#define handle_return(x) {return_code=x; return;}
#endif
#else
#include <stdarg.h>
#include <stdlib.h>
#include "etherport.h"
extern EthernetClient *m_client;
#define handle_return(x) {return_code=x; return;}
#endif
extern char ether_buffer[];
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() {
#if defined(ESP8266)
if (m_client) {
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentHTML, htmlNoCache, htmlAccessControl);
return;
}
// else
wifi_server->sendHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
wifi_server->sendHeader("Access-Control-Allow-Origin", "*");
#elif defined(ARDUINO)
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentHTML, htmlNoCache, htmlAccessControl);
#else
m_client->write((const uint8_t *)html200OK, strlen(html200OK));
m_client->write((const uint8_t *)htmlContentHTML, strlen(htmlContentHTML));
m_client->write((const uint8_t *)htmlNoCache, strlen(htmlNoCache));
m_client->write((const uint8_t *)htmlAccessControl, strlen(htmlAccessControl));
m_client->write((const uint8_t *)"\r\n", 2);
#endif
}
void print_json_header(bool bracket=true) {
#if defined(ESP8266)
if (m_client) {
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentJSON, htmlAccessControl, htmlNoCache);
if(bracket) bfill.emit_p(PSTR("{"));
return;
}
// else
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("{"));
#elif defined(ARDUINO)
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentJSON, htmlAccessControl, htmlNoCache);
if(bracket) bfill.emit_p(PSTR("{"));
#else
m_client->write((const uint8_t *)html200OK, strlen(html200OK));
m_client->write((const uint8_t *)htmlContentJSON, strlen(htmlContentJSON));
m_client->write((const uint8_t *)htmlNoCache, strlen(htmlNoCache));
m_client->write((const uint8_t *)htmlAccessControl, strlen(htmlAccessControl));
if(bracket) m_client->write((const uint8_t *)"\r\n{", 3);
else m_client->write((const uint8_t *)"\r\n", 2);
#endif
}
byte findKeyVal (const char *str,char *strbuf, uint16_t maxlen,const char *key,bool key_in_pgm=false,uint8_t *keyfound=NULL) {
uint8_t found=0;
#if defined(ESP8266)
// 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);
}
#endif
// case 2: otherwise, assume the key-val is stored in str
uint16_t i=0;
const char *kp;
kp=key;
#if defined(ARDUINO)
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
#endif
// for Linux, key_in_pgm is always false
{
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;
ether_buffer[0] = 0;
}
void send_packet(bool final=false) {
#if defined(ESP8266)
if (m_client) {
m_client->write((const uint8_t *)ether_buffer, strlen(ether_buffer));
if (final)
m_client->stop();
else
rewind_ether_buffer();
return;
}
// else
if(final || available_ether_buffer()<250) {
wifi_server->sendContent(ether_buffer);
if(final)
wifi_server->client().stop();
else
rewind_ether_buffer();
}
#elif defined(ARDUINO)
if(final || available_ether_buffer()<250) {
m_client->write(ether_buffer, strlen(ether_buffer));
if(final)
m_client->stop();
else
rewind_ether_buffer();
}
#else
m_client->write((const uint8_t *)ether_buffer, strlen(ether_buffer));
if (final)
m_client->stop();
else
rewind_ether_buffer();
#endif
}
#if defined(ESP8266)
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) {
if (m_client) {
return;
}
// else
wifi_server->send(200, "text/html", html);
}
void server_send_json(String json) {
if (m_client) {
return;
}
// else
wifi_server->send(200, "application/json", json);
}
void server_send_result(byte code) {
rewind_ether_buffer();
String html = F("{\"result\":");
html += code;
html += "}";
print_json_header(false);
server_send_json(html);
}
void server_send_result(byte code, const char* item) {
rewind_ether_buffer();
String html = F("{\"result\":");
html += code;
html += F(",\"item\":\"");
if(item) html += item;
html += "\"";
html += "}";
print_json_header(false);
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_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_ssid = wifi_server->arg("ssid");
os.wifi_pass = wifi_server->arg("pass");
os.sopt_save(SOPT_STA_SSID, os.wifi_ssid.c_str());
os.sopt_save(SOPT_STA_PASS, os.wifi_pass.c_str());
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(REBOOT_CAUSE_WIFIDONE);
}
}
#endif
/** Check and verify password */
#if defined(ESP8266)
boolean process_password(boolean fwv_on_fail=false, char *p = NULL)
#else
boolean check_password(char *p)
#endif
{
#if defined(DEMO)
return true;
#endif
if (os.iopts[IOPT_IGNORE_PASSWORD]) return true;
if (m_client && !p) {
p = get_buffer;
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pw"), true)) {
urlDecode(tmp_buffer);
if (os.password_verify(tmp_buffer))
return true;
}
#if defined(ESP8266)
if(m_client) { return false; }
/* 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}"), iopt_json_names+0, os.iopts[0]);
server_send_html(ether_buffer);
} else {
server_send_result(HTML_UNAUTHORIZED);
}
#endif
return false;
}
void server_json_stations_attrib(const char* name, byte *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"), os.attrib_mas);
server_json_stations_attrib(PSTR("masop2"), os.attrib_mas2);
server_json_stations_attrib(PSTR("ignore_rain"), os.attrib_igrd);
server_json_stations_attrib(PSTR("ignore_sn1"), os.attrib_igs);
server_json_stations_attrib(PSTR("ignore_sn2"), os.attrib_igs2);
server_json_stations_attrib(PSTR("stn_dis"), os.attrib_dis);
server_json_stations_attrib(PSTR("stn_seq"), os.attrib_seq);
server_json_stations_attrib(PSTR("stn_spe"), os.attrib_spe);
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() < 60) {
send_packet();
}
}
bfill.emit_p(PSTR("],\"maxlen\":$D}"), STATION_NAME_SIZE);
}
/** Output stations data */
void server_json_stations() {
#if defined(ESP8266)
if(!process_password()) return;
rewind_ether_buffer();
#endif
print_json_header();
server_json_stations_main();
handle_return(HTML_OK);
}
/** Output station special attribute */
void server_json_station_special() {
#if defined(ESP8266)
if(!process_password()) return;
rewind_ether_buffer();
#endif
byte sid;
byte comma=0;
StationData *data = (StationData*)tmp_buffer;
print_json_header();
for(sid=0;sid<os.nstations;sid++) {
if(os.get_station_type(sid)!=STN_TYPE_STANDARD) { // check if this is a special station
os.get_station_data(sid, data);
if (comma) bfill.emit_p(PSTR(","));
else {comma=1;}
bfill.emit_p(PSTR("\"$D\":{\"st\":$D,\"sd\":\"$S\"}"), sid, data->type, data->sped);
}
}
bfill.emit_p(PSTR("}"));
handle_return(HTML_OK);
}
void server_change_stations_attrib(char *p, char header, byte *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);
}
}
}
/**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() {
#if defined(ESP8266)
char* p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
#else
char* p = get_buffer;
#endif
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', os.attrib_mas); // master1
server_change_stations_attrib(p, 'i', os.attrib_igrd); // ignore rain delay
server_change_stations_attrib(p, 'j', os.attrib_igs); // ignore sensor1
server_change_stations_attrib(p, 'k', os.attrib_igs2); // ignore sensor2
server_change_stations_attrib(p, 'n', os.attrib_mas2); // master2
server_change_stations_attrib(p, 'd', os.attrib_dis); // disable
server_change_stations_attrib(p, 'q', os.attrib_seq); // sequential
server_change_stations_attrib(p, 'p', os.attrib_spe); // 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)) {
tmp_buffer[0]-='0';
tmp_buffer[STATION_SPECIAL_DATA_SIZE] = 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 (byte 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 defined(ESP8266) // ESP8266 performs automatic decoding so no need to do it again
if(m_server) urlDecode(tmp_buffer + 1);
#else
urlDecode(tmp_buffer + 1);
#endif
if (strlen(tmp_buffer+1) > sizeof(HTTPStationData)) {
handle_return(HTML_DATA_OUTOFBOUND);
}
}
// write spe data
file_write_block(STATIONS_FILENAME, tmp_buffer,
(uint32_t)sid*sizeof(StationData)+offsetof(StationData,type), STATION_SPECIAL_DATA_SIZE+1);
} else {
handle_return(HTML_DATA_MISSING);
}
}
os.attribs_save();
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() {
#if defined(ESP8266)
char* p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
#else
char *p = get_buffer;
#endif
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() {
#if defined(ESP8266)
char* p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
if(!findKeyVal(p,tmp_buffer,TMP_BUFFER_SIZE, "t", false)) handle_return(HTML_DATA_MISSING);
char *pv = tmp_buffer+1;
#else
char *p = get_buffer;
// decode url first
if(p) urlDecode(p);
// search for the start of t=[
char *pv;
boolean found=false;
for(pv=p;(*pv)!=0 && pv<p+100;pv++) {
if(strncmp(pv, "t=[", 3)==0) {
found=true;
break;
}
}
if(!found) handle_return(HTML_DATA_MISSING);
pv+=3;
#endif
// 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.attrib_dis[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() {
#if defined(ESP8266)
char *p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
#else
char *p = get_buffer;
#endif
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() {
#if defined(ESP8266)
char *p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
#else
char *p = get_buffer;
#endif
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() {
#if defined(ESP8266)
char *p = NULL;
if(!process_password()) return;
if (m_client)
p = get_buffer;
#else
char *p = get_buffer;
#endif
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 defined(ESP8266)
if(!findKeyVal(p,tmp_buffer,TMP_BUFFER_SIZE, "v",false)) handle_return(HTML_DATA_MISSING);
char *pv = tmp_buffer+1;
#else
// parse ad-hoc v=[...
// search for the start of v=[
char *pv;
boolean found=false;
for(pv=p;(*pv)!=0 && pv<p+100;pv++) {
if(strncmp(pv, "v=[", 3)==0) {
found=true;
break;
}
}
if(!found) handle_return(HTML_DATA_MISSING);
pv+=3;
#endif
// 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_IOPTS;oid++) {
#if !defined(ARDUINO) // do not send the following parameters for non-Arduino platforms
if (oid==IOPT_USE_NTP || oid==IOPT_USE_DHCP ||
(oid>=IOPT_STATIC_IP1 && oid<=IOPT_STATIC_IP4) ||
(oid>=IOPT_GATEWAY_IP1 && oid<=IOPT_GATEWAY_IP4) ||
(oid>=IOPT_DNS_IP1 && oid<=IOPT_DNS_IP4) ||
(oid>=IOPT_SUBNET_MASK1 && oid<=IOPT_SUBNET_MASK4))
continue;
#endif
#if !defined(ESP8266)
// so far only OS3.x has sensor2
if (oid==IOPT_SENSOR2_TYPE || oid==IOPT_SENSOR2_OPTION || oid==IOPT_SENSOR2_ON_DELAY || oid==IOPT_SENSOR2_OFF_DELAY)
continue;
#endif
int32_t v=os.iopts[oid];
if (oid==IOPT_MASTER_OFF_ADJ || oid==IOPT_MASTER_OFF_ADJ_2 ||
oid==IOPT_MASTER_ON_ADJ || oid==IOPT_MASTER_ON_ADJ_2 ||
oid==IOPT_STATION_DELAY_TIME) {
v=water_time_decode_signed(v);
}
#if defined(ARDUINO)
if (oid==IOPT_BOOST_TIME) {
if (os.hw_type==HW_TYPE_AC || os.hw_type==HW_TYPE_UNKNOWN) continue;
else v<<=2;
}
#else
if (oid==IOPT_BOOST_TIME) continue;
#endif
#if defined(ESP8266)
if (oid==IOPT_HW_VERSION) {
v+=os.hw_rev; // for OS3.x, add hardware revision number
}
#endif