-
Notifications
You must be signed in to change notification settings - Fork 22
/
Qlockwork.ino
2671 lines (2515 loc) · 94.8 KB
/
Qlockwork.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
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
//*****************************************************************************
// QLOCKWORK
// An advanced firmware for a DIY "word-clock"
//
// @mc ESP8266
// @created 12.03.2017
//
// This source file 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 source file 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/>.
//
//*****************************************************************************
#define FIRMWARE_VERSION 20240908
#include <Arduino.h>
#include <Arduino_JSON.h>
#include <ArduinoHttpClient.h>
#include <ArduinoOTA.h>
#include <DHT.h>
#include <DS3232RTC.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
#include <TimeLib.h>
#include "Colors.h"
#include "Configuration.h"
#include "Events.h"
#include "LedDriver.h"
#include "Modes.h"
#include "Ntp.h"
#include "MeteoWeather.h"
#include "Renderer.h"
#include "Settings.h"
#include "Syslog.h"
#include "Timezone.h"
#include "Timezones.h"
#include "WiFiManager.h"
//*****************************************************************************
// Init
//*****************************************************************************
// Servers
ESP8266WebServer webServer(80);
ESP8266HTTPUpdateServer httpUpdater;
// DHT22
#ifdef SENSOR_DHT22
DHT dht(PIN_DHT22, DHT22);
#endif
// IR receiver
#ifdef IR_RECEIVER
IRrecv irrecv(PIN_IR_RECEIVER);
decode_results irDecodeResult;
#endif
// Syslog
#ifdef SYSLOGSERVER_SERVER
WiFiUDP wifiUdp;
Syslog syslog(wifiUdp, SYSLOGSERVER_SERVER, SYSLOGSERVER_PORT, HOSTNAME, "QLOCKWORK", LOG_INFO);
#endif
// RTC
#ifdef RTC_BACKUP
DS3232RTC RTC;
#endif
// LED driver
LedDriver ledDriver;
// Renderer
Renderer renderer;
// Settings
Settings settings;
// NTP
Ntp ntp;
char ntpServer[] = NTP_SERVER;
uint8_t errorCounterNTP = 0;
// Screenbuffer
uint16_t matrix[10] = {};
uint16_t matrixOld[10] = {};
bool screenBufferNeedsUpdate = true;
// Mode
Mode mode = MODE_TIME;
Mode lastMode = mode;
uint32_t modeTimeout = 0;
uint32_t autoModeChangeTimer = AUTO_MODECHANGE_TIME;
bool runTransitionOnce = false;
uint8_t autoMode = 0;
// Time
uint8_t lastDay = 0;
uint8_t lastMinute = 0;
uint8_t lastHour = 0;
uint8_t lastSecond = 0;
// uint32_t last500Millis = 0;
// uint32_t last50Millis = 0;
time_t upTime = 0;
uint8_t randomHour = 0;
uint8_t randomMinute = 0;
uint8_t randomSecond = 0;
uint8_t moonphase = 0;
// Feed
String feedText = "";
uint8_t feedColor = WHITE;
uint8_t feedPosition = 0;
// MeteoWeather
#ifdef WEATHER
MeteoWeather outdoorWeather;
uint8_t errorCounterOutdoorWeather = 0;
#endif
// DHT22
float roomTemperature = 0;
float roomHumidity = 0;
uint8_t errorCounterDHT = 0;
// Brightness and LDR
uint8_t maxBrightness = map(settings.mySettings.brightness, 0, 100, MIN_BRIGHTNESS, MAX_BRIGHTNESS);
uint8_t brightness = maxBrightness;
#ifdef LDR
uint16_t ldrValue = 0;
uint16_t lastLdrValue = 0;
uint16_t minLdrValue = 511; // The ESP will crash if minLdrValue and maxLdrValue are equal due to an error in map()
uint16_t maxLdrValue = 512;
uint8_t iTargetBrightness = 0;
unsigned long iBrightnessMillis = 0;
#endif
// Alarm
#ifdef BUZZER
bool alarmTimerSet = false;
uint8_t alarmTimer = 0;
uint8_t alarmTimerSecond = 0;
uint8_t alarmOn = false;
#endif
// Events
#ifdef EVENT_TIME
uint32_t showEventTimer = EVENT_TIME;
#endif
#if defined(SHOW_MODE_SUNRISE_SUNSET) && defined(WEATHER)
bool sunrise_started = false;
unsigned long sunrise_millis = 0;
bool sunset_started = false;
unsigned long sunset_millis = 0;
time_t sunset_unix = 0;
time_t sunrise_unix = 0;
int save_color_sunrise_sunset = settings.mySettings.color;
#endif
// Misc
uint8_t testColumn = 0;
int updateInfo = 0;
IPAddress myIP = { 0,0,0,0 };
uint32_t lastButtonPress = 0;
bool testFlag = false;
//*****************************************************************************
// Setup()
//*****************************************************************************
void setup()
{
// init serial port
Serial.begin(SERIAL_SPEED);
while (!Serial);
delay(1000);
// And the monkey flips the switch. (Akiva Goldsman)
Serial.println();
Serial.println("*** QLOCKWORK ***");
Serial.println("Firmware: " + String(FIRMWARE_VERSION));
#ifdef POWERON_SELFTEST
renderer.setAllScreenBuffer(matrix);
Serial.println("Set all LEDs to red.");
writeScreenBuffer(matrix, RED, TEST_BRIGHTNESS);
delay(2500);
Serial.println("Set all LEDs to green.");
writeScreenBuffer(matrix, GREEN, TEST_BRIGHTNESS);
delay(2500);
Serial.println("Set all LEDs to blue.");
writeScreenBuffer(matrix, BLUE, TEST_BRIGHTNESS);
delay(2500);
Serial.println("Set all LEDs to white.");
writeScreenBuffer(matrix, WHITE, TEST_BRIGHTNESS);
delay(2500);
#endif
#ifdef ESP_LED
Serial.println("Setting up ESP-LED.");
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, HIGH);
#endif
#ifdef MODE_BUTTON
Serial.println("Setting up Mode-Button.");
pinMode(PIN_MODE_BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_MODE_BUTTON), buttonModeInterrupt, FALLING);
#endif
#ifdef ONOFF_BUTTON
Serial.println("Setting up Back-Button.");
pinMode(PIN_ONOFF_BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_ONOFF_BUTTON), buttonOnOffInterrupt, FALLING);
#endif
#ifdef TIME_BUTTON
Serial.println("Setting up Time-Button.");
pinMode(PIN_TIME_BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_TIME_BUTTON), buttonTimeInterrupt, FALLING);
#endif
#ifdef BUZZER
Serial.println("Setting up Buzzer.");
pinMode(PIN_BUZZER, OUTPUT);
#endif
#ifdef SENSOR_DHT22
Serial.println("Setting up DHT22.");
dht.begin();
#endif
#ifdef LDR
Serial.print("Setting up LDR. ABC: ");
settings.mySettings.useAbc ? Serial.println("enabled") : Serial.println("disabled");
pinMode(PIN_LDR, INPUT);
#endif
#ifdef IR_RECEIVER
Serial.println("Setting up IR-Receiver.");
irrecv.enableIRIn();
#endif
// Start WiFi and services
renderer.clearScreenBuffer(matrix);
renderer.setSmallText("WI", TEXT_POS_TOP, matrix);
renderer.setSmallText("FI", TEXT_POS_BOTTOM, matrix);
writeScreenBuffer(matrix, WHITE, brightness);
WiFiManager wifiManager;
//wifiManager.resetSettings();
wifiManager.setTimeout(WIFI_SETUP_TIMEOUT);
wifiManager.autoConnect(HOSTNAME, WIFI_AP_PASS);
WiFi.hostname(HOSTNAME);
WiFi.setAutoReconnect(true);
WiFi.setAutoConnect(true);
if (!WiFi.isConnected())
{
WiFi.mode(WIFI_AP);
Serial.println("No WLAN connected. Staying in AP mode.");
writeScreenBuffer(matrix, RED, brightness);
#if defined(BUZZER) && defined(WIFI_BEEPS)
digitalWrite(PIN_BUZZER, HIGH);
delay(1500);
digitalWrite(PIN_BUZZER, LOW);
#endif
delay(1000);
myIP = WiFi.softAPIP();
}
else
{
WiFi.mode(WIFI_STA);
Serial.println("WLAN connected. Switching to STA mode.");
Serial.println("RSSI: " + String(WiFi.RSSI()));
writeScreenBuffer(matrix, GREEN, brightness);
#if defined(BUZZER) && defined(WIFI_BEEPS)
for (uint8_t i = 0; i <= 2; i++)
{
#ifdef DEBUG
Serial.println("Beep!");
#endif
digitalWrite(PIN_BUZZER, HIGH);
delay(100);
digitalWrite(PIN_BUZZER, LOW);
delay(100);
}
#endif
delay(1000);
myIP = WiFi.localIP();
// mDNS is needed to see HOSTNAME in Arduino IDE
Serial.println("Starting mDNS responder.");
MDNS.begin(HOSTNAME);
//MDNS.addService("http", "tcp", 80);
Serial.println("Starting OTA service.");
#ifdef DEBUG
ArduinoOTA.onStart([]()
{
Serial.println("Start OTA update.");
});
ArduinoOTA.onError([](ota_error_t error)
{
Serial.println("OTA Error: " + String(error));
if (error == OTA_AUTH_ERROR) Serial.println("Auth failed.");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin failed.");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect failed.");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive failed.");
else if (error == OTA_END_ERROR) Serial.println("End failed.");
});
ArduinoOTA.onEnd([]()
{
Serial.println("End OTA update.");
});
#endif
ArduinoOTA.setPassword(OTA_PASS);
ArduinoOTA.begin();
#ifdef SYSLOGSERVER_SERVER
Serial.println("Starting syslog.");
#ifdef APIKEY
syslog.log(LOG_INFO, ";#;dateTime;roomTemperature;roomHumidity;outdoorTemperature;outdoorHumidity;sunriseTime;sunsetTime;ldrValue;errorCounterNTP;errorCounterDHT;errorCounterOutdoorWeather;freeHeapSize;upTime");
#else
syslog.log(LOG_INFO, ";#;dateTime;roomTemperature;roomHumidity;ldrValue;errorCounterNTP;errorCounterDHT;freeHeapSize;upTime");
#endif
#endif
// Get weather from MeteoWeather
#ifdef WEATHER
#ifdef DEBUG
Serial.println("Getting outdoor weather:");
#endif
!outdoorWeather.getOutdoorConditions(LATITUDE, LONGITUDE, TIMEZONE) ? errorCounterOutdoorWeather++ : errorCounterOutdoorWeather = 0;
#ifdef DEBUG
Serial.println("Outdoor temperature: " + String(outdoorWeather.temperature) + " °C");
Serial.println("Outdoor humidity: " + String(outdoorWeather.humidity) + " %rH");
Serial.println("Sunrise: " + padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunrise)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunrise)))));
Serial.println("Sunset: " + padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunset)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunset)))));
#endif
#endif
}
#ifdef SHOW_IP
WiFi.isConnected() ? feedText = " IP: " : feedText = " AP-IP: ";
feedText += String(myIP[0]) + "." + String(myIP[1]) + "." + String(myIP[2]) + "." + String(myIP[3]) + " ";
feedPosition = 0;
feedColor = WHITE;
mode = MODE_FEED;
#endif
Serial.println("Starting webserver.");
setupWebServer();
Serial.println("Starting updateserver.");
httpUpdater.setup(&webServer);
renderer.clearScreenBuffer(matrix);
#ifdef RTC_BACKUP
RTC.begin();
setSyncProvider(RTC.get);
Serial.print("RTC Sync.");
if (timeStatus() != timeSet) Serial.print(" FAIL!");
Serial.println();
#ifdef DEBUG
time_t tempRtcTime = RTC.get();
Serial.printf("Time (RTC): %02u:%02u:%02u %02u.%02u.%04u\r\n", hour(tempRtcTime), minute(tempRtcTime), second(tempRtcTime), day(tempRtcTime), month(tempRtcTime), year(tempRtcTime));
#endif
#endif
// Get the time!
if (WiFi.isConnected())
{
// Set ESP (and RTC) time from NTP
time_t tempNtpTime = ntp.getTime(ntpServer);
if (tempNtpTime)
{
errorCounterNTP = 0;
setTime(timeZone.toLocal(tempNtpTime));
#ifdef DEBUG
Serial.printf("Time (NTP): %02u:%02u:%02u %02u.%02u.%04u (UTC)\r\n", hour(tempNtpTime), minute(tempNtpTime), second(tempNtpTime), day(tempNtpTime), month(tempNtpTime), year(tempNtpTime));
Serial.printf("Drift (ESP): %d sec.\r\n", tempNtpTime - timeZone.toUTC(now()));
#endif
#ifdef RTC_BACKUP
RTC.set(timeZone.toLocal(tempNtpTime));
#ifdef DEBUG
Serial.printf("Drift (RTC): %d sec.\r\n", tempNtpTime - timeZone.toUTC(RTC.get()));
#endif
#endif
}
else
{
if (errorCounterNTP < 255)
errorCounterNTP++;
#ifdef DEBUG
Serial.printf("Error (NTP): %u\r\n", errorCounterNTP);
#endif
}
}
else
{
WiFi.reconnect();
}
// Define a random time
randomSeed(analogRead(A0));
randomHour = random(0, 24);
randomMinute = random(5, 56);
randomSecond = random(5, 56);
// Update room conditions
#if defined(RTC_BACKUP) || defined(SENSOR_DHT22)
getRoomConditions();
#endif
// print some infos
#ifdef DEBUG
Serial.printf("Defined events: %u\r\n", sizeof(events) / sizeof(event_t));
Serial.printf("Day on: %02u:%02u:00\r\n", hour(settings.mySettings.dayOnTime), minute(settings.mySettings.dayOnTime));
Serial.printf("Night off: %02u:%02u:00\r\n", hour(settings.mySettings.nightOffTime), minute(settings.mySettings.nightOffTime));
Serial.printf("Alarm1: %02u:%02u:00 ", hour(settings.mySettings.alarm1Time), minute(settings.mySettings.alarm1Time));
settings.mySettings.alarm1 ? Serial.print("on ") : Serial.print("off ");
Serial.println(settings.mySettings.alarm1Weekdays, BIN);
Serial.printf("Alarm2: %02u:%02u:00 ", hour(settings.mySettings.alarm2Time), minute(settings.mySettings.alarm2Time));
settings.mySettings.alarm2 ? Serial.print("on ") : Serial.print("off ");
Serial.println(settings.mySettings.alarm2Weekdays, BIN);
Serial.printf("Random time: %02u:%02u:%02u\r\n", randomHour, randomMinute, randomSecond);
Serial.println("DEBUG is on.");
#else
Serial.println("DEBUG is off.");
#endif
lastDay = day() - 1;
lastHour = hour();
lastMinute = minute();
lastSecond = second();
#ifdef FRONTCOVER_BINARY
settings.setTransition(TRANSITION_NORMAL);
#endif
} // setup()
//*****************************************************************************
// Loop()
//*****************************************************************************
void loop()
{
//*************************************************************************
// Run once a day
//*************************************************************************
if (day() != lastDay)
{
lastDay = day();
screenBufferNeedsUpdate = true;
#ifdef SHOW_MODE_MOONPHASE
moonphase = getMoonphase(year(), month(), day());
#endif
// Reset URL event 0
events[0].day = 0;
events[0].month = 0;
#ifdef DEBUG
Serial.printf("Uptime: %u days, %02u:%02u\r\n", int(upTime / 86400), hour(upTime), minute(upTime));
Serial.printf("Free RAM: %u bytes\r\n", system_get_free_heap_size());
Serial.printf("Moonphase: %u\r\n", moonphase);
#endif
// Change color
if (settings.mySettings.colorChange == COLORCHANGE_DAY)
{
settings.mySettings.color = random(0, COLORCHANGE_COUNT + 1);
#ifdef DEBUG
Serial.printf("Color changed to: %u\r\n", settings.mySettings.color);
#endif
}
}
//*************************************************************************
// Run once every hour
//*************************************************************************
if (hour() != lastHour)
{
lastHour = hour();
screenBufferNeedsUpdate = true;
// Change color
if (settings.mySettings.colorChange == COLORCHANGE_HOUR)
{
settings.mySettings.color = random(0, COLOR_COUNT + 1);
#ifdef DEBUG
Serial.printf("Color changed to: %u\r\n", settings.mySettings.color);
#endif
}
// Hourly beep
#ifdef BUZZER
if ((settings.mySettings.hourBeep == true) && (mode == MODE_TIME))
{
digitalWrite(PIN_BUZZER, HIGH);
delay(25);
digitalWrite(PIN_BUZZER, LOW);
#ifdef DEBUG
Serial.println("Beep!");
#endif
}
#endif
//*********************************************************************
// Run once every random hour (once a day)
//*********************************************************************
if (hour() == randomHour)
{
// Get updateinfo
#ifdef UPDATE_INFOSERVER
if (WiFi.isConnected())
getUpdateInfo();
#endif
}
}
//*************************************************************************
// Run once every minute
//*************************************************************************
if (minute() != lastMinute)
{
lastMinute = minute();
screenBufferNeedsUpdate = true;
#if defined(RTC_BACKUP) || defined(SENSOR_DHT22)
// Update room conditions
getRoomConditions();
#endif
#ifdef BUZZER
// Switch on buzzer for alarm 1
if (settings.mySettings.alarm1 && (hour() == hour(settings.mySettings.alarm1Time)) && (minute() == minute(settings.mySettings.alarm1Time)) && bitRead(settings.mySettings.alarm1Weekdays, weekday()))
{
alarmOn = BUZZTIME_ALARM_1;
#ifdef DEBUG
Serial.println("Alarm1 on.");
#endif
}
// Switch on buzzer for alarm 2
if (settings.mySettings.alarm2 && (hour() == hour(settings.mySettings.alarm2Time)) && (minute() == minute(settings.mySettings.alarm2Time)) && bitRead(settings.mySettings.alarm2Weekdays, weekday()))
{
alarmOn = BUZZTIME_ALARM_2;
#ifdef DEBUG
Serial.println("Alarm2 on.");
#endif
}
#endif
#ifdef DEBUG
time_t tempEspTime = now();
Serial.printf("Time (ESP): %02u:%02u:%02u %02u.%02u.%04u\r\n", hour(tempEspTime), minute(tempEspTime), second(tempEspTime), day(tempEspTime), month(tempEspTime), year(tempEspTime));
#ifdef RTC_BACKUP
time_t tempRtcTime = RTC.get();
Serial.printf("Time (RTC): %02u:%02u:%02u %02u.%02u.%04u\r\n", hour(tempRtcTime), minute(tempRtcTime), second(tempRtcTime), day(tempRtcTime), month(tempRtcTime), year(tempRtcTime));
#endif
#endif
// Set night- and daymode
if ((hour() == hour(settings.mySettings.nightOffTime)) && (minute() == minute(settings.mySettings.nightOffTime)))
{
#ifdef DEBUG
Serial.println("Night off.");
#endif
setMode(MODE_BLANK);
}
if ((hour() == hour(settings.mySettings.dayOnTime)) && (minute() == minute(settings.mySettings.dayOnTime)))
{
#ifdef DEBUG
Serial.println("Day on.");
#endif
setMode(lastMode);
if (!WiFi.isConnected())
ESP.restart();
}
//*********************************************************************
// Run once every random minute (once an hour) or if NTP has an error
//*********************************************************************
if ((minute() == randomMinute) || ((errorCounterNTP > 0) && (errorCounterNTP < 10)))
{
if (WiFi.isConnected())
{
// Set ESP (and RTC) time from NTP
time_t tempNtpTime = ntp.getTime(ntpServer);
if (tempNtpTime)
{
errorCounterNTP = 0;
setTime(timeZone.toLocal(tempNtpTime));
#ifdef DEBUG
Serial.printf("Time (NTP): %02u:%02u:%02u %02u.%02u.%04u (UTC)\r\n", hour(tempNtpTime), minute(tempNtpTime), second(tempNtpTime), day(tempNtpTime), month(tempNtpTime), year(tempNtpTime));
Serial.printf("Drift (ESP): %d sec.\r\n", tempNtpTime - timeZone.toUTC(now()));
#endif
#ifdef RTC_BACKUP
RTC.set(timeZone.toLocal(tempNtpTime));
#ifdef DEBUG
Serial.printf("Drift (RTC): %d sec.\r\n", tempNtpTime - timeZone.toUTC(RTC.get()));
#endif
#endif
}
else
{
if (errorCounterNTP < 255) errorCounterNTP++;
#ifdef DEBUG
Serial.printf("Error (NTP): %u\r\n", errorCounterNTP);
#endif
}
}
else
{
WiFi.reconnect();
}
}
if (minute() == randomMinute)
{
if (WiFi.isConnected())
{
// Get weather from MeteoWeather
#ifdef WEATHER
#ifdef DEBUG
Serial.println("Getting outdoor weather for latitude " + String(LATITUDE) + " and longitude " + String(LONGITUDE) + ":");
#endif
!outdoorWeather.getOutdoorConditions(LATITUDE, LONGITUDE, TIMEZONE) ? errorCounterOutdoorWeather++ : errorCounterOutdoorWeather = 0;
#ifdef DEBUG
Serial.println("Latitude: " + String(LATITUDE));
Serial.println("Longitude: " + String(LONGITUDE));
Serial.println("Timezone: " + String(TIMEZONE));
Serial.println("Outdoor temperature: " + String(outdoorWeather.temperature) + " °C");
Serial.println("Outdoor humidity: " + String(outdoorWeather.humidity) + " %rH");
Serial.println("Sunrise: " + padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunrise)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunrise)))));
Serial.println("Sunset: " + padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunset)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunset)))));
#endif
#endif
}
else
{
WiFi.reconnect();
}
}
//*********************************************************************
// Run once every 5 minutes
//*********************************************************************
if (minute() % 5 == 0)
{
#ifdef SYSLOGSERVER_SERVER
// Write some data to syslog
if (WiFi.isConnected())
{
time_t tempEspTime = now();
#ifdef WEATHER
syslog.log(LOG_INFO, ";D;" + String(tempEspTime) + ";" + String(roomTemperature) + ";" + String(roomHumidity) + ";" + String(outdoorWeather.temperature) + ";" + String(outdoorWeather.humidity) + ";" \
+ padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunrise)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunrise)))) + ";" \
+ padStringZeros(String(hour(timeZone.toLocal(outdoorWeather.sunset)))) + ":" + padStringZeros(String(minute(timeZone.toLocal(outdoorWeather.sunset)))) + ";" + String(ldrValue)\
+ ";" + String(errorCounterNTP) + ";" + String(errorCounterDHT) + ";" + String(errorCounterOutdoorWeather) + ";" + String(ESP.getFreeHeap()) + ";" + String(upTime));
#else
syslog.log(LOG_INFO, ";D;" + String(tempEspTime) + ";" + String(roomTemperature) + ";" + String(roomHumidity) + ";" + String(ldrValue)\
+ ";" + String(errorCounterNTP) + ";" + String(errorCounterDHT) + ";" + String(ESP.getFreeHeap()) + ";" + String(upTime));
#endif
#ifdef DEBUG
Serial.println("Data written to syslog.");
#endif
}
#endif
// Change color
if (settings.mySettings.colorChange == COLORCHANGE_FIVE)
{
settings.mySettings.color = random(0, COLOR_COUNT + 1);
#ifdef DEBUG
Serial.printf("Color changed to: %u\r\n", settings.mySettings.color);
#endif
}
}
}
//*************************************************************************
// Run once every second
//*************************************************************************
if (second() != lastSecond)
{
lastSecond = second();
upTime++;
#ifdef BUZZER
// Make some noise
if (alarmOn)
{
alarmOn--;
digitalRead(PIN_BUZZER) ? digitalWrite(PIN_BUZZER, LOW) : digitalWrite(PIN_BUZZER, HIGH);
if (!alarmOn)
{
#ifdef DEBUG
Serial.println("Alarm: off");
#endif
digitalWrite(PIN_BUZZER, LOW);
screenBufferNeedsUpdate = true;
}
}
#endif
#ifdef FRONTCOVER_BINARY
if (mode != MODE_BLANK)
screenBufferNeedsUpdate = true;
#else
// General Screenbuffer-Update every second.
// (not in MODE_TIME or MODE_BLANK because it will lock the ESP due to TRANSITION_FADE)
if ((mode != MODE_TIME) && (mode != MODE_BLANK))
screenBufferNeedsUpdate = true;
#endif
// Flash ESP LED
#ifdef ESP_LED
digitalWrite(PIN_LED, !digitalRead(PIN_LED));
#endif
// Countdown timeralarm by one minute in the second it was activated
#ifdef BUZZER
if (alarmTimer && alarmTimerSet && (alarmTimerSecond == second()))
{
alarmTimer--;
#ifdef DEBUG
if (alarmTimer)
Serial.printf("Timeralarm in %u min.\r\n", alarmTimer);
#endif
}
// Switch on buzzer for timer
if (!alarmTimer && alarmTimerSet)
{
alarmTimerSet = false;
alarmOn = BUZZTIME_TIMER;
#ifdef DEBUG
Serial.println("Timeralarm: on");
#endif
}
#endif
// Auto switch modes
if (settings.mySettings.modeChange && (mode == MODE_TIME))
{
autoModeChangeTimer--;
if (!autoModeChangeTimer)
{
#ifdef DEBUG
Serial.println("Auto modechange. (" + String(autoMode) + ")");
#endif
autoModeChangeTimer = AUTO_MODECHANGE_TIME;
switch (autoMode)
{
case 0:
#ifdef WEATHER
if (WiFi.isConnected())
{
setMode(MODE_EXT_TEMP);
}
else
{
WiFi.reconnect();
setMode(MODE_EXT_TEMP);
}
#endif
autoMode = 1;
break;
case 1:
#if defined(RTC_BACKUP) || defined(SENSOR_DHT22)
setMode(MODE_TEMP);
#else
#ifdef WEATHER
if (WiFi.isConnected())
{
setMode(MODE_EXT_TEMP);
}
else
{
WiFi.reconnect();
setMode(MODE_EXT_TEMP);
}
#endif
#endif
autoMode = 0;
break;
}
}
}
// Show event in feed
#ifdef EVENT_TIME
if (mode == MODE_TIME)
{
showEventTimer--;
if (!showEventTimer)
{
showEventTimer = EVENT_TIME;
for (uint8_t i = 0; i < (sizeof(events) / sizeof(event_t)); i++)
{
if ((day() == events[i].day) && (month() == events[i].month))
{
if (events[i].year)
feedText = " " + events[i].text + " (" + String(year() - events[i].year) + ") ";
else
feedText = " " + events[i].text + " ";
feedPosition = 0;
feedColor = events[i].color;
#ifdef DEBUG
Serial.println("Event: \"" + feedText + "\"");
#endif
setMode(MODE_FEED);
}
}
}
}
#endif
}
//*************************************************************************
// Run always
//*************************************************************************
if (mode == MODE_FEED)
screenBufferNeedsUpdate = true;
// Call HTTP- and OTA-handle
webServer.handleClient();
ArduinoOTA.handle();
// Set brightness from LDR and update display (not screenbuffer) at 40Hz.
#ifdef LDR
if (settings.mySettings.useAbc)
{
if ((millis() > iBrightnessMillis + 25) && !testFlag)
{
iBrightnessMillis = millis();
iTargetBrightness = getBrightnessFromLDR();
if (brightness < iTargetBrightness) brightness++;
if (brightness > iTargetBrightness) brightness--;
writeScreenBuffer(matrix, settings.mySettings.color, brightness);
}
}
#endif
#ifdef IR_RECEIVER
// Look for IR commands
if (irrecv.decode(&irDecodeResult))
{
#ifdef DEBUG_IR
Serial.print("IR signal: 0x");
serialPrintUint64(irDecodeResult.value, HEX);
Serial.println();
#endif
switch (irDecodeResult.value)
{
case IR_CODE_ONOFF:
buttonOnOffPressed();
break;
case IR_CODE_TIME:
buttonTimePressed();
break;
case IR_CODE_MODE:
buttonModePressed();
break;
}
irrecv.resume();
}
#endif
// Render a new screenbuffer if needed
if (screenBufferNeedsUpdate)
{
screenBufferNeedsUpdate = false;
// Save old screenbuffer (or not if it's the test pattern)
if (testFlag)
{
for (uint8_t i = 0; i <= 9; i++) matrixOld[i] = 0;
testFlag = false;
}
else
for (uint8_t i = 0; i <= 9; i++) matrixOld[i] = matrix[i];
switch (mode)
{
case MODE_TIME:
#if defined(SHOW_MODE_SUNRISE_SUNSET) && defined(WEATHER)
sunrise_started = false;
sunset_started = false;
#endif
renderer.clearScreenBuffer(matrix);
#ifdef FRONTCOVER_BINARY
matrix[0] = 0b1111000000000000;
matrix[1] = hour() << 5;
matrix[2] = minute() << 5;
matrix[3] = second() << 5;
matrix[5] = 0b1111000000000000;
matrix[6] = day() << 5;
matrix[7] = month() << 5;
matrix[8] = year() - 2000 << 5;
#else
renderer.setTime(hour(), minute(), matrix);
renderer.setCorners(minute(), matrix);
if (!settings.mySettings.itIs && ((minute() / 5) % 6)) renderer.clearEntryWords(matrix);
#endif
#ifdef BUZZER
if (settings.mySettings.alarm1 || settings.mySettings.alarm2 || alarmTimerSet) renderer.setAlarmLed(matrix);
#endif
break;
#ifdef SHOW_MODE_AMPM
case MODE_AMPM:
renderer.clearScreenBuffer(matrix);
isAM() ? renderer.setSmallText("AM", TEXT_POS_MIDDLE, matrix) : renderer.setSmallText("PM", TEXT_POS_MIDDLE, matrix);
break;
#endif
#ifdef SHOW_MODE_SECONDS
case MODE_SECONDS:
renderer.clearScreenBuffer(matrix);
renderer.setCorners(minute(), matrix);
for (uint8_t i = 0; i <= 6; i++)
{
matrix[1 + i] |= numbersBig[second() / 10][i] << 11;
matrix[1 + i] |= numbersBig[second() % 10][i] << 5;
}
break;
#endif
#ifdef SHOW_MODE_WEEKDAY
case MODE_WEEKDAY:
renderer.clearScreenBuffer(matrix);
renderer.setSmallText(String(sWeekday[weekday()][0]) + String(sWeekday[weekday()][1]), TEXT_POS_MIDDLE, matrix);
break;
#endif
#ifdef SHOW_MODE_DATE
case MODE_DATE:
renderer.clearScreenBuffer(matrix);
if (day() < 10)
renderer.setSmallText(("0" + String(day())), TEXT_POS_TOP, matrix);
else
renderer.setSmallText(String(day()), TEXT_POS_TOP, matrix);
if (month() < 10)
renderer.setSmallText(("0" + String(month())), TEXT_POS_BOTTOM, matrix);
else
renderer.setSmallText(String(month()), TEXT_POS_BOTTOM, matrix);
renderer.setPixelInScreenBuffer(5, 4, matrix);
renderer.setPixelInScreenBuffer(5, 9, matrix);
break;
#endif
#if defined(SHOW_MODE_SUNRISE_SUNSET) && defined(WEATHER)
case MODE_SUNRISE:
if (!sunrise_started)
{
sunrise_unix = timeZone.toLocal(outdoorWeather.sunrise);
sunrise_started = true;
sunrise_millis = millis();
save_color_sunrise_sunset = settings.mySettings.color;
}
// if (millis() < sunrise_millis + SUNSET_SUNRISE_SPEED * 0.5 * 0.333)
if (millis() < sunrise_millis + 1000)
{
settings.mySettings.color = YELLOW;
renderer.clearScreenBuffer(matrix);
// Sunrise screen
matrix[0] = 0b0000000000000000;
matrix[1] = 0b0000000000000000;
matrix[2] = 0b0000000000000000;
matrix[3] = 0b0000000000000000;
matrix[4] = 0b0000000000000000;
matrix[5] = 0b0000111000000000;
matrix[6] = 0b0011111110000000;
matrix[7] = 0b0111111111000000;
matrix[8] = 0b0111111111000000;
matrix[9] = 0b1111111111100000;
}