-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cpp
1631 lines (1476 loc) · 45.2 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 ([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 "OpenSprinkler.h"
#include "program.h"
// External variables defined in main ion file
#if defined(ARDUINO)
#include "SdFat.h"
extern SdFat sd;
static uint8_t ntpclientportL = 123; // Default NTP client port
extern ulong flow_count;
#else
#include <stdarg.h>
#include <stdlib.h>
#include "etherport.h"
#include "server.h"
extern char ether_buffer[];
extern EthernetClient *m_client;
#endif
extern BufferFiller bfill;
extern char tmp_buffer[];
extern OpenSprinkler os;
extern ProgramData pd;
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);
int available_ether_buffer();
// 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_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"
;
#if defined(ARDUINO)
void print_html_standard_header() {
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentHTML, htmlNoCache, htmlAccessControl);
}
void print_json_header(bool bracket=true) {
bfill.emit_p(PSTR("$F$F$F$F\r\n"), html200OK, htmlContentJSON, htmlAccessControl, htmlNoCache);
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;
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++;
}
*strbuf='\0';
}
// return the length of the value
if (keyfound) *keyfound = found;
return(i);
}
void rewind_ether_buffer() {
bfill = ether.tcpOffset();
}
void send_packet(bool final=false) {
if(final) {
ether.httpServerReply_with_flags(bfill.position(), TCP_FLAGS_ACK_V|TCP_FLAGS_FIN_V);
} else {
ether.httpServerReply_with_flags(bfill.position(), TCP_FLAGS_ACK_V);
bfill=ether.tcpOffset();
}
}
/* Check available space (number of bytes) in the Ethernet buffer */
int available_ether_buffer() {
return ETHER_BUFFER_SIZE - (int)bfill.position();
}
#else
void print_html_standard_header() {
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);
}
void print_json_header(bool bracket=true) {
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);
}
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;
uint8_t i=0;
const char *kp;
kp=key;
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++;
}
*strbuf='\0';
}
// return the length of the value
if (keyfound) *keyfound = found;
return(i);
}
void BufferFiller::emit_p(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
for (;;) {
char c = *fmt++;
if (c == 0)
break;
if (c != '$') {
*ptr++ = c;
continue;
}
c = *fmt++;
switch (c) {
case 'D':
itoa(va_arg(ap, int), (char*) ptr, 10); // ray
break;
case 'L':
ultoa(va_arg(ap, long), (char*) ptr, 10); // ray
break;
case 'S':
case 'F':
strcpy((char*) ptr, va_arg(ap, const char*));
break;
case 'E': {
byte* s = va_arg(ap, byte*);
char d;
while ((d = nvm_read_byte(s++)) != 0)
*ptr++ = d;
continue;
}
default:
*ptr++ = c;
continue;
}
ptr += strlen((char*) ptr);
}
*(ptr)=0;
va_end(ap);
}
void rewind_ether_buffer() {
bfill = ether_buffer;
}
void send_packet(bool final=false) {
m_client->write((const uint8_t *)ether_buffer, strlen(ether_buffer));
if (final)
m_client->stop();
else
rewind_ether_buffer();
}
int available_ether_buffer() {
return ETHER_BUFFER_SIZE - (int)bfill.position();
}
#endif
/** 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)
{
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';
}
/** Check and verify password */
boolean check_password(char *p)
{
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;
}
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);
#if defined(ARDUINO) // only output stn_spe if it's supported
if (os.status.has_sd) {
server_json_stations_attrib(PSTR("stn_spe"), ADDR_NVM_STNSPE);
}
#else
server_json_stations_attrib(PSTR("stn_spe"), ADDR_NVM_STNSPE);
#endif
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);
delay(1);
}
/** Output stations data */
byte server_json_stations(char *p) {
print_json_header();
server_json_stations_main();
return HTML_OK;
}
/** Output station special attribute */
byte server_json_station_special(char *p) {
#if defined(ARDUINO)
// if no sd card, return false
if (!os.status.has_sd) return HTML_PAGE_NOT_FOUND;
#endif
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("}"));
delay(1);
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
*/
byte server_change_stations(char *p)
{
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
#if defined(ARDUINO) // only parse station special bits if it's supported
if(os.status.has_sd) {
server_change_stations_attrib(p, 'p', ADDR_NVM_STNSPE); // special
}
#else
server_change_stations_attrib(p, 'p', ADDR_NVM_STNSPE); // special
#endif
/* handle special data */
if(findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("sid"), true)) {
sid = atoi(tmp_buffer);
if(sid<0 || sid>os.nstations) 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;
#if !defined(ARDUINO) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
// only process GPIO and HTTP stations for OS 2.3 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) return HTML_DATA_OUTOFBOUND;
} else if (tmp_buffer[0] == STN_TYPE_HTTP) {
urlDecode(tmp_buffer + 1); // Unwind any url encoding of special data
if (strlen(tmp_buffer+1) > sizeof(HTTPStationData)) {
return HTML_DATA_OUTOFBOUND;
}
}
#endif
write_to_file(stns_filename, tmp_buffer, strlen(tmp_buffer)+1, stepsize*sid, false);
} else {
return HTML_DATA_MISSING;
}
}
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)
*/
byte server_manual_program(char *p) {
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true))
return HTML_DATA_MISSING;
int pid=atoi(tmp_buffer);
if (pid < 0 || pid >= pd.nprograms) {
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);
return HTML_SUCCESS;
}
/**
* Change run-once program
* Command: /cr?pw=xxx&t=[x,x,x...]
*
* pw: password
* t: station water time
*/
byte server_change_runonce(char *p) {
// decode url first
urlDecode(p);
// search for the start of v=[
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) return HTML_DATA_MISSING;
pv+=3;
// 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());
return HTML_SUCCESS;
}
return HTML_DATA_MISSING;
}
/**
* Delete a program
* Command: /dp?pw=xxx&pid=xxx
*
* pw: password
* pid:program index (-1 will delete all programs)
*/
byte server_delete_program(char *p) {
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true))
return HTML_DATA_MISSING;
int pid=atoi(tmp_buffer);
if (pid == -1) {
pd.eraseall();
} else if (pid < pd.nprograms) {
pd.del(pid);
} else {
return HTML_DATA_OUTOFBOUND;
}
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)
*/
byte server_moveup_program(char *p) {
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true)) {
return HTML_DATA_MISSING;
}
int pid=atoi(tmp_buffer);
if (!(pid>=1 && pid< pd.nprograms)) return HTML_DATA_OUTOFBOUND;
pd.moveup(pid);
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 ";
byte server_change_program(char *p) {
byte i;
ProgramStruct prog;
// parse program index
if (!findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("pid"), true)) {
return HTML_DATA_MISSING;
}
int pid=atoi(tmp_buffer);
if (!(pid>=-1 && pid< pd.nprograms)) return HTML_DATA_OUTOFBOUND;
// 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
urlDecode(p);
// 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) return HTML_DATA_MISSING;
pv+=3;
// 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))
return HTML_DATA_OUTOFBOUND;
} else {
if(!pd.modify(pid, &prog))
return HTML_DATA_OUTOFBOUND;
}
return HTML_SUCCESS;
}
void server_json_options_main() {
byte oid;
for(oid=0;oid<NUM_OPTIONS;oid++) {
#if !defined(ARDUINO) // do not send the following parameters for non-Arduino platforms
if (oid==OPTION_USE_NTP || oid==OPTION_USE_DHCP ||
oid==OPTION_STATIC_IP1 || oid==OPTION_STATIC_IP2 || oid==OPTION_STATIC_IP3 || oid==OPTION_STATIC_IP4 ||
oid==OPTION_GATEWAY_IP1 || oid==OPTION_GATEWAY_IP2 || oid==OPTION_GATEWAY_IP3 || oid==OPTION_GATEWAY_IP4)
continue;
#endif
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 defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
if (oid==OPTION_BOOST_TIME) {
if (os.hw_type==HW_TYPE_AC) continue;
else v<<=2;
}
#else
if (oid==OPTION_BOOST_TIME) continue;
#endif
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 defined(ARDUINO)
if (os.lcd.type() == LCD_I2C) {
// for I2C type LCD, we can't adjust contrast or backlight
if(oid==OPTION_LCD_CONTRAST || oid==OPTION_LCD_BACKLIGHT) continue;
}
#endif
// 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}"), os.detect_exp(), MAX_EXT_BOARDS, os.hw_type);
delay(1);
}
/** Output Options */
byte server_json_options(char *p) {
print_json_header();
server_json_options_main();
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("]}"));
delay(1);
}
/** Output program data */
byte server_json_programs(char *p) {
print_json_header();
server_json_programs_main();
return HTML_OK;
}
/** Output script url form */
byte server_view_scripturl(char *p) {
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);
return HTML_OK;
}
extern ulong flow_count;
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,"
"\"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,
pd.lastrun.station,
pd.lastrun.program,
pd.lastrun.duration,
pd.lastrun.endtime);
#if defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
if(os.status.has_curr_sense) {
bfill.emit_p(PSTR("\"curr\":$D,"), os.read_current());
}
#endif
if(os.options[OPTION_SENSOR_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 !defined(ARDUINO) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
if(read_from_file(ifkey_filename, tmp_buffer)) {
bfill.emit_p(PSTR(",\"ifkey\":\"$S\""), tmp_buffer);
}
#endif
bfill.emit_p(PSTR("}"));
delay(1);
}
/** Output controller variables in json */
byte server_json_controller(char *p) {
print_json_header();
server_json_controller_main();
return HTML_OK;
}
/** Output homepage */
byte server_home()
{
print_html_standard_header();
bfill.emit_p(PSTR("<!DOCTYPE html>\n<html>\n<head>\n$F</head>\n<body>\n<script>"), htmlMobileHeader);
// send server variables and javascript packets
bfill.emit_p(PSTR("var ver=$D,ipas=$D;</script>\n"),
OS_FW_VERSION, os.options[OPTION_IGNORE_PASSWORD]);
bfill.emit_p(PSTR("<script src=\"$E/home.js\"></script>\n</body>\n</html>"), ADDR_NVM_JAVASCRIPTURL);
return HTML_OK;
}
/**
* Change controller variables
* Command: /cv?pw=xxx&rsn=x&rbt=x&en=x&rd=x&sl=x
*
* pw: password
* rsn: reset all stations (0 or 1)
* rbt: reboot controller (0 or 1)
* en: enable (0 or 1)
* rd: rain delay hours (0 turns off rain delay)
* re: remote extension mode
* update: launch update script (for OSPi/OSBo/Linux only)
*/
byte server_change_values(char *p)
{
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("rsn"), true)) {
reset_all_stations();
}
#ifndef ARDUINO
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("update"), true) && atoi(tmp_buffer) > 0) {
//bfill.emit_p(PSTR("Updating..."));
os.update_dev();
}
#endif
#define TIME_REBOOT_DELAY 20
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("rbt"), true) && atoi(tmp_buffer) > 0) {
print_html_standard_header();
//bfill.emit_p(PSTR("Rebooting..."));
send_packet(true);
os.reboot_dev();
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("en"), true)) {
if (tmp_buffer[0]=='1' && !os.status.enabled) os.enable();
else if (tmp_buffer[0]=='0' && os.status.enabled) os.disable();
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("rd"), true)) {
int rd = atoi(tmp_buffer);
if (rd>0) {
os.nvdata.rd_stop_time = os.now_tz() + (unsigned long) rd * 3600;
os.raindelay_start();
} else if (rd==0){
os.raindelay_stop();
} else return HTML_DATA_OUTOFBOUND;