-
Notifications
You must be signed in to change notification settings - Fork 288
/
opensprinkler_server.cpp
2444 lines (2204 loc) · 66.7 KB
/
opensprinkler_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 ([email protected])
*
* 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 "types.h"
#include "OpenSprinkler.h"
#include "program.h"
#include "opensprinkler_server.h"
#include "weather.h"
#include "mqtt.h"
#include "main.h"
// External variables defined in main ion file
#if defined(USE_OTF)
extern OTF::OpenThingsFramework *otf;
#define OTF_PARAMS_DEF const OTF::Request &req,OTF::Response &res
#define OTF_PARAMS req,res
#define FKV_SOURCE req
#define handle_return(x) {if(x==HTML_OK) res.writeBodyData(ether_buffer, strlen(ether_buffer)); else otf_send_result(req,res,x); return;}
#else
extern EthernetClient *m_client;
#define OTF_PARAMS_DEF
#define OTF_PARAMS
#define FKV_SOURCE p
#define handle_return(x) {return_code=x; return;}
#endif
#if defined(ARDUINO)
#if defined(ESP8266)
#include <FS.h>
#include <LittleFS.h>
#include "espconnect.h"
extern ESP8266WebServer *update_server;
extern ENC28J60lwIP enc28j60;
extern Wiznet5500lwIP w5500;
extern lwipEth eth;
#else
#include "SdFat.h"
extern SdFat sd;
#endif
#else
#include <stdarg.h>
#include <stdlib.h>
#include "etherport.h"
#endif
extern char ether_buffer[];
extern char tmp_buffer[];
extern OpenSprinkler os;
extern ProgramData pd;
extern ulong flow_count;
#if !defined(USE_OTF)
static unsigned char return_code;
static char* get_buffer = NULL;
#endif
BufferFiller bfill;
/* 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
#if !defined(USE_OTF)
static const char html200OK[] PROGMEM =
"HTTP/1.1 200 OK\r\n"
;
static const char htmlNoCache[] PROGMEM =
"Cache-Control: max-age=0, no-cache, no-store, must-revalidate\r\n"
;
static const char htmlContentJSON[] PROGMEM =
"Content-Type: application/json\r\n"
"Connection: close\r\n"
;
static const char htmlContentHTML[] PROGMEM =
"Content-Type: text/html\r\n"
"Connection: close\r\n"
;
static const char htmlAccessControl[] PROGMEM =
"Access-Control-Allow-Origin: *\r\n"
;
#endif
static const char htmlMobileHeader[] PROGMEM =
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no\">"
;
static const char htmlReturnHome[] PROGMEM =
"<script>window.location=\"/\";</script>\n"
;
#if defined(USE_OTF)
unsigned char findKeyVal (const OTF::Request &req,char *strbuf, uint16_t maxlen,const char *key,bool key_in_pgm=false,uint8_t *keyfound=NULL) {
#if defined(ARDUINO)
char* result = key_in_pgm ? req.getQueryParameter((const __FlashStringHelper *)key) : req.getQueryParameter(key);
#else
char* result = req.getQueryParameter(key);
#endif
if(result!=NULL) {
strncpy(strbuf, result, maxlen);
strbuf[maxlen-1]=0;
if(keyfound) *keyfound=1;
return strlen(strbuf);
} else {
if(keyfound) *keyfound=0;
}
return 0;
}
#endif
unsigned char 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;
uint16_t i=0;
const char *kp;
if(str==NULL||strbuf==NULL||key==NULL) {return 0;}
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 = BufferFiller(ether_buffer, ETHER_BUFFER_SIZE*2);
ether_buffer[0] = 0;
}
void send_packet(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
res.writeBodyData(ether_buffer, strlen(ether_buffer));
#else
m_client->write((const uint8_t *)ether_buffer, strlen(ether_buffer));
#endif
rewind_ether_buffer();
}
char dec2hexchar(unsigned char dec) {
if(dec<10) return '0'+dec;
else return 'A'+(dec-10);
}
#if defined(USE_OTF)
void print_header(OTF_PARAMS_DEF, bool isJson=true, int len=0) {
res.writeStatus(200, F("OK"));
res.writeHeader(F("Content-Type"), isJson?F("application/json"):F("text/html"));
if(len>0)
res.writeHeader(F("Content-Length"), len);
res.writeHeader(F("Access-Control-Allow-Origin"), F("*"));
res.writeHeader(F("Cache-Control"), F("max-age=0, no-cache, no-store, must-revalidate"));
res.writeHeader(F("Connection"), F("close"));
}
#else
void print_header(bool isJson=true) {
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, isJson?htmlContentJSON:htmlContentHTML, htmlAccessControl, htmlNoCache);
}
#endif
#if defined(USE_OTF)
#if !defined(ARDUINO)
string two_digits(uint8_t x) {
return std::to_string(x);
}
#else
String two_digits(uint8_t x) {
return String(x/10) + (x%10);
}
#endif
String toHMS(ulong t) {
return two_digits(t/3600)+":"+two_digits((t/60)%60)+":"+two_digits(t%60);
}
void otf_send_result(OTF_PARAMS_DEF, unsigned char code, const char *item = NULL) {
String json = F("{\"result\":");
#if defined(ARDUINO)
json += code;
#else
json += std::to_string(code);
#endif
if (!item) item = "";
json += F(",\"item\":\"");
json += item;
json += F("\"");
json += F("}");
print_header(OTF_PARAMS, true, json.length());
res.writeBodyChunk((char *)"%s",json.c_str());
}
#if defined(ESP8266)
void update_server_send_result(unsigned char code, const char* item = NULL) {
String json = F("{\"result\":");
json += code;
if (!item) item = "";
json += F(",\"item\":\"");
json += item;
json += F("\"");
json += F("}");
update_server->sendHeader("Access-Control-Allow-Origin", "*"); // from esp8266 2.4 this has to be sent explicitly
update_server->send(200, "application/json", json);
}
String get_ap_ssid() {
static String ap_ssid;
if(!ap_ssid.length()) {
unsigned char mac[6];
WiFi.macAddress(mac);
ap_ssid = "OS_";
for(unsigned char 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(OTF_PARAMS_DEF) {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
print_header(OTF_PARAMS, false, strlen_P((char*)ap_home_html));
res.writeBodyChunk((char *) "%s", ap_home_html);
}
void on_ap_scan(OTF_PARAMS_DEF) {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
print_header(OTF_PARAMS, true, scanned_ssids.length());
res.writeBodyChunk((char *)"%s",scanned_ssids.c_str());
}
void on_ap_change_config(OTF_PARAMS_DEF) {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
char *ssid = req.getQueryParameter("ssid");
if(ssid!=NULL&&strlen(ssid)!=0) {
os.wifi_ssid = ssid;
os.wifi_pass = req.getQueryParameter("pass");
char *extra = req.getQueryParameter("extra");
if(extra!=NULL) { // bssid and channel are in the format of xx:xx:xx:xx:xx:xx@ch
char *mac = strchr(extra, '@'); // search for symbol @
if(mac==NULL || !isValidMAC(extra)) { // if not found or if MAC is invalid
otf_send_result(OTF_PARAMS, HTML_DATA_FORMATERROR, "bssid");
return;
}
int chl = atoi(mac+1); // convert ch to integer
if(!(chl>=0 && chl<=255)) { // chl must be less than 255
otf_send_result(OTF_PARAMS, HTML_DATA_OUTOFBOUND, "channel");
return;
}
os.sopt_save(SOPT_STA_BSSID_CHL, extra); // save string to flash first
*mac=0; // terminate bssid string
str2mac(extra, os.wifi_bssid); // update controller variables
os.wifi_channel = chl;
} else {
os.sopt_save(SOPT_STA_BSSID_CHL, DEFAULT_EMPTY_STRING); // if extra is not present, write empty string
}
os.sopt_save(SOPT_STA_SSID, os.wifi_ssid.c_str());
os.sopt_save(SOPT_STA_PASS, os.wifi_pass.c_str());
otf_send_result(OTF_PARAMS, HTML_SUCCESS, nullptr);
os.state = OS_STATE_TRY_CONNECT;
os.lcd.setCursor(0, 2);
os.lcd.print(F("Connecting..."));
} else {
otf_send_result(OTF_PARAMS, HTML_DATA_MISSING, "ssid");
}
}
void reboot_in(uint32_t ms);
void on_ap_try_connect(OTF_PARAMS_DEF) {
if(os.get_wifi_mode()!=WIFI_MODE_AP) return;
String json = "{";
json += F("\"ip\":");
json += (WiFi.status() == WL_CONNECTED) ? (uint32_t)WiFi.localIP() : 0;
json += F("}");
print_header(OTF_PARAMS,true,json.length());
res.writeBodyChunk((char *)"%s",json.c_str());
if(WiFi.status() == WL_CONNECTED && WiFi.localIP()) {
os.iopts[IOPT_WIFI_MODE] = WIFI_MODE_STA;
os.iopts_save();
DEBUG_PRINTLN(F("IP received by client, restart."));
reboot_in(1000);
}
}
#endif
#endif
/** Check and verify password */
#if defined(USE_OTF)
boolean check_password(char *p) {
return true;
}
boolean process_password(OTF_PARAMS_DEF, boolean fwv_on_fail=false)
#else
boolean check_password(char *p)
#endif
{
#if defined(DEMO)
return true;
#endif
if (os.iopts[IOPT_IGNORE_PASSWORD]) return true;
#if !defined(USE_OTF)
if (m_client && !p) {
p = get_buffer;
}
if (findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pw"), true)) {
urlDecode(tmp_buffer);
if (os.password_verify(tmp_buffer)) return true;
}
#else
/*if(req.isCloudRequest()){ // password is not required if this is coming from cloud connection
return true;
}*/
const char *pw = req.getQueryParameter("pw");
if(pw != NULL && os.password_verify(pw)) return true;
/* if fwv_on_fail is true, output fwv if password check has failed */
if(fwv_on_fail) {
rewind_ether_buffer();
bfill.emit_p(PSTR("{\"$F\":$D}"), iopt_json_names+0, os.iopts[0]);
print_header(OTF_PARAMS,true,strlen(ether_buffer));
res.writeBodyChunk((char *)"%s",ether_buffer);
} else {
otf_send_result(OTF_PARAMS, HTML_UNAUTHORIZED);
}
#endif
return false;
}
void server_json_board_attrib(const char* name, unsigned char *attrib)
{
bfill.emit_p(PSTR("\"$F\":["), name);
for(unsigned char 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_attrib(const char* name, unsigned char *attrib)
{
bfill.emit_p(PSTR("\"$F\":["), name);
for(unsigned char bid=0;bid<os.nboards;bid++) {
for (unsigned char s = 0; s < 8; s++) {
bfill.emit_p(PSTR("$D"), attrib[bid * 8 + s]);
if(bid != os.nboards-1 || s < 7) {
bfill.emit_p(PSTR(","));
}
}
}
bfill.emit_p(PSTR("],"));
}
void server_json_stations_main(OTF_PARAMS_DEF) {
server_json_board_attrib(PSTR("masop"), os.attrib_mas);
server_json_board_attrib(PSTR("masop2"), os.attrib_mas2);
server_json_board_attrib(PSTR("ignore_rain"), os.attrib_igrd);
server_json_board_attrib(PSTR("ignore_sn1"), os.attrib_igs);
server_json_board_attrib(PSTR("ignore_sn2"), os.attrib_igs2);
server_json_board_attrib(PSTR("stn_dis"), os.attrib_dis);
server_json_board_attrib(PSTR("stn_spe"), os.attrib_spe);
server_json_stations_attrib(PSTR("stn_grp"), os.attrib_grp);
bfill.emit_p(PSTR("\"snames\":["));
unsigned char 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() <=0 ) {
send_packet(OTF_PARAMS);
}
}
bfill.emit_p(PSTR("],\"maxlen\":$D}"), STATION_NAME_SIZE);
}
/** Output stations data */
void server_json_stations(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
rewind_ether_buffer();
print_header(OTF_PARAMS);
#else
print_header();
#endif
bfill.emit_p(PSTR("{"));
server_json_stations_main(OTF_PARAMS);
handle_return(HTML_OK);
}
/** Output station special attribute */
void server_json_station_special(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
rewind_ether_buffer();
print_header(OTF_PARAMS);
#else
print_header();
#endif
unsigned char sid;
unsigned char comma=0;
StationData *data = (StationData*)tmp_buffer;
bfill.emit_p(PSTR("{"));
for(sid=0;sid<os.nstations;sid++) {
unsigned char bid=sid>>3,s=sid&0x07;
if(os.attrib_spe[bid]&(1<<s)) { // 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);
}
if (available_ether_buffer() <=0 ) {
send_packet(OTF_PARAMS);
}
}
bfill.emit_p(PSTR("}"));
handle_return(HTML_OK);
}
#if defined(USE_OTF)
void server_change_board_attrib(const OTF::Request &req, char header, unsigned char *attrib)
#else
void server_change_board_attrib(char *p, char header, unsigned char *attrib)
#endif
{
char tbuf2[5] = {0, 0, 0, 0, 0};
unsigned char bid;
tbuf2[0]=header;
for(bid=0;bid<os.nboards;bid++) {
snprintf(tbuf2+1, 3, "%d", bid);
if(findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, tbuf2)) {
attrib[bid] = atoi(tmp_buffer);
}
}
}
#if defined(USE_OTF)
void server_change_stations_attrib(const OTF::Request &req, char header, unsigned char *attrib)
#else
void server_change_stations_attrib(char *p, char header, unsigned char *attrib)
#endif
{
char tbuf2[6] = {0, 0, 0, 0, 0, 0};
unsigned char bid, s, sid;
tbuf2[0]=header;
for(bid=0;bid<os.nboards;bid++) {
for(s=0;s<8;s++) {
sid=bid*8+s;
snprintf(tbuf2+1, 3, "%d", sid);
if (findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, tbuf2)) {
attrib[sid] = 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 sequential bit field
* p?: station special flag bit field
* g?: sequential group id
*/
void server_change_stations(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
#else
char* p = get_buffer;
#endif
unsigned char sid;
char tbuf2[5] = {'s', 0, 0, 0, 0};
// process station names
for(sid=0;sid<os.nstations;sid++) {
snprintf(tbuf2+1, 3, "%d", sid);
if(findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, tbuf2)) {
urlDecode(tmp_buffer);
strReplace(tmp_buffer, '\"', '\'');
strReplace(tmp_buffer, '\\', '/');
os.set_station_name(sid, tmp_buffer);
}
}
server_change_board_attrib(FKV_SOURCE, 'm', os.attrib_mas); // master1
server_change_board_attrib(FKV_SOURCE, 'i', os.attrib_igrd); // ignore rain delay
server_change_board_attrib(FKV_SOURCE, 'j', os.attrib_igs); // ignore sensor1
server_change_board_attrib(FKV_SOURCE, 'k', os.attrib_igs2); // ignore sensor2
server_change_board_attrib(FKV_SOURCE, 'n', os.attrib_mas2); // master2
server_change_board_attrib(FKV_SOURCE, 'd', os.attrib_dis); // disable
server_change_stations_attrib(FKV_SOURCE, 'g', os.attrib_grp); // sequential groups
/* handle special data */
if(findKeyVal(FKV_SOURCE, 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(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, PSTR("st"), true) &&
findKeyVal(FKV_SOURCE, tmp_buffer+1, TMP_BUFFER_SIZE-1, PSTR("sd"), true)) {
tmp_buffer[0]-='0';
tmp_buffer[STATION_SPECIAL_DATA_SIZE] = 0;
if(tmp_buffer[0] == STN_TYPE_GPIO) {
// check that pin does not clash with OSPi pins
unsigned char gpio = (tmp_buffer[1] - '0') * 10 + tmp_buffer[2] - '0';
unsigned char activeState = tmp_buffer[3] - '0';
unsigned char gpioList[] = PIN_FREE_LIST;
bool found = false;
for (unsigned char 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) || (tmp_buffer[0] == STN_TYPE_HTTPS) || (tmp_buffer[0] == STN_TYPE_REMOTE_OTC)) {
#if !defined(ESP8266) // ESP8266 does automatic decoding
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);
}
}
// handle special attribute after parameters have been processed
server_change_board_attrib(FKV_SOURCE, 'p', os.attrib_spe);
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(unsigned char, unsigned char);
/** 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(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
#else
char *p = get_buffer;
#endif
if (!findKeyVal(FKV_SOURCE, 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);
}
unsigned char uwt = 0;
if (findKeyVal(FKV_SOURCE, 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(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
if(!findKeyVal(FKV_SOURCE,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();
unsigned char 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(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
#else
char *p = get_buffer;
#endif
if (!findKeyVal(FKV_SOURCE, 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(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
#else
char *p = get_buffer;
#endif
if (!findKeyVal(FKV_SOURCE, 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&from=x&to=x
*
* pw: password
* pid: program index
* flag: program flag
* start?:up to 4 start times
* dur?: station water time
* name: program name
* from: start date of the program: an integer that's (month*32+day)
* to: end date of the program, same format as from
*/
const char _str_program[] PROGMEM = "Program ";
void server_change_program(OTF_PARAMS_DEF) {
#if defined(USE_OTF)
if(!process_password(OTF_PARAMS)) return;
#else
char *p = get_buffer;
#endif
unsigned char i;
ProgramStruct prog;
// parse program index
if (!findKeyVal(FKV_SOURCE, 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(FKV_SOURCE, 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(FKV_SOURCE, 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(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, PSTR("name"), true)) {
urlDecode(tmp_buffer);
strReplace(tmp_buffer, '\"', '\'');
strReplace(tmp_buffer, '\\', '/');
strncpy(prog.name, tmp_buffer, PROGRAM_NAME_SIZE);
} else {
strcpy_P(prog.name, _str_program);
snprintf(prog.name+8, PROGRAM_NAME_SIZE - 8, "%d", (pid==-1)? (pd.nprograms+1): (pid+1));
}
// parse program start date and end date
if (findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, PSTR("from"), true)) {
int16_t date = atoi(tmp_buffer);
if(!isValidDate(date)) handle_return(HTML_DATA_OUTOFBOUND);
prog.daterange[0] = date;
if (findKeyVal(FKV_SOURCE, tmp_buffer, TMP_BUFFER_SIZE, PSTR("to"), true)) {
date = atoi(tmp_buffer);
if(!isValidDate(date)) handle_return(HTML_DATA_OUTOFBOUND);
prog.daterange[1] = date;
} else {
handle_return(HTML_DATA_MISSING);
}
}
#if !defined(USE_OTF)
if(p) urlDecode(p);
#endif
#if defined(USE_OTF)
if(!findKeyVal(FKV_SOURCE,tmp_buffer,TMP_BUFFER_SIZE, "v",false)) handle_return(HTML_DATA_MISSING);
char *pv = tmp_buffer+1;
// TODO: may need a urlDecode for non-ESP platforms
#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);
if (prog.type == PROGRAM_TYPE_INTERVAL) {
if (prog.days[1] == 0) handle_return(HTML_DATA_OUTOFBOUND)
else if (prog.days[1] >= 1) {
// process interval day remainder (relative-> absolute)
pd.drem_to_absolute(prog.days);
}
}
// 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
}
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() {
unsigned char 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) ||
(oid==IOPT_FORCE_WIRED))
continue;
#endif
#if !(defined(ESP8266) || defined(PIN_SENSOR2))
// only OS 3.x or controllers that have PIN_SENSOR2 defined support sensor 2 options
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
if (oid==IOPT_SEQUENTIAL_RETIRED || oid==IOPT_URS_RETIRED || oid==IOPT_RSO_RETIRED) continue;
#if defined(ARDUINO)
#if defined(ESP8266)
// for SSD1306, we can't adjust contrast or backlight
if(oid==IOPT_LCD_CONTRAST || oid==IOPT_LCD_BACKLIGHT) continue;
#else
if (os.lcd.type() == LCD_I2C) {
// for I2C type LCD, we can't adjust contrast or backlight
if(oid==IOPT_LCD_CONTRAST || oid==IOPT_LCD_BACKLIGHT) continue;
}
#endif
#else
// for Linux-based platforms, there is no LCD currently
if(oid==IOPT_LCD_CONTRAST || oid==IOPT_LCD_BACKLIGHT || oid==IOPT_LCD_DIMMING) continue;
#endif