Repository navigation
Expand file tree
/
Copy pathTankerkoenigModule.cpp
More file actions
1121 lines (956 loc) · 44.2 KB
/
Copy pathTankerkoenigModule.cpp
File metadata and controls
1121 lines (956 loc) · 44.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
#include "TankerkoenigModule.hpp"
#include "MultiLogger.hpp"
#include "WebClientModule.hpp"
#include "GeneralTimeConverter.hpp"
#include "FragmentationMonitor.hpp"
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <algorithm>
#include <esp_heap_caps.h>
#include "webconfig.hpp"
#define PRICE_CACHE_FILENAME "/last_prices.json"
#define FAILSAFE_BUFFER_MS 10000 // 10 Sekunden Puffer
StationData::StationData() : e5(0.0f), e10(0.0f), diesel(0.0f), isOpen(false), lastPriceChange(0) {}
TankerkoenigModule::TankerkoenigModule(U8G2_FOR_ADAFRUIT_GFX &u8g2, GFXcanvas16 &canvas, GeneralTimeConverter& timeConverter, int topOffset, WebClientModule* webClient, DeviceConfig* config)
: u8g2(u8g2), canvas(canvas), timeConverter(timeConverter), _deviceConfig(config), top_offset(topOffset), webClient(webClient), last_processed_update(0) {
dataMutex = xSemaphoreCreateMutex();
}
TankerkoenigModule::~TankerkoenigModule() {
if (dataMutex) vSemaphoreDelete(dataMutex);
if (pending_buffer) free(pending_buffer);
}
// =================================================================
// =========== IMPLEMENTIERUNG DER MODERN-SCHNITTSTELLE ============
// =================================================================
void TankerkoenigModule::configure(const ModuleConfig& config) {
_modConfig = config;
}
void TankerkoenigModule::onActivate() {
if (_modConfig.resetOnActivate) {
currentPage = 0;
}
_logicTicksSincePageSwitch = 0;
}
void TankerkoenigModule::resetPaging() {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
currentPage = 0;
_logicTicksSincePageSwitch = 0;
_isFinished = false;
xSemaphoreGive(dataMutex);
}
}
unsigned long TankerkoenigModule::getDisplayDuration() {
// Berechne Gesamtdauer basierend auf Anzahl Stationen * Dauer pro Station
unsigned long duration;
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
int num_pages = station_data_list.size() > 0 ? station_data_list.size() : 1;
duration = (num_pages * _pageDisplayDuration) + runtime_safe_buffer;
xSemaphoreGive(dataMutex);
} else {
duration = _pageDisplayDuration; // Fallback
}
return duration;
}
void TankerkoenigModule::tick() {
// Fordert Neuzeichnung an für flüssige Animationen
if (updateCallback) updateCallback();
}
void TankerkoenigModule::logicTick() {
// Wird alle 100ms aufgerufen
_logicTicksSincePageSwitch++;
if (_logicTicksSincePageSwitch >= _currentTicksPerPage) {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
int numPages = station_data_list.size() > 0 ? station_data_list.size() : 1;
currentPage++;
// Wenn alle Seiten durch -> Modul ist fertig
if (currentPage >= numPages) {
currentPage = 0;
_isFinished = true;
Log.printf("[Tanker] Alle %d Seiten gezeigt -> Modul beendet sich selbst\n", numPages);
} else if (totalPages > 1) {
if (updateCallback) updateCallback();
}
xSemaphoreGive(dataMutex);
}
_logicTicksSincePageSwitch = 0;
}
}
void TankerkoenigModule::updateFailsafeTimeout() {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
int num_pages = 0;
if (!_isEnabled) {
num_pages = 1;
} else {
PsramString temp_ids = this->station_ids;
if (temp_ids.empty()) {
num_pages = 1;
} else {
num_pages = 1;
for (char c : temp_ids) {
if (c == ',') {
num_pages++;
}
}
}
}
unsigned long expectedRuntime = (num_pages > 0 ? num_pages : 1) * _pageDisplayDuration;
this->maxRuntimeMs = expectedRuntime + FAILSAFE_BUFFER_MS;
xSemaphoreGive(dataMutex);
Log.printf("[TankerkoenigModule] Failsafe-Timeout auf %lu ms gesetzt (%d Seiten).\n", this->maxRuntimeMs, num_pages);
}
}
void TankerkoenigModule::setConfig(const PsramString& apiKey, const PsramString& stationIds, int fetchIntervalMinutes, unsigned long pageDisplaySec) {
this->api_key = apiKey;
this->station_ids = stationIds;
this->_pageDisplayDuration = pageDisplaySec > 0 ? pageDisplaySec * 1000UL : 10000;
// Berechne Ticks pro Seite für logicTick (100ms pro Tick)
_currentTicksPerPage = _pageDisplayDuration / 100; // z.B. 15000ms / 100ms = 150 Ticks
if (_currentTicksPerPage == 0) _currentTicksPerPage = 1; // Mindestens 1 Tick
_isEnabled = !apiKey.empty() && !stationIds.empty();
if (_isEnabled) {
this->resource_url = "https://creativecommons.tankerkoenig.de/json/prices.php?ids=";
this->resource_url += this->station_ids;
this->resource_url += "&apikey=";
this->resource_url += this->api_key;
webClient->registerResource(String(this->resource_url.c_str()), fetchIntervalMinutes, nullptr);
} else {
this->resource_url.clear();
}
updateFailsafeTimeout();
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(5000)) == pdTRUE) {
PsramVector<PsramString> current_id_list;
PsramString temp_ids = station_ids;
// FIX: Create a mutable copy for strtok_r to safely modify
char* temp_buffer = strdup(temp_ids.c_str());
if (temp_buffer) {
char* strtok_ctx;
char* id_token = strtok_r(temp_buffer, ",", &strtok_ctx);
while(id_token != nullptr) {
current_id_list.push_back(id_token);
id_token = strtok_r(nullptr, ",", &strtok_ctx);
}
free(temp_buffer);
}
// SAFETY: Only remove data if we successfully parsed station IDs
// This prevents accidental deletion of all data if parsing fails
if (!temp_ids.empty() && current_id_list.empty()) {
Log.println("[TankerkoenigModule] WARNING: Failed to parse station IDs, skipping cleanup to prevent data loss!");
} else {
auto remove_by_id = [&](const auto& entry){
for(const auto& id : current_id_list) { if (entry.stationId == id) return false; }
return true;
};
size_t original_stats_size = price_statistics.size();
price_statistics.erase(std::remove_if(price_statistics.begin(), price_statistics.end(), remove_by_id), price_statistics.end());
if(price_statistics.size() < original_stats_size) {
Log.printf("[TankerkoenigModule] Removed %d station histories no longer in config\n", original_stats_size - price_statistics.size());
#if TANKERKOENIG_SAVE_HISTORY
savePriceStatistics();
#endif
}
size_t original_cache_size = _lastPriceCache.size();
_lastPriceCache.erase(std::remove_if(_lastPriceCache.begin(), _lastPriceCache.end(), remove_by_id), _lastPriceCache.end());
if(_lastPriceCache.size() < original_cache_size) {
Log.printf("[TankerkoenigModule] Removed %d price cache entries no longer in config\n", original_cache_size - _lastPriceCache.size());
savePriceCache();
}
}
// Reload station cache to pick up any new stations from web search
loadStationCache();
xSemaphoreGive(dataMutex);
}
}
void TankerkoenigModule::begin() {
if (LittleFS.exists("/price_history.json")) {
Log.println("[TankerkoenigModule] Altes Preis-Format 'price_history.json' gefunden. Wird gelöscht.");
LittleFS.remove("/price_history.json");
}
if (LittleFS.exists("/avg_price_trends.json")) {
Log.println("[TankerkoenigModule] Veraltete Cache-Datei 'avg_price_trends.json' gefunden. Wird gelöscht.");
LittleFS.remove("/avg_price_trends.json");
}
// IMMER laden (unabhängig vom SAVE_HISTORY Flag)
loadPriceStatistics();
#if !TANKERKOENIG_SAVE_HISTORY
Log.println("[TankerkoenigModule] Historie-Speicherung DEAKTIVIERT (TANKERKOENIG_SAVE_HISTORY = false) - Daten werden NICHT persistiert");
#endif
loadStationCache();
loadPriceCache();
// SAFETY: Do NOT run cleanup at boot - wait for first data fetch to ensure time is synced
// cleanupOldPriceCacheEntries() will be called during first data update
Log.println("[TankerkoenigModule] Cleanup verzögert bis nach erster Datenaktualisierung (Zeit-Sync-Schutz)");
}
void TankerkoenigModule::onUpdate(std::function<void()> callback) {
updateCallback = callback;
}
bool TankerkoenigModule::isEnabled() { return _isEnabled; }
void TankerkoenigModule::queueData() {
LOG_MEM_OP("Tankerkoenig::queueData");
if (resource_url.empty() || !webClient) return;
webClient->accessResource(String(resource_url.c_str()), [this](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0 && last_update > this->last_processed_update) {
if (pending_buffer) free(pending_buffer);
pending_buffer = (char*)ps_malloc(size + 1);
if (pending_buffer) {
memcpy(pending_buffer, buffer, size);
pending_buffer[size] = '\0';
buffer_size = size;
last_processed_update = last_update;
data_pending = true;
}
}
});
}
void TankerkoenigModule::processData() {
LOG_MEM_OP("Tankerkoenig::processData");
if (data_pending) {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(5000)) == pdTRUE) {
parseAndProcessJson(pending_buffer, buffer_size);
free(pending_buffer);
pending_buffer = nullptr;
data_pending = false;
xSemaphoreGive(dataMutex);
if (this->updateCallback) this->updateCallback();
}
}
}
void TankerkoenigModule::parseAndProcessJson(const char* buffer, size_t size) {
JsonDocument doc;
PsramVector<StationData> new_station_data_list;
DeserializationError error = deserializeJson(doc, buffer, size);
if (!error && doc["ok"] == true) {
JsonObject prices = doc["prices"];
PsramVector<PsramString> id_list;
PsramString temp_ids = station_ids;
// FIX: Create a mutable copy for strtok_r to safely modify
char* temp_buffer = strdup(temp_ids.c_str());
if (temp_buffer) {
char* strtok_ctx;
char* id_token = strtok_r(temp_buffer, ",", &strtok_ctx);
while(id_token != nullptr) {
id_list.push_back(id_token);
id_token = strtok_r(nullptr, ",", &strtok_ctx);
}
free(temp_buffer);
}
_trendStatusCache.clear();
for (const auto& id : id_list) {
if (prices[id.c_str()].is<JsonObject>()) {
JsonObject station_json = prices[id.c_str()];
StationData new_data;
new_data.id = id;
for(const auto& cache_entry : station_cache) {
if (cache_entry.id == id) {
new_data.name = cache_entry.name; new_data.brand = cache_entry.brand;
new_data.street = cache_entry.street; new_data.houseNumber = cache_entry.houseNumber;
new_data.postCode = cache_entry.postCode; new_data.place = cache_entry.place;
break;
}
}
bool is_open = (station_json["status"] == "open");
new_data.isOpen = is_open;
const StationData* old_data_ptr = nullptr;
for(const auto& old_data : station_data_list) {
if (old_data.id == new_data.id) { old_data_ptr = &old_data; break; }
}
if (is_open) {
new_data.e5 = station_json["e5"].as<float>();
new_data.e10 = station_json["e10"].as<float>();
new_data.diesel = station_json["diesel"].as<float>();
if (old_data_ptr && (old_data_ptr->e5 != new_data.e5 || old_data_ptr->e10 != new_data.e10 || old_data_ptr->diesel != new_data.diesel)) {
new_data.lastPriceChange = last_processed_update;
} else if (old_data_ptr) {
new_data.lastPriceChange = old_data_ptr->lastPriceChange;
} else {
new_data.lastPriceChange = last_processed_update;
}
// IMMER Statistiken aktualisieren (Speichern wird intern geprüft)
updatePriceStatistics(new_data.id, new_data.e5, new_data.e10, new_data.diesel);
} else {
if (old_data_ptr && old_data_ptr->isOpen) {
updatePriceCache(new_data.id, old_data_ptr->e5, old_data_ptr->e10, old_data_ptr->diesel, old_data_ptr->lastPriceChange);
}
getPriceFromCache(new_data.id, new_data.e5, new_data.e10, new_data.diesel, new_data.lastPriceChange);
}
new_station_data_list.push_back(new_data);
// IMMER Trends berechnen (unabhängig vom Speichern)
updateAndDetermineTrends(id);
}
}
station_data_list = new_station_data_list;
// Run initial cleanup after first successful data fetch (ensures time is synced)
if (!_initialCleanupDone) {
_initialCleanupDone = true;
Log.println("[TankerkoenigModule] Führe initiales Cleanup durch (nach erster Datenaktualisierung)");
cleanupOldPriceCacheEntries();
}
} else { Log.printf("[TankerkoenigModule] JSON-Parsing-Fehler: %s\n", error.c_str()); }
}
void TankerkoenigModule::draw() {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(100)) != pdTRUE) return;
totalPages = station_data_list.size() > 0 ? station_data_list.size() : 1;
canvas.fillScreen(0);
u8g2.begin(canvas);
if (station_data_list.empty()) {
u8g2.setFont(u8g2_font_7x14_tf); u8g2.setForegroundColor(0xFFFF);
const char* text = "Keine Tankstelle konfiguriert.";
u8g2.setCursor((canvas.width() - u8g2.getUTF8Width(text)) / 2, 30);
u8g2.print(text);
xSemaphoreGive(dataMutex);
return;
}
const StationData& data = station_data_list[currentPage];
// Datenmocking: Erstelle gemockte Kopie der Daten nur für die Anzeige
PsramString displayStreet = data.street;
PsramString displayHouseNumber = data.houseNumber;
PsramString displayPostCode = data.postCode;
PsramString displayPlace = data.place;
if (_deviceConfig && _deviceConfig->dataMockingEnabled) {
displayStreet = "Musterstraße";
displayHouseNumber = "1";
displayPostCode = "12345";
displayPlace = "Musterstadt";
}
const int PADDING = 10;
const int LEFT_MARGIN = 5;
const int RIGHT_MARGIN = 5;
const int totalWidth = canvas.width() - LEFT_MARGIN - RIGHT_MARGIN;
u8g2.setFont(u8g2_font_helvB14_tf);
PsramString brandText = data.brand;
int brandWidth = u8g2.getUTF8Width(brandText.c_str());
u8g2.setFont(u8g2_font_5x8_tf);
PsramString line1 = displayStreet;
if (!displayHouseNumber.empty()) { line1 += " "; line1 += displayHouseNumber; }
PsramString line2 = displayPostCode;
if (!displayPlace.empty()) { line2 += " "; line2 += displayPlace; }
int addressWidth = std::max(u8g2.getUTF8Width(line1.c_str()), u8g2.getUTF8Width(line2.c_str()));
if (brandWidth + addressWidth + PADDING > totalWidth) {
int availableForBrand = brandWidth;
int availableForAddress = addressWidth;
if (brandWidth < (totalWidth - PADDING) / 2) {
availableForAddress = totalWidth - PADDING - brandWidth;
}
else if (addressWidth < (totalWidth - PADDING) / 2) {
availableForBrand = totalWidth - PADDING - addressWidth;
}
else {
availableForBrand = (totalWidth - PADDING) / 2;
availableForAddress = (totalWidth - PADDING) / 2;
}
if (brandWidth > availableForBrand) {
u8g2.setFont(u8g2_font_helvB14_tf);
brandText = truncateString(brandText, availableForBrand);
}
if (addressWidth > availableForAddress) {
u8g2.setFont(u8g2_font_5x8_tf);
line1 = truncateString(line1, availableForAddress);
line2 = truncateString(line2, availableForAddress);
}
}
u8g2.setFont(u8g2_font_helvB14_tf);
u8g2.setForegroundColor(0xFFFF);
u8g2.setCursor(LEFT_MARGIN, 15);
u8g2.print(brandText.c_str());
u8g2.setFont(u8g2_font_5x8_tf);
u8g2.setCursor(canvas.width() - u8g2.getUTF8Width(line1.c_str()) - RIGHT_MARGIN, 6);
u8g2.print(line1.c_str());
u8g2.setCursor(canvas.width() - u8g2.getUTF8Width(line2.c_str()) - RIGHT_MARGIN, 16);
u8g2.print(line2.c_str());
canvas.drawFastHLine(0, 17, canvas.width(), rgb565(128, 128, 128));
AveragePrices averages = calculateAverages(data.id);
if (averages.avgE5Low == 0.0) averages.avgE5Low = data.e5 > 0 ? data.e5 - 0.05 : 0;
if (averages.avgE5High == 0.0) averages.avgE5High = data.e5 > 0 ? data.e5 + 0.05 : 0;
if (averages.avgE10Low == 0.0) averages.avgE10Low = data.e10 > 0 ? data.e10 - 0.05 : 0;
if (averages.avgE10High == 0.0) averages.avgE10High = data.e10 > 0 ? data.e10 + 0.05 : 0;
if (averages.avgDieselLow == 0.0) averages.avgDieselLow = data.diesel > 0 ? data.diesel - 0.15 : 0;
if (averages.avgDieselHigh == 0.0) averages.avgDieselHigh = data.diesel > 0 ? data.diesel + 0.15 : 0;
u8g2.setFont(u8g2_font_5x8_tf);
u8g2.setForegroundColor(rgb565(0, 255, 255));
int y_pos = 25;
if (averages.count > 0 && _deviceConfig) {
char count_str[12];
snprintf(count_str, sizeof(count_str), "(%d/%d)", averages.count, _deviceConfig->movingAverageDays);
u8g2.setCursor(188 - u8g2.getUTF8Width(count_str), y_pos);
u8g2.print(count_str);
}
if (data.lastPriceChange > 0) {
time_t local_change_time = timeConverter.toLocal(data.lastPriceChange);
struct tm timeinfo;
gmtime_r(&local_change_time, &timeinfo);
char time_str[6]; strftime(time_str, sizeof(time_str), "%H:%M", &timeinfo);
u8g2.setCursor(84 + (50 - u8g2.getUTF8Width(time_str)) / 2, y_pos);
u8g2.print(time_str);
} else {
const char* no_time_str = "--:--";
u8g2.setCursor(84 + (50 - u8g2.getUTF8Width(no_time_str)) / 2, y_pos);
u8g2.print(no_time_str);
}
TrendStatus currentTrend;
for(const auto& ts : _trendStatusCache) {
if(ts.stationId == data.id) { currentTrend = ts; break; }
}
drawPriceLine(37, "E5", data.e5, averages.avgE5Low, averages.avgE5High, currentTrend.e5_min_trend, currentTrend.e5_max_trend);
drawPriceLine(50, "E10", data.e10, averages.avgE10Low, averages.avgE10High, currentTrend.e10_min_trend, currentTrend.e10_max_trend);
drawPriceLine(63, "Dies.", data.diesel, averages.avgDieselLow, averages.avgDieselHigh, currentTrend.diesel_min_trend, currentTrend.diesel_max_trend);
if (!data.isOpen) {
uint16_t red = rgb565(255, 0, 0);
canvas.drawLine(0, 17, canvas.width() - 1, canvas.height() - 1, red);
canvas.drawLine(canvas.width() - 1, 17, 0, canvas.height() - 1, red);
}
xSemaphoreGive(dataMutex);
}
void TankerkoenigModule::drawPriceLine(int y, const char* label, float current, float min, float max, PriceTrend minTrend, PriceTrend maxTrend) {
u8g2.setFont(u8g2_font_7x14_tf);
u8g2.setForegroundColor(0xFFFF);
u8g2.setCursor(2, y);
u8g2.print(label);
int x_min = 42, x_current = 92, x_max = 142;
int min_width = drawPrice(x_min, y, min, rgb565(0, 255, 0));
if(min > 0) drawTrendArrow(x_min + min_width + 2, y - 5, minTrend);
drawPrice(x_current, y, current, calcColor(current, min, max));
int max_width = drawPrice(x_max, y, max, rgb565(255, 0, 0));
if(max > 0) drawTrendArrow(x_max + max_width + 3, y - 6, maxTrend);
}
int TankerkoenigModule::drawPrice(int x, int y, float price, uint16_t color) {
if (price <= 0) return 0;
u8g2.setForegroundColor(color);
// Use stack buffer instead of String
char priceStr[16];
snprintf(priceStr, sizeof(priceStr), "%.3f", price);
// Replace . with ,
for (int i = 0; priceStr[i] != '\0'; ++i) {
if (priceStr[i] == '.') priceStr[i] = ',';
}
// Split into main part and last digit
int len = strlen(priceStr);
if (len == 0) return 0;
char mainPricePart[16];
strncpy(mainPricePart, priceStr, len - 1);
mainPricePart[len - 1] = '\0';
char last_digit_str[2] = {priceStr[len - 1], '\0'};
u8g2.setFont(u8g2_font_7x14_tf);
int mainPriceWidth = u8g2.getUTF8Width(mainPricePart);
u8g2.setCursor(x, y);
u8g2.print(mainPricePart);
int superscriptX = x + mainPriceWidth + 1;
u8g2.setFont(u8g2_font_5x8_tf);
int superscriptWidth = u8g2.getUTF8Width(last_digit_str);
u8g2.setCursor(superscriptX, y - 4);
u8g2.print(last_digit_str);
u8g2.setFont(u8g2_font_6x13_me);
int euroWidth = u8g2.getUTF8Width("€");
u8g2.setCursor(superscriptX + superscriptWidth + 1, y);
u8g2.print("€");
return mainPriceWidth + 1 + superscriptWidth + 1 + euroWidth;
}
void TankerkoenigModule::drawTrendArrow(int x, int y, PriceTrend trend) {
const int anim_cycle = 1200;
const int pattern_height = 4;
const int visible_height = 8;
int pixel_offset = (millis() % anim_cycle) * pattern_height / anim_cycle;
int y_base = y;
int y_base_arrow = y - 3;
uint16_t color;
switch (trend) {
case PriceTrend::TREND_RISING:
color = rgb565(255, 0, 0);
for (int i = 0; i < visible_height; ++i) {
int current_y = y_base_arrow + i;
int pattern_step = (i + pixel_offset) % pattern_height;
if (pattern_step == 0) {
canvas.drawPixel(x, current_y, color);
} else if (pattern_step == 1) {
canvas.drawFastHLine(x - 1, current_y, 3, color);
} else if (pattern_step == 2) {
canvas.drawFastHLine(x - 2, current_y, 5, color);
}
}
break;
case PriceTrend::TREND_FALLING:
color = rgb565(0, 255, 0);
for (int i = 0; i < visible_height; ++i) {
int current_y = y_base_arrow + i;
int pattern_step = (i - pixel_offset + pattern_height) % pattern_height;
if (pattern_step == 0) {
canvas.drawFastHLine(x - 2, current_y, 5, color);
} else if (pattern_step == 1) {
canvas.drawFastHLine(x - 1, current_y, 3, color);
} else if (pattern_step == 2) {
canvas.drawPixel(x, current_y, color);
}
}
break;
case PriceTrend::TREND_STABLE:
color = rgb565(200,0,200);
int x_offset;
if ((millis() % anim_cycle) < (anim_cycle / 2)) {
x_offset = -2;
} else {
x_offset = 2;
}
canvas.drawPixel(x + x_offset, y_base, color);
canvas.drawFastHLine(x + x_offset - 1, y_base + 1, 3, color);
canvas.drawPixel(x + x_offset, y_base + 2, color);
break;
}
}
uint16_t TankerkoenigModule::calcColor(float value, float low, float high) {
if (low >= high || value <= 0) return rgb565(255, 255, 0);
float val = (value < low) ? low : (value > high ? high : value);
int diff = (int)roundf(((high - val) / (high - low)) * 100.0f);
uint8_t rval, gval;
if (diff <= 50) {
rval = 255;
gval = map(diff, 0, 50, 0, 255);
} else {
gval = 255;
rval = map(diff, 50, 100, 255, 0);
}
return rgb565(rval, gval, 0);
}
PsramString TankerkoenigModule::truncateString(const PsramString& text, int maxWidth) {
if (u8g2.getUTF8Width(text.c_str()) <= maxWidth) { return text; }
PsramString truncated = text;
while (!truncated.empty() && u8g2.getUTF8Width((truncated + "...").c_str()) > maxWidth) {
truncated.pop_back();
}
return truncated + "...";
}
void TankerkoenigModule::loadPriceCache() {
if (LittleFS.exists(PRICE_CACHE_FILENAME)) {
File file = LittleFS.open(PRICE_CACHE_FILENAME, "r");
if (file) {
JsonDocument doc;
if (deserializeJson(doc, file) == DeserializationError::Ok) {
_lastPriceCache.clear();
for (JsonObject obj : doc.as<JsonArray>()) {
_lastPriceCache.push_back({
obj["id"].as<const char*>(), obj["e5"], obj["e10"], obj["diesel"], obj["ts"]
});
}
}
file.close();
}
}
}
void TankerkoenigModule::savePriceCache() {
File file = LittleFS.open(PRICE_CACHE_FILENAME, "w");
if (file) {
JsonDocument doc;
JsonArray arr = doc.to<JsonArray>();
for (const auto& entry : _lastPriceCache) {
JsonObject obj = arr.add<JsonObject>();
obj["id"] = entry.stationId; obj["e5"] = entry.e5; obj["e10"] = entry.e10;
obj["diesel"] = entry.diesel; obj["ts"] = entry.timestamp;
}
serializeJson(doc, file);
file.close();
}
}
void TankerkoenigModule::updatePriceCache(const PsramString& stationId, float e5, float e10, float diesel, time_t lastChange) {
bool found = false;
for (auto& entry : _lastPriceCache) {
if (entry.stationId == stationId) {
entry.e5 = e5; entry.e10 = e10; entry.diesel = diesel; entry.timestamp = lastChange;
found = true; break;
}
}
if (!found) { _lastPriceCache.push_back({stationId, e5, e10, diesel, lastChange}); }
savePriceCache();
}
bool TankerkoenigModule::getPriceFromCache(const PsramString& stationId, float& e5, float& e10, float& diesel, time_t& lastChange) {
for (const auto& entry : _lastPriceCache) {
if (entry.stationId == stationId) {
e5 = entry.e5; e10 = entry.e10; diesel = entry.diesel;
lastChange = entry.timestamp;
return true;
}
}
e5 = e10 = diesel = 0.0f;
lastChange = 0;
return false;
}
void TankerkoenigModule::cleanupOldPriceCacheEntries() {
LOG_MEM_OP("Tankerkoenig::cleanup");
if (!_deviceConfig) return;
time_t now_utc;
time(&now_utc);
// SAFETY CHECK 1: Validate system time is reasonable (after year 2020)
// Unix timestamp for 2020-01-01 00:00:00 UTC = 1577836800
const time_t MIN_VALID_TIME = 1577836800;
if (now_utc < MIN_VALID_TIME) {
Log.printf("[TankerkoenigModule] SAFETY: Cleanup aborted - system time appears invalid (before 2020): %ld\n", now_utc);
return;
}
// SAFETY CHECK 2: If we have historical data, ensure current time is not older than the newest data
// This protects against clock drift backwards or incorrect NTP sync
// NOTE: Mutex is already held by caller (parseAndProcessJson)
time_t newest_data_timestamp = 0;
for (const auto& entry : _lastPriceCache) {
if (entry.timestamp > newest_data_timestamp) {
newest_data_timestamp = entry.timestamp;
}
}
if (newest_data_timestamp > 0 && now_utc < newest_data_timestamp) {
Log.printf("[TankerkoenigModule] SAFETY: Cleanup aborted - system time (%ld) is older than newest data (%ld)\n",
now_utc, newest_data_timestamp);
return;
}
time_t cutoff_time = now_utc - (_deviceConfig->movingAverageDays * 86400L);
// NOTE: Mutex is already held by caller (parseAndProcessJson)
// Parse currently configured station IDs
PsramVector<PsramString> current_id_list;
PsramString temp_ids = station_ids; // Copy member variable
if (!temp_ids.empty()) {
// FIX: Create a mutable copy for strtok_r to safely modify
char* temp_buffer = strdup(temp_ids.c_str());
if (temp_buffer) {
char* strtok_ctx;
char* id_token = strtok_r(temp_buffer, ",", &strtok_ctx);
while(id_token != nullptr) {
current_id_list.push_back(id_token);
id_token = strtok_r(nullptr, ",", &strtok_ctx);
}
free(temp_buffer);
}
}
// SAFETY: Only cleanup if we successfully parsed station IDs
if (!temp_ids.empty() && current_id_list.empty()) {
Log.println("[TankerkoenigModule] WARNING: Failed to parse station IDs in cleanup, skipping to prevent data loss!");
return;
}
size_t original_size = _lastPriceCache.size();
_lastPriceCache.erase(
std::remove_if(_lastPriceCache.begin(), _lastPriceCache.end(),
[¤t_id_list, cutoff_time](const LastPriceCache& entry) {
// Remove entries with invalid timestamp
if (entry.timestamp == 0) return true;
// Check if station is in current configuration
bool is_configured = false;
for (const auto& id : current_id_list) {
if (entry.stationId == id) {
is_configured = true;
break;
}
}
// Remove if not configured OR (configured but older than retention period)
if (!is_configured) return true;
if (entry.timestamp < cutoff_time) return true;
return false;
}),
_lastPriceCache.end()
);
bool changed = (_lastPriceCache.size() < original_size);
// Save cache if entries were removed
// NOTE: savePriceCache() must be called while mutex is held because it accesses _lastPriceCache
if (changed) {
Log.printf("[TankerkoenigModule] Cleanup entfernt %d alte Cache-Einträge\n", original_size - _lastPriceCache.size());
savePriceCache();
}
}
PriceTrend TankerkoenigModule::calculateTrend(const PsramVector<float>& x_values, const PsramVector<float>& y_values) {
int n = x_values.size();
if (n < 2) {
return PriceTrend::TREND_STABLE;
}
double sum_x = 0.0, sum_y = 0.0, sum_xy = 0.0, sum_x_squared = 0.0;
for (int i = 0; i < n; ++i) {
sum_x += x_values[i];
sum_y += y_values[i];
sum_xy += x_values[i] * y_values[i];
sum_x_squared += x_values[i] * x_values[i];
}
const double SLOPE_DENOMINATOR_THRESHOLD = 0.000001;
double denominator = (n * sum_x_squared) - (sum_x * sum_x);
if (abs(denominator) < SLOPE_DENOMINATOR_THRESHOLD) {
return PriceTrend::TREND_STABLE;
}
double slope = (n * sum_xy - sum_x * sum_y) / denominator;
const double STABILITY_THRESHOLD = 0.001;
if (slope > STABILITY_THRESHOLD) {
return PriceTrend::TREND_RISING;
} else if (slope < -STABILITY_THRESHOLD) {
return PriceTrend::TREND_FALLING;
} else {
return PriceTrend::TREND_STABLE;
}
}
void TankerkoenigModule::updateAndDetermineTrends(const PsramString& stationId) {
if (!_deviceConfig) return;
StationPriceHistory* history = nullptr;
for (auto& h : price_statistics) {
if (h.stationId == stationId) {
history = &h;
break;
}
}
if (!history || history->dailyStats.size() < 2) {
return;
}
PsramVector<float> x_values, y_e5_low, y_e5_high, y_e10_low, y_e10_high, y_diesel_low, y_diesel_high;
time_t now_utc; time(&now_utc);
for (const auto& s : history->dailyStats) {
struct tm tm_stat = {0};
sscanf(s.date.c_str(), "%d-%d-%d", &tm_stat.tm_year, &tm_stat.tm_mon, &tm_stat.tm_mday);
tm_stat.tm_year -= 1900;
tm_stat.tm_mon -= 1;
time_t stat_time = mktime(&tm_stat);
double days_diff = difftime(now_utc, stat_time) / (60 * 60 * 24.0);
if (days_diff < _deviceConfig->trendAnalysisDays) {
x_values.push_back(-days_diff);
if(s.e5_low > 0) y_e5_low.push_back(s.e5_low);
if(s.e5_high > 0) y_e5_high.push_back(s.e5_high);
if(s.e10_low > 0) y_e10_low.push_back(s.e10_low);
if(s.e10_high > 0) y_e10_high.push_back(s.e10_high);
if(s.diesel_low > 0) y_diesel_low.push_back(s.diesel_low);
if(s.diesel_high > 0) y_diesel_high.push_back(s.diesel_high);
}
}
TrendStatus trends;
trends.stationId = stationId;
trends.e5_min_trend = calculateTrend(x_values, y_e5_low);
trends.e5_max_trend = calculateTrend(x_values, y_e5_high);
trends.e10_min_trend = calculateTrend(x_values, y_e10_low);
trends.e10_max_trend = calculateTrend(x_values, y_e10_high);
trends.diesel_min_trend = calculateTrend(x_values, y_diesel_low);
trends.diesel_max_trend = calculateTrend(x_values, y_diesel_high);
bool trend_found = false;
for(auto& ts : _trendStatusCache) {
if(ts.stationId == stationId) { ts = trends; trend_found = true; break; }
}
if(!trend_found) { _trendStatusCache.push_back(trends); }
}
void TankerkoenigModule::updatePriceStatistics(const PsramString& stationId, float currentE5, float currentE10, float currentDiesel) {
time_t now_utc;
time(&now_utc);
time_t now_local = timeConverter.toLocal(now_utc);
struct tm timeinfo;
gmtime_r(&now_local, &timeinfo);
char date_str[11];
strftime(date_str, sizeof(date_str), "%Y-%m-%d", &timeinfo);
PsramString today_date(date_str);
StationPriceHistory* history = nullptr;
for (auto& h : price_statistics) {
if (h.stationId == stationId) { history = &h; break; }
}
if (!history) {
price_statistics.push_back({stationId, {}});
history = &price_statistics.back();
}
DailyPriceStats* today_stats = nullptr;
for (auto& s : history->dailyStats) {
if (s.date == today_date) { today_stats = &s; break; }
}
bool changed = false;
if (!today_stats) {
DailyPriceStats new_stats; new_stats.date = today_date;
if (currentE5 > 0) { new_stats.e5_low = currentE5; new_stats.e5_high = currentE5; }
if (currentE10 > 0) { new_stats.e10_low = currentE10; new_stats.e10_high = currentE10; }
if (currentDiesel > 0) { new_stats.diesel_low = currentDiesel; new_stats.diesel_high = currentDiesel; }
history->dailyStats.push_back(new_stats);
changed = true;
trimPriceStatistics(*history);
} else {
if (currentE5 > 0 && (today_stats->e5_low == 0 || currentE5 < today_stats->e5_low)) { today_stats->e5_low = currentE5; changed = true; }
if (currentE5 > 0 && currentE5 > today_stats->e5_high) { today_stats->e5_high = currentE5; changed = true; }
if (currentE10 > 0 && (today_stats->e10_low == 0 || currentE10 < today_stats->e10_low)) { today_stats->e10_low = currentE10; changed = true; }
if (currentE10 > 0 && currentE10 > today_stats->e10_high) { today_stats->e10_high = currentE10; changed = true; }
if (currentDiesel > 0 && (today_stats->diesel_low == 0 || currentDiesel < today_stats->diesel_low)) { today_stats->diesel_low = currentDiesel; changed = true; }
if (currentDiesel > 0 && currentDiesel > today_stats->diesel_high) { today_stats->diesel_high = currentDiesel; changed = true; }
}
#if TANKERKOENIG_SAVE_HISTORY
if (changed) { savePriceStatistics(); }
#endif
}
void TankerkoenigModule::trimPriceStatistics(StationPriceHistory& history) {
if (!_deviceConfig) return;
time_t now_utc;
time(&now_utc);
// SAFETY CHECK: Validate system time is reasonable (after year 2020)
const time_t MIN_VALID_TIME = 1577836800; // 2020-01-01 00:00:00 UTC
if (now_utc < MIN_VALID_TIME) {
Log.printf("[TankerkoenigModule] SAFETY: Trim aborted - system time appears invalid (before 2020): %ld\n", now_utc);
return;
}
// SAFETY CHECK: If we have historical data, check that current time is not suspiciously old
// compared to the data we have
if (!history.dailyStats.empty()) {
// Get the most recent date in history
PsramString newest_date;
for (const auto& stats : history.dailyStats) {
if (stats.date > newest_date) {
newest_date = stats.date;
}
}
// Convert current time to local date string
time_t now_local = timeConverter.toLocal(now_utc);
struct tm now_tm;
gmtime_r(&now_local, &now_tm);
char now_date_str[11];
strftime(now_date_str, sizeof(now_date_str), "%Y-%m-%d", &now_tm);
// If current date is older than newest data date, abort
if (PsramString(now_date_str) < newest_date) {
Log.printf("[TankerkoenigModule] SAFETY: Trim aborted - current date (%s) is older than newest data (%s)\n",
now_date_str, newest_date.c_str());
return;
}
}
// Calculate cutoff date: movingAverageDays ago from today
time_t cutoff_epoch = now_utc - (_deviceConfig->movingAverageDays * 86400L);
time_t cutoff_local = timeConverter.toLocal(cutoff_epoch);
struct tm cutoff_tm;
gmtime_r(&cutoff_local, &cutoff_tm);
char cutoff_date_str_buf[11];
strftime(cutoff_date_str_buf, sizeof(cutoff_date_str_buf), "%Y-%m-%d", &cutoff_tm);
PsramString cutoff_date_str(cutoff_date_str_buf);
size_t original_count = history.dailyStats.size();
// Remove entries older than or equal to cutoff date
// Example: If movingAverageDays=31 and today is Dec 10:
// cutoff_date = Nov 9 (31 days before Dec 10)
// Remove all entries with date <= Nov 9
// Keep entries from Nov 10 through Dec 10 = exactly 31 days
history.dailyStats.erase(
std::remove_if(history.dailyStats.begin(), history.dailyStats.end(),
[&](const DailyPriceStats& stats) { return stats.date <= cutoff_date_str; }),
history.dailyStats.end());
if (history.dailyStats.size() < original_count) {
Log.printf("[TankerkoenigModule] Trimmed %d old statistics entries (cutoff: %s)\n",
original_count - history.dailyStats.size(), cutoff_date_str.c_str());
}
}
void TankerkoenigModule::trimAllPriceStatistics() {
for (auto& history : price_statistics) { trimPriceStatistics(history); }
savePriceStatistics();
}
AveragePrices TankerkoenigModule::calculateAverages(const PsramString& stationId) {
AveragePrices averages;
float sumE5Low = 0.0, sumE5High = 0.0, sumE10Low = 0.0, sumE10High = 0.0, sumDieselLow = 0.0, sumDieselHigh = 0.0;
int count = 0;
for (const auto& h : price_statistics) {
if (h.stationId == stationId) {
for (const auto& s : h.dailyStats) {
if(s.e5_low > 0) { sumE5Low += s.e5_low; sumE5High += s.e5_high; }
if(s.e10_low > 0) { sumE10Low += s.e10_low; sumE10High += s.e10_high; }
if(s.diesel_low > 0) { sumDieselLow += s.diesel_low; sumDieselHigh += s.diesel_high; }
count++;
}
break;
}
}
if (count > 0) {
averages.avgE5Low = sumE5Low / count; averages.avgE5High = sumE5High / count;
averages.avgE10Low = sumE10Low / count; averages.avgE10High = sumE10High / count;
averages.avgDieselLow = sumDieselLow / count; averages.avgDieselHigh = sumDieselHigh / count;
}
averages.count = count;