Repository navigation
Expand file tree
/
Copy pathThemeParkModule.cpp
More file actions
1237 lines (1041 loc) · 49.4 KB
/
Copy pathThemeParkModule.cpp
File metadata and controls
1237 lines (1041 loc) · 49.4 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 "ThemeParkModule.hpp"
#include "MultiLogger.hpp"
#include "WebClientModule.hpp"
#include "webconfig.hpp"
#include "FragmentationMonitor.hpp"
#include <ArduinoJson.h>
#include <algorithm>
#include <LittleFS.h>
#include <strings.h> // For strcasecmp
// Allocator for PSRAM
struct SpiRamAllocator : ArduinoJson::Allocator {
void* allocate(size_t size) override { return ps_malloc(size); }
void deallocate(void* pointer) override { free(pointer); }
void* reallocate(void* ptr, size_t new_size) override { return ps_realloc(ptr, new_size); }
};
ThemeParkModule::ThemeParkModule(U8G2_FOR_ADAFRUIT_GFX& u8g2, GFXcanvas16& canvas, WebClientModule* webClient)
: _u8g2(u8g2), _canvas(canvas), _webClient(webClient), _config(nullptr),
_currentPage(0), _currentParkIndex(0), _currentAttractionPage(0), _totalPages(1),
_logicTicksSincePageSwitch(0), _pageDisplayDuration(15000), _lastUpdate(0),
_lastParksListUpdate(0), _lastParkDetailsUpdate(0) {
_dataMutex = xSemaphoreCreateMutex();
// PixelScroller für Parknamen und Attraktionen erstellen
_parkNameScroller = new (ps_malloc(sizeof(PixelScroller))) PixelScroller(u8g2, 50);
_attractionScroller = new (ps_malloc(sizeof(PixelScroller))) PixelScroller(u8g2, 50);
// Default-Konfiguration
PixelScrollerConfig scrollConfig;
scrollConfig.mode = ScrollMode::CONTINUOUS;
scrollConfig.pauseBetweenCyclesMs = 0;
scrollConfig.scrollReverse = false;
scrollConfig.paddingPixels = 20;
_parkNameScroller->setConfig(scrollConfig);
_attractionScroller->setConfig(scrollConfig);
}
ThemeParkModule::~ThemeParkModule() {
if (_dataMutex) vSemaphoreDelete(_dataMutex);
if (_parkNameScroller) {
_parkNameScroller->~PixelScroller();
free(_parkNameScroller);
}
if (_attractionScroller) {
_attractionScroller->~PixelScroller();
free(_attractionScroller);
}
}
void ThemeParkModule::begin() {
loadParkCache();
// If cache is empty, trigger immediate fetch of parks list
if (_availableParks.empty()) {
Log.println("[ThemePark] Cache is empty, will fetch parks list on first queueData call");
_lastParksListUpdate = 0; // Ensure checkAndUpdateParksList will load cache or fetch
}
Log.println("[ThemePark] Module initialized");
}
void ThemeParkModule::setConfig(const DeviceConfig* config) {
_config = config;
_pageDisplayDuration = (_config && _config->themeParkDisplaySec > 0)
? _config->themeParkDisplaySec * 1000UL : 15000;
if (!_webClient || !_config) return;
// Parse park IDs from config
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
_parkIds.clear();
if (!_config->themeParkIds.empty()) {
PsramString parkIds = _config->themeParkIds;
size_t pos = 0;
while (pos < parkIds.length()) {
size_t commaPos = parkIds.find(',', pos);
if (commaPos == PsramString::npos) commaPos = parkIds.length();
PsramString parkId = parkIds.substr(pos, commaPos - pos);
// Trim whitespace
while (!parkId.empty() && (parkId[0] == ' ' || parkId[0] == '\t')) {
parkId = parkId.substr(1);
}
while (!parkId.empty() && (parkId[parkId.length()-1] == ' ' || parkId[parkId.length()-1] == '\t')) {
parkId = parkId.substr(0, parkId.length()-1);
}
if (!parkId.empty()) {
_parkIds.push_back(parkId);
}
pos = commaPos + 1;
}
}
xSemaphoreGive(_dataMutex);
}
// Register resources for each configured park
// Each park needs wait times data from the /waitingtimes endpoint
unsigned long updateIntervalMinutes = (_config && _config->themeParkFetchIntervalMin > 0)
? _config->themeParkFetchIntervalMin : 10;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
for (const auto& parkId : _parkIds) {
// Wait times endpoint uses header-based park selection
PsramString waitTimesUrl = "https://api.wartezeiten.app/v1/waitingtimes";
PsramString waitTimesHeaders = "accept: application/json\npark: " + parkId + "\nlanguage: de";
// Register the wait times resource with custom headers
_webClient->registerResourceWithHeaders(String(waitTimesUrl.c_str()),
String(waitTimesHeaders.c_str()),
updateIntervalMinutes,
nullptr);
// Register opening times resource (updated less frequently - every 6 hours)
PsramString openingTimesUrl = "https://api.wartezeiten.app/v1/openingtimes";
PsramString openingTimesHeaders = "accept: application/json\npark: " + parkId;
_webClient->registerResourceWithHeaders(String(openingTimesUrl.c_str()),
String(openingTimesHeaders.c_str()),
360, // 6 hours
nullptr);
// Register crowd level resource (updated every 30 minutes)
PsramString crowdLevelUrl = "https://api.wartezeiten.app/v1/crowdlevel";
PsramString crowdLevelHeaders = "accept: application/json\npark: " + parkId + "\nlanguage: de";
_webClient->registerResourceWithHeaders(String(crowdLevelUrl.c_str()),
String(crowdLevelHeaders.c_str()),
30, // 30 minutes
nullptr);
Log.printf("[ThemePark] Registered resources for park %s\n", parkId.c_str());
}
xSemaphoreGive(_dataMutex);
}
// PixelScroller Konfiguration aktualisieren
if (_config && _parkNameScroller && _attractionScroller) {
_parkNameScroller->setConfiguredScrollSpeed(_config->globalScrollSpeedMs);
_attractionScroller->setConfiguredScrollSpeed(_config->globalScrollSpeedMs);
PixelScrollerConfig scrollConfig;
scrollConfig.mode = (_config->scrollMode == 1) ? ScrollMode::PINGPONG : ScrollMode::CONTINUOUS;
scrollConfig.pauseBetweenCyclesMs = (uint32_t)_config->scrollPauseSec * 1000;
scrollConfig.scrollReverse = (_config->scrollReverse == 1);
scrollConfig.paddingPixels = 20;
_parkNameScroller->setConfig(scrollConfig);
_attractionScroller->setConfig(scrollConfig);
}
}
void ThemeParkModule::queueData() {
LOG_MEM_OP("ThemeParkModule::queueData");
if (!_webClient || !_config) return;
// Check if parks list needs daily update
checkAndUpdateParksList();
// Fetch wait times for each configured park
// Create a copy of park IDs to avoid holding the mutex during network operations
PsramVector<PsramString> parkIdsCopy;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
parkIdsCopy = _parkIds;
xSemaphoreGive(_dataMutex);
}
for (const auto& parkId : parkIdsCopy) {
// Fetch wait times from /waitingtimes endpoint
PsramString waitTimesUrl = "https://api.wartezeiten.app/v1/waitingtimes";
PsramString waitTimesHeaders = "accept: application/json\npark: " + parkId + "\nlanguage: de";
// Access the resource - this will use cached data if still fresh,
// or trigger a new fetch if the update interval has passed
_webClient->accessResource(String(waitTimesUrl.c_str()), String(waitTimesHeaders.c_str()),
[this, parkId](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0) {
// Only process if this is new data (not already processed)
bool shouldProcess = false;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Find existing entry in vector
time_t* existingTime = nullptr;
for (auto& entry : _lastProcessedWaitTimes) {
if (entry.parkId == parkId) {
existingTime = &entry.timestamp;
break;
}
}
if (!existingTime || *existingTime < last_update) {
shouldProcess = true;
if (existingTime) {
*existingTime = last_update;
} else {
_lastProcessedWaitTimes.push_back(ProcessedTimeEntry(parkId, last_update));
}
}
xSemaphoreGive(_dataMutex);
}
if (shouldProcess) {
// Take mutex before parsing to ensure thread safety
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
parseWaitTimes(buffer, size, parkId);
xSemaphoreGive(_dataMutex);
// Trigger a redraw if callback is set
if (_updateCallback) {
_updateCallback();
}
}
}
}
});
// Fetch opening times
PsramString openingTimesUrl = "https://api.wartezeiten.app/v1/openingtimes";
PsramString openingTimesHeaders = "accept: application/json\npark: " + parkId;
_webClient->accessResource(String(openingTimesUrl.c_str()), String(openingTimesHeaders.c_str()),
[this, parkId](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0) {
// Only process if this is new data (not already processed)
bool shouldProcess = false;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Find existing entry in vector
time_t* existingTime = nullptr;
for (auto& entry : _lastProcessedOpeningTimes) {
if (entry.parkId == parkId) {
existingTime = &entry.timestamp;
break;
}
}
if (!existingTime || *existingTime < last_update) {
shouldProcess = true;
if (existingTime) {
*existingTime = last_update;
} else {
_lastProcessedOpeningTimes.push_back(ProcessedTimeEntry(parkId, last_update));
}
}
xSemaphoreGive(_dataMutex);
}
if (shouldProcess) {
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
parseOpeningTimes(buffer, size, parkId);
xSemaphoreGive(_dataMutex);
// Trigger a redraw if callback is set
if (_updateCallback) {
_updateCallback();
}
}
}
}
});
// Fetch crowd level
PsramString crowdLevelUrl = "https://api.wartezeiten.app/v1/crowdlevel";
PsramString crowdLevelHeaders = "accept: application/json\npark: " + parkId + "\nlanguage: de";
_webClient->accessResource(String(crowdLevelUrl.c_str()), String(crowdLevelHeaders.c_str()),
[this, parkId](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0) {
// Only process if this is new data (not already processed)
bool shouldProcess = false;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Find existing entry in vector
time_t* existingTime = nullptr;
for (auto& entry : _lastProcessedCrowdLevel) {
if (entry.parkId == parkId) {
existingTime = &entry.timestamp;
break;
}
}
if (!existingTime || *existingTime < last_update) {
shouldProcess = true;
if (existingTime) {
*existingTime = last_update;
} else {
_lastProcessedCrowdLevel.push_back(ProcessedTimeEntry(parkId, last_update));
}
}
xSemaphoreGive(_dataMutex);
}
if (shouldProcess) {
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
parseCrowdLevel(buffer, size, parkId);
xSemaphoreGive(_dataMutex);
// Trigger a redraw if callback is set
if (_updateCallback) {
_updateCallback();
}
}
}
}
});
}
}
void ThemeParkModule::processData() {
LOG_MEM_OP("ThemeParkModule::processData");
// Data processing is now handled directly in queueData() callback
// This keeps it simple like the Calendar module pattern
}
void ThemeParkModule::parseAvailableParks(const char* jsonBuffer, size_t size) {
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, jsonBuffer, size);
if (error) {
Log.printf("[ThemePark] Failed to parse parks list: %s\n", error.c_str());
return;
}
_availableParks.clear();
JsonArray parks = doc.as<JsonArray>();
for (JsonObject park : parks) {
const char* id = park["id"] | "";
const char* name = park["name"] | "";
const char* country = park["land"] | ""; // API uses "land" not "country"
if (id && name && strlen(id) > 0 && strlen(name) > 0) {
_availableParks.push_back(AvailablePark(id, name, country));
}
}
// Save park cache to LittleFS for later use
saveParkCache();
// Update timestamp when parks list is manually refreshed (e.g., via web button)
// This ensures the daily auto-update timer is reset
_lastParksListUpdate = time(nullptr);
Log.printf("[ThemePark] Loaded %d available parks\n", _availableParks.size());
}
void ThemeParkModule::parseWaitTimes(const char* jsonBuffer, size_t size, const PsramString& parkId) {
Log.printf("[ThemePark] parseWaitTimes called for park: %s\n", parkId.c_str());
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, jsonBuffer, size);
if (error) {
Log.printf("[ThemePark] Failed to parse wait times: %s\n", error.c_str());
return;
}
// The API returns an array of attractions, not park metadata
// We need to get the park name and country from our cache
Log.printf("[ThemePark] About to lookup name for: %s\n", parkId.c_str());
PsramString parkName = getParkNameFromCache(parkId);
if (parkName.empty()) {
parkName = parkId; // Fallback to ID if name not found
Log.printf("[ThemePark] Using parkId as fallback name: %s\n", parkId.c_str());
}
Log.printf("[ThemePark] About to lookup country for: %s\n", parkId.c_str());
PsramString parkCountry = getParkCountryFromCache(parkId);
// Find or create park data
ThemeParkData* parkData = nullptr;
for (auto& park : _parkData) {
if (park.id == parkId) {
parkData = &park;
break;
}
}
if (!parkData) {
_parkData.push_back(ThemeParkData());
parkData = &_parkData[_parkData.size() - 1];
}
parkData->id = parkId;
parkData->name = parkName;
parkData->country = parkCountry;
parkData->attractions.clear();
parkData->lastUpdate = time(nullptr);
// Note: The API response doesn't include crowdLevel, isOpen, openingTime, closingTime
// These fields will remain at their default values (0/false/empty)
// If needed, these could be fetched from a different API endpoint
// Parse attractions array
JsonArray attractions = doc.as<JsonArray>();
int openAttractionsCount = 0;
if (attractions) {
for (JsonObject attr : attractions) {
const char* name = attr["name"] | "";
int waitTime = attr["waitingtime"] | 0; // Note: field is "waitingtime" not "waitTime"
const char* status = attr["status"] | "unknown";
if (name && strlen(name) > 0) {
Attraction attraction;
attraction.name = name;
attraction.waitTime = waitTime;
// Check attraction status (case-insensitive)
// Mark as open if status is explicitly "open" or "opened"
// This is more conservative and avoids marking maintenance/refurbishment as open
attraction.isOpen = (strcasecmp(status, "opened") == 0 ||
strcasecmp(status, "open") == 0 ||
strcasecmp(status, "operating") == 0);
parkData->attractions.push_back(attraction);
if (attraction.isOpen) {
openAttractionsCount++;
}
}
}
}
// Check if park should be considered closed:
// Park is closed if all attractions are closed
bool allAttractionsClosed = (parkData->attractions.size() > 0 && openAttractionsCount == 0);
// Don't remove parks here - opening times might not be fetched yet due to async callbacks
// The display logic will handle whether to show closed parks based on opening hours
if (allAttractionsClosed) {
Log.printf("[ThemePark] Park %s is closed (all attractions closed)\n", parkName.c_str());
}
// Sort attractions:
// 1. Open attractions first, then closed attractions
// 2. Within each group: Sort by wait time (descending), then by name (ascending, case-insensitive)
std::sort(parkData->attractions.begin(), parkData->attractions.end(),
[](const Attraction& a, const Attraction& b) {
// Criterion 1: Open status (open first, closed last)
if (a.isOpen != b.isOpen) {
return a.isOpen > b.isOpen; // true > false, so open comes first
}
// Criterion 2: Wait time (higher first)
if (a.waitTime != b.waitTime) {
return a.waitTime > b.waitTime;
}
// Criterion 3: Name (alphabetical, case-insensitive)
PsramString aLower = a.name;
PsramString bLower = b.name;
std::transform(aLower.begin(), aLower.end(), aLower.begin(), ::tolower);
std::transform(bLower.begin(), bLower.end(), bLower.begin(), ::tolower);
return aLower < bLower;
});
// Calculate how many pages needed to show all attractions
// 6 attractions per page as requested
// For open parks: show ALL attractions (both open and closed)
// For closed parks: show 1 page with opening times
int attractionsPerPage = 6;
parkData->attractionPages = (parkData->attractions.size() + attractionsPerPage - 1) / attractionsPerPage;
if (parkData->attractionPages < 1) parkData->attractionPages = 1;
// Calculate total pages across all parks using the helper method
// This properly accounts for closed parks (1 page) vs open parks (all attractions)
_totalPages = calculateTotalPages();
Log.printf("[ThemePark] Updated park %s with %d attractions (%d open), %d pages, total pages: %d\n",
parkName.c_str(), parkData->attractions.size(), openAttractionsCount, parkData->attractionPages, _totalPages);
}
void ThemeParkModule::parseCrowdLevel(const char* jsonBuffer, size_t size, const PsramString& parkId) {
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, jsonBuffer, size);
if (error) {
Log.printf("[ThemePark] Failed to parse crowd level: %s\n", error.c_str());
return;
}
// Extract crowd level from JSON
float crowdLevel = doc["crowd_level"] | 0.0f;
// Find the park data and update crowd level
for (auto& park : _parkData) {
if (park.id == parkId) {
park.crowdLevel = crowdLevel;
Log.printf("[ThemePark] Updated crowd level for %s: %.2f%%\n", parkId.c_str(), crowdLevel);
break;
}
}
}
void ThemeParkModule::parseOpeningTimes(const char* jsonBuffer, size_t size, const PsramString& parkId) {
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, jsonBuffer, size);
if (error) {
Log.printf("[ThemePark] Failed to parse opening times: %s\n", error.c_str());
return;
}
// API returns array like: [{"opened_today":true,"open_from":"2025-11-14T09:00:00+01:00","closed_from":"2025-11-14T18:00:00+01:00"}]
JsonArray timesArray = doc.as<JsonArray>();
if (!timesArray || timesArray.size() == 0) {
Log.printf("[ThemePark] No opening times data for park %s\n", parkId.c_str());
return;
}
JsonObject today = timesArray[0];
bool openedToday = today["opened_today"] | false;
const char* openFrom = today["open_from"] | "";
const char* closedFrom = today["closed_from"] | "";
// Find the park data and update opening times
for (auto& park : _parkData) {
if (park.id == parkId) {
park.isOpen = openedToday;
// Extract just the time portion (HH:MM) from ISO 8601 timestamp
// Format is "2025-11-14T09:00:00+01:00", we want "09:00"
if (openFrom && strlen(openFrom) >= 16) {
PsramString openStr(openFrom);
size_t tPos = openStr.find('T');
if (tPos != PsramString::npos && tPos + 6 <= openStr.length()) {
park.openingTime = openStr.substr(tPos + 1, 5); // Extract "09:00"
}
}
if (closedFrom && strlen(closedFrom) >= 16) {
PsramString closedStr(closedFrom);
size_t tPos = closedStr.find('T');
if (tPos != PsramString::npos && tPos + 6 <= closedStr.length()) {
park.closingTime = closedStr.substr(tPos + 1, 5); // Extract "18:00"
}
}
Log.printf("[ThemePark] Updated opening times for %s: %s - %s (open: %s)\n",
parkId.c_str(), park.openingTime.c_str(), park.closingTime.c_str(),
park.isOpen ? "yes" : "no");
break;
}
}
}
void ThemeParkModule::onUpdate(std::function<void()> callback) {
_updateCallback = callback;
}
bool ThemeParkModule::isEnabled() {
return _config && _config->themeParkEnabled;
}
unsigned long ThemeParkModule::getDisplayDuration() {
unsigned long duration;
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
// Use the helper method to calculate total pages
// This properly accounts for closed parks (1 page) vs open parks (attraction pages)
int totalPages = calculateTotalPages();
duration = (totalPages * _pageDisplayDuration) + runtime_safe_buffer;
xSemaphoreGive(_dataMutex);
} else {
duration = _pageDisplayDuration;
}
return duration;
}
void ThemeParkModule::resetPaging() {
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
_currentPage = 0;
_currentParkIndex = 0;
_currentAttractionPage = 0;
_logicTicksSincePageSwitch = 0;
_isFinished = false;
// Reset PixelScroller
if (_parkNameScroller) _parkNameScroller->reset();
if (_attractionScroller) _attractionScroller->reset();
xSemaphoreGive(_dataMutex);
}
}
void ThemeParkModule::configure(const ModuleConfig& config) {
_modConfig = config;
}
void ThemeParkModule::onActivate() {
if (_modConfig.resetOnActivate) {
_currentPage = 0;
}
_logicTicksSincePageSwitch = 0;
}
bool ThemeParkModule::shouldDisplayPark(const ThemeParkData& park) const {
// A park is OPEN if at least ONE attraction is open
// A park is CLOSED if ALL attractions are closed
// Display open parks (at least one attraction open)
if (parkHasOpenAttractions(park)) {
return true;
}
// Display closed parks ONLY if they have opening time information
// Skip closed parks without opening times entirely
return !park.openingTime.empty() || !park.closingTime.empty();
}
bool ThemeParkModule::parkHasOpenAttractions(const ThemeParkData& park) const {
for (const auto& attr : park.attractions) {
if (attr.isOpen) {
return true;
}
}
return false;
}
int ThemeParkModule::calculateTotalPages() const {
// NOTE: This function expects _dataMutex to already be held by the caller
//
// Page calculation logic:
// - OPEN park (at least one attraction open): Show all attractions (6 per page)
// - CLOSED park with opening times: Show 1 page with "Geschlossen" message and opening hours
// - CLOSED park without opening times: Skip entirely (not counted)
int totalPages = 0;
for (const auto& park : _parkData) {
if (shouldDisplayPark(park)) {
if (parkHasOpenAttractions(park)) {
// OPEN park: use attractionPages (all attractions, 6 per page)
totalPages += park.attractionPages;
} else {
// CLOSED park with opening times: count as 1 page
totalPages += 1;
}
}
}
if (totalPages == 0) totalPages = 1;
return totalPages;
}
void ThemeParkModule::tick() {
// PixelScroller tick für pixelweises Scrolling
bool scrolled = false;
if (_parkNameScroller) {
if (_parkNameScroller->tick()) {
scrolled = true;
}
}
if (_attractionScroller) {
if (_attractionScroller->tick()) {
scrolled = true;
}
}
if (scrolled && _updateCallback) {
_updateCallback();
}
}
void ThemeParkModule::logicTick() {
_logicTicksSincePageSwitch++;
uint32_t ticksPerPage = (_pageDisplayDuration / 100);
if (_logicTicksSincePageSwitch >= ticksPerPage) {
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
// Filter displayable parks
PsramVector<int> displayableIndices;
for (size_t i = 0; i < _parkData.size(); i++) {
if (shouldDisplayPark(_parkData[i])) {
displayableIndices.push_back(i);
}
}
// Sort displayable parks:
// 1. OPEN parks first (at least one attraction open)
// 2. Then CLOSED parks (with opening times)
// 3. Alphabetically by name within each group (case-insensitive)
std::sort(displayableIndices.begin(), displayableIndices.end(),
[this](int idxA, int idxB) {
const auto& parkA = _parkData[idxA];
const auto& parkB = _parkData[idxB];
// Criterion 1: Open parks first
bool aHasOpen = parkHasOpenAttractions(parkA);
bool bHasOpen = parkHasOpenAttractions(parkB);
if (aHasOpen != bHasOpen) {
return aHasOpen > bHasOpen;
}
// Criterion 2: Alphabetically by name (case-insensitive)
PsramString aLower = parkA.name;
PsramString bLower = parkB.name;
std::transform(aLower.begin(), aLower.end(), aLower.begin(), ::tolower);
std::transform(bLower.begin(), bLower.end(), bLower.begin(), ::tolower);
return aLower < bLower;
});
if (displayableIndices.empty()) {
_currentPage = 0;
_currentParkIndex = 0;
_currentAttractionPage = 0;
_totalPages = 1;
_isFinished = true;
xSemaphoreGive(_dataMutex);
_logicTicksSincePageSwitch = 0;
return;
}
// Compute pages per park for the sorted displayable list
PsramVector<int> pagesPerPark;
int computedTotalPages = 0;
for (int idx : displayableIndices) {
const auto& park = _parkData[idx];
int pages = parkHasOpenAttractions(park) ? park.attractionPages : 1;
if (pages < 1) pages = 1;
pagesPerPark.push_back(pages);
computedTotalPages += pages;
}
if (computedTotalPages < 1) computedTotalPages = 1;
_totalPages = computedTotalPages;
// Bounds check current park index
if (_currentParkIndex < 0 || _currentParkIndex >= (int)displayableIndices.size()) {
_currentParkIndex = 0;
_currentAttractionPage = 0;
}
// Move to next attraction page within current park
_currentAttractionPage++;
// NUR Attraktions-Scroller zurücksetzen, NICHT den Parknamen-Scroller
// Der Parkname soll kontinuierlich weiterscrollen
if (_attractionScroller) _attractionScroller->reset();
// Determine pages for current park (with bounds check)
int pagesForThisPark = (_currentParkIndex >= 0 && _currentParkIndex < (int)pagesPerPark.size())
? pagesPerPark[_currentParkIndex] : 1;
// If we've shown all pages for current park, move to next park
if (_currentAttractionPage >= pagesForThisPark) {
_currentAttractionPage = 0;
_currentParkIndex++;
// Bei Park-Wechsel: Parkname-Scroller zurücksetzen (neuer Park = neuer Name)
if (_parkNameScroller) _parkNameScroller->reset();
// If we've shown all displayable parks, we're done
if (_currentParkIndex >= (int)displayableIndices.size()) {
_currentParkIndex = 0;
_currentAttractionPage = 0;
_isFinished = true;
Log.printf("[ThemePark] All %d displayable parks shown -> Module finished\n", (int)displayableIndices.size());
}
}
// Compute _currentPage as cumulative pages before current park + current attraction page
int cumulativePages = 0;
for (int i = 0; i < _currentParkIndex && i < (int)pagesPerPark.size(); i++) {
cumulativePages += pagesPerPark[i];
}
_currentPage = cumulativePages + _currentAttractionPage;
if (_updateCallback) _updateCallback();
xSemaphoreGive(_dataMutex);
}
_logicTicksSincePageSwitch = 0;
}
}
void ThemeParkModule::draw() {
_canvas.fillScreen(0);
_u8g2.begin(_canvas); // Initialize u8g2 with canvas - required for proper rendering
if (xSemaphoreTake(_dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
// Filter displayable parks
PsramVector<int> displayableIndices;
for (size_t i = 0; i < _parkData.size(); i++) {
if (shouldDisplayPark(_parkData[i])) {
displayableIndices.push_back(i);
}
}
// Sort displayable parks consistently with logicTick():
// 1. OPEN parks first (at least one attraction open)
// 2. Then CLOSED parks (with opening times)
// 3. Alphabetically by name within each group (case-insensitive)
std::sort(displayableIndices.begin(), displayableIndices.end(),
[this](int idxA, int idxB) {
const auto& parkA = _parkData[idxA];
const auto& parkB = _parkData[idxB];
// Criterion 1: Open parks first
bool aHasOpen = parkHasOpenAttractions(parkA);
bool bHasOpen = parkHasOpenAttractions(parkB);
if (aHasOpen != bHasOpen) {
return aHasOpen > bHasOpen;
}
// Criterion 2: Alphabetically by name (case-insensitive)
PsramString aLower = parkA.name;
PsramString bLower = parkB.name;
std::transform(aLower.begin(), aLower.end(), aLower.begin(), ::tolower);
std::transform(bLower.begin(), bLower.end(), bLower.begin(), ::tolower);
return aLower < bLower;
});
if (displayableIndices.empty()) {
drawNoDataPage();
} else {
// Find which displayable park we should show based on current index
// Bounds check to prevent invalid access
int displayIndex = (_currentParkIndex >= 0 && _currentParkIndex < (int)displayableIndices.size())
? _currentParkIndex : 0;
drawParkPage(displayableIndices[displayIndex], _currentAttractionPage);
}
xSemaphoreGive(_dataMutex);
} else {
drawNoDataPage();
}
}
void ThemeParkModule::drawParkPage(int parkIndex, int attractionPage) {
if (parkIndex < 0 || parkIndex >= (int)_parkData.size()) {
drawNoDataPage();
return;
}
const ThemeParkData& park = _parkData[parkIndex];
// Check if this park should be displayed
if (!shouldDisplayPark(park)) {
drawNoDataPage();
return;
}
// Check if park has any open attractions
bool hasOpenAttractions = parkHasOpenAttractions(park);
// Draw park name with country as headline - scrolling text
// Use smaller font (6x13 like CalendarModule uses) and scrolling
_u8g2.setFont(u8g2_font_6x13_tf);
_u8g2.setForegroundColor(0xFFFF);
PsramString displayName = park.name;
if (!park.country.empty()) {
displayName = displayName + " (" + park.country + ")";
}
// Add opening hours to scrolling text ONLY if park is OPEN
if (hasOpenAttractions && !park.openingTime.empty() && !park.closingTime.empty()) {
// Show opening hours in format: "Geöffnet von HH:MM - HH:MM Uhr"
displayName = displayName + " : Geöffnet von " + park.openingTime + " - " + park.closingTime + " Uhr";
}
// Determine if crowd level will be shown
bool showCrowdLevel = hasOpenAttractions && park.crowdLevel > 0.0f;
// Calculate max name width - leave space for crowd level only if it will be shown
int maxNameWidth = showCrowdLevel ? (_canvas.width() - 50) : (_canvas.width() - 4);
// Pixelweises Scrolling für Parknamen
if (_parkNameScroller) {
_parkNameScroller->drawScrollingText(_canvas, displayName.c_str(), 2, 11, maxNameWidth, 0, 0xFFFF);
} else {
_u8g2.setCursor(2, 11);
_u8g2.print(displayName.c_str());
}
// Draw crowd level as percentage text (no box)
// Only show for OPEN parks (not closed parks)
// Use same font as park name (u8g2_font_6x13_tf)
// Color: green <= 40%, yellow 41-60%, red > 60%
if (showCrowdLevel) {
uint16_t crowdColor;
if (park.crowdLevel <= 40.0f) {
crowdColor = 0x07E0; // Green
} else if (park.crowdLevel <= 60.0f) {
crowdColor = 0xFFE0; // Yellow
} else {
crowdColor = 0xF800; // Red
}
_u8g2.setFont(u8g2_font_6x13_tf); // Same font as park name
_u8g2.setForegroundColor(crowdColor);
char crowdText[8];
snprintf(crowdText, sizeof(crowdText), "%.0f%%", park.crowdLevel);
int crowdW = _u8g2.getUTF8Width(crowdText);
_u8g2.setCursor(_canvas.width() - crowdW - 2, 11);
_u8g2.print(crowdText);
}
// If park is closed (no open attractions), show closed message instead of attraction list
if (!hasOpenAttractions) {
int yPos = 16;
_u8g2.setFont(u8g2_font_9x15_tf);
_u8g2.setForegroundColor(0xF800); // Red
yPos += 10;
const char* closedMsg = "Geschlossen";
int closedW = _u8g2.getUTF8Width(closedMsg);
_u8g2.setCursor((_canvas.width() - closedW) / 2, yPos);
_u8g2.print(closedMsg);
// Show when park reopens if opening hours available
if (!park.openingTime.empty() && !park.closingTime.empty()) {
yPos += 20;
_u8g2.setFont(u8g2_font_6x13_tf);
_u8g2.setForegroundColor(0xFFFF); // White
PsramString reopenMsg = "Öffnet wieder von";
int reopenW = _u8g2.getUTF8Width(reopenMsg.c_str());
_u8g2.setCursor((_canvas.width() - reopenW) / 2, yPos);
_u8g2.print(reopenMsg.c_str());
yPos += 16;
PsramString timeMsg = park.openingTime + " - " + park.closingTime + " Uhr";
int timeW = _u8g2.getUTF8Width(timeMsg.c_str());
_u8g2.setCursor((_canvas.width() - timeW) / 2, yPos);
_u8g2.print(timeMsg.c_str());
}
return; // Don't draw attractions list
}
// Park is open - draw attractions using smaller font like CalendarModule
// Start position moved down by 2 more pixels
int yPos = 16;
_u8g2.setFont(u8g2_font_5x8_tf);
_u8g2.setForegroundColor(0xFFFF);
yPos += 4; // Gap before attractions
int lineHeight = 8;
// Force exactly 6 attractions per page as requested
int maxLines = 6;
// Find maximum wait time for this park (for dynamic color gradient)
int maxWaitTime = 0;
for (const auto& attr : park.attractions) {
if (attr.isOpen && attr.waitTime > maxWaitTime) {
maxWaitTime = attr.waitTime;
}
}
// Ensure we have a reasonable maximum (at least 1 to avoid division by zero)
if (maxWaitTime < 1) maxWaitTime = 1;
// Show ALL attractions (both open and closed) when park is open
// Calculate which attractions to show on this page
int startIdx = attractionPage * maxLines;
int endIdx = min(startIdx + maxLines, (int)park.attractions.size());
// Ensure PixelScroller slots for attractions
int attractionsToShow = endIdx - startIdx;
if (_attractionScroller) {
_attractionScroller->ensureSlots(attractionsToShow);
}
// Calculate max width for attraction names (leave space for wait time)
int maxAttrNameWidth = _canvas.width() - 45;
for (int i = startIdx; i < endIdx; i++) {
const Attraction& attr = park.attractions[i];
int scrollIndex = i - startIdx;
// Draw attraction name - use WHITE if open, RED if closed
uint16_t attrColor = attr.isOpen ? 0xFFFF : 0xF800;
// Pixelweises Scrolling für Attraktionsnamen
if (_attractionScroller) {
_attractionScroller->drawScrollingText(_canvas, attr.name.c_str(), 2, yPos, maxAttrNameWidth, scrollIndex, attrColor);
} else {
_u8g2.setForegroundColor(attrColor);
_u8g2.setCursor(2, yPos);
_u8g2.print(attr.name.c_str());
}
// Draw wait time or "Geschlossen" for closed attractions
if (attr.isOpen) {
char waitStr[10];
snprintf(waitStr, sizeof(waitStr), "%d min", attr.waitTime);
int waitW = _u8g2.getUTF8Width(waitStr);
// Calculate color using dynamic gradient from green (0 min) to red (max wait time)
uint16_t waitColor = calcColor(attr.waitTime, 5, maxWaitTime);
_u8g2.setForegroundColor(waitColor);
_u8g2.setCursor(_canvas.width() - waitW - 2, yPos);
_u8g2.print(waitStr);
} else {
// Show "Geschlossen" in red for closed attractions
const char* closedText = "Geschl.";
int closedW = _u8g2.getUTF8Width(closedText);
_u8g2.setForegroundColor(0xF800); // Red
_u8g2.setCursor(_canvas.width() - closedW - 2, yPos);
_u8g2.print(closedText);
}
_u8g2.setForegroundColor(0xFFFF);
yPos += lineHeight;
}
}
void ThemeParkModule::drawNoDataPage() {