Repository navigation
Expand file tree
/
Copy pathSofaScoreLiveModule.cpp
More file actions
2426 lines (2086 loc) · 103 KB
/
Copy pathSofaScoreLiveModule.cpp
File metadata and controls
2426 lines (2086 loc) · 103 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 "SofaScoreLiveModule.hpp"
#include "WebClientModule.hpp"
#include "webconfig.hpp"
#include "MultiLogger.hpp"
#include "FragmentationMonitor.hpp"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <algorithm>
#include <time.h>
// Allocator for PSRAM (for ArduinoJson)
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); }
};
// --- SofaScoreTournament Implementation ---
SofaScoreTournament::SofaScoreTournament() = default;
SofaScoreTournament::SofaScoreTournament(const SofaScoreTournament& other)
: id(0), name(nullptr), slug(nullptr), isEnabled(false) {
id = other.id;
name = other.name ? psram_strdup(other.name) : nullptr;
slug = other.slug ? psram_strdup(other.slug) : nullptr;
isEnabled = other.isEnabled;
}
SofaScoreTournament& SofaScoreTournament::operator=(const SofaScoreTournament& other) {
if (this != &other) {
free(name); free(slug);
id = other.id;
name = other.name ? psram_strdup(other.name) : nullptr;
slug = other.slug ? psram_strdup(other.slug) : nullptr;
isEnabled = other.isEnabled;
}
return *this;
}
SofaScoreTournament::SofaScoreTournament(SofaScoreTournament&& other) noexcept {
id = other.id;
name = other.name;
slug = other.slug;
isEnabled = other.isEnabled;
other.name = nullptr;
other.slug = nullptr;
}
SofaScoreTournament& SofaScoreTournament::operator=(SofaScoreTournament&& other) noexcept {
if (this != &other) {
free(name); free(slug);
id = other.id;
name = other.name;
slug = other.slug;
isEnabled = other.isEnabled;
other.name = nullptr;
other.slug = nullptr;
}
return *this;
}
SofaScoreTournament::~SofaScoreTournament() {
if (name) free(name);
if (slug) free(slug);
}
// --- SofaScoreMatch Implementation ---
SofaScoreMatch::SofaScoreMatch() = default;
SofaScoreMatch::SofaScoreMatch(const SofaScoreMatch& other)
: eventId(0), homePlayerName(nullptr), awayPlayerName(nullptr), homeCountry(nullptr), awayCountry(nullptr),
homeScore(0), awayScore(0), homeLegs(0), awayLegs(0), tournamentName(nullptr),
status(MatchStatus::SCHEDULED), startTimestamp(0),
homeAverage(0.0f), awayAverage(0.0f), home180s(0), away180s(0),
homeOver140(0), awayOver140(0), homeOver100(0), awayOver100(0),
homeCheckoutsOver100(0), awayCheckoutsOver100(0),
homeHighestCheckout(0), awayHighestCheckout(0),
homeCheckoutPercent(0.0f), awayCheckoutPercent(0.0f),
homeCheckoutHits(0), homeCheckoutAttempts(0),
awayCheckoutHits(0), awayCheckoutAttempts(0) {
eventId = other.eventId;
homePlayerName = other.homePlayerName ? psram_strdup(other.homePlayerName) : nullptr;
awayPlayerName = other.awayPlayerName ? psram_strdup(other.awayPlayerName) : nullptr;
homeCountry = other.homeCountry ? psram_strdup(other.homeCountry) : nullptr;
awayCountry = other.awayCountry ? psram_strdup(other.awayCountry) : nullptr;
homeScore = other.homeScore;
awayScore = other.awayScore;
homeLegs = other.homeLegs;
awayLegs = other.awayLegs;
tournamentName = other.tournamentName ? psram_strdup(other.tournamentName) : nullptr;
status = other.status;
startTimestamp = other.startTimestamp;
homeAverage = other.homeAverage;
awayAverage = other.awayAverage;
home180s = other.home180s;
away180s = other.away180s;
homeOver140 = other.homeOver140;
awayOver140 = other.awayOver140;
homeOver100 = other.homeOver100;
awayOver100 = other.awayOver100;
homeCheckoutsOver100 = other.homeCheckoutsOver100;
awayCheckoutsOver100 = other.awayCheckoutsOver100;
homeHighestCheckout = other.homeHighestCheckout;
awayHighestCheckout = other.awayHighestCheckout;
homeCheckoutPercent = other.homeCheckoutPercent;
awayCheckoutPercent = other.awayCheckoutPercent;
homeCheckoutHits = other.homeCheckoutHits;
homeCheckoutAttempts = other.homeCheckoutAttempts;
awayCheckoutHits = other.awayCheckoutHits;
awayCheckoutAttempts = other.awayCheckoutAttempts;
}
SofaScoreMatch& SofaScoreMatch::operator=(const SofaScoreMatch& other) {
if (this != &other) {
free(homePlayerName); free(awayPlayerName); free(homeCountry); free(awayCountry); free(tournamentName);
eventId = other.eventId;
homePlayerName = other.homePlayerName ? psram_strdup(other.homePlayerName) : nullptr;
awayPlayerName = other.awayPlayerName ? psram_strdup(other.awayPlayerName) : nullptr;
homeCountry = other.homeCountry ? psram_strdup(other.homeCountry) : nullptr;
awayCountry = other.awayCountry ? psram_strdup(other.awayCountry) : nullptr;
homeScore = other.homeScore;
awayScore = other.awayScore;
homeLegs = other.homeLegs;
awayLegs = other.awayLegs;
tournamentName = other.tournamentName ? psram_strdup(other.tournamentName) : nullptr;
status = other.status;
startTimestamp = other.startTimestamp;
homeAverage = other.homeAverage;
awayAverage = other.awayAverage;
home180s = other.home180s;
away180s = other.away180s;
homeOver140 = other.homeOver140;
awayOver140 = other.awayOver140;
homeOver100 = other.homeOver100;
awayOver100 = other.awayOver100;
homeCheckoutsOver100 = other.homeCheckoutsOver100;
awayCheckoutsOver100 = other.awayCheckoutsOver100;
homeHighestCheckout = other.homeHighestCheckout;
awayHighestCheckout = other.awayHighestCheckout;
homeCheckoutPercent = other.homeCheckoutPercent;
awayCheckoutPercent = other.awayCheckoutPercent;
homeCheckoutHits = other.homeCheckoutHits;
homeCheckoutAttempts = other.homeCheckoutAttempts;
awayCheckoutHits = other.awayCheckoutHits;
awayCheckoutAttempts = other.awayCheckoutAttempts;
}
return *this;
}
SofaScoreMatch::SofaScoreMatch(SofaScoreMatch&& other) noexcept {
eventId = other.eventId;
homePlayerName = other.homePlayerName;
awayPlayerName = other.awayPlayerName;
homeCountry = other.homeCountry;
awayCountry = other.awayCountry;
homeScore = other.homeScore;
awayScore = other.awayScore;
homeLegs = other.homeLegs;
awayLegs = other.awayLegs;
tournamentName = other.tournamentName;
status = other.status;
startTimestamp = other.startTimestamp;
homeAverage = other.homeAverage;
awayAverage = other.awayAverage;
home180s = other.home180s;
away180s = other.away180s;
homeOver140 = other.homeOver140;
awayOver140 = other.awayOver140;
homeOver100 = other.homeOver100;
awayOver100 = other.awayOver100;
homeCheckoutsOver100 = other.homeCheckoutsOver100;
awayCheckoutsOver100 = other.awayCheckoutsOver100;
homeHighestCheckout = other.homeHighestCheckout;
awayHighestCheckout = other.awayHighestCheckout;
homeCheckoutPercent = other.homeCheckoutPercent;
awayCheckoutPercent = other.awayCheckoutPercent;
homeCheckoutHits = other.homeCheckoutHits;
homeCheckoutAttempts = other.homeCheckoutAttempts;
awayCheckoutHits = other.awayCheckoutHits;
awayCheckoutAttempts = other.awayCheckoutAttempts;
other.homePlayerName = nullptr;
other.awayPlayerName = nullptr;
other.homeCountry = nullptr;
other.awayCountry = nullptr;
other.tournamentName = nullptr;
}
SofaScoreMatch& SofaScoreMatch::operator=(SofaScoreMatch&& other) noexcept {
if (this != &other) {
free(homePlayerName); free(awayPlayerName); free(homeCountry); free(awayCountry); free(tournamentName);
eventId = other.eventId;
homePlayerName = other.homePlayerName;
awayPlayerName = other.awayPlayerName;
homeCountry = other.homeCountry;
awayCountry = other.awayCountry;
homeScore = other.homeScore;
awayScore = other.awayScore;
homeLegs = other.homeLegs;
awayLegs = other.awayLegs;
tournamentName = other.tournamentName;
status = other.status;
startTimestamp = other.startTimestamp;
homeAverage = other.homeAverage;
awayAverage = other.awayAverage;
home180s = other.home180s;
away180s = other.away180s;
homeOver140 = other.homeOver140;
awayOver140 = other.awayOver140;
homeOver100 = other.homeOver100;
awayOver100 = other.awayOver100;
homeCheckoutsOver100 = other.homeCheckoutsOver100;
awayCheckoutsOver100 = other.awayCheckoutsOver100;
homeHighestCheckout = other.homeHighestCheckout;
awayHighestCheckout = other.awayHighestCheckout;
homeCheckoutPercent = other.homeCheckoutPercent;
awayCheckoutPercent = other.awayCheckoutPercent;
homeCheckoutHits = other.homeCheckoutHits;
homeCheckoutAttempts = other.homeCheckoutAttempts;
awayCheckoutHits = other.awayCheckoutHits;
awayCheckoutAttempts = other.awayCheckoutAttempts;
other.homePlayerName = nullptr;
other.awayPlayerName = nullptr;
other.homeCountry = nullptr;
other.awayCountry = nullptr;
other.tournamentName = nullptr;
}
return *this;
}
SofaScoreMatch::~SofaScoreMatch() {
if (homePlayerName) free(homePlayerName);
if (awayPlayerName) free(awayPlayerName);
if (homeCountry) free(homeCountry);
if (awayCountry) free(awayCountry);
if (tournamentName) free(tournamentName);
}
// --- SofaScoreLiveModule Implementation ---
SofaScoreLiveModule::SofaScoreLiveModule(U8G2_FOR_ADAFRUIT_GFX& u8g2_ref, GFXcanvas16& canvas_ref,
const GeneralTimeConverter& timeConverter_ref,
WebClientModule* webClient_ptr, DeviceConfig* config)
: u8g2(u8g2_ref), canvas(canvas_ref), _currentCanvas(&canvas_ref),
timeConverter(timeConverter_ref),
webClient(webClient_ptr), config(config) {
dataMutex = xSemaphoreCreateMutex();
// Create pixel scrollers
_nameScroller = new (ps_malloc(sizeof(PixelScroller))) PixelScroller(u8g2, 50);
_tournamentScroller = new (ps_malloc(sizeof(PixelScroller))) PixelScroller(u8g2, 50);
// Default scroll configuration
PixelScrollerConfig scrollConfig;
scrollConfig.mode = ScrollMode::CONTINUOUS;
scrollConfig.pauseBetweenCyclesMs = 0;
scrollConfig.scrollReverse = false;
scrollConfig.paddingPixels = 20;
_nameScroller->setConfig(scrollConfig);
_tournamentScroller->setConfig(scrollConfig);
#if SOFASCORE_DEBUG_JSON
// Clean up json_debug directory on startup to prevent file manager crashes
if (LittleFS.exists("/json_debug")) {
Log.println("[SofaScore] Cleaning up /json_debug directory...");
File dir = LittleFS.open("/json_debug", "r");
if (dir && dir.isDirectory()) {
File file = dir.openNextFile();
int deletedCount = 0;
while (file) {
char filename[128];
snprintf(filename, sizeof(filename), "/json_debug/%s", file.name());
file.close();
if (LittleFS.remove(filename)) {
deletedCount++;
}
file = dir.openNextFile();
}
dir.close();
Log.printf("[SofaScore] Deleted %d debug files from /json_debug\n", deletedCount);
}
} else {
// Create the directory if it doesn't exist
LittleFS.mkdir("/json_debug");
Log.println("[SofaScore] Created /json_debug directory");
}
#endif
}
SofaScoreLiveModule::~SofaScoreLiveModule() {
if (dataMutex) vSemaphoreDelete(dataMutex);
if (tournaments_pending_buffer) free(tournaments_pending_buffer);
if (daily_pending_buffer) free(daily_pending_buffer);
if (live_pending_buffer) free(live_pending_buffer);
if (_nameScroller) {
_nameScroller->~PixelScroller();
free(_nameScroller);
}
if (_tournamentScroller) {
_tournamentScroller->~PixelScroller();
free(_tournamentScroller);
}
clearAllData();
}
void SofaScoreLiveModule::onUpdate(std::function<void()> callback) {
updateCallback = callback;
}
void SofaScoreLiveModule::setConfig(bool enabled, uint32_t fetchIntervalMinutes, unsigned long displaySec,
const PsramString& enabledTournamentSlugs, bool fullscreen, bool interruptOnLive,
uint32_t playNextMinutes, bool continuousLive,
uint32_t liveCheckIntervalSec, uint32_t liveDataFetchIntervalSec,
bool excludeMode) {
if (!webClient) return;
this->_enabled = enabled;
this->_wantsFullscreen = fullscreen;
this->_interruptOnLive = interruptOnLive;
this->_playNextMinutes = playNextMinutes;
this->_continuousLiveDisplay = continuousLive;
this->_tournamentExcludeMode = excludeMode;
this->_displayDuration = displaySec > 0 ? displaySec * 1000UL : 20000;
_currentTicksPerPage = _displayDuration / 100;
if (_currentTicksPerPage == 0) _currentTicksPerPage = 1;
// Set configurable live intervals (convert seconds to milliseconds)
this->_liveCheckIntervalMs = liveCheckIntervalSec * 1000UL;
this->_liveDataFetchIntervalMs = liveDataFetchIntervalSec * 1000UL;
Log.printf("[SofaScore] Config updated: enabled=%d, fetch=%d min, display=%d sec, fullscreen=%d, interrupt=%d, playNext=%d min, continuousLive=%d, liveCheck=%d sec, liveFetch=%d sec, excludeMode=%d\n",
enabled, fetchIntervalMinutes, displaySec, fullscreen, interruptOnLive, playNextMinutes, continuousLive, liveCheckIntervalSec, liveDataFetchIntervalSec, excludeMode);
// Parse enabled tournament slugs
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
this->enabledTournamentSlugs.clear();
if (!enabledTournamentSlugs.empty()) {
size_t pos = 0;
while (pos < enabledTournamentSlugs.length()) {
size_t commaPos = enabledTournamentSlugs.find(',', pos);
if (commaPos == PsramString::npos) commaPos = enabledTournamentSlugs.length();
PsramString slug = enabledTournamentSlugs.substr(pos, commaPos - pos);
// Trim whitespace
while (!slug.empty() && (slug[0] == ' ' || slug[0] == '\t')) {
slug = slug.substr(1);
}
while (!slug.empty() && (slug[slug.length()-1] == ' ' || slug[slug.length()-1] == '\t')) {
slug = slug.substr(0, slug.length()-1);
}
if (!slug.empty()) {
this->enabledTournamentSlugs.push_back(slug);
}
pos = commaPos + 1;
}
}
xSemaphoreGive(dataMutex);
}
if (enabled) {
// No need to pre-register active-tournaments URL
// It will be fetched on-demand when needed
// Daily events will be fetched dynamically in queueData()
// Live match statistics will be fetched on-demand in queueData()
}
// Update scroll configuration
if (config && _nameScroller && _tournamentScroller) {
uint32_t scrollSpeed = config->globalScrollSpeedMs;
_nameScroller->setConfiguredScrollSpeed(scrollSpeed);
_tournamentScroller->setConfiguredScrollSpeed(scrollSpeed);
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;
_nameScroller->setConfig(scrollConfig);
_tournamentScroller->setConfig(scrollConfig);
}
}
bool SofaScoreLiveModule::isEnabled() {
return _enabled;
}
unsigned long SofaScoreLiveModule::getDisplayDuration() {
// If continuous live display is enabled and we're in live mode, return 0 (no timeout)
if (_continuousLiveDisplay && _currentMode == SofaScoreDisplayMode::LIVE_MATCH) {
return 0; // Continuous display - module controls its own lifetime
}
// Total duration depends on number of pages
return _displayDuration * _totalPages;
}
void SofaScoreLiveModule::resetPaging() {
_currentPage = 0;
_currentTournamentIndex = 0;
_currentTournamentPage = 0;
_currentMode = SofaScoreDisplayMode::DAILY_RESULTS;
_logicTicksSincePageSwitch = 0;
_logicTicksSinceModeSwitch = 0;
_isFinished = false;
_liveEventsRegistered = false; // Reset registration flag
if (_nameScroller) _nameScroller->reset();
if (_tournamentScroller) _tournamentScroller->reset();
// Recalculate pages when resetting
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
groupMatchesByTournament();
_totalPages = calculateTotalPages();
xSemaphoreGive(dataMutex);
}
// Release interrupt if active
if (_hasActiveInterrupt && _interruptUID > 0) {
releasePriorityEx(_interruptUID);
_hasActiveInterrupt = false;
Log.println("[SofaScore] Released interrupt on reset");
}
// Release PlayNext if active
if (_hasActivePlayNext && _playNextUID > 0) {
releasePriorityEx(_playNextUID);
_hasActivePlayNext = false;
Log.println("[SofaScore] Released PlayNext on reset");
}
}
void SofaScoreLiveModule::tick() {
bool anyScrolled = false;
if (_nameScroller && _nameScroller->tick()) {
anyScrolled = true;
}
if (_tournamentScroller && _tournamentScroller->tick()) {
anyScrolled = true;
}
if (anyScrolled && updateCallback) {
updateCallback();
}
}
void SofaScoreLiveModule::logicTick() {
_logicTicksSincePageSwitch++;
_logicTicksSinceModeSwitch++;
bool needsRedraw = false;
// Page switching within current mode
if (_logicTicksSincePageSwitch >= _currentTicksPerPage) {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
bool needsModeSwitch = false;
switch (_currentMode) {
case SofaScoreDisplayMode::DAILY_RESULTS:
// NOTE: groupMatchesByTournament() is now called only in processData()
// and resetPaging(), not on every page advance for performance
if (_tournamentGroups.empty()) {
_currentPage = 0;
_currentTournamentIndex = 0;
_currentTournamentPage = 0;
needsModeSwitch = true;
} else {
// Advance to next page within current tournament
_currentTournamentPage++;
if (_currentTournamentIndex < _tournamentGroups.size()) {
const auto& currentGroup = _tournamentGroups[_currentTournamentIndex];
if (_currentTournamentPage >= currentGroup.pagesNeeded) {
// Move to next tournament
_currentTournamentPage = 0;
_currentTournamentIndex++;
// If no more tournaments, switch mode
if (_currentTournamentIndex >= _tournamentGroups.size()) {
_currentTournamentIndex = 0;
_currentTournamentPage = 0;
needsModeSwitch = true;
}
}
} else {
needsModeSwitch = true;
}
// Calculate absolute current page for display
_currentPage = 0;
for (int i = 0; i < _currentTournamentIndex && i < _tournamentGroups.size(); i++) {
_currentPage += _tournamentGroups[i].pagesNeeded;
}
_currentPage += _currentTournamentPage;
}
break;
case SofaScoreDisplayMode::LIVE_MATCH:
_totalPages = liveMatches.size() > 0 ? liveMatches.size() : 1;
_currentPage++;
if (_currentPage >= _totalPages) {
_currentPage = 0;
needsModeSwitch = true;
}
break;
case SofaScoreDisplayMode::TOURNAMENT_LIST:
_totalPages = 1;
_currentPage = 0;
needsModeSwitch = true;
break;
}
// In continuous live display mode, check if all matches are finished
// This check happens on every page switch, not just at the end of the cycle
// Performance note: Live match count is typically small (1-3), and page switches
// occur every ~20 seconds, so the overhead is negligible compared to the benefit
// of quickly detecting when matches finish
if (_continuousLiveDisplay && _currentMode == SofaScoreDisplayMode::LIVE_MATCH &&
!needsModeSwitch && areAllLiveMatchesFinished()) {
needsModeSwitch = true; // Force mode switch to exit continuous display
Log.println("[SofaScore] All live matches finished - exiting continuous display");
}
if (needsModeSwitch) {
switchToNextMode();
}
if (_nameScroller) _nameScroller->reset();
if (_tournamentScroller) _tournamentScroller->reset();
needsRedraw = true;
_logicTicksSincePageSwitch = 0;
xSemaphoreGive(dataMutex);
}
}
if (needsRedraw && updateCallback) {
updateCallback();
}
}
bool SofaScoreLiveModule::areAllLiveMatchesFinished() const {
// Check if all live matches have finished status
// IMPORTANT: Caller must hold dataMutex - this function accesses shared liveMatches vector
// Currently called from:
// - logicTick() at line ~451 (mutex held)
// - switchToNextMode() at line ~510 (called from logicTick, mutex held)
if (liveMatches.empty()) {
return true; // No live matches means nothing to show
}
for (const auto& match : liveMatches) {
if (match.status != MatchStatus::FINISHED) {
return false; // Found a match that's not finished
}
}
return true; // All matches are finished
}
void SofaScoreLiveModule::switchToNextMode() {
// Cycle through modes: DAILY_RESULTS -> LIVE_MATCH
// After completing all modes, set _isFinished = true so PanelManager can handle it
if (_currentMode == SofaScoreDisplayMode::DAILY_RESULTS) {
if (liveMatches.size() > 0) {
// Switch to live match mode
_currentMode = SofaScoreDisplayMode::LIVE_MATCH;
_currentPage = 0;
_logicTicksSinceModeSwitch = 0;
Log.println("[SofaScore] Switched to LIVE_MATCH mode");
} else {
// No live matches - cycle is complete
_isFinished = true;
Log.println("[SofaScore] Cycle complete (no live matches)");
}
} else if (_currentMode == SofaScoreDisplayMode::LIVE_MATCH) {
// If liveMatches is empty (e.g., filtered out by tournament selection, or matches ended),
// skip live mode and finish the cycle
if (liveMatches.empty()) {
_isFinished = true;
Log.println("[SofaScore] Live matches empty - cycle complete");
// Release interrupt if active
if (_hasActiveInterrupt && _interruptUID > 0) {
releasePriorityEx(_interruptUID);
_hasActiveInterrupt = false;
Log.println("[SofaScore] Released interrupt - no matching live matches");
}
return;
}
// Check if continuous live display is enabled
if (_continuousLiveDisplay && !liveMatches.empty()) {
// Check if all live matches are finished
if (areAllLiveMatchesFinished()) {
// All live matches are finished - exit continuous mode
_isFinished = true;
Log.println("[SofaScore] Continuous live display ended - all matches finished");
// Release interrupt if active
if (_hasActiveInterrupt && _interruptUID > 0) {
releasePriorityEx(_interruptUID);
_hasActiveInterrupt = false;
Log.println("[SofaScore] Released interrupt after all matches finished");
}
} else {
// Keep showing live matches - loop back to first page
_currentPage = 0;
_logicTicksSincePageSwitch = 0;
Log.println("[SofaScore] Continuous live display - looping live matches");
}
} else {
// After showing live matches, cycle is complete
_isFinished = true;
// Release interrupt if we were showing live matches via interrupt
if (_hasActiveInterrupt && _interruptUID > 0) {
releasePriorityEx(_interruptUID);
_hasActiveInterrupt = false;
Log.println("[SofaScore] Released interrupt, cycle complete");
} else {
Log.println("[SofaScore] Cycle complete after live matches");
}
}
}
// Release PlayNext when cycle finishes (but not when looping in continuous mode)
if (_isFinished && _hasActivePlayNext && _playNextUID > 0) {
releasePriorityEx(_playNextUID);
_hasActivePlayNext = false;
Log.println("[SofaScore] Released PlayNext after cycle complete");
}
}
void SofaScoreLiveModule::queueData() {
LOG_MEM_OP("SofaScore::queueData");
if (!webClient) return;
// Don't make web requests if module is disabled
if (!_enabled) return;
// Check for live events every minute
checkAndFetchLiveEvents();
// Only fetch daily schedules if not paused (no live events active)
if (!_dailySchedulesPaused) {
// Fetch today's events using GeneralTimeConverter for correct timezone handling
time_t now_utc;
time(&now_utc);
time_t now_local = timeConverter.toLocal(now_utc);
struct tm timeinfo;
gmtime_r(&now_local, &timeinfo);
char dateStr[16];
strftime(dateStr, sizeof(dateStr), "%Y-%m-%d", &timeinfo);
PsramString dailyUrl = PsramString("https://api.sofascore.com/api/v1/sport/darts/scheduled-events/") + dateStr;
// Register only if URL changed (new day)
if (dailyUrl != _lastRegisteredDailyUrl) {
uint32_t fetchInterval = config->dartsSofascoreFetchIntervalMin > 0 ? config->dartsSofascoreFetchIntervalMin : 60;
// Convert minutes to seconds and use registerResourceSeconds for consistency with live events
webClient->registerResourceSeconds(dailyUrl.c_str(), fetchInterval * 60, false, false);
_lastRegisteredDailyUrl = dailyUrl;
Log.printf("[SofaScore] Registered daily events: interval=%d min (%d sec)\n", fetchInterval, fetchInterval * 60);
}
webClient->accessResource(dailyUrl.c_str(),
[this](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0 && last_update > this->daily_last_processed_update) {
if (daily_pending_buffer) free(daily_pending_buffer);
daily_pending_buffer = (char*)ps_malloc(size + 1);
if (daily_pending_buffer) {
memcpy(daily_pending_buffer, buffer, size);
daily_pending_buffer[size] = '\0';
daily_buffer_size = size;
daily_last_processed_update = last_update;
daily_data_pending = true;
}
}
});
}
}
void SofaScoreLiveModule::checkAndFetchLiveEvents() {
if (!webClient) return;
const char* liveUrl = "https://api.sofascore.com/api/v1/sport/darts/events/live";
// Register live events endpoint for periodic fetching (60s when idle, 15s when active)
// Only re-register when state changes or when not yet registered
static bool wasLiveLastCheck = false; // Track previous state
bool stateChanged = (wasLiveLastCheck != _hasLiveEvents);
bool shouldRegister = !_liveEventsRegistered || stateChanged;
if (!_hasLiveEvents) {
// No live events: check for live events at configured interval
if (shouldRegister) {
webClient->registerResourceSeconds(liveUrl, _liveCheckIntervalMs / 1000, false, false);
_liveEventsRegistered = true;
wasLiveLastCheck = false;
}
} else {
// Has live events: fetch live data at configured interval with priority
// Only re-register when switching to live mode (state change)
if (shouldRegister) {
webClient->registerResourceSeconds(liveUrl, _liveDataFetchIntervalMs / 1000, true, false); // Priority=true for live events
_liveEventsRegistered = true;
wasLiveLastCheck = true;
}
}
// Access the resource to fetch latest data
webClient->accessResource(liveUrl,
[this](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0 && last_update > this->live_last_processed_update) {
if (live_pending_buffer) free(live_pending_buffer);
live_pending_buffer = (char*)ps_malloc(size + 1);
if (live_pending_buffer) {
memcpy(live_pending_buffer, buffer, size);
live_pending_buffer[size] = '\0';
live_buffer_size = size;
live_last_processed_update = last_update;
live_data_pending = true;
}
}
});
}
void SofaScoreLiveModule::fetchLiveData() {
_lastLiveDataFetchTime = millis();
// Fetch live events endpoint
const char* liveUrl = "https://api.sofascore.com/api/v1/sport/darts/events/live";
webClient->accessResource(liveUrl,
[this](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0 && last_update > this->live_last_processed_update) {
if (live_pending_buffer) free(live_pending_buffer);
live_pending_buffer = (char*)ps_malloc(size + 1);
if (live_pending_buffer) {
memcpy(live_pending_buffer, buffer, size);
live_pending_buffer[size] = '\0';
live_buffer_size = size;
live_last_processed_update = last_update;
live_data_pending = true;
}
}
});
}
void SofaScoreLiveModule::updateLiveMatchStats() {
LOG_MEM_OP("SofaScore::updateStats");
// Collect live event IDs while holding mutex, then fetch stats without holding mutex
std::vector<int, PsramAllocator<int>> liveEventIds;
std::vector<int, PsramAllocator<int>> eventIdsToRegister;
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
// Collect all live event IDs that need statistics updates
for (const auto& match : liveMatches) {
if (match.status == MatchStatus::LIVE) {
liveEventIds.push_back(match.eventId);
// Check if already registered
bool alreadyRegistered = false;
for (int registeredId : _registeredEventIds) {
if (registeredId == match.eventId) {
alreadyRegistered = true;
break;
}
}
if (!alreadyRegistered) {
eventIdsToRegister.push_back(match.eventId);
_registeredEventIds.push_back(match.eventId);
}
}
}
xSemaphoreGive(dataMutex);
}
// Register new resources with PRIORITY mode and force_new=true (outside mutex to avoid holding mutex during registration)
// force_new=true allows multiple statistics resources with same base URL but different event IDs
// Statistics are only fetched during live events at configured interval
uint32_t statsIntervalSec = _liveDataFetchIntervalMs / 1000;
for (int eventId : eventIdsToRegister) {
char statsUrl[128];
snprintf(statsUrl, sizeof(statsUrl), "https://api.sofascore.com/api/v1/event/%d/statistics", eventId);
// Use registerResourceSeconds with priority=true and force_new=true for live data fetch interval
webClient->registerResourceSeconds(statsUrl, statsIntervalSec, true, true, nullptr); // Priority pull, live data interval, force new
Log.printf("[SofaScore] Registered PRIORITY live match statistics: eventId=%d (%d sec interval)\n", eventId, statsIntervalSec);
}
// Fetch statistics for all live matches WITHOUT holding dataMutex to avoid nested mutex locks
for (int eventId : liveEventIds) {
char statsUrl[128];
snprintf(statsUrl, sizeof(statsUrl), "https://api.sofascore.com/api/v1/event/%d/statistics", eventId);
// Access the statistics data - callback will acquire dataMutex as needed
webClient->accessResource(statsUrl,
[this, eventId](const char* buffer, size_t size, time_t last_update, bool is_stale) {
if (buffer && size > 0) {
// parseMatchStatistics() will acquire dataMutex internally
this->parseMatchStatistics(eventId, buffer, size);
}
});
}
}
void SofaScoreLiveModule::processData() {
LOG_MEM_OP("SofaScore::processData");
// Process pending live events data FIRST (higher priority)
if (live_data_pending) {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(500)) == pdTRUE) {
parseLiveEventsJson(live_pending_buffer, live_buffer_size);
free(live_pending_buffer);
live_pending_buffer = nullptr;
live_data_pending = false;
xSemaphoreGive(dataMutex);
// After parsing live events, update statistics for live matches
// This is done AFTER parsing so liveMatches is populated
Log.println("[SofaScore] Live events parsed, fetching statistics...");
updateLiveMatchStats();
if (updateCallback) updateCallback();
}
}
// Process pending daily events data (only if no live events)
if (daily_data_pending && !_dailySchedulesPaused) {
if (xSemaphoreTake(dataMutex, pdMS_TO_TICKS(500)) == pdTRUE) {
parseDailyEventsJson(daily_pending_buffer, daily_buffer_size);
free(daily_pending_buffer);
daily_pending_buffer = nullptr;
daily_data_pending = false;
xSemaphoreGive(dataMutex);
if (updateCallback) updateCallback();
}
}
}
void SofaScoreLiveModule::parseTournamentsJson(const char* json, size_t len) {
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, json, len);
if (error) {
Log.printf("[SofaScore] JSON parse error: %s\n", error.c_str());
return;
}
availableTournaments.clear();
JsonArray groups = doc["groups"].as<JsonArray>();
for (JsonObject group : groups) {
JsonArray tournaments = group["uniqueTournaments"].as<JsonArray>();
for (JsonObject tournament : tournaments) {
SofaScoreTournament t;
t.id = tournament["id"] | 0;
const char* name = tournament["name"];
if (name) t.name = psram_strdup(name);
const char* slug = tournament["slug"];
if (slug) t.slug = psram_strdup(slug);
// Check if this tournament is in enabled list (by slug)
t.isEnabled = false;
for (const PsramString& enabledSlug : enabledTournamentSlugs) {
if (t.slug && enabledSlug == t.slug) {
t.isEnabled = true;
break;
}
}
availableTournaments.push_back(std::move(t));
}
}
}
void SofaScoreLiveModule::parseDailyEventsJson(const char* json, size_t len) {
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
DeserializationError error = deserializeJson(doc, json, len);
if (error) {
Log.printf("[SofaScore] JSON parse error: %s\n", error.c_str());
return;
}
dailyMatches.clear();
// IMPORTANT: Don't clear liveMatches here if we have active live events from the live endpoint
// The live endpoint is the source of truth for live match scores/legs when _hasLiveEvents is true
if (!_hasLiveEvents) {
liveMatches.clear();
}
// Get today's time for comparison using GeneralTimeConverter
time_t now = time(nullptr);
JsonArray events = doc["events"].as<JsonArray>();
int skippedNotToday = 0;
int skippedTournamentFilter = 0;
int parsedCount = 0;
Log.printf("[SofaScore] Parsing daily events - Total events in JSON: %d\n", events.size());
for (JsonObject event : events) {
// Check match timestamp - filter to TODAY only using GeneralTimeConverter
time_t matchTimestamp = event["startTimestamp"] | 0;
// Use isSameDay to check if match is today (isSameDay handles timezone conversion internally)
if (!timeConverter.isSameDay(now, matchTimestamp)) {
skippedNotToday++;
continue; // Skip matches not happening today
}
// Get tournament slugs for matching
// Check both tournament.slug (e.g., "pdc-world-championship-2026")
// and tournament.uniqueTournament.slug (e.g., "pdc-world-championship")
const char* tournamentSlug = event["tournament"]["slug"];
const char* uniqueTournamentSlug = event["tournament"]["uniqueTournament"]["slug"];
// Check if this tournament is enabled (by slug)
// In normal mode: empty list = show all, list = show only these
// In exclude mode: empty list = show all, list = show all EXCEPT these
bool isInList = false;
for (const PsramString& enabledSlug : enabledTournamentSlugs) {
if ((tournamentSlug && enabledSlug == tournamentSlug) ||
(uniqueTournamentSlug && enabledSlug == uniqueTournamentSlug)) {
isInList = true;
break;
}
}
bool isEnabled;
if (enabledTournamentSlugs.empty()) {
// No filter configured - show all tournaments
isEnabled = true;
} else if (_tournamentExcludeMode) {
// Exclude mode: show if NOT in list
isEnabled = !isInList;
} else {
// Include mode: show if IN list
isEnabled = isInList;
}
if (!isEnabled) {
skippedTournamentFilter++;
continue; // Skip tournaments filtered out
}
// Parse match data
SofaScoreMatch match;
match.eventId = event["id"] | 0;
// Get player names (with NULL checks)
const char* homeName = event["homeTeam"]["shortName"].as<const char*>();
if (!homeName || *homeName == '\0') {
homeName = event["homeTeam"]["name"].as<const char*>();
}
if (homeName && *homeName != '\0') {
match.homePlayerName = psram_strdup(homeName);
}
const char* awayName = event["awayTeam"]["shortName"].as<const char*>();
if (!awayName || *awayName == '\0') {
awayName = event["awayTeam"]["name"].as<const char*>();
}
if (awayName && *awayName != '\0') {
match.awayPlayerName = psram_strdup(awayName);
}
// Get country names (with NULL checks)
const char* homeCountryName = event["homeTeam"]["country"]["name"].as<const char*>();
if (homeCountryName && *homeCountryName != '\0') {
match.homeCountry = psram_strdup(homeCountryName);
}
const char* awayCountryName = event["awayTeam"]["country"]["name"].as<const char*>();
if (awayCountryName && *awayCountryName != '\0') {
match.awayCountry = psram_strdup(awayCountryName);
}
// Check if score objects exist before accessing fields
JsonObject homeScore = event["homeScore"];
if (!homeScore.isNull() && homeScore.size() > 0) {
match.homeScore = homeScore["current"] | 0;