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
|
/*
* HouseControl.ino - Arduino sketch to operate electric strike and garage door openers
*
* Copyright (c) 2012 Mike Beattie <mike@ethernal.org>
*
*
*/
#define WEBDUINO_FAVICON_DATA ""
#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <WebServer.h>
#include <MemoryFree.h>
#include <EEPROM.h>
#include "EEPROM_IO.h"
#include "strings.h"
/*********************************************************************************/
/* Pin definitions */
#define METER_PULSE 2
#define STATUS_LED 7
#define FDOOR_STRIKE 8
#define FDOOR_CLOSED 9
#define GDOOR1_ACTIVATE 3
#define GDOOR1_OPEN 0
#define GDOOR1_CLOSED 1
#define GDOOR2_ACTIVATE 6
#define GDOOR2_OPEN 4
#define GDOOR2_CLOSED 5
/*********************************************************************************/
/* Typedefs/datastructures */
struct st_config {
byte configVersion;
byte mac[6];
byte def_ip[4];
byte def_netmask[4];
byte def_gateway[4];
byte def_dnsserver[4];
byte ntpServer[4];
int UTC_offset;
byte notifyHost[4];
unsigned int notifyPort;
byte frontdoor_holdtime;
byte garagedoor_nightgracetime;
byte dawn;
byte dusk;
};
struct st_door {
byte openSensePin;
byte closedSensePin;
byte controlPin;
boolean open;
boolean closed;
boolean last_open;
boolean last_closed;
boolean controlActive;
time_t controlTime;
time_t openTime;
};
/*********************************************************************************/
/* Variable declarations */
#define BUF1_SIZE 64
#define BUF2_SIZE 16
byte buf1[BUF1_SIZE];
byte buf2[BUF2_SIZE];
time_t time;
time_t blinkTime = 0;
struct st_config config = {
// Config version. Set to 0 to debug (doesn't read from eeprom)
9,
//0,
// Ethernet MAC address
0x00, 0xA5, 0xCB, 0x28, 0xF4, 0xCC, // "Production"
//0x00, 0xA5, 0xCB, 0x28, 0xF4, 0xCD, // "Testing"
10, 113, 1, 160, // Default IP if no DHCP
255, 255, 255, 0, // Default Netmask if no DHCP
10, 113, 1, 254, // Default GW if no DHCP
10, 113, 1, 1, // Default DNS if no DHCP
10, 113, 1, 1, // NTP Server
1300, // UTC offset
10, 113, 1, 255, // Host to send UDP status packets to
8888, // Port to send UDP status packets to
10, // Seconds to leave front door unlocked
1, // Minutes to leave garage doors open at night
7, // "Dawn" Hour - auto close before this.
21 // "Dusk" Hour - auto close after this.
};
struct st_door frontDoor;
struct st_door garageDoor1;
struct st_door garageDoor2;
EthernetUDP NTPSocket;
time_t lastNTPtime = 0;
time_t lastNTPquery = 0;
//Server telnetServer(23);
WebServer httpServer("", 80);
/*********************************************************************************/
/* Utility functions */
char* mac_to_str(void *buf, const uint8_t* macAddr) {
sprintf_P((char*)buf, PSTR("%02X:%02X:%02X:%02X:%02X:%02X"), macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
return (char*)buf;
}
char* ip_to_str(void *buf, const uint8_t* ipAddr) {
sprintf_P((char*)buf, PSTR("%d.%d.%d.%d"), ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return (char*)buf;
}
char* time_to_str(void *buf, time_t t) {
sprintf_P((char*)buf, PSTR("%d/%d/%d %02d:%02d:%02d"), day(t), month(t), year(t), hour(t), minute(t), second(t));
return (char*)buf;
}
bool str_to_bytearray(byte *buf, byte *dest, byte base, byte n, char delim) {
byte i;
char *cur = (char*)buf, *next;
unsigned long int v;
for (i=0;i<n;i++) {
v = strtoul(cur, &next, base);
if (i==(n-1)) delim = '\0';
if ((v > 255) || (next[0] != delim) || (next == cur))
return false;
buf[i] = v;
cur = ++next;
}
memcpy(dest,buf,n);
return true;
}
bool str_to_ip(byte *buf, byte *ip) {
return str_to_bytearray(buf,ip,10,4,'.');
}
bool str_to_mac(byte *buf, byte *mac) {
return str_to_bytearray(buf,mac,16,6,':');
}
bool verify_utcoffset(byte *buf, int *dest) {
int v, min;
char *next;
v = strtoul((char*)buf, &next, 10);
min = v % 100;
if ((v < -1200) || (v > 1400) || (min <= -60) || (min >= 60) || (next == (char*)buf))
return false;
*dest = v;
return true;
}
/*********************************************************************************/
/* NTP/Time functions */
// send an NTP request to the time server at the given address
void sendNTPpacket() {
// update query time...
lastNTPquery = time;
// Packet buffer
byte pb[48];
// set all bytes in the buffer to 0
memset(pb, 0, sizeof(pb));
// Initialize values needed to form NTP request
pb[0] = 0b11100011; // LI, Version, Mode
pb[1] = 0; // Stratum, or type of clock
pb[2] = 6; // Polling Interval
pb[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
pb[12] = 49;
pb[13] = 0x4E;
pb[14] = 49;
pb[15] = 52;
// all NTP fields have been given values, now
// we send a packet requesting a timestamp:
NTPSocket.beginPacket(config.ntpServer, 123);
NTPSocket.write(pb, sizeof(pb));
NTPSocket.endPacket();
}
void parseNTPresponse() {
// byte pb[48];
unsigned long ntp_time = 0;
float ntp_time_frac;
// read the packet into the buffer
NTPSocket.read(buf1, sizeof(buf1));
// NTP contains four timestamps with an integer part and a fraction part
// we only use the integer part here
for (int i=40; i<44; i++)
ntp_time = ntp_time << 8 | buf1[i];
// part of the fractional part
// could be 4 bytes but this is more precise than the 1307 RTC
// which has a precision of ONE second
// in fact one byte is sufficient for 1307
ntp_time_frac = ((long)buf1[44] * 256 + buf1[45]) / 65536.0;
// convert NTP to UNIX time, differs seventy years = 2208988800 seconds
// NTP starts Jan 1, 1900
// Unix time starts on Jan 1 1970.
ntp_time -= 2208988800UL;
// Adjust timezone and DST...
ntp_time += (config.UTC_offset * 3600L) / 100L; // Notice the L for long calculations!!
if (ntp_time_frac > 0.4) ntp_time++; // adjust fractional part, see above
setTime(ntp_time);
lastNTPtime = now();
}
/*********************************************************************************/
/* HTTP Handler function */
void httpHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
/* for a GET or HEAD, send the standard "it's all OK headers" */
server.httpSuccess("text/html; charset=iso-8859-1", "Content-Encoding: gzip\r\n");
/* we don't output the body for a HEAD request */
if (type == WebServer::GET) {
server.writeP(index_html, sizeof(index_html));
}
}
void jsonHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
/* for a GET or HEAD, send the standard "it's all OK headers" */
server.httpSuccess("application/json");
/* we don't output the body for a HEAD request */
if (type == WebServer::GET) {
/* store the HTML in program memory using the P macro */
server.print(F("{\"fdo\":\""));
server.print(((frontDoor.open )?"open" :"state"));
server.print(F("\",\"fdc\":\""));
server.print(((frontDoor.closed )?"closed":"state"));
server.print(F("\",\"fdu\":\""));
server.print(((frontDoor.controlActive)?"unlocked":"locked"));
server.print(F("\",\"gd1o\":\""));
server.print(((garageDoor1.open )?"open" :"state"));
server.print(F("\",\"gd1c\":\""));
server.print(((garageDoor1.closed)?"closed":"state"));
server.print(F("\",\"gd2o\":\""));
server.print(((garageDoor2.open )?"open" :"state"));
server.print(F("\",\"gd2c\":\""));
server.print(((garageDoor2.closed)?"closed":"state"));
server.print(F("\"}"));
}
}
void doHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
if (type == WebServer::POST) {
while (server.readPOSTparam((char*)buf2, BUF2_SIZE, (char*)buf1, BUF1_SIZE)) {
if ((strcmp((const char*)buf2, "frontdoor") == 0))
toggleDoorControl(&frontDoor);
if ((strcmp((const char*)buf2, "garagedoor1") == 0))
toggleDoorControl(&garageDoor1);
if ((strcmp((const char*)buf2, "garagedoor2") == 0))
toggleDoorControl(&garageDoor2);
}
server.httpSuccess();
server.print("OK");
return;
}
server.httpSeeOther("/");
return;
}
void configHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
/* for a GET or HEAD, send the standard "it's all OK headers" */
server.httpSuccess("text/html; charset=iso-8859-1", "Content-Encoding: gzip\r\n");
/* we don't output the body for a HEAD request */
if (type == WebServer::GET) {
server.writeP(config_html, sizeof(config_html));
}
}
void configGetHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
/* for a GET or HEAD, send the standard "it's all OK headers" */
server.httpSuccess("application/json");
/* we don't output the body for a HEAD request */
if (type == WebServer::GET) {
sprintf_P((char*)buf1, PSTR("{\"info\":{\"version\":%d,\"time\":\""), config.configVersion);
server.print((char*)buf1);
server.print(time_to_str(buf2, time));
server.print(F("\",\"lastntp\":\""));
server.print(time_to_str(buf2, lastNTPtime));
server.print(F("\"},\"settings\":{\"mac\":\""));
server.print(mac_to_str(buf2, config.mac));
server.print(F("\",\"def_ip\":\""));
server.print(ip_to_str(buf2, config.def_ip));
server.print(F("\",\"def_nm\":\""));
server.print(ip_to_str(buf2, config.def_netmask));
server.print(F("\",\"def_gw\":\""));
server.print(ip_to_str(buf2, config.def_gateway));
server.print(F("\",\"def_dns\":\""));
server.print(ip_to_str(buf2, config.def_dnsserver));
server.print(F("\",\"ntpserver\":\""));
server.print(ip_to_str(buf2, config.ntpServer));
sprintf((char*)buf1, "\",\"utcoffset\":\"%+05d\",\"stathost\":\"", config.UTC_offset);
server.print((char*)buf1);
server.print(ip_to_str(buf2, config.notifyHost));
sprintf((char*)buf1, "\",\"statport\":%u,\"fd_utime\":%u,\"gd_gtime\":%u,", config.notifyPort, config.frontdoor_holdtime, config.garagedoor_nightgracetime);
server.print((char*)buf1);
sprintf_P((char*)buf1, PSTR("\"dawn\":%u,\"dusk\":%u}}"), config.dawn, config.dusk);
server.print((char*)buf1);
}
}
void configSetHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
if (type == WebServer::POST) {
server.httpSuccess();
while (server.readPOSTparam((char*)buf2, BUF2_SIZE, (char*)buf1, BUF1_SIZE)) {
if ((strcmp((const char*)buf2, "mac") == 0))
if (!str_to_mac(buf1, config.mac)) { server.print(F("Invalid MAC Address")); return; }
if ((strcmp((const char*)buf2, "def_ip") == 0))
if (!str_to_ip(buf1, config.def_ip)) { server.print(F("Invalid IP Address")); return; }
if ((strcmp((const char*)buf2, "def_nm") == 0))
if (!str_to_ip(buf1, config.def_netmask)) { server.print(F("Invalid Netmask")); return; }
if ((strcmp((const char*)buf2, "def_gw") == 0))
if (!str_to_ip(buf1, config.def_gateway)) { server.print(F("Invalid Gateway")); return; }
if ((strcmp((const char*)buf2, "def_dns") == 0))
if (!str_to_ip(buf1, config.def_dnsserver)) { server.print(F("Invalid DNS Server")); return; }
if ((strcmp((const char*)buf2, "ntpserver") == 0))
if (!str_to_ip(buf1, config.ntpserver)) { server.print(F("Invalid NTP Server")); return; }
if ((strcmp((const char*)buf2, "utcoffset") == 0))
if (!verify_utcoffset(buf1, &config.utcoffset)) { server.print(F("Invalid UTC offset")); return; }
if ((strcmp((const char*)buf2, "stathost") == 0))
if (!str_to_ip(buf1, config.notifyhost)) { server.print(F("Invalid Status target host")); return; }
server.print((char*)buf2);
server.print(" = '");
server.print((char*)buf1);
server.print("'<br />\n");
}
server.print(F("Settings Saved Successfully"));
return;
}
server.httpSeeOther("/config");
return;
}
/*void debugHandler(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
server.httpSuccess("text/plain");
if (type == WebServer::GET) {
sprintf((char*)buf1, "Time Now: %d/%d/%d %02d:%02d:%02d\n\0", day(time), month(time), year(time), hour(time), minute(time), second(time));
server.print((char*)buf1);
sprintf((char*)buf1, "Last NTP: %d/%d/%d %02d:%02d:%02d\n\nPacket:\n\0", day(lastNTPtime), month(lastNTPtime), year(lastNTPtime), hour(lastNTPtime), minute(lastNTPtime), second(lastNTPtime));
server.print((char*)buf1);
for (int i = 0; i < 48; i++) {
sprintf((char*)buf1, "%02X \0", pb[i]);
server.print((char*)buf1);
}
}
}
*/
/*********************************************************************************/
/* Miscellaneous functions */
void setupDoor (struct st_door *door, byte cp, byte csp, byte osp) {
door->controlPin = cp;
door->closedSensePin = csp;
door->openSensePin = osp;
door->controlActive = false;
pinMode(door->controlPin, OUTPUT);
pinMode(door->closedSensePin, INPUT);
digitalWrite(door->closedSensePin, HIGH);
if (door->openSensePin != 255) {
pinMode(door->openSensePin, INPUT);
digitalWrite(door->openSensePin, HIGH);
}
}
boolean readDoorState (struct st_door *door) {
door->last_closed = door->closed;
door->closed = !digitalRead(door->closedSensePin);
door->last_open = door->open;
if (door->openSensePin != 255) {
door->open = !digitalRead(door->openSensePin);
} else {
door->open = !door->closed;
}
if (!door->last_open && door->open)
door->openTime = time;
if ((door->last_open != door->open) || (door->last_closed != door->closed))
return true;
return false;
}
void toggleDoorControl(struct st_door *door) {
if (!door->controlActive) {
digitalWrite(door->controlPin, HIGH);
door->controlTime = time;
} else {
digitalWrite(door->controlPin, LOW);
}
door->controlActive = !door->controlActive;
}
void deToggleDoorCheck(struct st_door *door, byte controlHoldTime) {
if (door->controlActive && ((time - door->controlTime) >= controlHoldTime) )
toggleDoorControl(door);
}
void garageDoorNightCheck(struct st_door *door) {
if ( lastNTPtime > 0
&& !door->controlActive && door->open
&& ((hour(time) >= config.dusk) || (hour(time) < config.dawn))
&& ((time - door->openTime) >= (config.garagedoor_nightgracetime * 60))
)
toggleDoorControl(door);
}
/*********************************************************************************/
/* Setup function */
void setup() {
byte eepromVersion;
eepromRead(0, eepromVersion);
if (config.configVersion > eepromVersion)
eepromWrite(0, config);
if (config.configVersion > 0)
eepromRead(0, config);
if(Ethernet.begin(config.mac) == 0) {
Ethernet.begin(config.mac, config.def_ip, config.def_dnsserver, config.def_gateway, config.def_netmask);
}
// Udp.begin(config.notifyPort);
NTPSocket.begin(123);
httpServer.setDefaultCommand(&httpHandler);
httpServer.addCommand("json", &jsonHandler);
httpServer.addCommand("do", &doHandler);
httpServer.addCommand("config", &configHandler);
httpServer.addCommand("config/get", &configGetHandler);
httpServer.addCommand("config/set", &configSetHandler);
// httpServer.addCommand("debug", &debugHandler);
httpServer.begin();
setupDoor(&frontDoor, FDOOR_STRIKE, FDOOR_CLOSED, 255);
setupDoor(&garageDoor1, GDOOR1_ACTIVATE, GDOOR1_CLOSED, GDOOR1_OPEN);
setupDoor(&garageDoor2, GDOOR2_ACTIVATE, GDOOR2_CLOSED, GDOOR2_OPEN);
pinMode(STATUS_LED, OUTPUT);
sendNTPpacket();
}
/*********************************************************************************/
/* MAIN PROGRAM */
void loop() {
time = now();
// query time every 10 minutes, but only once a minute till we get a response
if ((((time - lastNTPtime) >= 600) || lastNTPtime == 0) && ((time - lastNTPquery) >= 60))
sendNTPpacket();
if (NTPSocket.parsePacket() >= 46)
parseNTPresponse();
readDoorState(&frontDoor);
readDoorState(&garageDoor1);
readDoorState(&garageDoor2);
deToggleDoorCheck(&frontDoor, config.frontdoor_holdtime);
deToggleDoorCheck(&garageDoor1, 1);
deToggleDoorCheck(&garageDoor2, 1);
garageDoorNightCheck(&garageDoor1);
garageDoorNightCheck(&garageDoor2);
httpServer.processConnection();
/* Toggle Status LED so we know things are OK */
if (time != blinkTime) {
blinkTime = time;
digitalWrite(STATUS_LED, HIGH);
delay(80);
digitalWrite(STATUS_LED, LOW);
}
}
|