-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20260104_electricity_ticker_10_6_0_github.ino
More file actions
1662 lines (1402 loc) · 54.2 KB
/
20260104_electricity_ticker_10_6_0_github.ino
File metadata and controls
1662 lines (1402 loc) · 54.2 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
/*
20260127_electricity_ticker_6_0_nvs_daily_fetch.ino
-----------------------------------------------------
Derived from: 20251027_electricity_ticker_10_5_5_latest_DST_fix.ino (v5.5)
VERSION 6.0 CHANGES (2026-01-27):
---------------------------------
GOALS:
- Reduce API calls (boot + post‑midnight only, with retries).
- Use ESP32‑C3 NVS to store daily API data (prices + timestamps).
- Improve resilience after power outage by reusing same‑day stored data.
- Keep LCD/LED/button UI behavior identical where possible.
MAIN BEHAVIOR CHANGES:
1. API CALL OPTIMIZATION:
- On boot:
* Wi‑Fi + NTP time sync as before.
* Check NVS for stored data.
- If stored data is for *today*, load it and skip initial API fetch.
- If stored data is for previous day (or invalid), DO NOT use it.
- Normal operation:
* No longer fetch at the top of *every* hour.
* Instead:
- One fetch on boot (only if NVS does not already have today's data).
- Another fetch after local midnight rollover, with retry logic.
* Display and LED updates run continuously using in‑memory data until
the next successful daily fetch.
2. MIDNIGHT FETCH & RETRY LOGIC:
- On local day rollover (midnight detected via trackedDay):
* Immediately:
- Mark isTodayDataAvailable = false.
- Force displayState = NO_DATA_OFFSET.
- Turn off LEDs (same as "no data").
- Clear any "today" data markers in RAM.
* Start midnight fetch sequence:
- First fetch scheduled immediately at midnight.
- If first (or any) midnight fetch attempt fails:
- Keep "No data for today" on LCD.
- Keep LEDs off (no data).
- Retry policy:
a) Retry every 10 minutes, up to 5 attempts total.
b) If still unsuccessful after 5 attempts, then retry once at the
top of each following hour until data for today is obtained.
- As soon as a fetch for today succeeds:
- isTodayDataAvailable = true
- displayState automatically switches back to CURRENT_PRICES
(existing absolute‑state logic reused).
- LEDs resume reflecting current prices as before.
3. NVS STORAGE LOGIC:
- Namespace: "my-ticker".
- Keys:
* "ssid" / "pass" (unchanged, Wi‑Fi credentials)
* "data_day" (int, 1‑31)
* "data_mon" (int, 0‑11)
* "data_year" (int, e.g. 2026)
* "data_prc" (raw JSON string of last successful API response)
* "data_last_store" (time_t, unix seconds when data last written)
- On boot:
* Load "data_day", "data_mon", "data_year".
* Compare with current local date (after time sync).
* If same calendar day:
-> parse "data_prc" back into `doc` and call processJsonData().
-> isTodayDataAvailable = true; no immediate API fetch needed.
Else:
-> DO NOT use stored data for display.
-> System behaves as if no data exists for today.
- After each successful fetch for today:
* Save entire API JSON payload + date + unix store time into NVS.
* Overwrite previous day's content.
* Update secondary menu "NVS status" screen.
4. UI / MENU CHANGES:
- Keep all LCD layout, LED behavior, and button behavior the same.
* Primary list: unchanged.
* Secondary list base content: still 16 lines.
- NEW: NVS status section in secondary menu:
* Adds 4 extra scrollable lines (total 20 lines instead of 16).
* Layout (lines 16–19):
16: "NVS status:"
17: "Data day: DD.MM.YYYY"
or "Data day: none"
18: "Last save: DD.MM.YY"
or "Last save: none"
19: "OK" or "ERR" (basic internal status text)
* All strings limited to <=20 characters to fit 20x4 LCD.
5. SAFETY / CLARITY:
- Yesterday's data is never displayed as today's:
* On boot: previous‑day stored data is ignored.
* After midnight: previous‑day in‑RAM data is invalidated and UI is
forced into "No data for today" until the first successful new fetch.
*/
// ========================================================================
// Dynamic Electricity Ticker for XIAO ESP32C3 - VERSION 6.0
// 15-MINUTE DETAIL MODE, DST / TIMEZONE FIXED (CET <-> CEST automatic)
// ========================================================================
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <math.h>
#include <Preferences.h> // For non-volatile storage
#include <DNSServer.h> // For captive portal
#include <WebServer.h> // For provisioning web server
#include <time.h>
// ========================================================================
// CONFIG STRUCT
// ========================================================================
struct Config {
static const int JSON_BUFFER_SIZE = 4096;
static const int HTTP_TIMEOUT = 10000;
static const int HTTP_CONNECT_TIMEOUT = 5000;
static const int WIFI_RETRY_MAX = 20;
static const int NTP_TIMEOUT = 15000;
static const int LOOP_UPDATE_INTERVAL = 100;
};
#define DEBUG_LEVEL 2
#define HAS_WHITE_LED true
// ========================================================================
// GLOBALS
// ========================================================================
const int whiteLedPin = 5;
const int builtinLedPin = 21;
const int buttonPin = 4;
const int presencePin = 9;
bool ledsConnected = HAS_WHITE_LED;
bool areLedsOn = false;
int breatheValue = 0;
int breatheDir = 1;
unsigned long lastBreatheMillis = 0;
const int breatheInterval = 10;
bool blinkState = false;
unsigned long lastBlinkMillis = 0;
const int BLINK_INTERVAL_1000MS = 1000;
const int BLINK_INTERVAL_500MS = 500;
const int BLINK_INTERVAL_200MS = 200;
bool doubleBlinkState = false;
int doubleBlinkCount = 0;
unsigned long lastDoubleBlinkMillis = 0;
const int DOUBLE_BLINK_FAST_INTERVAL = 200;
const int DOUBLE_BLINK_LONG_ON_INTERVAL = 400;
const int DOUBLE_BLINK_PAUSE_INTERVAL = 1000;
const float PRICE_THRESHOLD_0_05 = 0.05;
const float PRICE_THRESHOLD_0_15 = 0.15;
const float PRICE_THRESHOLD_0_25 = 0.25;
const float PRICE_THRESHOLD_0_35 = 0.35;
const float PRICE_THRESHOLD_0_50 = 0.50;
LiquidCrystal_I2C lcd(0x27, 20, 4);
const char* api_url = "https://api.energy-charts.info/price?bzn=SI";
// Scheduling & retry
time_t nextScheduledFetchTime = 0;
int lastSuccessfulFetchDay = 0;
int httpGetRetryCount = 0;
const int HTTP_GET_RETRY_MAX = 5;
const int HTTP_GET_BACKOFF_FACTOR = 2;
time_t lastSuccessfulFetchTime = 0;
int apiSuccessCount = 0;
int apiFailCount = 0;
// Timezone
const long gmtOffset_sec = 3600;
const int daylightOffset_sec = 3600;
const char* TZ_CET_CEST = "CET-1CEST,M3.5.0/02:00,M10.5.0/03:00";
// Price computation
const bool APPLY_FEES_AND_VAT = true;
const float POWER_COMPANY_FEE_PERCENTAGE = 12.0;
const float VAT_PERCENTAGE = 22.0;
// Button handling
int buttonState = 0;
int lastButtonState = 0;
unsigned long lastDebounceTime = 0;
unsigned long buttonPressStartTime = 0;
bool longPressDetected = false;
const unsigned long debounceDelay = 50;
const unsigned long longPressThreshold = 3000;
unsigned long lastClickTime = 0;
const unsigned long doubleClickWindow = 500;
bool waitingForDoubleClick = false;
bool pendingClick = false;
// Auto scroll timeout
unsigned long lastButtonActivity = 0;
const unsigned long autoScrollTimeout = 10000;
bool autoScrollExecuted = false;
// Time-based display refresh markers
unsigned long lastHourlyRefresh = 0;
unsigned long last15MinRefresh = 0;
// Secondary list / menu
int secondaryListOffset = 0;
// INCREASED: now 20 lines total (16 old + 4 NVS status)
const int SECONDARY_LIST_TOTAL_LINES = 20;
const int SECONDARY_LIST_SCROLL_INCREMENT = 4;
// Backlight / presence
const unsigned long backlightOffDelay = 30000;
unsigned long lastPresenceTime = 0;
bool presenceSensorConnected = false;
// Loop pacing
unsigned long lastLoopUpdate = 0;
// Display state
enum DisplayState { CURRENT_PRICES, CUSTOM_MESSAGE, NO_DATA_OFFSET };
DisplayState displayState = CURRENT_PRICES;
int timeOffsetHours = 0;
enum ListType { PRIMARY_LIST, SECONDARY_LIST };
ListType currentList = PRIMARY_LIST;
// JSON doc and data flags
StaticJsonDocument<Config::JSON_BUFFER_SIZE> doc;
bool isTodayDataAvailable = false;
float averagePrice = 0.0;
int lowestPriceIndex = -1;
int highestPriceIndex = -1;
// NVS and provisioning
Preferences preferences;
DNSServer dnsServer;
WebServer server(80);
const char* ap_ssid = "MyTicker_Setup";
bool inProvisioningMode = false;
bool needsRestart = false;
// Time sync flag
bool isTimeSynced = false;
bool initialBoot = true;
// NEW: Track the current local day so we can detect midnight rollover
int trackedDay = -1;
// NEW: NVS-related state (for secondary menu / debug)
bool nvsDataLoadedForToday = false;
bool nvsDataPresent = false;
int nvsStoredDay = -1;
int nvsStoredMonth = -1;
int nvsStoredYear = -1;
time_t nvsLastStoreTime = 0;
// NEW: Midnight retry tracking
int midnightRetryCount = 0; // Number of 10-minute retries attempted since midnight (max 5)
bool midnightPhaseActive = false; // true from midnight rollover until successful fetch for that day
// ========================================================================
// CUSTOM CHARACTER BITMAPS
// ========================================================================
byte bitmap_c[8] = { B00100, B00000, B01110, B10001, B10000, B10001, B01110, B00000 };
byte bitmap_s[8] = { B00100, B00000, B01110, B10000, B01110, B00001, B11110, B00000 };
byte bitmap_z[8] = { B00100, B00000, B11111, B00010, B00100, B01000, B11111, B00000 };
byte lo_prc[] = { B00000, B00100, B00100, B00100, B10101, B01110, B00100, B00000 };
byte hi_prc[] = { B00000, B00100, B01110, B10101, B00100, B00100, B00100, B00000 };
// Forward declarations
int getCurrentQuarterHourIndex();
void displayPrices();
void processJsonData();
void scheduleAfterMidnightFailure();
// ========================================================================
// UTILS
// ========================================================================
void debugPrint(int level, const String& message) {
#if DEBUG_LEVEL >= 1
if (DEBUG_LEVEL >= level) {
Serial.println("[DEBUG] " + message);
}
#endif
}
void lcdPrint(const char* text) {
for (int i = 0; text[i] != '\0'; i++) {
char currentChar = text[i];
if (currentChar == '^') {
lcd.write(byte(0));
} else if (currentChar == '~') {
lcd.write(byte(1));
} else if (currentChar == '|') {
lcd.write(byte(2));
} else {
lcd.print(currentChar);
}
}
}
void commaPrint(float value, int places) {
String numStr = String(value, places);
numStr.replace('.', ',');
lcd.print(numStr);
}
bool isValidUnixTime(unsigned long timestamp) {
return (timestamp > 946684800UL && timestamp < 2147483647UL);
}
// ========================================================================
// PROVISIONING
// ========================================================================
void startProvisioning() {
debugPrint(1, "Starting Wi-Fi Provisioning AP");
inProvisioningMode = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("No Wi-Fi access!");
lcd.setCursor(0, 1);
lcd.print("Setup Wi-Fi:");
lcd.setCursor(0, 2);
lcd.print("SSID: MyTicker_Setup");
WiFi.mode(WIFI_AP);
WiFi.softAP(ap_ssid);
IPAddress apIP = WiFi.softAPIP();
dnsServer.start(53, "*", apIP);
lcd.setCursor(0, 3);
lcd.print("IP: " + apIP.toString());
debugPrint(1, "AP IP address: " + apIP.toString());
server.onNotFound([]() {
String html = "<h3>Wi-Fi Setup</h3><form action='/save' method='get'>SSID: <input type='text' name='ssid'><br>Password: <input type='password' name='pass'><br><input type='submit' value='Save'></form>";
server.send(200, "text/html", html);
});
server.on("/save", HTTP_GET, []() {
String newSsid = server.arg("ssid");
String newPass = server.arg("pass");
if (newSsid.length() > 0) {
preferences.begin("my-ticker", false);
preferences.putString("ssid", newSsid);
preferences.putString("pass", newPass);
preferences.end();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Saved!");
lcd.setCursor(0, 1);
lcd.print("Restarting...");
server.send(200, "text/html", "Wi-Fi credentials saved. Restarting ESP32...");
needsRestart = true;
debugPrint(1, "Credentials saved, restarting.");
} else {
server.send(200, "text/html", "Invalid credentials. Please go back and try again.");
}
});
server.begin();
debugPrint(1, "HTTP server started");
}
void handleProvisioning() {
dnsServer.processNextRequest();
server.handleClient();
}
void connectToWiFi() {
String stored_ssid = "";
String stored_pass = "";
preferences.begin("my-ticker", false);
stored_ssid = preferences.getString("ssid", "");
stored_pass = preferences.getString("pass", "");
preferences.end();
if (stored_ssid.length() > 0) {
lcd.setCursor(0, 0);
lcd.print("Elec. Rate SI v6.0");
lcd.setCursor(0, 1);
lcd.print("Connecting...");
WiFi.begin(stored_ssid.c_str(), stored_pass.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < Config::WIFI_RETRY_MAX) {
delay(500);
lcd.setCursor(12 + (attempts % 8), 1);
lcd.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
debugPrint(2, "WiFi connected successfully");
digitalWrite(builtinLedPin, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Connected!");
lcd.setCursor(0, 1);
lcd.print(WiFi.localIP());
delay(2000);
lcd.backlight();
} else {
debugPrint(1, "WiFi connection failed after " + String(attempts) + " attempts");
digitalWrite(builtinLedPin, LOW);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WiFi Failed!");
startProvisioning();
}
} else {
startProvisioning();
}
}
// ========================================================================
// LED HANDLING
// ========================================================================
void updateLeds() {
if (!ledsConnected || !areLedsOn || !isTodayDataAvailable || !isTimeSynced) {
digitalWrite(whiteLedPin, LOW);
breatheValue = 0;
breatheDir = 1;
blinkState = LOW;
doubleBlinkCount = 0;
return;
}
JsonArray prices = doc["price"];
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) return;
int currentHour = timeinfo.tm_hour;
int quarterHourIndex = getCurrentQuarterHourIndex();
int currentIntervalIndex = currentHour * 4 + quarterHourIndex;
if (currentIntervalIndex >= (int)prices.size()) {
digitalWrite(whiteLedPin, LOW);
return;
}
float currentRate = prices[currentIntervalIndex].as<float>();
if (currentRate <= 0) {
digitalWrite(whiteLedPin, LOW);
return;
}
float finalPrice = currentRate;
if (APPLY_FEES_AND_VAT) {
finalPrice = finalPrice * (1 + POWER_COMPANY_FEE_PERCENTAGE / 100.0) * (1 + VAT_PERCENTAGE / 100.0);
}
finalPrice /= 1000.0;
if (finalPrice <= PRICE_THRESHOLD_0_05) {
if (millis() - lastBreatheMillis > breatheInterval) {
breatheValue += breatheDir;
if (breatheValue >= 255 || breatheValue <= 0) {
breatheDir *= -1;
}
analogWrite(whiteLedPin, breatheValue);
lastBreatheMillis = millis();
}
doubleBlinkCount = 0;
} else if (finalPrice <= PRICE_THRESHOLD_0_15) {
digitalWrite(whiteLedPin, HIGH);
doubleBlinkCount = 0;
} else if (finalPrice <= PRICE_THRESHOLD_0_25) {
if (millis() - lastBlinkMillis > BLINK_INTERVAL_1000MS) {
blinkState = !blinkState;
digitalWrite(whiteLedPin, blinkState);
lastBlinkMillis = millis();
}
doubleBlinkCount = 0;
} else if (finalPrice <= PRICE_THRESHOLD_0_35) {
if (millis() - lastBlinkMillis > BLINK_INTERVAL_500MS) {
blinkState = !blinkState;
digitalWrite(whiteLedPin, blinkState);
lastBlinkMillis = millis();
}
doubleBlinkCount = 0;
} else if (finalPrice <= PRICE_THRESHOLD_0_50) {
int targetBlinks = 2;
if (doubleBlinkCount < targetBlinks * 2) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_FAST_INTERVAL) {
doubleBlinkState = !doubleBlinkState;
digitalWrite(whiteLedPin, doubleBlinkState);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_PAUSE_INTERVAL) {
doubleBlinkCount = 0;
lastDoubleBlinkMillis = millis();
}
}
} else {
if (doubleBlinkCount == 0) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_PAUSE_INTERVAL) {
digitalWrite(whiteLedPin, HIGH);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else if (doubleBlinkCount == 1) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_FAST_INTERVAL) {
digitalWrite(whiteLedPin, LOW);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else if (doubleBlinkCount == 2) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_FAST_INTERVAL) {
digitalWrite(whiteLedPin, HIGH);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else if (doubleBlinkCount == 3) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_FAST_INTERVAL) {
digitalWrite(whiteLedPin, LOW);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else if (doubleBlinkCount == 4) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_FAST_INTERVAL) {
digitalWrite(whiteLedPin, HIGH);
lastDoubleBlinkMillis = millis();
doubleBlinkCount++;
}
} else if (doubleBlinkCount == 5) {
if (millis() - lastDoubleBlinkMillis > DOUBLE_BLINK_LONG_ON_INTERVAL) {
digitalWrite(whiteLedPin, LOW);
lastDoubleBlinkMillis = millis();
doubleBlinkCount = 0;
}
}
}
}
// ========================================================================
// DATA FETCHING / NVS PERSISTENCE
// ========================================================================
// Helper: hourly average from 15-minute data
float getHourlyAverage(int hourIndex, const JsonArray& prices) {
if (hourIndex < 0 || hourIndex >= 24) return 0.0;
int startIndex = hourIndex * 4;
if (startIndex + 3 >= (int)prices.size()) return 0.0;
float sum = 0.0;
int validCount = 0;
for (int i = 0; i < 4; i++) {
if (startIndex + i < (int)prices.size()) {
sum += prices[startIndex + i].as<float>();
validCount++;
}
}
return validCount > 0 ? sum / validCount : 0.0;
}
// Helper: current 15‑minute index within hour
int getCurrentQuarterHourIndex() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) return 0;
int minute = timeinfo.tm_min;
return minute / 15;
}
// Helper: compact 15‑minute price formatting
void format15MinPrice(float price, char* buffer, int bufferSize) {
if (APPLY_FEES_AND_VAT) {
price = price * (1 + POWER_COMPANY_FEE_PERCENTAGE / 100.0) * (1 + VAT_PERCENTAGE / 100.0);
}
price /= 1000.0;
int hundredths = (int)round(price * 100);
if (hundredths > 99) {
snprintf(buffer, bufferSize, "+99");
} else if (hundredths < -99) {
snprintf(buffer, bufferSize, "-99");
} else if (hundredths >= 0) {
snprintf(buffer, bufferSize, " %02d", hundredths);
} else {
snprintf(buffer, bufferSize, "%03d", hundredths);
}
}
// ---- NVS helpers for data persistence ----
void saveDataToNVS(const String& rawJson) {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
debugPrint(1, "saveDataToNVS: cannot get local time, aborting save");
return;
}
int day = timeinfo.tm_mday;
int month = timeinfo.tm_mon; // 0-11
int year = timeinfo.tm_year + 1900; // full year
time_t now;
time(&now);
preferences.begin("my-ticker", false);
preferences.putInt("data_day", day);
preferences.putInt("data_mon", month);
preferences.putInt("data_year", year);
preferences.putString("data_prc", rawJson);
preferences.putULong("data_last_store", (unsigned long)now);
preferences.end();
nvsDataPresent = true;
nvsStoredDay = day;
nvsStoredMonth = month;
nvsStoredYear = year;
nvsLastStoreTime = now;
nvsDataLoadedForToday = true;
debugPrint(2, "Data saved to NVS for day " + String(day) + "." + String(month + 1) + "." + String(year));
}
bool loadDataFromNVSForToday() {
preferences.begin("my-ticker", false);
int storedDay = preferences.getInt("data_day", -1);
int storedMonth = preferences.getInt("data_mon", -1);
int storedYear = preferences.getInt("data_year", -1);
String storedJson = preferences.getString("data_prc", "");
unsigned long storedTime = preferences.getULong("data_last_store", 0);
preferences.end();
if (storedDay == -1 || storedMonth == -1 || storedYear == -1 || storedJson.length() == 0) {
debugPrint(1, "NVS: no valid stored data");
nvsDataPresent = false;
nvsDataLoadedForToday = false;
nvsStoredDay = -1;
nvsStoredMonth = -1;
nvsStoredYear = -1;
nvsLastStoreTime = 0;
return false;
}
nvsDataPresent = true;
nvsStoredDay = storedDay;
nvsStoredMonth = storedMonth;
nvsStoredYear = storedYear;
nvsLastStoreTime = storedTime;
struct tm nowInfo;
if (!getLocalTime(&nowInfo)) {
debugPrint(1, "NVS: cannot get local time to validate stored data");
nvsDataLoadedForToday = false;
return false;
}
if (storedDay == nowInfo.tm_mday &&
storedMonth == nowInfo.tm_mon &&
storedYear == (nowInfo.tm_year + 1900)) {
DeserializationError err = deserializeJson(doc, storedJson);
if (err) {
debugPrint(1, "NVS: failed to parse stored JSON: " + String(err.c_str()));
nvsDataLoadedForToday = false;
return false;
}
// Process data as if freshly fetched
processJsonData();
isTodayDataAvailable = true;
nvsDataLoadedForToday = true;
debugPrint(2, "NVS: loaded data for TODAY from NVS successfully");
return true;
} else {
debugPrint(1, "NVS: stored data is NOT for today - ignoring");
nvsDataLoadedForToday = false;
return false;
}
}
// ---- Core fetch & process ----
void fetchAndProcessData() {
// Require Wi‑Fi and valid time
if (WiFi.status() != WL_CONNECTED || !isTimeSynced) {
debugPrint(1, "Not connected to WiFi or time not synced.");
apiFailCount++;
return;
}
HTTPClient http;
http.begin(api_url);
http.setTimeout(Config::HTTP_TIMEOUT);
http.setConnectTimeout(Config::HTTP_CONNECT_TIMEOUT);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
debugPrint(2, "HTTP Response: " + String(httpResponseCode));
// Read full body into String so we can also store it into NVS
String payload = http.getString();
doc.clear();
DeserializationError error = deserializeJson(doc, payload);
if (error) {
debugPrint(1, "deserializeJson() failed: " + String(error.c_str()));
apiFailCount++;
displayPrices();
http.end();
return;
}
apiSuccessCount++;
time(&lastSuccessfulFetchTime);
// Process/validate "today" check
processJsonData();
// Only store into NVS if data is for TODAY
if (isTodayDataAvailable) {
saveDataToNVS(payload);
}
httpGetRetryCount = 0;
debugPrint(2, "Data fetched and processed successfully");
// Force display update
displayPrices();
// If we are in midnight retry phase and we now have today's data,
// end the midnight phase and reset counters.
if (midnightPhaseActive && isTodayDataAvailable) {
debugPrint(2, "Midnight phase completed successfully - data for today acquired");
midnightPhaseActive = false;
midnightRetryCount = 0;
}
// NOTE: In v6.0 we no longer schedule regular hourly fetches.
// nextScheduledFetchTime will be managed by midnight logic
// and possibly other explicit manual refresh triggers.
} else {
debugPrint(1, "HTTP request failed with code: " + String(httpResponseCode));
apiFailCount++;
httpGetRetryCount++;
displayPrices();
// For non-midnight usage (e.g. manual long-press refresh),
// schedule a modest backoff (10 minutes).
time_t now;
time(&now);
if (midnightPhaseActive) {
// In midnight phase we rely on dedicated retry scheduler.
// This fetchAndProcessData() call itself might have been from that,
// so we don't reschedule here (scheduler sets nextScheduledFetchTime).
debugPrint(2, "HTTP failed during midnight phase; scheduler will adjust next retries");
} else {
// Normal failure outside midnight:
nextScheduledFetchTime = now + 600; // 10 minutes
debugPrint(2, "HTTP failed (non-midnight). Next fetch scheduled in 10 minutes.");
}
}
http.end();
}
void processJsonData() {
JsonArray prices = doc["price"];
JsonArray unixSeconds = doc["unix_seconds"];
if (prices.size() == 0 || unixSeconds.size() == 0) {
debugPrint(1, "No price data in API response");
isTodayDataAvailable = false;
return;
}
unsigned long firstUnixTime = unixSeconds[0].as<unsigned long>();
time_t firstDataTime = (time_t)firstUnixTime;
struct tm* timeinfo_ptr = localtime(&firstDataTime);
struct tm currentTimeinfo;
if (!getLocalTime(¤tTimeinfo)) {
debugPrint(1, "Could not get current time for data validation.");
isTodayDataAvailable = false;
return;
}
if (timeinfo_ptr != NULL && timeinfo_ptr->tm_mday != currentTimeinfo.tm_mday) {
debugPrint(1, "Fetched data is not for the current day. Ignoring.");
isTodayDataAvailable = false;
// Force NO_DATA_OFFSET when data is not for today
if (displayState != NO_DATA_OFFSET) {
displayState = CURRENT_PRICES;
}
return;
}
// Data is for today
isTodayDataAvailable = true;
float sum = 0;
float minPrice = 999999;
float maxPrice = -999999;
lowestPriceIndex = 0;
highestPriceIndex = 0;
for (int hour = 0; hour < 24; hour++) {
float hourlyAvg = getHourlyAverage(hour, prices);
if (hourlyAvg > 0) {
sum += hourlyAvg;
if (hourlyAvg < minPrice) {
minPrice = hourlyAvg;
lowestPriceIndex = hour * 4;
}
if (hourlyAvg > maxPrice) {
maxPrice = hourlyAvg;
highestPriceIndex = hour * 4;
}
}
}
averagePrice = sum / 24.0;
debugPrint(3, "Processed " + String(prices.size()) + " price entries (15-min intervals)");
debugPrint(3, "Daily average: " + String(averagePrice) + " EUR/MWh");
}
// ========================================================================
// DISPLAY HELPERS
// ========================================================================
void display15MinuteDetails(int row, int hourIndex, const JsonArray& prices) {
lcd.setCursor(0, row);
if (hourIndex < 0 || hourIndex >= 24) {
lcd.print(" ");
return;
}
struct tm timeinfo;
int currentHour = -1;
int currentMinute = -1;
bool hasValidTime = false;
if (getLocalTime(&timeinfo)) {
currentHour = timeinfo.tm_hour;
currentMinute = timeinfo.tm_min;
hasValidTime = true;
// Prevent wraparound showing early hours at night
if (hourIndex >= 0 && hourIndex <= 5 && currentHour >= 18) {
lcd.print(" ");
return;
}
if (hourIndex < currentHour && currentHour < 22) {
lcd.print(" ");
return;
}
}
int startIndex = hourIndex * 4;
char priceBuffer[4];
int cursorPos = 0;
int currentSegment = -1;
if (hasValidTime && hourIndex == currentHour) {
currentSegment = currentMinute / 15;
}
for (int i = 0; i < 4; i++) {
bool shouldShowPlaceholder = false;
if (hasValidTime && hourIndex == currentHour && i < currentSegment) {
shouldShowPlaceholder = true;
}
if (shouldShowPlaceholder) {
lcd.print(" > ");
cursorPos += 3;
} else if (startIndex + i < (int)prices.size()) {
float price = prices[startIndex + i].as<float>();
format15MinPrice(price, priceBuffer, sizeof(priceBuffer));
lcd.print(priceBuffer);
cursorPos += 3;
} else {
lcd.print("---");
cursorPos += 3;
}
if (i < 3) {
lcd.print(" ");
cursorPos += 2;
}
}
for (int i = cursorPos; i < 20; i++) {
lcd.print(" ");
}
}
void displayPriceRow(int row, int hourIndex, const JsonArray& prices, const JsonArray& unixSeconds) {
lcd.setCursor(0, row);
struct tm timeinfo;
if (getLocalTime(&timeinfo)) {
int currentHour = timeinfo.tm_hour;
if (hourIndex >= 0 && hourIndex <= 5 && currentHour >= 18) {
lcd.print(" ");
return;
}
if (hourIndex < currentHour && currentHour < 22) {
lcd.print(" ");
return;
}
}
if (hourIndex >= 0 && hourIndex < 24) {
float rates = getHourlyAverage(hourIndex, prices);
int dataIndex = hourIndex * 4;
if (dataIndex < (int)unixSeconds.size()) {
unsigned long hourlyUnixTime = unixSeconds[dataIndex].as<unsigned long>();
if (isValidUnixTime(hourlyUnixTime)) {
time_t t = (time_t)hourlyUnixTime;
struct tm *time_ptr = localtime(&t);
if (time_ptr != NULL) {
char buffer[21];
int hour = time_ptr->tm_hour;
int minute = 0;
snprintf(buffer, sizeof(buffer), "%02d:%02d", hour, minute);
lcd.print(buffer);
if (dataIndex == lowestPriceIndex) {
lcd.setCursor(7, row);
lcd.write(byte(3));
lcd.print(" ");
} else if (dataIndex == highestPriceIndex) {
lcd.setCursor(7, row);
lcd.write(byte(4));
lcd.print(" ");
} else {
lcd.setCursor(6, row);
lcd.print(" ");
}
float finalPrice = rates;
if (APPLY_FEES_AND_VAT) {
finalPrice = finalPrice * (1 + POWER_COMPANY_FEE_PERCENTAGE / 100.0) * (1 + VAT_PERCENTAGE / 100.0);
}
finalPrice /= 1000.0;
if (finalPrice < 0) {
lcd.setCursor(9, row);
} else {
lcd.setCursor(10, row);
}
commaPrint(finalPrice, 4);
lcd.print(" EUR");
} else {
lcd.print("Time Error ");
}
} else {
lcd.print("Invalid Time ");
}
} else {
lcd.print("No Data Available ");
}
} else {
lcd.print(" ");
}