-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1356 lines (1285 loc) · 40.2 KB
/
main.c
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
/*********************************************
* Author: Tim Dorssers
*
* This software implements a NTP synchronized clock with two classic HDLX2416
* LED matrix displays and a DHT11 temperature and humidity sensor. Dynamic IP
* address assignment is done using DHCP. DNS lookup is used for NTP host name
* resolution. It is configurable via a built-in web server that implements GET
* and POST methods and HTTP basic authentication. Web configurable parameters
* are stored in EEPROM. At Ethernet link up, an IP address is obtained and
* displayed for 30 seconds in which ARP, DNS and NTP are executed. If one of
* those fails, the clock is reinitialized after that time. The modified DHCP
* client retries obtaining the initial IP at exponential increasing intervals
* and renews the address lease at half lease time, at 12.5% of the lease time
* increasing intervals. Standard AVR Libc time keeping functions are used.
* The highest and lowest temperature and humidity is recorded in RAM with time
* stamps. Useful log messages are sent to the UART.
*
* It uses a modified version of Guido Socher's TCP/IP stack, with changes to:
* - enc28j60.c
* - dhcp_client.c
* - dnslkup.c
* - websrv_help_functions.c
*
* You need to define F_CPU as a symbol to gcc eg. -DF_CPU=7372800
*
* Copyright: GPL V2
* See http://www.gnu.org/licenses/gpl.html
*
* Chip type : Atmega328 with ENC28J60
*********************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/eeprom.h>
#include <avr/wdt.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include "ip_arp_udp_tcp.h"
#include "websrv_help_functions.h"
#include "enc28j60.h"
#include "dhcp_client.h"
#include "dnslkup.h"
#include "hdlx2416.h"
#include "uart.h"
#include "dht.h"
// Board MAC address
static uint8_t mymac[6] = {0x54,0x10,0xEC,0x00,0x28,0x60};
// Time zone in minutes offset to UTC
int16_t mins_offset_to_utc = 60;
// Enable daylight saving time for EU
static uint8_t enable_eu_dst = 1;
// NTP Host name
#define HOSTNAME_SIZE 24
static char ntphostname[HOSTNAME_SIZE+1] = "time.apple.com";
// Config web page password
#define PASSWORD_SIZE 16
static char password[PASSWORD_SIZE+1] = "secret";
// NTP Update period in seconds
static uint16_t ntp_update_period = 3600;
// NTP IP (DNS will provide a value for it):
static uint8_t ntpip[4];
// DNS (DHCP will provide a value for it):
static uint8_t mydns[4];
// My own IP (DHCP will provide a value for it):
static uint8_t myip[4];
// Default gateway (DHCP will provide a value for it):
static uint8_t gwip[4];
// Net mask (DHCP will provide a value for it):
static uint8_t netmask[4];
// ARP resolving:
#define TRANS_NUM_NTPMAC 1
#define TRANS_NUM_DNSMAC 2
static uint8_t ntproutingmac[6];
static uint8_t dnsroutingmac[6];
// state vars:
static uint8_t have_ntp_mac=0;
static uint8_t have_dns_mac=0;
static int8_t init_state=-1; // 0=link up, 1=initial IP assignment, 2=resolve arps, 3=dns lookup, 4=ready for ntp req, 5=running
static uint8_t dns_state=0; // 0=pending, 1=started, 2=finished
static uint8_t ntp_state=0; // 0=never sent a ntp req, 1=have time, 2=request sent no answer yet
// global string buffer
#define STR_BUFFER_SIZE 32
static char gStrbuf[STR_BUFFER_SIZE+1];
// NTP:
static uint8_t ntpclientportL; // lower 8 bytes of local port number
static uint8_t ntp_retry_count=0;
static time_t start_t; // time of last ntp update
static uint8_t display_24hclock=1;
static uint8_t alarm_hour=0;
static uint8_t alarm_min=0;
static uint8_t alarm_enabled=0;
// timer:
static volatile uint8_t display_update_pending=0;
static volatile uint8_t delay_sec=0;
static volatile uint8_t dht_delay_sec=0;
static volatile uint8_t uptime_sec=0;
static volatile uint8_t uptime_min=0;
static volatile uint8_t uptime_hour=0;
static volatile uint16_t uptime_day=0;
// eth/ip buffer:
#define BUFFER_SIZE 808
static uint8_t buf[BUFFER_SIZE+1];
static uint16_t dat_p;
// Display:
static uint8_t intensity=4;
const char PROGMEM intensity0[]={">100%"};
const char PROGMEM intensity1[]={">60%"};
const char PROGMEM intensity2[]={">40%"};
const char PROGMEM intensity3[]={">27%"};
const char PROGMEM intensity4[]={">17%"};
const char PROGMEM intensity5[]={">10%"};
const char PROGMEM intensity6[]={">7%"};
const char PROGMEM intensity7[]={">3%"};
PGM_P const PROGMEM intensities[8]={intensity0,intensity1,intensity2,intensity3,intensity4,intensity5,intensity6,intensity7};
// DHT:
static uint8_t display_temperature=1;
static int8_t temperature;
static int8_t humidity;
static time_t low_temp_t;
static time_t high_temp_t;
static time_t low_hum_t;
static time_t high_hum_t;
static int8_t low_temp=127;
static int8_t low_hum=127;
static int8_t high_temp=0;
static int8_t high_hum=0;
// EEPROM:
uint8_t EEMEM nv_magic_number_config;
uint8_t EEMEM nv_ntpip[4];
uint8_t EEMEM nv_password[PASSWORD_SIZE+1];
uint8_t EEMEM nv_enable_eu_dst;
uint8_t EEMEM nv_display_24hclock;
uint16_t EEMEM nv_mins_offset_to_utc;
uint8_t EEMEM nv_ntphostname[HOSTNAME_SIZE+1];
uint8_t EEMEM nv_mymac[6];
uint8_t EEMEM nv_magic_number_display;
uint8_t EEMEM nv_display_temperature;
uint8_t EEMEM nv_intensity;
uint16_t EEMEM nv_ntp_update_period;
uint8_t EEMEM nv_magic_number_password;
uint8_t EEMEM nv_alarm_hour;
uint8_t EEMEM nv_alarm_min;
uint8_t EEMEM nv_alarm_enabled;
uint8_t EEMEM nv_magic_number_alarm;
// WDT:
uint8_t mcusr_mirror __attribute__ ((section (".noinit")));
// Buzzer:
#define buzzer_on() PORTC |= 1<<PINC5
#define buzzer_init() DDRC |= 1<<PINC5
#define buzzer_off() PORTC &= ~(1<<PINC5)
void __attribute__((naked)) __attribute__((section(".init3"))) get_mcusr(void)
{
mcusr_mirror = MCUSR;
MCUSR = 0;
wdt_disable();
}
// Daylight Saving function for the European Union
// From http://savannah.nongnu.org/bugs/?44327
static int eu_dst(const time_t *timer, int32_t *z)
{
uint32_t t = *timer;
if ((uint8_t)(t >> 24) >= 194) t -= 3029443200U;
t = (t + 655513200) / 604800 * 28;
if ((uint16_t)(t % 1461) < 856) return 3600;
else return 0;
}
// convert two decimal number to string with leading zero
// s must point a 3 bytes buffer minimum
static void zero_two_d(char *s, uint8_t v) {
if (v > 99) return;
if (v < 10) *s++ = '0';
itoa(v, s, 10);
}
// convert utc offset in minutes to string
// buf must point a 7 bytes buffer minimum
static void offset_to_dispstr(int16_t min_offset, char *buf) {
uint8_t min, hour;
if (min_offset < 0) {
buf[0] = '-';
min_offset = -min_offset;
} else {
buf[0] = '+';
}
min = min_offset % 60;
hour = min_offset / 60;
zero_two_d(buf + 1, hour);
buf[3] = ':';
zero_two_d(buf + 4, min);
}
// parse utc offset string to offset
// returns offset in minutes
static int16_t parse_offset(char *buf) {
int16_t min_offset;
int8_t hour;
uint8_t min = 0;
char *sep;
hour = atoi(buf);
if ((sep = strchr(buf, ':'))) {
*sep++ = '\0';
min = atoi(sep);
}
min_offset = hour * 60;
if (hour < 0) {
min_offset -= min;
} else {
min_offset += min;
}
return min_offset;
}
static void alarm_time_to_dispstr(char *buf) {
zero_two_d(buf, alarm_hour);
buf[2] = ':';
zero_two_d(buf + 3, alarm_min);
}
static void parse_alarm_time(char *str) {
char *sep;
alarm_hour = atoi(str);
if ((sep = strchr(str, ':'))) {
*sep++ = '\0';
alarm_min = atoi(sep);
}
}
// 62 bytes
static uint16_t http200ok(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n")));
}
// 59 bytes
static uint16_t http200okjs(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 200 OK\r\nContent-Type: application/x-javascript\r\n\r\n")));
}
// 43 bytes
static uint16_t http200okcss(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/css\r\n\r\n")));
}
// 47 bytes
static uint16_t http302moved(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 302 Moved Temporarily\r\nLocation: /\r\n\r\n")));
}
// 95 bytes
static uint16_t http401unauth(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 401 Unauthorized\r\nContent-Type: text/html\r\nWWW-Authenticate: Basic realm=NTP clock\r\n\r\n")));
}
// 51 bytes
static uint16_t http404notfound(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 404 Not Found\r\nContent-Type: text/html\r\n\r\n")));
}
// 63 bytes
static uint16_t http500interr(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 500 Internal Server Error\r\nContent-Type: text/html\r\n\r\n")));
}
// 57 bytes
static uint16_t http501notimpl(void){
return(fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 501 Not Implemented\r\nContent-Type: text/html\r\n\r\n")));
}
// tz.js
static uint16_t print_tzjs(void)
{
uint16_t plen;
plen=http200okjs();
// show this computers TZ offset
plen=fill_tcp_data_p(buf,plen,PSTR("\
function tzi(){\n\
var d = new Date();\n\
var tzo = -d.getTimezoneOffset();\n\
var rem = tzo % 60;\n\
var min = (\"0\" + rem).slice(-2);\n\
var hour = (\"0\" + (tzo - rem) / 60).slice(-2);\n\
var st = hour + \":\" + min;\n\
if (tzo > 0) st = \"UTC+\" + st; else st = \"UTC\" + st;\n\
document.write(\" [Info: your PC is \"+st+\"]\");\n\
}\n"));
return(plen);
}
// s.css
static uint16_t print_s1css(void) {
uint16_t plen;
plen=http200okcss();
plen=fill_tcp_data_p(buf,plen,PSTR("\
body {\n\
font-family: arial, sans-serif;\n\
}\n\
h2 {\n\
background: #4caf50;\n\
padding: 4px;\n\
color: #fff;\n\
}\n\
pre {\n\
border: 1px solid #ddd;\n\
padding: 8px;\n\
}\n\
div {\n\
width: 550px;\n\
border: 2px solid;\n\
margin: 10px auto;\n\
padding: 0 20px 10px 20px;\n\
}\n\
a {\n\
text-decoration: none;\n\
}\n\
a:hover {\n\
text-decoration: underline;\n\
}\n"));
return(plen);
}
// returns netmask length
static uint8_t get_netmask_length(uint8_t *mask){
uint8_t i,j;
uint8_t l=0;
i=0;
while(i<4){
j=0;
while(j<8){
if (mask[i] & (1<<j)){
l++;
}
j++;
}
i++;
}
return(l);
}
// prints progmem string followed by a number on the web page to the tcp send buffer
static uint16_t print_number_on_webpage(uint16_t pos, uint16_t num, const char *progmem_s) {
pos=fill_tcp_data_p(buf,pos,progmem_s);
utoa(num,gStrbuf,10);
pos=fill_tcp_data(buf,pos,gStrbuf);
return(pos);
}
// prints a number followed by a progmem string on the web page to the tcp send buffer
static uint16_t print_number_first_on_webpage(uint16_t pos, uint16_t num, const char *progmem_s) {
utoa(num,gStrbuf,10);
pos=fill_tcp_data(buf,pos,gStrbuf);
pos=fill_tcp_data_p(buf,pos,progmem_s);
return(pos);
}
// prints progmem string followed by an IP address on the web page to the tcp send buffer
static uint16_t print_ip_on_webpage(uint16_t pos, uint8_t *ip, const char *progmem_s) {
pos=fill_tcp_data_p(buf,pos,progmem_s);
mk_net_str(gStrbuf,ip,4,'.',10);
pos=fill_tcp_data(buf,pos,gStrbuf);
return(pos);
}
// prints progmem string followed by a MAC address on the web page to the tcp send buffer
static uint16_t print_mac_on_webpage(uint16_t pos, uint8_t *mac, const char *progmem_s) {
pos=fill_tcp_data_p(buf,pos,progmem_s);
mk_net_str(gStrbuf,mac,6,':',16);
pos=fill_tcp_data(buf,pos,gStrbuf);
return(pos);
}
// prints progmem string followed by a timestamp on the web page to the tcp send buffer
static uint16_t print_time_on_webpage(uint16_t pos, time_t *t, const char *progmem_s) {
struct tm *ts;
pos=fill_tcp_data_p(buf,pos,progmem_s);
ts = localtime(t);
asctime_r(ts, gStrbuf);
pos=fill_tcp_data(buf,pos,gStrbuf);
return(pos);
}
// prints the header of a web page with optional progmem string to the tcp send buffer
static uint16_t print_html_head(uint16_t pos,const char *progmem_s) {
pos=fill_tcp_data_p(buf,pos,PSTR("<!DOCTYPE html>\n<html><head><title>NTP clock</title><link rel=stylesheet href=s.css>"));
if (progmem_s) pos=fill_tcp_data_p(buf,pos,progmem_s);
pos=fill_tcp_data_p(buf,pos,PSTR("</head><body><div>"));
return(pos);
}
// prints the footer of a web page to the tcp send buffer
static uint16_t print_html_foot(uint16_t pos) {
return(fill_tcp_data_p(buf,pos,PSTR("</div></body></html>")));
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_ok(void) {
return(print_html_foot(fill_tcp_data_p(buf,print_html_head(http200ok(),NULL),PSTR("<h2>Config</h2><a href=/>OK</a>"))));
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_error(void) {
return(print_html_foot(fill_tcp_data_p(buf,print_html_head(http200ok(),NULL),PSTR("<h2>Config</h2><a href=/?pg=1>Error</a>"))));
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_authfail(void) {
return(print_html_foot(fill_tcp_data_p(buf,print_html_head(http401unauth(),NULL),PSTR("<h2>Config</h2><a href=/>Authentication Failure</a>"))));
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_config(void)
{
uint16_t plen;
plen=print_html_head(http200ok(),PSTR("<script src=tz.js></script>"));
plen=fill_tcp_data_p(buf,plen,PSTR("<h2>Config</h2><pre><form action=/cu method=post>\n<b>NTP hostname:</b>\t<input type=text name=nt value="));
plen=fill_tcp_data(buf,plen,ntphostname);
plen=print_number_on_webpage(plen,ntp_update_period,PSTR(">\n<b>Update period:</b>\t<input type=text name=up value="));
plen=print_mac_on_webpage(plen,mymac,PSTR(">\n<b>MAC address:</b>\t<input type=text name=ma value="));
plen=fill_tcp_data_p(buf,plen,PSTR(">\n<b>UTC offset:</b>\t<input type=text name=tz value="));
offset_to_dispstr(mins_offset_to_utc,gStrbuf);
plen=fill_tcp_data(buf,plen,gStrbuf);
plen=fill_tcp_data_p(buf,plen,PSTR("><script>tzi()</script>\n<b>Apply:</b>\t\t<input type=checkbox name=st"));
if (enable_eu_dst){
plen=fill_tcp_data_p(buf,plen,PSTR(" checked"));
}
plen=fill_tcp_data_p(buf,plen,PSTR(">EU DST\n<br><input type=submit value=apply> <input type=button value=cancel onclick=\"window.location='/'\"></form></pre>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_password(void) {
uint16_t plen;
plen=print_html_head(http200ok(),NULL);
plen=fill_tcp_data_p(buf,plen,PSTR("<h2>Password</h2><pre><form action=/pu method=post>\n<b>New password:</b>\t<input type=password name=pw>\n<br><input type=submit value=apply> <input type=button value=cancel onclick=\"window.location='/'\"></form></pre>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_display(void) {
uint16_t plen;
PGM_P ptr;
uint8_t i;
plen=print_html_head(http200ok(),NULL);
plen=fill_tcp_data_p(buf,plen,PSTR("<h2>Display</h2><pre><form action=/du method=post>\n<b>Show:</b>\t\t<input type=checkbox name=hh"));
if (display_24hclock){
plen=fill_tcp_data_p(buf,plen,PSTR(" checked"));
}
plen=fill_tcp_data_p(buf,plen,PSTR(">24h <input type=checkbox name=te"));
if (display_temperature){
plen=fill_tcp_data_p(buf,plen,PSTR(" checked"));
}
plen=fill_tcp_data_p(buf,plen,PSTR(">Temperature\n<b>Intensity:</b>\t<select name=in>"));
for (i=0;i<8;i++) {
plen=fill_tcp_data_p(buf,plen,PSTR("<option value="));
gStrbuf[0]='0'+i;
gStrbuf[1]='\0';
plen=fill_tcp_data(buf,plen,gStrbuf);
if (intensity==i){
plen=fill_tcp_data_p(buf,plen,PSTR(" selected"));
}
memcpy_P(&ptr, &intensities[i], sizeof(PGM_P));
plen=fill_tcp_data_p(buf,plen,ptr);
plen=fill_tcp_data_p(buf,plen,PSTR("</option>"));
}
plen=fill_tcp_data_p(buf,plen,PSTR("</select>\n<br><input type=submit value=apply> <input type=button value=cancel onclick=\"window.location='/'\"></form></pre>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_history(void) {
uint16_t plen;
plen=print_html_head(http200ok(),NULL);
plen=fill_tcp_data_p(buf,plen,PSTR("<h2>History</h2><pre><form action=/ method=get>\n"));
plen=print_number_on_webpage(plen,high_temp,PSTR("<b>Highest Temperature:</b>\t"));
plen=print_time_on_webpage(plen,&high_temp_t,PSTR(" °C @ "));
plen=print_number_on_webpage(plen,low_temp,PSTR("\n<b>Lowest Temperature:</b>\t"));
plen=print_time_on_webpage(plen,&low_temp_t,PSTR(" °C @ "));
plen=print_number_on_webpage(plen,high_hum,PSTR("\n<b>Highest Humidity:</b>\t"));
plen=print_time_on_webpage(plen,&high_hum_t,PSTR(" % @ "));
plen=print_number_on_webpage(plen,low_hum,PSTR("\n<b>Lowest Humidity:</b>\t"));
plen=print_time_on_webpage(plen,&low_hum_t,PSTR(" % @ "));
plen=fill_tcp_data_p(buf,plen,PSTR("\n<br><input name=pg type=hidden value=3><input name=ac type=submit value=clear></form></pre><a href=/>home</a> | <a href=/?pg=3>refresh</a>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_info(void) {
uint16_t plen;
uint8_t *gwmac=NULL;
uint8_t server_id[4];
uint32_t leasetime;
plen=print_html_head(http200ok(),NULL);
plen=print_number_on_webpage(plen,enc28j60getrev(),PSTR("<h2>Info</h2><pre><b>ENC28J60 Rev:</b>\tB"));
plen=print_mac_on_webpage(plen,mymac,PSTR("\n<b>MAC address:</b>\t"));
plen=print_ip_on_webpage(plen,myip,PSTR("\n<b>IP address:</b>\t"));
gStrbuf[0]='/';
itoa(get_netmask_length(netmask),gStrbuf+1,10);
plen=fill_tcp_data(buf,plen,gStrbuf);
plen=print_ip_on_webpage(plen,gwip,PSTR("\n<b>Gateway:</b>\t"));
if (route_via_gw(ntpip))
gwmac=&ntproutingmac[0];
else
plen=print_mac_on_webpage(plen,ntproutingmac,PSTR("\n<b>NTP MAC:</b>\t"));
if (route_via_gw(mydns))
gwmac=&dnsroutingmac[0];
else
plen=print_mac_on_webpage(plen,dnsroutingmac,PSTR("\n<b>DNS MAC:</b>\t"));
if (gwmac)
plen=print_mac_on_webpage(plen,gwmac,PSTR("\n<b>Gateway MAC:</b>\t"));
plen=print_number_on_webpage(plen,ntp_update_period,PSTR("\n<b>Update period:</b>\t"));
dhcp_get_info(server_id,&leasetime);
plen=print_ip_on_webpage(plen,server_id,PSTR(" seconds\n<b>DHCP server:</b>\t"));
plen=print_number_on_webpage(plen,leasetime/60,PSTR("\n<b>Lease time:</b>\t"));
plen=fill_tcp_data_p(buf,plen,PSTR(" minutes\n<b>Uptime:</b>\t\t"));
if (uptime_day)
plen=print_number_first_on_webpage(plen,uptime_day,PSTR(" days, "));
if (uptime_hour)
plen=print_number_first_on_webpage(plen,uptime_hour,PSTR(" hours, "));
if (uptime_min)
plen=print_number_first_on_webpage(plen,uptime_min,PSTR(" minutes, "));
plen=print_number_first_on_webpage(plen,uptime_sec,PSTR(" seconds\n<b>Reset reason:</b>\t"));
if (mcusr_mirror & (1<<PORF)){
plen=fill_tcp_data_p(buf,plen,PSTR("Power-on"));
}else{
if (mcusr_mirror & (1<<EXTRF))
plen=fill_tcp_data_p(buf,plen,PSTR("External "));
if (mcusr_mirror & (1<<BORF))
plen=fill_tcp_data_p(buf,plen,PSTR("Brown-out "));
if (mcusr_mirror & (1<<WDRF))
plen=fill_tcp_data_p(buf,plen,PSTR("Watchdog System"));
}
plen=fill_tcp_data_p(buf,plen,PSTR("\n</pre><a href=/>home</a> | <a href=/?pg=4>refresh</a>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the web page by writing the data to the tcp send buffer
static uint16_t print_webpage_alarm(void) {
uint16_t plen;
plen=print_html_head(http200ok(),NULL);
plen=fill_tcp_data_p(buf,plen,PSTR("<h2>Alarm</h2><pre><form action=/au method=post>\n<b>Time (hh:mm):</b>\t<input type=text name=ti value="));
alarm_time_to_dispstr(gStrbuf);
plen=fill_tcp_data(buf,plen,gStrbuf);
plen=fill_tcp_data_p(buf,plen,PSTR(">\n<b>Alarm:</b>\t\t<input type=checkbox name=al"));
if (alarm_enabled){
plen=fill_tcp_data_p(buf,plen,PSTR(" checked"));
}
plen=fill_tcp_data_p(buf,plen,PSTR(">enabled\n<br><input type=submit value=apply> <input type=button value=cancel onclick=\"window.location='/'\"></form></pre>"));
plen=print_html_foot(plen);
return(plen);
}
// prepare the main web page by writing the data to the tcp send buffer
static uint16_t print_webpage_main(void)
{
uint16_t plen;
time_t now;
plen=print_html_head(http200ok(),NULL);
time(&now);
plen=print_time_on_webpage(plen,&now,PSTR("<h2>NTP clock</h2><pre><b>Time:</b>\t\t"));
plen=fill_tcp_data_p(buf,plen,PSTR(" (UTC"));
offset_to_dispstr(mins_offset_to_utc,gStrbuf);
plen=fill_tcp_data(buf,plen,gStrbuf);
plen=print_ip_on_webpage(plen,mydns,PSTR(")\n<b>DNS server:</b>\t"));
plen=fill_tcp_data_p(buf,plen,PSTR(" ["));
if (dnslkup_get_error_info())
plen=fill_tcp_data_p(buf,plen,PSTR("Error"));
else if (!dnslkup_haveanswer())
plen=fill_tcp_data_p(buf,plen,PSTR("Timeout"));
else
plen=fill_tcp_data_p(buf,plen,PSTR("OK"));
plen=fill_tcp_data_p(buf,plen,PSTR("]\n<b>NTP server:</b>\t"));
plen=fill_tcp_data(buf,plen,ntphostname);
plen=print_ip_on_webpage(plen,ntpip,PSTR(" ["));
plen=print_time_on_webpage(plen,&start_t,PSTR("]\n<b>Last sync:</b>\t"));
if (ntp_state!=1)
plen=fill_tcp_data_p(buf,plen,PSTR(" [Syncing]"));
else
plen=fill_tcp_data_p(buf,plen,PSTR(" [OK]"));
plen=fill_tcp_data_p(buf,plen,PSTR("\n<b>Alarm:</b>\t\t"));
alarm_time_to_dispstr(gStrbuf);
plen=fill_tcp_data(buf,plen,gStrbuf);
if (alarm_enabled)
plen=fill_tcp_data_p(buf,plen,PSTR(" [Enabled]"));
else
plen=fill_tcp_data_p(buf,plen,PSTR(" [Disabled]"));
plen=print_number_on_webpage(plen,temperature,PSTR("\n<b>Temperature:</b>\t"));
plen=print_number_on_webpage(plen,humidity,PSTR(" °C\n<b>Humidity:</b>\t"));
plen=fill_tcp_data_p(buf,plen,PSTR(" %\n</pre><a href=/?pg=1>config</a> | <a href=/?pg=2>display</a> | <a href=/?pg=3>history</a> | <a href=/?pg=4>info</a> | <a href=/?pg=5>password</a> | <a href=/?pg=6>alarm</a> | <a href=/>refresh</a>"));
plen=print_html_foot(plen);
return(plen);
}
// parse a string that is a MAC address and extract the MAC to mac_byte_str
// returns 1 if successful or 0 otherwise
static uint8_t parse_mac(uint8_t *mac_byte_str,const char *str)
{
uint8_t c,b;
uint8_t i=0;
while(i<6){
mac_byte_str[i]=0;
i++;
}
i=0;
while(*str && i<6){
if (isxdigit(*str)) {
c=toupper(*str);
if (c>'9') c-=7;
c-='0';
b=c;
str++;
if (isxdigit(*str)) {
c=toupper(*str);
if (c>'9') c-=7;
c-='0';
b<<=4;
b|=c;
}
mac_byte_str[i++]=b;
}
str++;
}
if (i==6) return(0);
return(1);
}
// decodes a base64-encoded string
static void base64_decode(char *str) {
char *out = str;
char stream[4];
while (strlen(str) >= 4) {
for (uint8_t i = 0; i < 4; ++i) {
if (*str >= 'A' && *str <= 'Z') {
stream[i] = *str - 'A';
}
else if (*str >= 'a' && *str <= 'z') {
stream[i] = *str - 'a' + 26;
}
else if (*str >= '0' && *str <= '9') {
stream[i] = *str - '0' + 52;
}
else if (*str == '+') {
stream[i] = 62;
}
else if (*str == '/') {
stream[i] = 63;
}
else if (*str == '=') {
stream[i] = 0;
}
++str;
}
*out++ = stream[0] << 2 | stream[1] >> 4;
*out++ = stream[1] << 4 | stream[2] >> 2;
*out++ = stream[2] << 6 | stream[3] >> 0;
}
*out = '\0';
}
// verifies credentials in the given html header
// returns 1 if credentials match, 0 otherwise
static uint8_t check_authorization(char *str) {
char *auth_str,*pw_str;
if ((auth_str=strstr_P(str,PSTR("Authorization:")))){
auth_str+=21;
base64_decode(auth_str);
pw_str=strchr(auth_str,':');
*pw_str++='\0';
if (strncmp(password,pw_str,PASSWORD_SIZE)==0){
return(1);
}
}
return(0);
}
// analyze the url given
static uint8_t analyse_get_url(char *str)
{
if (str[0] == '/' && str[1] == ' '){
// end of url, display just the root web page
dat_p=print_webpage_main();
return(0);
}
if (str[0] == '/' && str[1] == '?'){
if (find_key_val_p(str,gStrbuf,STR_BUFFER_SIZE,PSTR("ac"))){
low_temp_t=high_temp_t=low_hum_t=high_hum_t=0;
low_hum=low_temp=127;
high_hum=high_temp=0;
}
if (find_key_val_p(str,gStrbuf,STR_BUFFER_SIZE,PSTR("pg"))){
urldecode(gStrbuf);
switch (atoi(gStrbuf)) {
case 1:
if (check_authorization(str)) {
dat_p=print_webpage_config();
} else {
dat_p=print_webpage_authfail();
}
return(0);
case 2:
dat_p=print_webpage_display();
return(0);
case 3:
dat_p=print_webpage_history();
return(0);
case 4:
dat_p=print_webpage_info();
return(0);
case 5:
if (check_authorization(str)) {
dat_p=print_webpage_password();
} else {
dat_p=print_webpage_authfail();
}
return(0);
case 6:
dat_p=print_webpage_alarm();
return(0);
}
}
}
if (strncmp_P(str,PSTR("/tz.js"),6)==0){
dat_p=print_tzjs();
return(0);
}
if (strncmp_P(str,PSTR("/s.css"),6)==0){
dat_p=print_s1css();
return(0);
}
dat_p=http404notfound();
return(0);
}
// analyze the body of the given html document
static uint8_t analyse_post_url(char *str) {
char *body;
int16_t i=0;
uint8_t updateerr=0;
if ((body=strstr_P(str,PSTR("\r\n\r\n")))) {
body+=4;
uart_puts(body);
uart_puts_P("\r\n");
if (strncmp_P(str,PSTR("/pu"),3)==0){
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("pw"))){
urldecode(gStrbuf);
strncpy(password,gStrbuf,PASSWORD_SIZE);
password[PASSWORD_SIZE]='\0';
// store in eeprom:
eeprom_write_byte(&nv_magic_number_password,0x33); // magic number
eeprom_write_block(&password,&nv_password,sizeof(password));
}
dat_p=http302moved();
return(0);
}
if (strncmp_P(str,PSTR("/au"),3)==0){
alarm_enabled=0;
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("al"))){
alarm_enabled=1;
}
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("ti"))){
urldecode(gStrbuf);
parse_alarm_time(gStrbuf);
}
// store in eeprom:
eeprom_write_byte(&nv_magic_number_alarm,0xCC); // magic number
eeprom_write_byte(&nv_alarm_enabled,alarm_enabled);
eeprom_write_byte(&nv_alarm_hour,alarm_hour);
eeprom_write_byte(&nv_alarm_min,alarm_min);
dat_p=http302moved();
return(0);
}
if (strncmp_P(str,PSTR("/du"),3)==0){
display_24hclock=0;
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("hh"))){
display_24hclock=1;
}
display_temperature=0;
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("te"))){
display_temperature=1;
}
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("in"))){
urldecode(gStrbuf);
intensity=atoi(gStrbuf);
hdlx2416_intensity(intensity);
}
// store in eeprom:
eeprom_write_byte(&nv_magic_number_display,0xAA); // magic number
eeprom_write_byte(&nv_display_24hclock,display_24hclock);
eeprom_write_byte(&nv_display_temperature,display_temperature);
eeprom_write_byte(&nv_intensity,intensity);
dat_p=http302moved();
return(0);
}
if (strncmp_P(str,PSTR("/cu"),3)==0){
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("ma"))){
urldecode(gStrbuf);
if (parse_mac(mymac,gStrbuf)!=0){
updateerr=1;
}
}
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("nt"))){
urldecode(gStrbuf);
strncpy(ntphostname, gStrbuf,HOSTNAME_SIZE);
ntphostname[HOSTNAME_SIZE]='\0';
if (strlen(gStrbuf)>HOSTNAME_SIZE) {
updateerr=1;
}
}
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("up"))){
urldecode(gStrbuf);
ntp_update_period=atoi(gStrbuf);
}
enable_eu_dst=0;
set_dst(NULL);
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("st"))){
enable_eu_dst=1;
set_dst(eu_dst);
}
if (find_key_val_p(body,gStrbuf,STR_BUFFER_SIZE,PSTR("tz"))){
urldecode(gStrbuf);
i=parse_offset(gStrbuf);
if (i>=-720 && i<=840){
mins_offset_to_utc=i;
set_zone((int32_t)mins_offset_to_utc * 60);
}else{
updateerr=1;
}
}
if (updateerr){
dat_p=print_webpage_error();
return(0);
}
// store in eeprom:
eeprom_write_byte(&nv_magic_number_config,0x55); // magic number
eeprom_write_block(&ntpip,&nv_ntpip,sizeof(ntpip));
eeprom_write_byte(&nv_enable_eu_dst,enable_eu_dst);
eeprom_write_word(&nv_mins_offset_to_utc,mins_offset_to_utc);
eeprom_write_block(&ntphostname,&nv_ntphostname,sizeof(ntphostname));
eeprom_write_block(&mymac,&nv_mymac,sizeof(mymac));
eeprom_write_word(&nv_ntp_update_period,ntp_update_period);
dat_p=print_webpage_ok();
return(1);
}
}
dat_p=http500interr();
return(0);
}
// prints timestamp with offset to utc to uart
static void print_time_to_uart(void) {
time_t now;
struct tm *ts;
time(&now);
ts = localtime(&now);
asctime_r(ts, gStrbuf);
uart_puts(gStrbuf);
uart_puts_P(" (UTC");
offset_to_dispstr(mins_offset_to_utc,gStrbuf);
uart_puts(gStrbuf);
uart_puts_P(")\r\n");
}
// prints ip, netmask and dns to uart
static void print_ip_to_uart(void) {
mk_net_str(gStrbuf,myip,4,'.',10);
uart_puts_P("Got IP:");
uart_puts(gStrbuf);
uart_putc('/');
itoa(get_netmask_length(netmask),gStrbuf,10);
uart_puts(gStrbuf);
uart_puts_P("\r\n");
mk_net_str(gStrbuf,mydns,4,'.',10);
uart_puts_P("DNS IP:");
uart_puts(gStrbuf);
uart_puts_P("\r\n");
}
// prints enc28j60 silicon revision to uart
static void print_rev_to_uart(void) {
itoa(enc28j60getrev(),gStrbuf,10);
uart_puts_P("ENC28J60 Rev B");
uart_puts(gStrbuf);
uart_puts_P("\r\n");
}
// prints temperature and humidity to display
static void print_dht_to_display(void) {
hdlx2416_goto(0);
itoa(temperature,gStrbuf,10);
hdlx2416_puts(gStrbuf);
hdlx2416_puts_P("'C ");
itoa(humidity,gStrbuf,10);
hdlx2416_puts(gStrbuf);
hdlx2416_putc('%');
}
// sounds buzzer when alarm goes off and checks if the ntp update period has passed
static void check_alarm_and_ntp_period(void) {
time_t now;
struct tm *ts;
time(&now);
ts = localtime(&now);
// check alarm
if (alarm_enabled && ts->tm_sec < 10 && ts->tm_hour == alarm_hour && ts->tm_min == alarm_min) {
if (ts->tm_sec % 2 == 0)
buzzer_on();
else
buzzer_off();
} else {
buzzer_off();
}
// check for ntp update
if (difftime(now, start_t)>ntp_update_period && ntp_state==1){
// mark that we will wait for new ntp update
ntp_state=2;
ntp_retry_count=0;
}
}
// prints timestamp to display
static void print_time_to_display(void)
{
time_t now;
struct tm *ts;
uint8_t hour;
time(&now);
ts = localtime(&now);
hdlx2416_goto(0);
hour = ts->tm_hour;
if (display_24hclock == 0 && hour > 12) {
hour -= 12;
}
zero_two_d(gStrbuf,hour);
hdlx2416_puts(gStrbuf);
// blink colon
if (display_24hclock == 0 && ts->tm_sec % 2) {
hdlx2416_putc(' ');
} else {
hdlx2416_putc(':');
}
zero_two_d(gStrbuf,ts->tm_min);
hdlx2416_puts(gStrbuf);
if (display_24hclock==0) {
if (ts->tm_hour < 12) {
hdlx2416_puts_P("am ");
} else {
hdlx2416_puts_P("pm ");
}
} else {
hdlx2416_putc(':');
zero_two_d(gStrbuf,ts->tm_sec);
hdlx2416_puts(gStrbuf);
}
}
// interrupt, step seconds counter
ISR(TIMER1_COMPA_vect){
system_tick();
dhcp_tick();
uptime_sec++;
if (uptime_sec>59) {
uptime_sec=0;
uptime_min++;
}
if (uptime_min>59) {
uptime_min=0;
uptime_hour++;
}
if (uptime_hour>23) {
uptime_hour=0;
uptime_day++;
}
if (delay_sec) delay_sec--;
if (dht_delay_sec) dht_delay_sec--;
display_update_pending=1;
}
// Generate a 1s clock signal as interrupt