-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEPaper-Display-Weather-Clock.ino
More file actions
1553 lines (1362 loc) · 49.1 KB
/
Copy pathEPaper-Display-Weather-Clock.ino
File metadata and controls
1553 lines (1362 loc) · 49.1 KB
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
/*
epdWeatherClockV1.ino
Copyright (C) 2024 desiFish
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//=============== HEADER SECTION ===============
// E-paper weather clock v1 - Main code
// Uses GxEPD2 library for e-paper display control
// Using Huge App partition (3MB NO OTA/1MB SPIFFS)
//=============== CONFIGURATION ===============
// Enable/disable GxEPD2_GFX base class - uses ~1.2k more code
#define ENABLE_GxEPD2_GFX 0
#include <GxEPD2_3C.h> // 3-color e-paper display
#include <Fonts/FreeMonoBold9pt7b.h>
#include <U8g2_for_Adafruit_GFX.h> // Include U8g2 fonts
#include <Wire.h> // Used to establish serial communication on the I2C bus
#include <SparkFun_TMP117.h> // TMP117 temperature sensor library
#include <Adafruit_Sensor.h> // Adafruit sensor library
#include "Adafruit_BME680.h" // BME680 environmental sensor library
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "RTClib.h" // RTC library
#include "image.h" //for sleep icon
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <BH1750.h> // Light sensor library
#include <TimeLib.h> // for time functions
#include "icons.h" // for weather icons
#include <Arduino.h>
#include <ESPAsyncWebServer.h> // for web server
#include <AsyncTCP.h> // for tcp connection
#include <Preferences.h> // for storing data in flash memory
#include <esp_wifi.h> // for wifi functions
//=============== GLOBAL OBJECTS =================
Preferences pref;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// your wifi name and password
String ssid;
String password;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 19800); // 19800 is offset of India, pool.ntp.org automatically selects nearest pool for you
// save number of boots
RTC_DATA_ATTR int bootCount = 0; // Persistent boot counter stored in RTC memory
const byte ghostProtek = 5; // ghost protection, 5 means for every 5 boots, 1 boot will be in dark mode
// openWeatherMap Api Key from your profile in account section
String openWeatherMapApiKey = ""; // add your profile key here when running for the first time
// personal custom Api Key from your server
String customApiKey = ""; // add your api key here when running for the first time
// Replace with your lat and lon
String lat = "22.5895515";
String lon = "88.2876455";
RTC_DS3231 rtc; // Initalize rtc
TMP117 sensor; // Initalize temperature sensor
Adafruit_BME680 bme; // Initalize environmental sensor
BH1750 lightMeter(0x23); // Initalize light sensor
// Initalize display for 400x300, UC8276
GxEPD2_3C<GxEPD2_420c_Z21, GxEPD2_420c_Z21::HEIGHT> display(GxEPD2_420c_Z21(/*CS=5*/ /* SS*/ D7, /*DC=*/D1, /*RST=*/D2, /*BUSY=*/D3)); // universal declaration for XIAO series
#define BATPIN A0 // Battery voltage divider pin (1M Ohm with 104 Capacitor)
#define DEBUG_PIN D6 // Debug mode toggle pin
U8G2_FOR_ADAFRUIT_GFX u8g2Fonts; // u8g2 fonts
//=============== GLOBAL CONSTANTS ===============
#define BATTERY_LEVEL_SAMPLING 4 // BATTERY_LEVEL_SAMPLING: Number of samples to average for battery reading
#define battType 3.6 // battType: Battery nominal voltage (ICR: 4.2V, LFP: 3.6V) (Change accordingly)
#define battChangeThreshold 0.06 // battChangeThreshold: Minimum voltage change to update battery level
#define battHigh 3.3 // battHigh: Healthy battery threshold voltage (Change accordingly)
#define battLow 2.9 // battLow: Low battery warning threshold (Change accordingly)
#define critBattPercent 30 // critBattPercent: Critical battery percentage threshold
// #define SHOW_BATTERY_VOLT false // SHOW_BATTERY_VOLT: Set to true to display battery voltage, false to display percentage
/**
* @brief Sleep configuration
* uS_TO_S_FACTOR: Microseconds to seconds conversion
* TIME_TO_SLEEP: Sleep duration in seconds (default 15 mins)
*/
#define uS_TO_S_FACTOR 1000000
int TIME_TO_SLEEP = 900; // 15 minutes
//=============== GLOBAL VARIABLES ===============
// State variables
RTC_DATA_ATTR byte nightFlag = 0; // Night mode state preserved across sleep
RTC_DATA_ATTR float hTemp = 0.0; // Highest temperature recorded
RTC_DATA_ATTR float lTemp = 60.0; // Lowest temperature recorded
RTC_DATA_ATTR float battLevel = battType; // Battery level
RTC_DATA_ATTR bool BATTERY_CRITICAL = false; // Critical battery state
bool DEBUG_MODE = false; // Debug mode state
bool RTC_READY = false; // RTC hardware state
bool TMP117_READY = false; // TMP117 hardware state
bool BME680_READY = false; // BME680 hardware state
String jsonBuffer; // for storing json data from api
String systemAlertMessage = ""; // Hardware/runtime alerts shown in the alert line
char daysOfTheWeek[7][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
char monthName[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char fullDaysOfTheWeek[7][10] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const char fullMonthName[12][10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int httpResponseCode; // for storing http response code
const int16_t TOP_STATUS_HEIGHT = 14;
const int16_t TOP_STATUS_PADDING_X = 4;
const int16_t TOP_STATUS_TEXT_Y = 11;
const int16_t TOP_STATUS_ICON_Y = -1;
const int16_t TOP_STATUS_BATTERY_Y = 4;
const int16_t TOP_STATUS_BATTERY_WIDTH = 16;
const int16_t TOP_STATUS_WIFI_WIDTH = 12;
const int16_t TOP_STATUS_WIFI_ERROR_WIDTH = 13;
const int16_t TOP_STATUS_GAP = 6;
const byte TOP_STATUS_WIFI_CONNECTED = 0;
const byte TOP_STATUS_WIFI_OFF = 1;
const byte TOP_STATUS_WIFI_ERROR = 2;
// DEBUG_MODE update frequency
unsigned long lastTime1 = 0; // Last light sensor update
const long timerDelay1 = 60000; // Light sensor update interval (60 seconds)
// Define base URLs as const char arrays
const char OPEN_WEATHER_BASE_URL[] = "http://api.openweathermap.org/data/3.0/onecall?lat=";
const char OPEN_WEATHER_PARAMS[] = "&exclude=hourly,minutely&units=metric&appid=";
const char CUSTOM_WEATHER_BASE_URL[] = "http://iotthings.pythonanywhere.com/api/weatherStation/serve?api_key=";
//=============== HTML CODE =================
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><title>WiFi Setup</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font-family:Arial;text-align:center;margin:20px}input{margin:10px;padding:5px}form{background:#f0f0f0;padding:20px;display:inline-block}</style></head><body><h1>Weather Station Setup</h1><form action="/" method="POST"><label for="ssid">SSID</label><br><input type="text" id="ssid" name="ssid"><br><label for="pass">Password</label><br><input type="text" id="pass" name="pass"><br><input type="submit" value="Connect"></form></body></html>
)rawliteral";
// Search for parameter in HTTP POST request
const char *PARAM_INPUT_1 = "ssid";
const char *PARAM_INPUT_2 = "pass";
//=============== HELPER FUNCTIONS ===============
/**
* @brief Measures battery voltage with averaging
* @return float Averaged battery voltage in volts
* @note Uses voltage divider with 1MΩ resistor and 104 capacitor
*/
float batteryLevel()
{
uint32_t Vbatt = 0;
for (int i = 0; i < BATTERY_LEVEL_SAMPLING; i++)
{
Vbatt = Vbatt + analogReadMilliVolts(BATPIN); // ADC with correction
delay(10);
}
float Vbattf = 2 * Vbatt / BATTERY_LEVEL_SAMPLING / 1000.0; // attenuation ratio 1/2, mV --> V
// if (DEBUG_MODE) Serial.println(Vbattf);
return (Vbattf);
}
/**
* @brief Adds one hardware/runtime alert to the shared top alert line
*/
void addSystemAlert(const char *msg)
{
if (systemAlertMessage.indexOf(msg) >= 0)
return;
if (systemAlertMessage.length() > 0)
systemAlertMessage += " | ";
systemAlertMessage += msg;
}
/**
* @brief Builds the current alert line, including dynamic battery state
*/
String currentAlertText()
{
String text = systemAlertMessage;
if (BATTERY_CRITICAL)
{
if (text.length() > 0)
text += " | ";
text += "BATTERY CRITICAL";
}
return text;
}
/**
* @brief Prints an alert in the same compact "Alerts:" style used for weather alerts
* @param msg Alert text to print
* @param invert Clears the alert strip with the current screen background color
*/
void printAlertLine(const String &msg, bool invert)
{
uint16_t bg = invert ? GxEPD_BLACK : GxEPD_WHITE;
display.fillRect(0, TOP_STATUS_HEIGHT, display.width(), 16, bg);
if (msg.length() == 0)
return;
String text = "Alerts: " + msg;
u8g2Fonts.setFont(u8g2_font_luRS08_tf);
while (u8g2Fonts.getUTF8Width(text.c_str()) > display.width() && text.length() > 4)
text = text.substring(0, text.length() - 4) + "...";
uint16_t textWidth = u8g2Fonts.getUTF8Width(text.c_str());
int16_t x = 0;
if (textWidth < display.width())
x = (display.width() - textWidth) / 2;
u8g2Fonts.setCursor(x, TOP_STATUS_HEIGHT + 11);
u8g2Fonts.print(text);
}
void drawTopWifiIcon(byte wifiState, int16_t x, int16_t y, bool invert)
{
uint16_t fg = invert ? GxEPD_WHITE : GxEPD_BLACK;
if (wifiState == TOP_STATUS_WIFI_OFF)
display.drawBitmap(x, y, wifiOff, 12, 12, fg);
else if (wifiState == TOP_STATUS_WIFI_ERROR)
display.drawBitmap(x, y, wifiError, 13, 13, fg);
else if (WiFi.RSSI() >= -60)
display.drawBitmap(x, y, wifiOn, 12, 12, fg);
else
display.drawBitmap(x, y, wifiAvg, 12, 12, fg);
}
int16_t topStatusWifiX(byte wifiState)
{
u8g2Fonts.setFont(u8g2_font_luRS08_tf);
uint16_t timeWidth = u8g2Fonts.getUTF8Width("00:00");
int16_t wifiWidth = (wifiState == TOP_STATUS_WIFI_ERROR) ? TOP_STATUS_WIFI_ERROR_WIDTH : TOP_STATUS_WIFI_WIDTH;
return display.width() - TOP_STATUS_PADDING_X - timeWidth - TOP_STATUS_GAP - wifiWidth;
}
void drawTopStatusBar(float voltage, int percent, const char *timeText, bool invert, byte wifiState, const char *centerText)
{
uint16_t bg = invert ? GxEPD_BLACK : GxEPD_WHITE;
uint16_t fg = invert ? GxEPD_WHITE : GxEPD_BLACK;
display.fillRect(0, 0, display.width(), TOP_STATUS_HEIGHT, bg);
u8g2Fonts.setFont(u8g2_font_luRS08_tf);
u8g2Fonts.setForegroundColor(fg);
u8g2Fonts.setBackgroundColor(bg);
char voltageText[8];
char powerText[18];
dtostrf(voltage, 0, 2, voltageText);
if (voltage < 4)
snprintf(powerText, sizeof(powerText), "%sV %d%%", voltageText, percent);
else
snprintf(powerText, sizeof(powerText), "USB");
int16_t leftX = TOP_STATUS_PADDING_X;
iconBattery(display, percent, invert, leftX, TOP_STATUS_BATTERY_Y);
leftX += TOP_STATUS_BATTERY_WIDTH + TOP_STATUS_GAP;
u8g2Fonts.setCursor(leftX, TOP_STATUS_TEXT_Y);
u8g2Fonts.print(powerText);
leftX += u8g2Fonts.getUTF8Width(powerText);
uint16_t timeWidth = (timeText && timeText[0]) ? u8g2Fonts.getUTF8Width(timeText) : 0;
int16_t wifiWidth = (wifiState == TOP_STATUS_WIFI_ERROR) ? TOP_STATUS_WIFI_ERROR_WIDTH : TOP_STATUS_WIFI_WIDTH;
int16_t timeX = display.width() - TOP_STATUS_PADDING_X - timeWidth;
int16_t wifiX = timeX - TOP_STATUS_GAP - wifiWidth;
drawTopWifiIcon(wifiState, wifiX, TOP_STATUS_ICON_Y, invert);
if (timeWidth > 0)
{
u8g2Fonts.setCursor(timeX, TOP_STATUS_TEXT_Y);
u8g2Fonts.print(timeText);
}
if (centerText && centerText[0])
{
uint16_t centerWidth = u8g2Fonts.getUTF8Width(centerText);
int16_t centerX = (display.width() - centerWidth) / 2;
int16_t minCenterX = leftX + TOP_STATUS_GAP;
int16_t maxCenterX = wifiX - TOP_STATUS_GAP - centerWidth;
if (centerX < minCenterX)
centerX = minCenterX;
if (centerX <= maxCenterX)
{
u8g2Fonts.setCursor(centerX, TOP_STATUS_TEXT_Y);
u8g2Fonts.print(centerText);
}
}
}
/**
* @brief Disables WiFi and lowers CPU frequency
* @param extreme If true, uses the lowest CPU frequency for critical-battery mode
* @note Reduces CPU frequency and disables unused peripherals
*/
void turnOffWifi(bool extreme = false)
{
// Disable WiFi
WiFi.disconnect(true); // Disconnect and clear credentials
WiFi.mode(WIFI_OFF); // Set WiFi mode to off
esp_wifi_stop(); // Stop WiFi
// Additional power savings
btStop(); // Disable Bluetooth - more compatible than esp_bt_controller_disable()
// Reduce CPU frequency last
if (extreme)
setCpuFrequencyMhz(10); // Set CPU to 10MHz
else
setCpuFrequencyMhz(20); // Set CPU to 20MHz
delay(5); // wait for 5ms
if (DEBUG_MODE)
{
if (extreme)
Serial.println("Critical-battery power saver: WiFi off, CPU reduced");
else
Serial.println("WiFi off, CPU reduced after network activity");
Serial.print("CPU frequency MHz: ");
Serial.println(getCpuFrequencyMhz());
}
}
/**
* @brief Updates RTC time from NTP server if necessary
* If an update is needed and WiFi is connected, it fetches the current time
* from an NTP server and updates the RTC.
*
* @return bool Returns true if the time was successfully updated, false otherwise
* @note Requires an active WiFi connection to function
*/
bool autoTimeUpdate()
{
if (!RTC_READY)
return false;
if (WiFi.status() == WL_CONNECTED)
{
timeClient.begin();
if (timeClient.update() && timeClient.isTimeSet())
{
time_t rawtime = timeClient.getEpochTime();
struct tm *ti = localtime(&rawtime);
uint16_t year = ti->tm_year + 1900;
uint8_t month = ti->tm_mon + 1;
uint8_t day = ti->tm_mday;
rtc.adjust(DateTime(year, month, day,
timeClient.getHours(),
timeClient.getMinutes(),
timeClient.getSeconds()));
if (DEBUG_MODE)
{
Serial.print("RTC updated: ");
Serial.print(year);
Serial.print("-");
Serial.print(month);
Serial.print("-");
Serial.println(day);
}
return true;
}
else
return false;
}
else
return false;
}
/**
* @brief Prints temperature and environmental data
* @param offset Vertical offset for display positioning (default: 0)
* @param invert Inverts colors for ghost protection (default: false)
*/
void onlineTimePrint(bool invert = false);
/**
* @brief Displays network debugging information
* @param msg Message to display in debug info
*/
void networkInfo(const String &msg = "");
/**
* @brief Prints a compact alert line without replacing the full screen
* @param msg Alert text to print
* @param invert Clears the alert strip with the current screen background color
*/
void printAlertLine(const String &msg, bool invert);
/**
* @brief Fetches and displays weather data
* @param invert Inverts display colors for ghost protection
* @note Requires active WiFi connection and valid API keys
*/
void weatherPrint(bool invert = false);
//=============== MAIN SETUP AND LOOP ===============
/**
* @brief Initialize and configure all hardware and software components
*
* This function performs the following initializations:
* 1. CPU and Debug Configuration
* - Sets CPU frequency to power-saving mode (20MHz)
* - Initializes serial communication if in debug mode
* - Configures debug pin and mode
*
* 2. Power Management
* - Initializes battery monitoring
* - Manages critical battery state
* - Configures WiFi power state based on battery level
*
* 3. Hardware Initialization
* - Configures I2C communication
* - Initializes e-paper display
* - Sets up environmental sensors (TMP117, BME680)
* - Configures light sensor (BH1750)
*
* 4. State Management
* - Handles night mode transitions
* - Manages data persistence with preferences
* - Updates high/low temperature records
*
* 5. Network Configuration
* - Handles WiFi setup and connection
* - Configures NTP time synchronization
* - Sets up weather API access
*
* 6. Display Functions
* - Updates screen based on current state
* - Handles ghost protection display rotation
* - Shows status information and sensor data
*
* @note Enters deep sleep mode after completion unless in debug mode
* @note Some features are disabled when battery is critical
*/
void setup()
{
setCpuFrequencyMhz(20); // Set CPU to 20MHz
pinMode(BATPIN, INPUT);
pinMode(DEBUG_PIN, INPUT);
if (digitalRead(DEBUG_PIN) == 1) // Check if debug mode is enabled
DEBUG_MODE = true;
if (DEBUG_MODE)
{
Serial.begin(115200);
Serial.println("Setup");
Serial.println(getCpuFrequencyMhz());
}
pref.begin("database", false); // Open the preferences "database"
if (BATTERY_CRITICAL)
turnOffWifi(true); // turn off wifi to save power when battery is critical
Wire.begin(); // Start the I2C communication
Wire.setClock(400000); // Set clock speed to be the fastest for better communication (fast mode)
analogReadResolution(12); // Set ADC resolution to 12-bit
display.init(115200, true, 2, false); // USE THIS for Waveshare boards with "clever" reset circuit, 2ms reset pulse
u8g2Fonts.begin(display); // connect u8g2 procedures to Adafruit GFX
/*if (lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE))
{
if (DEBUG_MODE)
Serial.println(F("BH1750 Advanced begin"));
}
else
{
if (DEBUG_MODE)
Serial.println(F("Error initialising BH1750"));
addSystemAlert("BH1750 ERROR");
}
float lux = 0; // Light level in lux
while (!lightMeter.measurementReady(true))
{
yield(); // Wait for the measurement to be ready
}*/
float lux = 50; // lightMeter.readLightLevel(); // Get Lux value from sensor
if (DEBUG_MODE)
{
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
}
// if battery is critical, then no need to check wifi and weather api
if ((!BATTERY_CRITICAL && lux != 0) || DEBUG_MODE == true)
{
if (!pref.isKey("ssid"))
{ // create key:value pairs
pref.putString("ssid", "");
pref.putString("password", "");
}
ssid = pref.getString("ssid", "");
password = pref.getString("password", "");
if (ssid == "" || password == "")
{
setCpuFrequencyMhz(80); // Set CPU to 80MHz for wifi manager
// if no ssid or password saved, then start the wifi manager
if (DEBUG_MODE)
Serial.println("No values saved for ssid or password");
// Connect to Wi-Fi network with SSID and password
if (DEBUG_MODE)
Serial.println("Setting AP (Access Point)");
// NULL sets an open Access Point
WiFi.softAP("WCLOCK-WIFI-MANAGER", NULL);
IPAddress IP = WiFi.softAPIP();
if (DEBUG_MODE)
{
Serial.print("AP IP address: ");
Serial.println(IP);
}
debugPrinter("Connect to 'WCLOCK-WIFI-MANAGER' \nfrom your phone or computer (Wifi).\n\nThen go to " + IP.toString() + "\nfrom your browser.");
// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", index_html); });
server.on("/", HTTP_POST, [](AsyncWebServerRequest *request)
{
int params = request->params();
for (int i = 0; i < params; i++) {
const AsyncWebParameter *p = request->getParam(i);
if (p->isPost()) {
// HTTP POST ssid value
if (p->name() == PARAM_INPUT_1) {
ssid = p->value();
if (DEBUG_MODE) {
Serial.print("SSID set to: ");
Serial.println(ssid);
}
ssid.trim();
pref.putString("ssid", ssid);
}
// HTTP POST pass value
if (p->name() == PARAM_INPUT_2) {
password = p->value();
if (DEBUG_MODE) {
Serial.print("Password set to: ");
Serial.println(password);
}
password.trim(); // remove leading and trailing spaces
pref.putString("password", password);
}
//if (DEBUG_MODE) Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
}
}
request->send(200, "text/html", "<h2>Done. Weather Station will now restart</h2>");
delay(2000);
ESP.restart(); });
server.begin();
while (true)
yield(); // Runs forever
}
}
// if lux is 0, then the device is in dark mode and no need to initialize sensors
if (lux != 0 || DEBUG_MODE == true)
{
RTC_READY = rtc.begin();
if (RTC_READY)
{
if (DEBUG_MODE)
Serial.println("RTC Ready");
DateTime now = rtc.now();
if ((now.hour() == 0) && (now.minute() >= 0 && now.minute() <= 15))
{ // reset high low at midnight
hTemp = 0.0;
lTemp = 60.0;
}
}
else
{
if (DEBUG_MODE)
Serial.println("RTC unavailable; using 00:00 and placeholder date");
addSystemAlert("RTC ERROR");
}
TMP117_READY = sensor.begin();
if (TMP117_READY) // Function to check if the TMP117 will correctly self-identify with the proper Device ID/Address
{
if (DEBUG_MODE)
Serial.println("TMP117 Begin");
}
else
{
if (DEBUG_MODE)
Serial.println("TMP117 unavailable; displaying -- for indoor temperature");
addSystemAlert("TMP117 ERROR");
}
BME680_READY = bme.begin();
if (BME680_READY)
{
if (DEBUG_MODE)
Serial.println("BME Ready");
// Set up oversampling and filter initialization for accurate readings
bme.setTemperatureOversampling(BME680_OS_2X);
bme.setHumidityOversampling(BME680_OS_16X);
bme.setPressureOversampling(BME680_OS_16X);
bme.setIIRFilterSize(BME680_FILTER_SIZE_7);
bme.setGasHeater(0, 0); // 320°C for 150 ms
}
else
{
if (DEBUG_MODE)
Serial.println(F("BME680 unavailable; displaying -- for humidity and pressure"));
addSystemAlert("BME680 ERROR");
}
if (!BATTERY_CRITICAL) // Connect to Wi-Fi network with SSID and password if battery is not critical
{
setCpuFrequencyMhz(80); // Set CPU to 80MHz for wifi
delay(2);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
if (WiFi.waitForConnectResult() != WL_CONNECTED)
{
if (DEBUG_MODE)
Serial.println("WiFi connection failed");
}
if (WiFi.status() == WL_CONNECTED) // if wifi is connected
{
if (DEBUG_MODE)
{
Serial.println("IP Address: ");
Serial.println(WiFi.localIP());
}
if (RTC_READY)
{
// Get the current day
if (!pref.isKey("timeNeedsUpdate")) // create key:value pairs
pref.putBool("timeNeedsUpdate", true);
bool timeNeedsUpdate = pref.getBool("timeNeedsUpdate", false);
DateTime now = rtc.now();
if ((now.year() == 1970) || rtc.lostPower()) // if RTC lost power or not set
timeNeedsUpdate = true;
// Get the current day
byte currentDay = now.day();
// Check if we need to update time (every 15 days)
if (!pref.isKey("lastCheckedDay")) // create key:value pairs
pref.putUChar("lastCheckedDay", 0);
byte lastCheckedDay = pref.getUChar("lastCheckedDay", 0);
byte daysPassed = (currentDay - lastCheckedDay + 31) % 31;
if ((daysPassed >= 15) || timeNeedsUpdate) // check if 15 days passed or force update
{
Serial.println("RTC sync needed; updating time from NTP server");
if (autoTimeUpdate()) // Update time from NTP server
{
if (DEBUG_MODE)
Serial.println("RTC sync succeeded");
timeNeedsUpdate = false;
}
else
{
if (DEBUG_MODE)
Serial.println("RTC sync failed");
}
pref.putBool("timeNeedsUpdate", timeNeedsUpdate);
pref.putUChar("lastCheckedDay", currentDay); // Update last checked day
}
else
Serial.println("RTC sync not required");
}
else if (DEBUG_MODE)
{
Serial.println("RTC unavailable, skipping RTC time sync");
}
// Check if the API keys are saved in the preferences
if (!pref.isKey("api")) // create key:value pairs
pref.putString("api", openWeatherMapApiKey);
openWeatherMapApiKey = pref.getString("api", "");
if (!pref.isKey("apiCustom")) // create key:value pairs
pref.putString("apiCustom", customApiKey);
customApiKey = pref.getString("apiCustom", "");
}
else
turnOffWifi(); // turn off wifi to save power when wifi is not connected
}
}
if (DEBUG_MODE)
Serial.println("Setup done");
if (lux == 0)
{
TIME_TO_SLEEP = 300; // 5 min sleep time in dark mode
if (nightFlag == 0) // prevents unnecessary redrawing of same thing in dark mode
{
nightFlag = 1;
display.setRotation(0);
display.setFullWindow();
display.firstPage();
do
{
display.fillScreen(GxEPD_WHITE);
display.drawInvertedBitmap(0, 0, nightMode, 400, 300, GxEPD_BLACK); // display sleep icon
} while (display.nextPage());
}
display.hibernate();
display.powerOff();
}
else // if lux is not 0, then the device is in normal mode
{
nightFlag = 0;
display.setRotation(0);
display.setFullWindow();
display.firstPage();
do
{
if (WiFi.status() == WL_CONNECTED) // if wifi is connected, then fetch weather data
{
++bootCount; // increment the boot counter
if (DEBUG_MODE)
Serial.println("Drawing online time and weather screen");
if (bootCount == ghostProtek)
{
display.fillScreen(GxEPD_BLACK);
onlineTimePrint(true); // prints temperature and battery level
weatherPrint(true); // prints weather data
}
else // if not ghost protection, then normal display
{
display.fillScreen(GxEPD_WHITE);
onlineTimePrint(); // prints temperature and battery level
weatherPrint(); // prints weather data
}
if (bootCount == ghostProtek) // reset boot counter after ghost protection
bootCount = 0;
if (DEBUG_MODE)
Serial.println("Online time and weather screen drawn");
// Turn off WiFi as soon as possible
turnOffWifi();
}
else // if wifi is not connected, then only display time
{
display.fillScreen(GxEPD_WHITE);
if (DEBUG_MODE)
Serial.println("Drawing offline time screen");
offlineTimePrint();
if (DEBUG_MODE)
Serial.println("Offline time screen drawn");
if (BATTERY_CRITICAL)
TIME_TO_SLEEP = 1800; // 30 min sleep time when battery is critical (POWER SAVER MODE)
}
} while (display.nextPage());
display.hibernate();
display.powerOff();
}
if (DEBUG_MODE)
Serial.println("Closing preferences and I2C");
pref.end(); // Close the preferences
Wire.end(); // End I2C communication
if (DEBUG_MODE)
{
Serial.println("Preferences closed; I2C stopped");
Serial.print("Configured sleep interval: ");
Serial.print(TIME_TO_SLEEP / 60);
Serial.println(" min");
Serial.flush(); // Flush the serial buffer
delay(5);
}
if (!DEBUG_MODE) // if debug mode is off, then go to deep sleep
{
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); // Set the sleep time
esp_deep_sleep_start(); // Enter deep sleep
}
else
Serial.println("DEBUG_MODE active: staying awake and entering loop");
}
/**
* @brief Main loop function that runs continuously in debug mode
*
* This function only executes when DEBUG_MODE is true. It provides
* continuous monitoring and debugging capabilities by:
* 1. Checking timing conditions every timerDelay1 interval
* 2. Displaying debug messages on the e-paper display
* 3. Allowing for interactive testing and monitoring
*
* Future debug functionality can be added within the timer check.
* The function uses non-blocking delays via millis() to maintain
* responsiveness.
*
* @note This loop is skipped during normal operation (DEBUG_MODE = false)
* @note Uses timerDelay1 (60s) to prevent excessive display updates
*/
void loop()
{
if ((millis() - lastTime1) > timerDelay1)
{
Serial.println("In LOOP");
// addSystemAlert("DEBUG MODE"); // Display debug message
// Additional debug functions can be added here
lastTime1 = millis();
}
yield();
}
//=============== WEATHER AND DISPLAY FUNCTIONS ===============
/**
* @brief Fetches weather data from API endpoint
* @param serverName URL of the weather API endpoint
* @return String JSON response from server
*/
String weatherDataAPI(const char *serverName)
{
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
http.setTimeout(8000);
// Send HTTP POST request
httpResponseCode = http.GET();
String payload = "{}";
if (httpResponseCode > 0)
{
if (DEBUG_MODE)
{
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
payload = http.getString();
}
else
{
if (DEBUG_MODE)
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
}
// Free resources
http.end();
return payload;
}
/**
* @brief Checks HTTP response code and displays error if needed
* @param source String identifying the API source for debug messages
* @return bool Returns true if response code is 200, false otherwise
*/
bool checkHttpResponse(const char *source)
{
if (httpResponseCode != 200)
{
if (DEBUG_MODE)
{
Serial.print(source);
Serial.print(" API request failed with code: ");
Serial.println(httpResponseCode);
}
if (httpResponseCode == -1 || httpResponseCode == -11)
addSystemAlert("WEATHER API ERROR");
networkInfo(source);
return false;
}
return true;
}
/**
* @brief Prints temperature and environmental data when WiFi is connected
* @param invert Inverts colors for ghost protection
*
* Layout groups:
* 1. Sensor/cache refresh
* 2. Header: battery, status, update time
* 3. Main panel: date and indoor temperature
* 4. Footer strip: humidity, pressure, high/low temperature
*/
void onlineTimePrint(bool invert)
{
if (DEBUG_MODE)
Serial.println("Online Time Print");
//=============== 1. SENSOR AND STATE REFRESH ===============
float tempC = 0;
bool tempReady = TMP117_READY && sensor.dataReady();
if (tempReady)
{
tempC = sensor.readTempC();
hTemp = max(hTemp, tempC);
lTemp = min(lTemp, tempC);
}
float newBattLevel = batteryLevel();
bool acceptBatteryRise = ((newBattLevel - battLevel) >= battChangeThreshold) || (newBattLevel > battHigh);
if (newBattLevel < battLevel || acceptBatteryRise)
battLevel = newBattLevel;
int percent = constrain(((battLevel - battLow) / (battHigh - battLow)) * 100, 0, 100);
BATTERY_CRITICAL = percent < critBattPercent;
// Start BME680 sampling early so display drawing hides part of the wait.
bool bmeStarted = BME680_READY && bme.beginReading();
//=============== 2. DISPLAY STYLE ===============
uint16_t bg = invert ? GxEPD_BLACK : GxEPD_WHITE;
uint16_t fg = invert ? GxEPD_WHITE : GxEPD_BLACK;
uint16_t lineColor = (BATTERY_CRITICAL || invert) ? GxEPD_WHITE : GxEPD_RED;
u8g2Fonts.setFontMode(1);
u8g2Fonts.setFontDirection(0);
u8g2Fonts.setForegroundColor(fg);
u8g2Fonts.setBackgroundColor(bg);
//=============== 3. HEADER: POWER, WIFI, UPDATE TIME ===============
byte currentHour = 0;
byte currentMinute = 0;
byte currentDay = 0;
byte currentMonth = 0;
byte currentDayOfWeek = 0;
if (RTC_READY)
{
DateTime now = rtc.now();
currentHour = now.hour();
currentMinute = now.minute();
currentDay = now.day();
currentMonth = now.month();
currentDayOfWeek = now.dayOfTheWeek();
}
char timeStr[6] = "--:--";
if (RTC_READY)
snprintf(timeStr, sizeof(timeStr), "%02d:%02d", currentHour, currentMinute);
drawTopStatusBar(battLevel, percent, timeStr, invert, TOP_STATUS_WIFI_CONNECTED, invert ? "GHOSTING PROTECTION" : "");
//=============== 4. MAIN PANEL: DATE AND INDOOR TEMP ===============
u8g2Fonts.setFont(u8g2_font_logisoso20_tf);
u8g2Fonts.setCursor(10, 75);
if (RTC_READY)
{
if (currentDay < 10)
u8g2Fonts.print("0");
u8g2Fonts.print(currentDay);
u8g2Fonts.print(", ");
u8g2Fonts.print(monthName[currentMonth - 1]);
}
else
u8g2Fonts.print("--, ---");
u8g2Fonts.setCursor(10, 105);
u8g2Fonts.print(RTC_READY ? daysOfTheWeek[currentDayOfWeek] : "---");
u8g2Fonts.setFont(u8g2_font_inb19_mf);
u8g2Fonts.setCursor(320, 60);
u8g2Fonts.print("o");
u8g2Fonts.setFont(u8g2_font_logisoso58_tf);
u8g2Fonts.setCursor(150, 110);
if (tempReady)
u8g2Fonts.print(tempC);
else