-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArduinoClock.ino
595 lines (544 loc) · 17.3 KB
/
ArduinoClock.ino
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
#include <Wire.h>
#include <RTClib.h> // https://github.com/adafruit/RTClib
#include <EEPROM.h>
#include <ShiftDisplay2.h> // https://github.com/ameer1234567890/ShiftDisplay2
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <TelnetStream.h> // https://github.com/jandrassy/TelnetStream
#include <ArduinoOTA.h>
#include <ESP8266httpUpdate.h>
#include "Secrets.h"
/* Secrets.h file should contain data as below: */
#ifndef STA_SSID
#define STA_SSID "your-ssid" // your network SSID (name)
#define STA_PSK "your-password" // your network password
#define OTA_HOSTNAME "ArduinoClock" // desired hostname for OTA
#endif
/* Configurable variables */
#define TICK_PIN D5
#define DATA_PIN D6
#define LATCH_PIN D7
#define CLOCK_PIN D8
#define BUTTON_PIN D0
#define DISPLAY_SIZE 4 // number of digits
#define DISPLAY_TYPE COMMON_ANODE // either COMMON_ANODE or COMMON_CATHODE
const int ALARM_BEEPS = 10; // number of beeps during alarm
const int SERVER_PORT = 80; // Port number for server to initiate sync remotely
const String TIMEZONE = "+5"; // local timezone
const int INIT_SYNC = 1000 * 30; // NTP sync on startup, after 30 seconds
const bool AUTO_SYNC = true; // true to update clock via NTP automatically
const int NTP_TIMEOUT = 5000; // NTP request timeout interval
const int WIFI_TIMEOUT = 3000; // Wifi connect timeout interval
const bool HOURLY_CHIME = false; // true for a chime at the start of every hour
const bool LEADING_ZEROS = true; // true for leading zeros
const bool MILITARY_TIME = false; // true for 24 hour clock
const String OTA_URL = "http://miwifimini.lan/Arduino/ArduinoClock.ino.bin"; // HTTP OTA update URL
/* Do not change unless you know what you are doing */
String logMsg;
String timeString;
int wifiCount = 0;
int chimeCount = 0;
uint eepromAddr = 0;
bool synced = false;
bool chimed = false;
bool alarmed = false;
const int numChimes = 4;
bool dismissAlarm = false;
bool stopCountdown = false;
unsigned long lastTime = 0;
const int ntpPacketSize = 48;
unsigned long previousMillis = 0;
byte packetBuffer[ntpPacketSize];
unsigned long lastTimeInitSync = 0;
const unsigned int localPort = 2390;
const long intervalBetweenChimes = 200;
String logTime = "00/00/0000 00:00:00";
const char* ntpServerName = "pool.ntp.org";
typedef struct {
uint set = 0;
uint hour = 0;
uint minute = 0;
} eepromData;
eepromData alarmData;
eepromData alarmDataOld;
WiFiUDP udp;
RTC_DS1307 rtc;
HTTPClient http;
WiFiClient wClient;
IPAddress timeServerIP;
ESP8266WebServer server(SERVER_PORT);
ShiftDisplay2 display(LATCH_PIN, CLOCK_PIN, DATA_PIN, DISPLAY_TYPE, DISPLAY_SIZE);
void setup() {
TelnetStream.begin();
log("I/system: startup");
pinMode(TICK_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
if (digitalRead(BUTTON_PIN) == LOW) {
runHTTPUpdate(true);
}
if (!rtc.begin()) {
display.set("ERR1");
while (true) {
display.show();
}
}
if (!rtc.isrunning()) {
display.set("ERR2");
while (true) {
display.show();
}
}
server.on("/", []() {
server.send(200, "text/html", \
"<a href=\"/log\">/log</a><br>"\
"<a href=\"/sync\">/sync</a><br>"\
"<a href=\"/reboot\">/reboot</a><br>"\
"<a href=\"/countdown?secs=10\">/countdown?secs=10</a><br>"\
"<a href=\"/stopcountdown\">/stopcountdown</a><br>"\
"<a href=\"/setalarm?hour=14&minute=44\">/setalarm?hour=14&minute=44</a><br>"\
"<a href=\"/showalarm\">/showalarm</a><br>"\
"<a href=\"/cancelalarm\">/cancelalarm</a><br>"\
"<a href=\"/dismissalarm\">/dismissalarm</a><br>"\
"<a href=\"/otaupdate\">/otaupdate</a><br>"\
"<a href=\"/covid19info\">/covid19info</a><br>"\
"<br><p><small>"\
"Powered by: <a href=\"https://github.com/ameer1234567890/ArduinoClock\">ArduinoClock</a> | "\
"Chip ID: " + String(ESP.getChipId()) + " | " + \
"Compiled at: " + __DATE__ + " " + __TIME__ + \
"</small></p>"\
);
log("I/server: served / to " + server.client().remoteIP().toString());
});
server.on("/log", []() {
log("I/server: served /log to " + server.client().remoteIP().toString());
server.send(200, "text/plain", logMsg);
});
server.on("/sync", []() {
server.send(200, "text/plain", "Sync started");
log("I/system: running clock sync routine upon request from " + server.client().remoteIP().toString());
syncntp();
});
server.on("/reboot", []() {
server.send(200, "text/plain", "Rebooting clock");
log("I/system: rebooting upon request from " + server.client().remoteIP().toString());
delay(1000);
ESP.restart();
});
server.on("/countdown", countdown);
server.on("/stopcountdown", []() {
server.send(200, "text/plain", "Stopping countdown");
log("I/system: stopping countdown upon request from " + server.client().remoteIP().toString());
stopCountdown = true;
});
server.on("/setalarm", setAlarm);
server.on("/showalarm", showAlarm);
server.on("/cancelalarm", cancelAlarm);
server.on("/dismissalarm", []() {
server.send(200, "text/plain", "Dismissing alarm");
log("I/system: dismissing alarm upon request from " + server.client().remoteIP().toString());
dismissAlarm = true;
});
server.on("/otaupdate", []() {
server.send(200, "text/plain", "HTTP OTA update started");
log("I/system: ota update started upon request from " + server.client().remoteIP().toString());
runHTTPUpdate(false);
});
server.on("/covid19info", showCOVIDCases);
server.begin();
ArduinoOTA.setHostname(OTA_HOSTNAME);
ArduinoOTA.begin();
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
display.set(String(progress / (total / 100)), ALIGN_RIGHT);
display.show();
});
ArduinoOTA.onError([](ota_error_t error) {
log("E/ota : ota failed: " + String(error));
});
EEPROM.begin(512);
EEPROM.get(eepromAddr, alarmData);
}
void loop() {
DateTime now = rtc.now();
int day = now.day();
int month = now.month();
int year = now.year();
int hour = now.hour();
int minute = now.minute();
int second = now.second();
if (alarmData.set == 1 && hour == alarmData.hour && minute == alarmData.minute) {
if (!alarmed) {
doAlarm();
alarmed = true;
}
} else {
alarmed = false;
dismissAlarm = false; // this is to avoid dismissal before the alarm starts
}
if (day < 10) {
logTime = "0" + String(day) + "/";
} else {
logTime = String(day) + "/";
}
if (month < 10) {
logTime += "0" + String(month) + "/";
} else {
logTime += String(month) + "/";
}
logTime += String(year) + " ";
if (hour < 10) {
logTime += "0" + String(hour) + ":";
} else {
logTime += String(hour) + ":";
}
if (minute < 10) {
logTime += "0" + String(minute) + ":";
} else {
logTime += String(minute) + ":";
}
if (second < 10) {
logTime += "0" + String(second);
} else {
logTime += String(second);
}
if (hour > 12 && !MILITARY_TIME) {
hour = hour - 12;
}
if (hour == 0 && !MILITARY_TIME) {
hour = 12;
}
timeString = getTimeString(hour, minute);
if (minute == 0) {
if (HOURLY_CHIME && !chimed) {
if (chimeCount < numChimes) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervalBetweenChimes) {
previousMillis = currentMillis;
chimeCount++;
tone(TICK_PIN, 1000, 70);
}
} else {
chimed = true;
}
}
} else {
chimed = false;
}
if (millis() > INIT_SYNC && !synced && AUTO_SYNC && millis() - lastTimeInitSync > INIT_SYNC) {
lastTimeInitSync = millis();
log("I/system: running auto sync via NTP");
syncntp();
}
display.set(timeString);
if ((now.second() % 2) == 0) {
display.setDot(1, true);
}
display.show();
if (millis() - lastTime >= 1000 || !lastTime) {
lastTime = millis();
tone(TICK_PIN, 500, 2);
}
if (digitalRead(BUTTON_PIN) == LOW) {
syncntp();
debounce();
}
server.handleClient();
ArduinoOTA.handle();
stopCountdown = false; // this is to avoid countdown being unable to start
switch (TelnetStream.read()) {
case 'R':
TelnetStream.println("Rebooting device");
TelnetStream.stop();
delay(100);
ESP.restart();
break;
case 'C':
TelnetStream.println("Closing telnet connection");
TelnetStream.flush();
TelnetStream.stop();
break;
case 'S':
TelnetStream.println("Synchronizing clock");
syncntp();
break;
}
}
void setupWifi() {
if (WiFi.status() == WL_CONNECTED) {
log("I/wifi : wifi connected already. IP address: " + WiFi.localIP().toString());
} else {
WiFi.mode(WIFI_STA);
WiFi.begin(STA_SSID, STA_PSK);
while (WiFi.status() != WL_CONNECTED) {
wifiCount++;
if (wifiCount > WIFI_TIMEOUT) {
wifiCount = 0;
log("E/wifi : wifi timeout");
display.set("ERR4");
display.show(3000);
return;
} else {
display.set("WIFI");
display.show();
}
}
log("I/wifi : wifi connected. IP address: " + WiFi.localIP().toString());
}
}
void log(String msg) {
TelnetStream.println("[" + logTime + "] " + msg);
logMsg = logMsg + "[" + logTime + "] ";
logMsg = logMsg + msg + "\n";
}
void syncntp() {
setupWifi();
log("I/ntp : clock update started");
udp.begin(localPort);
WiFi.hostByName(ntpServerName, timeServerIP);
sendNTPpacket(timeServerIP);
display.set("SYNC");
display.show(3000);
int cb = udp.parsePacket();
if (!cb) {
log("E/ntp : packet empty");
display.set("ERR5");
display.show(3000);
} else {
udp.read(packetBuffer, ntpPacketSize);
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = highWord << 16 | lowWord;
unsigned long unixEpoch = secsSince1900 - 2208988800;
unsigned long localTime;
if (TIMEZONE.startsWith("+")) {
localTime = unixEpoch + (TIMEZONE.toInt() * 60 * 60);
} else {
localTime = unixEpoch - (TIMEZONE.toInt() * 60 * 60);
}
rtc.adjust(DateTime(localTime));
synced = true;
log("I/ntp : clock updated");
display.set("DONE");
display.show(3000);
}
}
unsigned long sendNTPpacket(IPAddress& address) {
memset(packetBuffer, 0, ntpPacketSize);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(address, 123);
udp.write(packetBuffer, ntpPacketSize);
udp.endPacket();
}
String getTimeString(uint hour, uint minute) {
if (hour < 10 && LEADING_ZEROS) {
timeString = "0" + String(hour);
} else if (hour < 10 && !LEADING_ZEROS) {
timeString = " " + String(hour);
} else {
timeString = String(hour);
}
if (minute < 10 && LEADING_ZEROS) {
timeString += "0" + String(minute);
} else if (minute < 10 && !LEADING_ZEROS) {
timeString += " " + String(minute);
} else {
timeString += String(minute);
}
return timeString;
}
void debounce() {
// de-bouce by re-setting the pin
pinMode(BUTTON_PIN, OUTPUT);
digitalWrite(BUTTON_PIN, HIGH);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void runHTTPUpdate(bool reboot) {
log("I/updatr: HTTP OTA update started");
display.set("OTA ");
display.show(3000);
setupWifi();
ESPhttpUpdate.rebootOnUpdate(reboot);
display.set("UPDT");
display.show(1000);
ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);
HTTPUpdateResult ret = ESPhttpUpdate.update(wClient, OTA_URL);
switch(ret) {
case HTTP_UPDATE_FAILED:
log("E/updatr: HTTP OTA update failed " + String(ESPhttpUpdate.getLastError()) + " " + ESPhttpUpdate.getLastErrorString());
display.set("ERR6");
display.show(3000);
break;
case HTTP_UPDATE_OK:
log("I/updatr: HTTP OTA update completed. reboot required!");
display.set("DONE");
display.show(3000);
break;
}
debounce();
}
void countdown() {
if (server.arg("secs") == "" && server.arg("mins") == "") {
server.send(400, "text/plain", "Countdown period not specified!");
log("I/ctdown: no period specified. request from " + server.client().remoteIP().toString());
} else {
int secs = (server.arg("mins").toInt() * 60) + server.arg("secs").toInt();
log("I/ctdown: started countdown for " + String(secs) + " seconds upon request from " + server.client().remoteIP().toString());
server.send(200, "text/plain", "Countdown started");
for (secs; secs > 0; secs--) {
if (secs <= 60) {
display.set(secs, ALIGN_RIGHT);
} else {
display.set(getTimeString(abs(secs / 60), secs % 60));
display.setDot(1, true);
}
tone(TICK_PIN, 1000, 100);
display.show(1000);
if (digitalRead(BUTTON_PIN) == LOW || stopCountdown) {
stopCountdown = true;
log("I/ctdown: countdown stopped");
break;
}
server.handleClient();
ArduinoOTA.handle();
}
if (stopCountdown == true) {
stopCountdown = false;
display.set("STOP");
display.show(2000);
debounce();
} else {
display.set("GO", ALIGN_RIGHT);
tone(TICK_PIN, 1000, 1000);
display.show(1000);
display.set("");
display.show(500);
display.set("GO", ALIGN_RIGHT);
tone(TICK_PIN, 1000, 1000);
display.show(1000);
log("I/ctdown: countdown completed");
}
}
}
void setAlarm() {
log("I/alarm : started setAlarm upon request from " + server.client().remoteIP().toString());
if (server.arg("hour") == "" || server.arg("minute") == "") {
server.send(400, "text/plain", "Alarm time not specified!");
} else {
int alarmHour = server.arg("hour").toInt();
int alarmMinute = server.arg("minute").toInt();
alarmData.set = 1;
alarmData.hour = alarmHour;
alarmData.minute = alarmMinute;
EEPROM.get(eepromAddr, alarmDataOld);
if (alarmDataOld.set == alarmData.set && alarmDataOld.hour == alarmData.hour && alarmDataOld.minute == alarmData.minute) {
server.send(200, "text/plain", "Alarm already set for " + String(alarmData.hour) + ":" + String(alarmData.minute));
} else {
EEPROM.put(eepromAddr, alarmData);
EEPROM.commit();
server.send(200, "text/plain", "Alarm set for " + String(alarmData.hour) + ":" + String(alarmData.minute));
}
timeString = getTimeString(alarmData.hour, alarmData.minute);
display.set("ALRM");
display.show(1000);
display.set(timeString);
display.setDot(1, true);
display.show(3000);
display.set("DONE");
display.show(1000);
}
log("I/alarm : completed setAlarm");
}
void showAlarm() {
log("I/alarm : started showAlarm upon request from " + server.client().remoteIP().toString());
if (alarmData.set == 0) {
server.send(200, "text/plain", "No alarm set");
display.set("ALRM");
display.show(1000);
display.set("NONE");
display.show(3000);
} else {
EEPROM.get(eepromAddr, alarmData);
server.send(200, "text/plain", "Alarm is set for " + String(alarmData.hour) + ":" + String(alarmData.minute));
timeString = getTimeString(alarmData.hour, alarmData.minute);
display.set("ALRM");
display.show(1000);
display.set(timeString);
display.setDot(1, true);
display.show(3000);
display.set("DONE");
display.show(1000);
}
log("I/alarm : completed showAlarm");
}
void cancelAlarm() {
log("I/alarm : started cancelAlarm upon request from " + server.client().remoteIP().toString());
if (EEPROM.read(eepromAddr) == 0) {
server.send(200, "text/plain", "No alarm set");
display.set("ALRM");
display.show(1000);
display.set("NONE");
display.show(3000);
} else {
EEPROM.write(0, 0);
EEPROM.commit();
alarmData.set = 0;
server.send(200, "text/plain", "Alarm cancelled");
display.set("ALRM");
display.show(1000);
display.set("CXLD");
display.show(3000);
}
log("I/alarm : completed cancelAlarm");
}
void doAlarm() {
log("I/alarm : started doAlarm");
for (int i = 0; i < ALARM_BEEPS; i++) {
if (digitalRead(BUTTON_PIN) == LOW || dismissAlarm) {
dismissAlarm = false;
log("I/alarm : alarm dismissed");
break;
}
server.handleClient();
ArduinoOTA.handle();
display.set("ALRM");
display.show(1000);
display.set(timeString);
display.setDot(1, true);
tone(TICK_PIN, 1000, 1000);
display.show(1000);
}
debounce();
delay(3000);
log("I/alarm : completed doAlarm");
}
void showCOVIDCases() {
server.send(200, "text/plain", "Showing COVID19 information");
log("I/covid : COVID19 information shown upon request from " + server.client().remoteIP().toString());
display.set("COVD");
display.show(2000);
http.begin(wClient, "http://192.168.100.71/covid/");
int httpCode = http.GET();
String httpResponse = http.getString();
http.end();
if (httpCode == HTTP_CODE_OK && httpResponse != "") {
int startIndex = httpResponse.indexOf("<div class=\"covid_major_value\">") + 31;
int endIndex = httpResponse.indexOf("</div>", startIndex);
String casesToday = httpResponse.substring(startIndex, endIndex);
casesToday.replace(",", "");
log("I/covid : covid-19 positive cases now => " + casesToday);
display.set(casesToday);
display.show(5000);
} else {
log("E/covid : invalid HTTP response. HTTP code => " + String(httpCode));
display.set("ERR7");
display.show(2000);
}
}