-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
trainprogram.cpp
1786 lines (1633 loc) · 82 KB
/
trainprogram.cpp
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 "trainprogram.h"
#include "zwiftworkout.h"
#include <QFile>
#include <QMutexLocker>
#include <QtXml/QtXml>
#include <algorithm>
#include <chrono>
#ifdef Q_OS_ANDROID
#include "androidactivityresultreceiver.h"
#include "keepawakehelper.h"
#include <QAndroidJniObject>
#elif defined(Q_OS_WINDOWS)
#include "windows_zwift_incline_paddleocr_thread.h"
#include "windows_zwift_workout_paddleocr_thread.h"
#endif
#ifdef Q_CC_MSVC
#include "zwift-api/zwift_messages.pb.h"
#endif
#include "localipaddress.h"
using namespace std::chrono_literals;
trainprogram::trainprogram(const QList<trainrow> &rows, bluetooth *b, QString *description, QString *tags,
bool videoAvailable) {
QSettings settings;
bool treadmill_force_speed =
settings.value(QZSettings::treadmill_force_speed, QZSettings::default_treadmill_force_speed).toBool();
this->bluetoothManager = b;
this->rows = rows;
this->loadedRows = rows;
if (description)
this->description = *description;
if (tags)
this->tags = *tags;
if(settings.value(QZSettings::zwift_username, QZSettings::default_zwift_username).toString().length() > 0) {
zwift_auth_token = new AuthToken(settings.value(QZSettings::zwift_username, QZSettings::default_zwift_username).toString(), settings.value(QZSettings::zwift_password, QZSettings::default_zwift_password).toString());
zwift_auth_token->getAccessToken();
}
/*
int c = 0;
for (c = 0; c < rows.length(); c++) {
qDebug() << qSetRealNumberPrecision(10)<< "Trainprogramdata"
<< c
<< rows.at(c).latitude
<< rows.at(c).longitude
<< rows.at(c).altitude
<< QTime(0, 0, 0).secsTo(rows.at(c).gpxElapsed)
<< rows.at(c).distance
<< rows.at(c).inclination
<< QTime(0, 0, 0).secsTo(rows.at(c).duration)
<< QTime(0, 0, 0).secsTo(rows.at(c).rampDuration)
<< QTime(0, 0, 0).secsTo(rows.at(c).rampElapsed)
<< rows.at(c).speed;
}
*/
// speed filter only to GPX workouts with timestamp
if (rows.length() && !isnan(rows.at(0).latitude) && !isnan(rows.at(0).longitude) &&
QTime(0, 0, 0).secsTo(rows.at(0).gpxElapsed) != 0 && !treadmill_force_speed && videoAvailable) {
applySpeedFilter();
}
this->videoAvailable = videoAvailable;
connect(&timer, SIGNAL(timeout()), this, SLOT(scheduler()));
timer.setInterval(1s);
timer.start();
}
QString trainrow::toString() const {
QString rv;
rv += QStringLiteral("duration = %1").arg(duration.toString());
rv += QStringLiteral(" distance = %1").arg(distance);
rv += QStringLiteral(" speed = %1").arg(speed);
rv += QStringLiteral(" lower_speed = %1").arg(lower_speed); // used for peloton
rv += QStringLiteral(" average_speed = %1").arg(average_speed); // used for peloton
rv += QStringLiteral(" upper_speed = %1").arg(upper_speed); // used for peloton
rv += QStringLiteral(" fanspeed = %1").arg(fanspeed);
rv += QStringLiteral(" inclination = %1").arg(inclination);
rv += QStringLiteral(" lower_inclination = %1").arg(lower_inclination); // used for peloton
rv += QStringLiteral(" average_inclination = %1").arg(average_inclination); // used for peloton
rv += QStringLiteral(" upper_inclination = %1").arg(upper_inclination); // used for peloton
rv += QStringLiteral(" resistance = %1").arg(resistance);
rv += QStringLiteral(" lower_resistance = %1").arg(lower_resistance);
rv += QStringLiteral(" average_resistance = %1").arg(average_resistance); // used for peloton
rv += QStringLiteral(" upper_resistance = %1").arg(upper_resistance);
rv += QStringLiteral(" requested_peloton_resistance = %1").arg(requested_peloton_resistance);
rv += QStringLiteral(" lower_requested_peloton_resistance = %1").arg(lower_requested_peloton_resistance);
rv += QStringLiteral(" average_requested_peloton_resistance = %1")
.arg(average_requested_peloton_resistance); // used for peloton
rv += QStringLiteral(" upper_requested_peloton_resistance = %1").arg(upper_requested_peloton_resistance);
rv += QStringLiteral(" pace_intensity = %1").arg(pace_intensity);
rv += QStringLiteral(" cadence = %1").arg(cadence);
rv += QStringLiteral(" lower_cadence = %1").arg(lower_cadence);
rv += QStringLiteral(" average_cadence = %1").arg(average_cadence); // used for peloton
rv += QStringLiteral(" upper_cadence = %1").arg(upper_cadence);
rv += QStringLiteral(" forcespeed = %1").arg(forcespeed);
rv += QStringLiteral(" loopTimeHR = %1").arg(loopTimeHR);
rv += QStringLiteral(" zoneHR = %1").arg(zoneHR);
rv += QStringLiteral(" HRmin = %1").arg(HRmin);
rv += QStringLiteral(" HRmax = %1").arg(HRmax);
rv += QStringLiteral(" maxSpeed = %1").arg(maxSpeed);
rv += QStringLiteral(" minSpeed = %1").arg(minSpeed);
rv += QStringLiteral(" maxResistance = %1").arg(maxResistance);
rv += QStringLiteral(" power = %1").arg(power);
rv += QStringLiteral(" mets = %1").arg(mets);
rv += QStringLiteral(" latitude = %1").arg(latitude);
rv += QStringLiteral(" longitude = %1").arg(longitude);
rv += QStringLiteral(" altitude = %1").arg(altitude);
rv += QStringLiteral(" azimuth = %1").arg(azimuth);
rv += QStringLiteral(" rampElapsed = %1").arg(rampElapsed.toString());
rv += QStringLiteral(" rampDuration = %1").arg(rampDuration.toString());
return rv;
}
void trainprogram::applySpeedFilter() {
if (rows.length() == 0)
return;
int r = 0;
double weight[] = {0.15, 0.15, 0.1, 0.05, 0.05, 0.1, 0.1, 0.15, 0.15};
QList<double> newdistance;
newdistance.reserve(rows.length() + 1);
while (r < rows.length()) {
int ws = (r - 4);
int we = (r + 4);
// filtering starting point
if (ws < 1)
ws = 1;
if (we >= rows.length())
we = (rows.length() -
2); // Subtract 2 Points because duration is calculated with row+1! Fixes inf calculation in #973
int wc = 0;
double wma = 0;
int rowduration = 0;
for (wc = 0; wc <= (we - ws); wc++) {
int currow = (ws + wc);
// filtering starting point
if (currow <= 1)
rowduration = QTime(0, 0, 0).secsTo(rows.at(currow).gpxElapsed);
else
rowduration = ((QTime(0, 0, 0).secsTo(rows.at(currow).gpxElapsed)) -
(QTime(0, 0, 0).secsTo(rows.at(currow - 1).gpxElapsed)));
// generally avoid a division by 0 or negative (who knows what's coming from gpx)
if (rowduration > 0)
wma += ((rows.at(currow).distance) / ((double)(rowduration)) * weight[wc]);
}
// filtering starting point
if (r <= 1)
rowduration = QTime(0, 0, 0).secsTo(rows.at(r).gpxElapsed);
else
rowduration =
((QTime(0, 0, 0).secsTo(rows.at(r).gpxElapsed)) - (QTime(0, 0, 0).secsTo(rows.at(r - 1).gpxElapsed)));
/* it takes a lot of time during the opening of the file*/
/*
qDebug() << qSetRealNumberPrecision(10)<< "TrainprogramapplySpeedFilter"
<< r
<< rows.at(r).latitude
<< rows.at(r).longitude
<< rows.at(r).altitude
<< QTime(0, 0, 0).secsTo(rows.at(r).gpxElapsed)
<< rows.at(r).distance
<< (wma * ((double)(rowduration)))
<< wma
<< rowduration
<< rows.at(r).inclination;*/
newdistance.append(wma * ((double)(rowduration)));
r++;
}
for (r = 0; r < rows.length(); r++) {
rows[r].distance = newdistance.at(r);
}
}
uint32_t trainprogram::calculateTimeForRow(int32_t row) {
if (row >= rows.length())
return 0;
if (rows.at(row).distance == -1)
return (rows.at(row).duration.second() + (rows.at(row).duration.minute() * 60) +
(rows.at(row).duration.hour() * 3600));
else {
if(rows.at(row).started.isValid() && rows.at(row).ended.isValid())
return rows.at(row).started.secsTo(rows.at(row).ended);
}
return 0;
}
double trainprogram::calculateDistanceForRow(int32_t row) {
if (row >= rows.length())
return 0;
if (rows.at(row).distance == -1)
return 0;
else
return rows.at(row).distance;
}
// meters, inclination
QList<MetersByInclination> trainprogram::inclinationNext300Meters() {
int c = currentStep;
double km = 0;
QList<MetersByInclination> next300;
while (1) {
if (c < rows.length()) {
if (km > 0.3) {
return next300;
}
MetersByInclination p;
if (c == currentStep) {
p.meters = (rows.at(c).distance - currentStepDistance) * 1000.0;
km += (rows.at(c).distance - currentStepDistance);
} else {
p.meters = (rows.at(c).distance) * 1000.0;
km += (rows.at(c).distance);
}
p.inclination = rows.at(c).inclination;
next300.append(p);
} else {
return next300;
}
c++;
}
return next300;
}
// meters, inclination
QList<MetersByInclination> trainprogram::avgInclinationNext300Meters() {
int c = currentStep;
double km = 0;
QList<MetersByInclination> next300;
while (1) {
if (c < rows.length()) {
if (km > 0.3) {
return next300;
}
MetersByInclination p;
if (c == currentStep) {
p.meters = (rows.at(c).distance - currentStepDistance) * 1000.0;
km += (rows.at(c).distance - currentStepDistance);
} else {
p.meters = (rows.at(c).distance) * 1000.0;
km += (rows.at(c).distance);
}
p.inclination = avgInclinationNext100Meters(c);
next300.append(p);
} else {
return next300;
}
c++;
}
return next300;
}
// speed in Km/h
double trainprogram::avgSpeedFromGpxStep(int gpxStep, int seconds) {
int start = gpxStep;
if (gpxStep >= rows.length())
return 0.0;
double km = (rows.at(gpxStep).distance);
int timesum = 0;
if (gpxStep > 0)
timesum = (QTime(0, 0, 0).secsTo(rows.at(gpxStep).gpxElapsed) -
QTime(0, 0, 0).secsTo(rows.at(gpxStep - 1).gpxElapsed));
else
timesum = QTime(0, 0, 0).secsTo(rows.at(gpxStep).gpxElapsed);
int c = gpxStep + 1;
while (1) {
if ((timesum >= seconds) || (c >= rows.length())) {
return (km / ((double)timesum) * 3600.0);
}
km += (rows.at(c).distance);
if (c > 0)
timesum = (timesum + QTime(0, 0, 0).secsTo(rows.at(c).gpxElapsed) -
QTime(0, 0, 0).secsTo(rows.at(c - 1).gpxElapsed));
c++;
}
return (km / ((double)timesum) * 3600.0);
}
int trainprogram::TotalGPXSecs() {
if (rows.length() == 0)
return 0;
return QTime(0, 0, 0).secsTo(rows.at(rows.length() - 1).gpxElapsed);
}
double trainprogram::TimeRateFromGPX(double gpxsecs, double videosecs, double currentspeed, int recordingFactor) {
// no rows available, return 1
if (rows.length() <= 0) {
qDebug() << "TimeRateFromGPX no Rows";
return 1.0;
}
if (videosecs == 0.0) {
qDebug() << "TimeRateFromGPX Videopos = 0";
return 1.0;
}
double prevAvgSpeed = lastGpxSpeedSet;
double avgNextSpeed = -1.0;
if (prevAvgSpeed == 0.0)
avgNextSpeed = avgSpeedFromGpxStep(currentStep, 5);
else {
int testpos = currentStep;
while (testpos < (currentStep + 6)) {
double avgTestSpeed = avgSpeedFromGpxStep(testpos, 5);
double deviation = (avgTestSpeed / prevAvgSpeed);
if (deviation >= 0.85 && deviation <= 1.15) {
avgNextSpeed = avgTestSpeed;
testpos = (currentStep + 6);
}
testpos++;
}
}
if (avgNextSpeed == -1.0) {
avgNextSpeed = avgSpeedFromGpxStep(currentStep, 5);
}
// Avoid a Division by Zero
if (avgNextSpeed == 0.0) {
qDebug() << "TimeRateFromGPX Nextspeed = 0";
return 1.0;
}
// set the maximum Speed that the player can reached based on the Video speed.
// if Rate get too high the Video jumps
if (bluetoothManager->device()->deviceType() == bluetoothdevice::BIKE) {
double avgSpeedForLimit = avgSpeedFromGpxStep(currentStep + 1, 5);
if (avgSpeedForLimit > 0.0) {
bike *dev = (bike *)bluetoothManager->device();
// bepo70: Replay allows Factor 2 max, so set the speed Limit to 2 * Video recording Factor speed to
// avoid any jumps in Video
dev->setSpeedLimit(avgSpeedForLimit * (double)recordingFactor * 2.0 / 3.0);
}
}
if (gpxsecs == lastGpxRateSetAt) {
qDebug() << "TimeRateFromGPX Gpxpos=lastPos" << lastGpxRateSet;
return lastGpxRateSet;
}
// Calculate the Factor between current Players Speed and the next average GPX Speed
double playedToGpxSpeedFactor = (currentspeed / avgNextSpeed);
// Calculate where the gpx would be in 1 Second
double gpxTarget = (gpxsecs + playedToGpxSpeedFactor);
// Get needed Rate for the next second
double rate = (gpxTarget - videosecs);
// If rate < 0 Video is highly before the gpx and Video would be rewinded. Wait with Video for gpx to reach it
if (rate < 0.0) {
rate = 0.1;
}
qDebug() << qSetRealNumberPrecision(10) << "TimeRateFromGPX" << gpxsecs << videosecs << (gpxsecs - videosecs)
<< currentspeed << avgNextSpeed << gpxTarget << lastGpxRateSetAt << lastGpxRateSet << rate;
// Save the last Gpx Timestamp and the last Rate for later calls.
lastGpxSpeedSet = avgNextSpeed;
if (lastGpxRateSetAt != gpxsecs) {
lastGpxRateSetAt = gpxsecs;
lastGpxRateSet = rate;
}
return rate;
}
// Calculate the Median Inclination for a given Step. Median is built from the given Step -2 Steps and +2 Steps (5 Steps
// in total)
double trainprogram::medianInclination(int step) {
QList<double> inclinations;
inclinations.reserve(5);
if (rows.length() == 0)
return 0;
if ((step > 1) && (rows.length() > step - 2))
inclinations.append(rows.at(step - 2).inclination);
else
inclinations.append(0);
if ((step > 0) && (rows.length() > step - 1))
inclinations.append(rows.at(step - 1).inclination);
else
inclinations.append(0);
if (rows.length() > step)
inclinations.append(rows.at(step).inclination);
else
inclinations.append(0);
if (rows.length() > step + 1)
inclinations.append(rows.at(step + 1).inclination);
else
inclinations.append(0);
if (rows.length() > step + 2)
inclinations.append(rows.at(step + 2).inclination);
else
inclinations.append(0);
std::sort(inclinations.begin(), inclinations.end());
return (inclinations.at(2));
}
// Calculates a weighted Inclination for a given Step. Inclination is calculated for the given Step + windowsize Steps
// (7) The inclination for each Point needed goes through a Median Filter first to eliminate/minimize Errors in the
// recorded elevation Data
double trainprogram::weightedInclination(int step) {
int windowsize = 7;
int firststep = step;
double inc = 0;
double sumweights = 0;
double pointweight = 0;
if (rows.length() == 0)
return 0;
// Determine first and last possible Steps
if (firststep < 0)
firststep = 0;
int laststep = step + windowsize;
if (laststep >= rows.length()) {
firststep = rows.length() - 1 - (windowsize * 2);
if (firststep < 0)
firststep = 0;
}
// Loop through the determined Steps
for (int s = firststep; s <= laststep; s++) {
// Calculate the Weight used for the inclination
pointweight = ((((double)windowsize * 2.0) - 1.0) - ((s - firststep) * 2.0));
// Calculate the sum of weights
sumweights = (sumweights + pointweight);
// Calculate the sum of weighted median inclinations
inc = (inc + (medianInclination(s)) * pointweight);
}
// avoid a Division by 0
if (sumweights == 0)
return 0;
// Return the sum of weighted median inclinations / sum of all weights
return (inc / sumweights);
}
double trainprogram::avgInclinationNext100Meters(int step) {
int c = step;
double km = 0;
double avg = 0;
int sum = 0;
while (1) {
if (c < rows.length()) {
if (km > 0.1) {
if (sum == 1) {
return rows.at(currentStep).inclination;
}
return avg / (double)km;
}
if (c == currentStep)
km += (rows.at(c).distance - currentStepDistance);
else
km += (rows.at(c).distance);
avg += rows.at(c).inclination * rows.at(c).distance;
sum++;
} else {
if (sum == 1) {
return rows.at(currentStep).inclination;
}
return avg / (double)km;
}
c++;
}
if (sum == 1) {
return rows.at(currentStep).inclination;
}
return avg / (double)km;
}
double trainprogram::avgAzimuthNext300Meters() {
int c = currentStep;
double km = 0;
double sinTotal = 0;
double cosTotal = 0;
if (!isnan(rows.at(c).latitude) && !isnan(rows.at(c).longitude)) {
while (1) {
if (c < rows.length()) {
if (km > 0.3) {
double averageDirection = atan(sinTotal / cosTotal) * (180 / M_PI);
if (cosTotal < 0) {
averageDirection += 180;
} else if (sinTotal < 0) {
averageDirection += 360;
}
return averageDirection;
}
for (double i = 0; i < rows.at(c).distance; i += 0.001) {
sinTotal += sin(rows.at(c).azimuth * (M_PI / 180));
cosTotal += cos(rows.at(c).azimuth * (M_PI / 180));
}
km += rows.at(c).distance;
} else {
double averageDirection = atan(sinTotal / cosTotal) * (180 / M_PI);
if (cosTotal < 0) {
averageDirection += 180;
} else if (sinTotal < 0) {
averageDirection += 360;
}
return averageDirection;
}
c++;
}
}
return 0;
}
void trainprogram::clearRows() {
QMutexLocker(&this->schedulerMutex);
rows.clear();
}
void trainprogram::pelotonOCRprocessPendingDatagrams() {
qDebug() << "in !";
QHostAddress sender;
QSettings settings;
uint16_t port;
while (pelotonOCRsocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(pelotonOCRsocket->pendingDatagramSize());
pelotonOCRsocket->readDatagram(datagram.data(), datagram.size(), &sender, &port);
qDebug() << "PelotonOCR Message From :: " << sender.toString();
qDebug() << "PelotonOCR Port From :: " << port;
qDebug() << "PelotonOCR Message :: " << datagram;
QString s = datagram;
pelotonOCRcomputeTime(s);
QString url = "http://" + localipaddress::getIP(sender).toString() + ":" +
QString::number(settings.value("template_inner_QZWS_port", 6666).toInt()) +
"/floating/floating.htm";
int r = pelotonOCRsocket->writeDatagram(QByteArray(url.toLatin1()), sender, 8003);
qDebug() << "url floating" << url << r;
}
}
void trainprogram::pelotonOCRcomputeTime(QString t) {
static bool pelotonOCRcomputeTime_intro = false;
static bool pelotonOCRcomputeTime_syncing = false;
QRegularExpression re("\\d\\d:\\d\\d");
QRegularExpressionMatch match = re.match(t.left(5));
if (t.contains(QStringLiteral("INTRO")) || t.contains(QStringLiteral("UNTIL START"))) {
qDebug() << QStringLiteral("PELOTON OCR: SKIPPING INTRO, restarting training program");
if (!pelotonOCRcomputeTime_intro) {
pelotonOCRcomputeTime_intro = true;
emit toastRequest("Peloton Syncing! Skipping intro...");
}
restart();
} else if (match.hasMatch()) {
int minutes = t.left(2).toInt();
int seconds = t.left(5).right(2).toInt();
seconds -= 1; //(due to the OCR delay)
seconds += minutes * 60;
QTime ocrRemaining = QTime(0, 0, 0, 0).addSecs(seconds);
QTime currentRemaining = remainingTime();
qDebug() << QStringLiteral("PELOTON OCR USING: ocrRemaining") << ocrRemaining
<< QStringLiteral("currentRemaining") << currentRemaining;
uint32_t abs = qAbs(ocrRemaining.secsTo(currentRemaining));
if (abs < 120) {
qDebug() << QStringLiteral("PELOTON OCR SYNCING!");
if (!pelotonOCRcomputeTime_syncing) {
pelotonOCRcomputeTime_syncing = true;
emit toastRequest("Peloton Syncing!");
}
// applying the differences
if (ocrRemaining > currentRemaining)
decreaseElapsedTime(abs);
else
increaseElapsedTime(abs);
}
}
}
void trainprogram::scheduler() {
QMutexLocker(&this->schedulerMutex);
QSettings settings;
// outside the if case about a valid train program because the information for the floating window url should be
// sent anyway
if (settings.value(QZSettings::peloton_companion_workout_ocr, QZSettings::default_companion_peloton_workout_ocr)
.toBool()) {
if (!pelotonOCRsocket) {
pelotonOCRsocket = new QUdpSocket(this);
bool result = pelotonOCRsocket->bind(QHostAddress::AnyIPv4, 8003);
qDebug() << result;
pelotonOCRprocessPendingDatagrams();
connect(pelotonOCRsocket, SIGNAL(readyRead()), this, SLOT(pelotonOCRprocessPendingDatagrams()));
}
}
if (rows.count() == 0 || started == false || enabled == false || bluetoothManager->device() == nullptr ||
(bluetoothManager->device()->currentSpeed().value() <= 0 &&
!settings.value(QZSettings::continuous_moving, QZSettings::default_continuous_moving).toBool()) ||
bluetoothManager->device()->isPaused()) {
if(bluetoothManager->device() && (bluetoothManager->device()->deviceType() == bluetoothdevice::TREADMILL || bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL) &&
settings.value(QZSettings::zwift_username, QZSettings::default_zwift_username).toString().length() > 0 && zwift_auth_token &&
zwift_auth_token->access_token.length() > 0) {
if(!zwift_world) {
zwift_world = new World(1, zwift_auth_token->getAccessToken());
qDebug() << "creating zwift api world";
}
else {
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
if(!h)
h = new lockscreen();
#endif
#endif
if(zwift_player_id == -1) {
QString id = zwift_world->player_id();
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(id.toLocal8Bit(), &parseError);
QJsonObject ride = document.object();
qDebug() << "zwift api player" << ride;
zwift_player_id = ride[QStringLiteral("id")].toInt();
emit zwiftLoginState(true);
} else {
static int zwift_counter = 5;
int timeout = settings.value(QZSettings::zwift_api_poll, QZSettings::default_zwift_api_poll).toInt();
if(timeout < 5)
timeout = 5;
if(zwift_counter++ >= (timeout - 1)) {
zwift_counter = 0;
QByteArray bb = zwift_world->playerStatus(zwift_player_id);
qDebug() << " ZWIFT API PROTOBUF << " + bb.toHex(' ');
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
h->zwift_api_decodemessage_player(bb.data(), bb.length());
float alt = h->zwift_api_getaltitude();
float distance = h->zwift_api_getdistance();
#else
float alt = 0;
float distance = 0;
#endif
#elif defined(Q_OS_ANDROID)
QAndroidJniEnvironment env;
jbyteArray d = env->NewByteArray(bb.length());
jbyte *b = env->GetByteArrayElements(d, 0);
for (int i = 0; i < bb.length(); i++)
b[i] = bb[i];
env->SetByteArrayRegion(d, 0, bb.length(), b);
QAndroidJniObject::callStaticMethod<void>(
"org/cagnulen/qdomyoszwift/ZwiftAPI", "zwift_api_decodemessage_player", "([B)V", d);
env->DeleteLocalRef(d);
float alt = QAndroidJniObject::callStaticMethod<float>("org/cagnulen/qdomyoszwift/ZwiftAPI", "getAltitude", "()F");
float distance = QAndroidJniObject::callStaticMethod<float>("org/cagnulen/qdomyoszwift/ZwiftAPI", "getDistance", "()F");
#elif defined Q_CC_MSVC
PlayerState state;
float alt = 0;
float distance = 0;
if (state.ParseFromArray(bb.constData(), bb.size())) {
// Parsing riuscito, ora puoi accedere ai dati in `state`
alt = state.altitude();
distance = state.distance();
} else {
// Errore durante il parsing
qDebug() << "Error parsing PlayerState";
}
#else
float alt = 0;
float distance = 0;
#endif
static float old_distance = 0;
static float old_alt = 0;
qDebug() << "zwift api incline1" << old_distance << old_alt << distance << alt;
if(old_distance > 0) {
float delta = distance - old_distance;
float deltaA = alt - old_alt;
float incline = (deltaA / delta);
if(delta > 1) {
bool zwift_negative_inclination_x2 =
settings.value(QZSettings::zwift_negative_inclination_x2, QZSettings::default_zwift_negative_inclination_x2)
.toBool();
double offset =
settings.value(QZSettings::zwift_inclination_offset, QZSettings::default_zwift_inclination_offset).toDouble();
double gain =
settings.value(QZSettings::zwift_inclination_gain, QZSettings::default_zwift_inclination_gain).toDouble();
double grade = (incline * gain) + offset;
if (zwift_negative_inclination_x2 && incline < 0) {
grade = ((incline * 2.0) * gain) + offset;
}
bool zwift_api_autoinclination = settings.value(QZSettings::zwift_api_autoinclination, QZSettings::default_zwift_api_autoinclination).toBool();
qDebug() << "zwift api incline" << incline << grade << delta << deltaA << zwift_api_autoinclination;
if(zwift_api_autoinclination) {
if(bluetoothManager->device()->deviceType() == bluetoothdevice::TREADMILL ||
(bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL && ((elliptical*)bluetoothManager->device())->inclinationAvailableByHardware())) {
bluetoothManager->device()->changeInclination(grade, grade);
}
if (bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL &&
(!((elliptical*)bluetoothManager->device())->inclinationAvailableByHardware() ||
((elliptical*)bluetoothManager->device())->inclinationSeparatedFromResistance())) {
QSettings settings;
double bikeResistanceOffset = settings.value(QZSettings::bike_resistance_offset, bikeResistanceOffset).toInt();
double bikeResistanceGain = settings.value(QZSettings::bike_resistance_gain_f, bikeResistanceGain).toDouble();
bluetoothManager->device()->changeResistance((resistance_t)(round(grade * bikeResistanceGain)) + bikeResistanceOffset + 1); // resistance start from 1
}
}
}
}
old_distance = distance;
old_alt = alt;
}
}
}
}
// in case no workout has been selected
// Zwift OCR
if ((settings.value(QZSettings::zwift_ocr, QZSettings::default_zwift_ocr).toBool() ||
settings.value(QZSettings::zwift_ocr_climb_portal, QZSettings::default_zwift_ocr_climb_portal).toBool()) &&
bluetoothManager && bluetoothManager->device() &&
(bluetoothManager->device()->deviceType() == bluetoothdevice::TREADMILL ||
bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL)) {
#ifdef Q_OS_ANDROID
{
QAndroidJniObject text = QAndroidJniObject::callStaticObjectMethod<jstring>(
"org/cagnulen/qdomyoszwift/ScreenCaptureService", "getLastText");
QString t = text.toString();
QAndroidJniObject textExtended = QAndroidJniObject::callStaticObjectMethod<jstring>(
"org/cagnulen/qdomyoszwift/ScreenCaptureService", "getLastTextExtended");
// 2272 1027
jint w = QAndroidJniObject::callStaticMethod<jint>("org/cagnulen/qdomyoszwift/ScreenCaptureService",
"getImageWidth", "()I");
jint h = QAndroidJniObject::callStaticMethod<jint>("org/cagnulen/qdomyoszwift/ScreenCaptureService",
"getImageHeight", "()I");
QString tExtended = textExtended.toString();
QAndroidJniObject packageNameJava = QAndroidJniObject::callStaticObjectMethod<jstring>(
"org/cagnulen/qdomyoszwift/MediaProjection", "getPackageName");
QString packageName = packageNameJava.toString();
if (packageName.contains("com.zwift.zwiftgame")) {
qDebug() << QStringLiteral("ZWIFT OCR ACCEPTED") << packageName << w << h << t << tExtended;
foreach (QString s, tExtended.split("§§")) {
// qDebug() << s;
QStringList ss = s.split("$$");
if (ss.length() > 1) {
// (2195, 75 - 2254, 106)"
qDebug() << ss[0] << ss[1];
QString inc = ss[1].replace("Rect(", "").replace(")", "");
if (inc.split(",").length() > 2) {
int w_minbound = w * 0.93;
int h_minbound = h * 0.08;
int h_maxbound = h * 0.15;
int x = inc.split(",").at(0).toInt();
int y = inc.split(",").at(2).toInt();
qDebug() << x << w_minbound << h_maxbound << y << h_minbound;
if (x > w_minbound && y < h_maxbound && y > h_minbound) {
ss[0] = ss[0].replace("%", "");
ss[0] = ss[0].replace("O", "0");
ss[0] = ss[0].replace("l", "1");
ss[0] = ss[0].replace(" ", "");
if (ss[0].toInt() < 15 && ss[0].toInt() > -15) {
bluetoothManager->device()->changeInclination(ss[0].toInt(), ss[0].toInt());
} else {
qDebug() << "filtering" << ss[0].toInt();
}
}
}
}
}
} else {
qDebug() << QStringLiteral("ZWIFT OCR IGNORING") << packageName << t;
}
}
#elif defined(Q_OS_WINDOWS)
static windows_zwift_incline_paddleocr_thread *windows_zwift_ocr_thread = nullptr;
if (!windows_zwift_ocr_thread) {
windows_zwift_ocr_thread = new windows_zwift_incline_paddleocr_thread(bluetoothManager->device());
connect(windows_zwift_ocr_thread, &windows_zwift_incline_paddleocr_thread::debug, bluetoothManager,
&bluetooth::debug);
connect(windows_zwift_ocr_thread, &windows_zwift_incline_paddleocr_thread::onInclination, this,
&trainprogram::changeInclination);
windows_zwift_ocr_thread->start();
}
#endif
} else if (settings.value(QZSettings::zwift_workout_ocr, QZSettings::default_zwift_workout_ocr).toBool() &&
bluetoothManager && bluetoothManager->device() &&
(bluetoothManager->device()->deviceType() == bluetoothdevice::TREADMILL ||
bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL)) {
#ifdef Q_OS_WINDOWS
static windows_zwift_workout_paddleocr_thread *windows_zwift_workout_ocr_thread = nullptr;
if (!windows_zwift_workout_ocr_thread) {
windows_zwift_workout_ocr_thread =
new windows_zwift_workout_paddleocr_thread(bluetoothManager->device());
connect(windows_zwift_workout_ocr_thread, &windows_zwift_workout_paddleocr_thread::debug,
bluetoothManager, &bluetooth::debug);
connect(windows_zwift_workout_ocr_thread, &windows_zwift_workout_paddleocr_thread::onInclination, this,
&trainprogram::changeInclination);
connect(windows_zwift_workout_ocr_thread, &windows_zwift_workout_paddleocr_thread::onSpeed, this,
&trainprogram::changeSpeed);
windows_zwift_workout_ocr_thread->start();
}
#endif
}
return;
}
#ifdef Q_OS_ANDROID
if (settings.value(QZSettings::peloton_workout_ocr, QZSettings::default_peloton_workout_ocr).toBool()) {
QAndroidJniObject text = QAndroidJniObject::callStaticObjectMethod<jstring>(
"org/cagnulen/qdomyoszwift/ScreenCaptureService", "getLastText");
QString t = text.toString();
QAndroidJniObject packageNameJava = QAndroidJniObject::callStaticObjectMethod<jstring>(
"org/cagnulen/qdomyoszwift/MediaProjection", "getPackageName");
QString packageName = packageNameJava.toString();
if (packageName.contains("com.onepeloton.callisto")) {
qDebug() << QStringLiteral("PELOTON OCR ACCEPTED") << packageName << t;
pelotonOCRcomputeTime(t);
} else {
qDebug() << QStringLiteral("PELOTON OCR IGNORING") << packageName << t;
}
}
#endif
ticks++;
double odometerFromTheDevice = bluetoothManager->device()->odometer();
if(ticks < 0) {
qDebug() << "waiting for the start...";
return;
}
// entry point
if (ticks == 1 && currentStep == 0) {
rows[currentStep].started = QDateTime::currentDateTime();
currentStepDistance = 0;
lastOdometer = odometerFromTheDevice;
if (bluetoothManager->device()->deviceType() == bluetoothdevice::TREADMILL) {
if (rows.at(0).forcespeed && rows.at(0).speed) {
qDebug() << QStringLiteral("trainprogram change speed") + QString::number(rows.at(0).speed);
emit changeSpeed(rows.at(0).speed);
}
if (rows.at(0).inclination != -200) {
double inc;
if (!isnan(rows.at(0).latitude) && !isnan(rows.at(0).longitude)) {
inc = avgInclinationNext100Meters(currentStep);
} else {
inc = rows.at(0).inclination;
}
qDebug() << QStringLiteral("trainprogram change inclination") + QString::number(inc);
emit changeInclination(inc, inc);
emit changeNextInclination300Meters(avgInclinationNext300Meters());
}
if (rows.at(0).power != -1) {
qDebug() << QStringLiteral("trainprogram change power") + QString::number(rows.at(0).power);
emit changePower(rows.at(0).power);
}
} else if (bluetoothManager->device()->deviceType() == bluetoothdevice::ROWING) {
if (rows.at(0).forcespeed && rows.at(0).speed) {
qDebug() << QStringLiteral("trainprogram change speed") + QString::number(rows.at(0).speed);
emit changeSpeed(rows.at(0).speed);
}
if (rows.at(0).cadence != -1) {
qDebug() << QStringLiteral("trainprogram change cadence") + QString::number(rows.at(0).cadence);
emit changeCadence(rows.at(0).cadence);
}
if (rows.at(0).power != -1) {
qDebug() << QStringLiteral("trainprogram change power") + QString::number(rows.at(0).power);
emit changePower(rows.at(0).power);
}
if (rows.at(0).resistance != -1) {
qDebug() << QStringLiteral("trainprogram change resistance") + QString::number(rows.at(0).resistance);
emit changeResistance(rows.at(0).resistance);
}
} else {
if (rows.at(0).resistance != -1) {
qDebug() << QStringLiteral("trainprogram change resistance") + QString::number(rows.at(0).resistance);
emit changeResistance(rows.at(0).resistance);
}
if (rows.at(0).cadence != -1) {
qDebug() << QStringLiteral("trainprogram change cadence") + QString::number(rows.at(0).cadence);
emit changeCadence(rows.at(0).cadence);
}
if (rows.at(0).power != -1) {
qDebug() << QStringLiteral("trainprogram change power") + QString::number(rows.at(0).power);
emit changePower(rows.at(0).power);
}
if (rows.at(0).requested_peloton_resistance != -1) {
qDebug() << QStringLiteral("trainprogram change requested peloton resistance") +
QString::number(rows.at(0).requested_peloton_resistance);
emit changeRequestedPelotonResistance(rows.at(0).requested_peloton_resistance);
}
if (rows.at(0).inclination != -200 && (bluetoothManager->device()->deviceType() == bluetoothdevice::BIKE ||
(bluetoothManager->device()->deviceType() == bluetoothdevice::ELLIPTICAL && !((elliptical*)bluetoothManager->device())->inclinationAvailableByHardware()))) {
// this should be converted in a signal as all the other signals...
double bikeResistanceOffset =
settings.value(QZSettings::bike_resistance_offset, QZSettings::default_bike_resistance_offset)
.toInt();
double bikeResistanceGain =
settings.value(QZSettings::bike_resistance_gain_f, QZSettings::default_bike_resistance_gain_f)
.toDouble();
double inc = rows.at(0).inclination;
bluetoothManager->device()->changeResistance((resistance_t)(round(inc * bikeResistanceGain)) +
bikeResistanceOffset + 1); // resistance start from 1)
if (bluetoothManager->device()->deviceType() == bluetoothdevice::BIKE && !((bike *)bluetoothManager->device())->inclinationAvailableByHardware())
bluetoothManager->device()->setInclination(inc);
qDebug() << QStringLiteral("trainprogram change inclination") + QString::number(inc);
emit changeInclination(inc, inc);
emit changeNextInclination300Meters(inclinationNext300Meters());
}
}
if (rows.at(0).fanspeed != -1) {
qDebug() << QStringLiteral("trainprogram change fanspeed") + QString::number(rows.at(0).fanspeed);
emit changeFanSpeed(rows.at(0).fanspeed);
}
if (!isnan(rows.at(0).latitude) || !isnan(rows.at(0).longitude) || !isnan(rows.at(0).altitude)) {
qDebug() << qSetRealNumberPrecision(10) << QStringLiteral("trainprogram change GEO position")
<< rows.at(0).latitude << rows.at(0).longitude << rows.at(0).altitude << rows.at(0).azimuth;
QGeoCoordinate p;
p.setAltitude(rows.at(0).altitude);
p.setLatitude(rows.at(0).latitude);
p.setLongitude(rows.at(0).longitude);
emit changeGeoPosition(p, rows.at(0).azimuth, avgAzimuthNext300Meters());
}
}
uint32_t currentRowLen = calculateTimeForRow(currentStep);
qDebug() << QStringLiteral("trainprogram elapsed ") + QString::number(ticks) + QStringLiteral("current row len") +
QString::number(currentRowLen);
uint32_t calculatedLine;
uint32_t calculatedElapsedTime = 0;
for (calculatedLine = 0; calculatedLine < static_cast<uint32_t>(rows.length()); calculatedLine++) {
calculatedElapsedTime += calculateTimeForRow(calculatedLine);
if (calculateDistanceForRow(calculatedLine) > 0 && calculatedLine >= currentStep) {
break;
}
if (calculatedElapsedTime > static_cast<uint32_t>(ticks) && calculatedLine >= currentStep) {
break;
}
}
bool distanceEvaluation = false;
int sameIteration = 0;
do {
currentStepDistance += (odometerFromTheDevice - lastOdometer);
lastOdometer = odometerFromTheDevice;
if(currentStep >= rows.length()) {
qDebug() << "currentStep greater than row.length" << currentStep << rows.length();
end();
return;
}
bool distanceStep = (rows.at(currentStep).distance > 0);
distanceEvaluation = (distanceStep && currentStepDistance >= rows.at(currentStep).distance);
qDebug() << qSetRealNumberPrecision(10) << QStringLiteral("currentStepDistance") << currentStepDistance
<< QStringLiteral("distanceStep") << distanceStep << QStringLiteral("distanceEvaluation")
<< distanceEvaluation << QStringLiteral("rows distance") << rows.at(currentStep).distance
<< QStringLiteral("same iteration") << sameIteration;
if ((calculatedLine != currentStep && !distanceStep) || distanceEvaluation) {
if (calculateTimeForRow(calculatedLine) || calculateDistanceForRow(calculatedLine) > 0) {
if(rows.at(currentStep).distance != -1)
lastOdometer -= (currentStepDistance - rows.at(currentStep).distance);
rows[currentStep].ended = QDateTime::currentDateTime();
if (!distanceStep)
currentStep = calculatedLine;
else
currentStep++;
if(currentStep >= rows.length()) {
qDebug() << "currentStep greater than row.length" << currentStep << rows.length();
end();
return;