-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathftmsbike.cpp
More file actions
2170 lines (1871 loc) · 96.4 KB
/
Copy pathftmsbike.cpp
File metadata and controls
2170 lines (1871 loc) · 96.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 "ftmsbike.h"
#include "speedracex_defaults.h"
#include "homeform.h"
#include "virtualdevices/virtualbike.h"
#include <QBluetoothLocalDevice>
#include <QDateTime>
#include <QFile>
#include <QMetaEnum>
#include <QSettings>
#include <QThread>
#include <math.h>
#ifdef Q_OS_ANDROID
#include <QLowEnergyConnectionParameters>
#endif
#ifdef Q_OS_ANDROID
#include "keepawakehelper.h"
#endif
#include <chrono>
#include "wheelcircumference.h"
#ifdef Q_OS_IOS
extern quint8 QZ_EnableDiscoveryCharsAndDescripttors;
#endif
using namespace std::chrono_literals;
ftmsbike::ftmsbike(bool noWriteResistance, bool noHeartService, int8_t bikeResistanceOffset,
double bikeResistanceGain) {
QSettings settings;
m_watt.setType(metric::METRIC_WATT, deviceType());
Speed.setType(metric::METRIC_SPEED);
refresh = new QTimer(this);
this->noWriteResistance = noWriteResistance;
this->noHeartService = noHeartService;
this->bikeResistanceGain = bikeResistanceGain;
this->bikeResistanceOffset = bikeResistanceOffset;
initDone = false;
ergModeSupported = true; // by default ftms devices SHOULD have ergMode supported
connect(refresh, &QTimer::timeout, this, &ftmsbike::update);
refresh->start(settings.value(QZSettings::poll_device_time, QZSettings::default_poll_device_time).toInt());
writeTimeoutTimer = new QTimer(this);
writeTimeoutTimer->setSingleShot(true);
connect(writeTimeoutTimer, &QTimer::timeout, this, [this]() {
qDebug() << QStringLiteral("writeCharacteristic timeout - processing next in queue");
completeCurrentWrite();
});
wheelCircumference::GearTable g;
g.printTable();
}
void ftmsbike::writeCharacteristicZwiftPlay(uint8_t *data, uint8_t data_len, const QString &info, bool disable_log,
bool wait_for_response) {
QSettings settings;
bool gears_zwift_ratio = settings.value(QZSettings::gears_zwift_ratio, QZSettings::default_gears_zwift_ratio).toBool();
if(!zwiftPlayService || !gears_zwift_ratio) {
qDebug() << QStringLiteral("zwiftPlayService is null!");
return;
}
enqueueWrite(zwiftPlayService, zwiftPlayWriteChar, data, data_len, info, disable_log, wait_for_response,
zwiftPlayWriteChar.properties() & QLowEnergyCharacteristic::WriteNoResponse);
}
bool ftmsbike::writeCharacteristic(uint8_t *data, uint8_t data_len, const QString &info, bool disable_log,
bool wait_for_response) {
QSettings settings;
bool gears_zwift_ratio = settings.value(QZSettings::gears_zwift_ratio, QZSettings::default_gears_zwift_ratio).toBool();
if(!gattFTMSService) {
qDebug() << QStringLiteral("gattFTMSService is null!");
return false;
}
if(zwiftPlayService && gears_zwift_ratio) {
qDebug() << QStringLiteral("zwiftPlayService is present!");
return false;
}
return enqueueWrite(gattFTMSService, gattWriteCharControlPointId, data, data_len, info, disable_log,
wait_for_response,
gattWriteCharControlPointId.properties() & QLowEnergyCharacteristic::WriteNoResponse &&
!DOMYOS);
}
bool ftmsbike::enqueueWrite(QLowEnergyService *service, const QLowEnergyCharacteristic &characteristic, uint8_t *data,
uint8_t data_len, const QString &info, bool disable_log, bool wait_for_response,
bool write_without_response) {
if (!service || !characteristic.isValid()) {
qDebug() << QStringLiteral("writeCharacteristic error because service/characteristic is invalid");
return false;
}
WriteRequest request;
request.data = QByteArray((const char *)data, data_len);
request.info = info;
request.disable_log = disable_log;
request.wait_for_response = wait_for_response;
request.service = service;
request.characteristic = characteristic;
request.write_without_response = write_without_response;
writeQueue.enqueue(request);
processWriteQueue();
return true;
}
void ftmsbike::processWriteQueue() {
if (isWriting || writeQueue.isEmpty()) {
return;
}
WriteRequest request = writeQueue.dequeue();
if (!request.service || request.service->state() != QLowEnergyService::ServiceDiscovered) {
qDebug() << QStringLiteral("writeCharacteristic error because the connection is closed");
writeQueue.clear();
return;
}
if (writeBuffer) {
delete writeBuffer;
}
writeBuffer = new QByteArray(request.data);
isWriting = true;
currentWriteWaitingForResponse = request.wait_for_response;
currentWriteService = request.service;
if (request.write_without_response) {
request.service->writeCharacteristic(request.characteristic, *writeBuffer, QLowEnergyService::WriteWithoutResponse);
} else {
request.service->writeCharacteristic(request.characteristic, *writeBuffer);
}
if (!request.disable_log) {
emit debug(QStringLiteral(" >> ") + writeBuffer->toHex(' ') + QStringLiteral(" // ") + request.info);
}
writeTimeoutTimer->start(300);
}
void ftmsbike::completeCurrentWrite() {
writeTimeoutTimer->stop();
isWriting = false;
currentWriteWaitingForResponse = false;
currentWriteService = nullptr;
processWriteQueue();
}
void ftmsbike::init() {
if (initDone)
return;
if(ICSE || HAMMER) {
uint8_t write[] = {FTMS_REQUEST_CONTROL};
bool ret = writeCharacteristic(write, sizeof(write), "requestControl", false, true);
write[0] = {FTMS_RESET};
ret = writeCharacteristic(write, sizeof(write), "reset", false, true);
}
uint8_t write[] = {FTMS_REQUEST_CONTROL};
bool ret = writeCharacteristic(write, sizeof(write), "requestControl", false, true);
if (USDC_D700) {
// Kinomap keeps this bike streaming by following request-control with STOP/PAUSE(0x01)
// instead of the usual START/RESUME opcode.
uint8_t usdcStart[] = {FTMS_STOP_PAUSE, 0x01};
ret = writeCharacteristic(usdcStart, sizeof(usdcStart), "usdc d700 start workaround", false, true);
} else {
write[0] = {FTMS_START_RESUME};
ret = writeCharacteristic(write, sizeof(write), "start simulation", false, true);
}
if(ret) {
initDone = true;
initRequest = false;
}
}
ftmsbike::~ftmsbike() {
}
void ftmsbike::zwiftPlayInit() {
QSettings settings;
bool gears_zwift_ratio = settings.value(QZSettings::gears_zwift_ratio, QZSettings::default_gears_zwift_ratio).toBool();
if(zwiftPlayService && gears_zwift_ratio) {
uint8_t rideOn[] = {0x52, 0x69, 0x64, 0x65, 0x4f, 0x6e, 0x02, 0x01};
writeCharacteristicZwiftPlay(rideOn, sizeof(rideOn), "rideOn", false, true);
uint8_t init1[] = {0x41, 0x08, 0x05};
writeCharacteristicZwiftPlay(init1, sizeof(init1), "init1", false, true);
uint8_t init2[] = {0x04, 0x2a, 0x04, 0x10, 0xc0, 0xbb, 0x01};
writeCharacteristicZwiftPlay(init2, sizeof(init2), "init2", false, true);
uint8_t init3[] = {0x00, 0x08, 0x00};
writeCharacteristicZwiftPlay(init3, sizeof(init3), "init3", false, true);
writeCharacteristicZwiftPlay(init1, sizeof(init1), "init1", false, true);
uint8_t init4[] = {0x00, 0x08, 0x88, 0x04};
writeCharacteristicZwiftPlay(init4, sizeof(init4), "init4", false, true);
uint8_t init5[] = {0x04, 0x2a, 0x0a, 0x10, 0xc0, 0xbb, 0x01, 0x20, 0xbf, 0x06, 0x28, 0xb4, 0x42};
writeCharacteristicZwiftPlay(init5, sizeof(init5), "init5", false, true);
uint8_t init6[] = {0x04, 0x22, 0x0b, 0x08, 0x00, 0x10, 0xda, 0x02, 0x18, 0xec, 0x27, 0x20, 0x90, 0x03};
writeCharacteristicZwiftPlay(init6, sizeof(init6), "init6", false, true);
writeCharacteristicZwiftPlay(init2, sizeof(init2), "init2", false, true);
writeCharacteristicZwiftPlay(init4, sizeof(init4), "init4", false, true);
uint8_t init7[] = {0x04, 0x22, 0x03, 0x10, 0xa9, 0x01};
writeCharacteristicZwiftPlay(init7, sizeof(init7), "init7", false, true);
writeCharacteristicZwiftPlay(init2, sizeof(init2), "init2", false, true);
writeCharacteristicZwiftPlay(init4, sizeof(init4), "init4", false, true);
uint8_t init8[] = {0x04, 0x22, 0x02, 0x10, 0x00};
writeCharacteristicZwiftPlay(init8, sizeof(init8), "init8", false, true);
}
}
void ftmsbike::forcePower(int16_t requestPower) {
if((resistance_lvl_mode || TITAN_7000) && !MAGNUS && !SS2K) {
forceResistance(resistanceFromPowerRequest(requestPower));
} else {
uint8_t write[] = {FTMS_SET_TARGET_POWER, 0x00, 0x00};
write[1] = ((uint16_t)requestPower) & 0xFF;
write[2] = ((uint16_t)requestPower) >> 8;
writeCharacteristic(write, sizeof(write), QStringLiteral("forcePower ") + QString::number(requestPower));
powerForced = true;
}
}
uint16_t ftmsbike::wattsFromResistance(double resistance) {
if(DU30_bike) {
double y = 1.46193548 * Cadence.value() + 0.0000887836638 * Cadence.value() * resistance + 0.000625 * resistance * resistance + 0.0580645161 * Cadence.value() + 0.00292986091 * resistance + 6.48448135542904;
return y;
}
return _ergTable.estimateWattage(Cadence.value(), resistance);
}
resistance_t ftmsbike::resistanceFromPowerRequest(uint16_t power) {
return _ergTable.resistanceFromPowerRequest(power, Cadence.value(), max_resistance);
}
void ftmsbike::forceResistance(resistance_t requestResistance) {
if (DOMYOS) {
lastDomyosResistanceCommand = QDateTime::currentDateTime();
lastDomyosRequestedResistance = requestResistance;
}
QSettings settings;
bool ergModeNotSupported = (requestPower > 0 && !ergModeSupported);
if (!settings.value(QZSettings::ss2k_peloton, QZSettings::default_ss2k_peloton).toBool() &&
resistance_lvl_mode == false && _3G_Cardio_RB == false && JFBK5_0 == false) {
uint8_t write[] = {FTMS_SET_INDOOR_BIKE_SIMULATION_PARAMS, 0x00, 0x00, 0x00, 0x00, 0x28, 0x19};
double fr = (((double)requestResistance) * bikeResistanceGain) + ((double)bikeResistanceOffset);
if(ergModeNotSupported) {
if(requestResistance < 0) {
qDebug() << "Negative resistance detected:" << requestResistance << "using fallback value 1";
requestResistance = 1;
}
requestResistance = _inclinationResistanceTable.estimateInclination(requestResistance) * 10.0;
qDebug() << "ergMode Not Supported so the resistance will be" << requestResistance;
} else {
requestResistance = fr;
}
if(TITAN_7000)
Resistance = requestResistance;
write[3] = ((uint16_t)requestResistance * 10) & 0xFF;
write[4] = ((uint16_t)requestResistance * 10) >> 8;
writeCharacteristic(write, sizeof(write),
QStringLiteral("forceResistance ") + QString::number(requestResistance));
} else {
if(requestResistance < 0) {
qDebug() << "Negative resistance detected:" << requestResistance << "using fallback value 1";
requestResistance = 1;
}
if(SL010 || SPORT01)
Resistance = requestResistance;
if(JFBK5_0 || DIRETO_XR || YPBM || FIT_BK || ZIPRO_RAVE || SPEEDRACEX || MRK_S28 || USDC_D700) {
uint8_t write[] = {FTMS_SET_TARGET_RESISTANCE_LEVEL, 0x00, 0x00};
write[1] = ((uint16_t)requestResistance * 10) & 0xFF;
write[2] = ((uint16_t)requestResistance * 10) >> 8;
writeCharacteristic(write, sizeof(write),
QStringLiteral("forceResistance ") + QString::number(requestResistance));
} else {
uint8_t write[] = {FTMS_SET_TARGET_RESISTANCE_LEVEL, 0x00};
if(_3G_Cardio_RB || SL010)
requestResistance = requestResistance * 10;
write[1] = ((uint8_t)(requestResistance));
writeCharacteristic(write, sizeof(write),
QStringLiteral("forceResistance ") + QString::number(requestResistance));
}
}
}
void ftmsbike::forceInclination(double requestInclination) {
// FTMS SET_INDOOR_BIKE_SIMULATION_PARAMS command
// Byte 0: OpCode
// Byte 1-2: Wind Speed (sint16, 0.001 m/s)
// Byte 3-4: Grade/Inclination (sint16, 0.01%)
// Byte 5-6: Coefficient of Rolling Resistance (uint8, 0.0001)
uint8_t write[] = {FTMS_SET_INDOOR_BIKE_SIMULATION_PARAMS, 0x00, 0x00, 0x00, 0x00, 0x28, 0x19};
// Convert inclination to FTMS format (multiply by 100 for 0.01% units)
int16_t inclination = (int16_t)(requestInclination * 100.0);
// Pack Grade in bytes 3-4 as little-endian sint16
write[3] = ((uint16_t)inclination) & 0xFF;
write[4] = ((uint16_t)inclination) >> 8;
writeCharacteristic(write, sizeof(write),
QStringLiteral("forceInclination ") + QString::number(requestInclination));
}
void ftmsbike::sendZwiftPlayInclination(double inclination) {
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
QByteArray message = lockscreen::zwift_hub_inclinationCommand(inclination);
#else
QByteArray message;
#endif
#elif defined(Q_OS_ANDROID)
QAndroidJniObject result = QAndroidJniObject::callStaticObjectMethod(
"org/cagnulen/qdomyoszwift/ZwiftHubBike",
"inclinationCommand",
"(D)[B",
inclination);
if(!result.isValid()) {
qDebug() << "inclinationCommand returned invalid value";
return;
}
jbyteArray array = result.object<jbyteArray>();
QAndroidJniEnvironment env;
jbyte* bytes = env->GetByteArrayElements(array, nullptr);
jsize length = env->GetArrayLength(array);
QByteArray message((char*)bytes, length);
env->ReleaseByteArrayElements(array, bytes, JNI_ABORT);
#else
QByteArray message;
qDebug() << "implement zwift hub protobuf!";
return;
#endif
writeCharacteristicZwiftPlay((uint8_t*)message.data(), message.length(), "gearInclination", false, false);
gearInclinationSent = true;
}
void ftmsbike::update() {
QSettings settings;
if (m_control->state() == QLowEnergyController::UnconnectedState) {
emit disconnected();
return;
}
if (initRequest) {
zwiftPlayInit();
// when we are emulating the zwift protocol, zwift doesn't senf the start simulation frames, so we have to send them
if(settings.value(QZSettings::zwift_play_emulator, QZSettings::default_zwift_play_emulator).toBool())
init();
initRequest = false;
} else if (bluetoothDevice.isValid() &&
m_control->state() == QLowEnergyController::DiscoveredState //&&
// gattCommunicationChannelService &&
// gattWriteCharacteristic.isValid() &&
// gattNotify1Characteristic.isValid() &&
/*initDone*/) {
update_metrics(false, watts());
// updating the treadmill console every second
if (sec1Update++ == (500 / refresh->interval())) {
sec1Update = 0;
// updateDisplay(elapsed);
}
if (powerForced && !autoResistance()) {
qDebug() << QStringLiteral("disabling resistance ") << QString::number(currentResistance().value());
powerForced = false;
requestPower = -1;
init();
forceResistance(currentResistance().value());
}
auto virtualBike = this->VirtualBike();
bool gears_zwift_ratio = settings.value(QZSettings::gears_zwift_ratio, QZSettings::default_gears_zwift_ratio).toBool();
if (requestResistance != -1 || lastGearValue != gears()) {
bool deferResistanceRequest = false;
if (requestResistance > 100) {
requestResistance = 100;
} // TODO, use the bluetooth value
else if (requestResistance == 0) {
requestResistance = 1;
}
double gearMultiplier = 5;
if(REEBOK)
gearMultiplier = 1;
resistance_t rR = requestResistance + (gears() * gearMultiplier);
if (rR != currentResistance().value() || lastGearValue != gears()) {
bool ergModeNotSupported = (requestPower > 0 && !ergModeSupported);
qDebug() << QStringLiteral("writing resistance ") << requestResistance << ergModeNotSupported << requestPower << resistance_lvl_mode;
// if the FTMS is connected, the ftmsCharacteristicChanged event will do all the stuff because it's a
// FTMS bike. This condition handles the peloton requests
if (((virtualBike && !virtualBike->ftmsDeviceConnected()) || !virtualBike || resistance_lvl_mode || ergModeNotSupported) &&
(requestPower == 0 || requestPower == -1 || resistance_lvl_mode || ergModeNotSupported)) {
if (DOMYOS) {
QDateTime now = QDateTime::currentDateTime();
const qint64 sinceLastDomyosResistance = lastDomyosResistanceCommand.msecsTo(now);
if (now < domyosResistanceRetryAfter) {
qDebug() << "Deferring DOMYOS resistance write due to control-point backoff"
<< "requested:" << rR
<< "retryAfterMs:" << now.msecsTo(domyosResistanceRetryAfter);
deferResistanceRequest = true;
} else if (sinceLastDomyosResistance >= 0 && sinceLastDomyosResistance < 1500) {
qDebug() << "Deferring DOMYOS resistance write due to rate limit"
<< "requested:" << rR
<< "elapsedMs:" << sinceLastDomyosResistance;
deferResistanceRequest = true;
}
}
if (deferResistanceRequest) {
requestResistance = rR;
} else {
init();
forceResistance(rR);
}
}
}
if (!deferResistanceRequest) {
requestResistance = -1;
}
}
// gpx scenario for example
if(!virtualBike || !virtualBike->ftmsDeviceConnected()) {
if ((requestInclination != -100 || (lastGearValue != gears() && requestInclination != -100))) {
emit debug(QStringLiteral("writing inclination ") + QString::number(requestInclination));
forceInclination(requestInclination + gears()); // since this bike doesn't have the concept of resistance,
// i'm using the gears in the inclination
requestInclination = -100;
} else if(lastGearValue != gears() && lastRawRequestedInclinationValue != -100) {
// in order to send the new gear value ASAP
forceInclination(lastRawRequestedInclinationValue + gears()); // since this bike doesn't have the concept of resistance,
// i'm using the gears in the inclination
}
}
if((virtualBike && virtualBike->ftmsDeviceConnected()) && lastGearValue != gears() && lastRawRequestedInclinationValue != -100 && lastPacketFromFTMS.length() >= 7) {
qDebug() << "injecting fake ftms frame in order to send the new gear value ASAP" << lastPacketFromFTMS.toHex(' ');
ftmsCharacteristicChanged(QLowEnergyCharacteristic(), lastPacketFromFTMS);
}
if(zwiftPlayService && gears_zwift_ratio && lastGearValue != gears()) {
// Workaround: gear commands don't work until an inclination command has been sent first
if (!gearInclinationSent) {
qDebug() << "Sending initial inclination command (0.4%) before first gear command";
sendZwiftPlayInclination(0.4);
}
QSettings settings;
wheelCircumference::GearTable table;
wheelCircumference::GearTable::GearInfo g = table.getGear((int)gears());
double original_ratio = ((double)settings.value(QZSettings::gear_crankset_size, QZSettings::default_gear_crankset_size).toDouble()) /
((double)settings.value(QZSettings::gear_cog_size, QZSettings::default_gear_cog_size).toDouble());
double current_ratio = ((double)g.crankset / (double)g.rearCog);
uint32_t gear_value = static_cast<uint32_t>(10000.0 * (current_ratio/original_ratio) * (42.0/14.0));
qDebug() << "zwift hub gear current ratio" << current_ratio << g.crankset << g.rearCog << "gear_value" << gear_value << "original_ratio" << original_ratio;
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
QByteArray proto = lockscreen::zwift_hub_setGearsCommand(gear_value);
#else
QByteArray proto;
#endif
#elif defined Q_OS_ANDROID
QAndroidJniObject result = QAndroidJniObject::callStaticObjectMethod(
"org/cagnulen/qdomyoszwift/ZwiftHubBike",
"setGearCommand",
"(I)[B",
gear_value);
if (!result.isValid()) {
qDebug() << "setGearCommand returned invalid value";
return;
}
jbyteArray array = result.object<jbyteArray>();
QAndroidJniEnvironment env;
jbyte* bytes = env->GetByteArrayElements(array, nullptr);
jsize length = env->GetArrayLength(array);
QByteArray proto((char*)bytes, length);
env->ReleaseByteArrayElements(array, bytes, JNI_ABORT);
#else
QByteArray proto;
qDebug() << "ERROR: gear message not handled!";
return;
#endif
writeCharacteristicZwiftPlay((uint8_t*)proto.data(), proto.length(), "gear", false, true);
uint8_t gearApply[] = {0x00, 0x08, 0x88, 0x04};
writeCharacteristicZwiftPlay(gearApply, sizeof(gearApply), "gearApply", false, true);
}
lastGearValue = gears();
// Power request routing logic:
// 1. No virtualBike: route directly to bike
// 2. VirtualBike not connected to FTMS: route directly to bike
// 3. ZwiftPlay with gear ratio: route directly to bike
// 4. ErgMode supported + power sensor: use delta power system (bypass FTMS routing)
bool power_sensor = !settings.value(QZSettings::power_sensor_name, QZSettings::default_power_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"));
if (requestPower != -1 && (!virtualBike || !virtualBike->ftmsDeviceConnected() || (zwiftPlayService != nullptr && gears_zwift_ratio) || (ergModeSupported && power_sensor))) {
qDebug() << QStringLiteral("writing power") << requestPower;
init();
forcePower(requestPower);
requestPower = -1;
}
// Continuous ERG for resistance-level bikes:
// Re-evaluate resistance when cadence changes to maintain target power.
// Without this, resistance is only set once when Zwift sends a new power target,
// and cadence changes don't trigger resistance adjustment.
if (resistance_lvl_mode && !ergModeSupported &&
lastRequestedPower().value() > 0 && autoResistance()) {
resistance_t newR = resistanceFromPowerRequest(
(uint16_t)lastRequestedPower().value());
if (newR != m_lastErgResistance && newR > 0) {
// ERG death spiral protection: below 50 RPM, only allow resistance decreases
if (Cadence.value() > 0 && Cadence.value() < 50 && newR > m_lastErgResistance) {
qDebug() << "ERG death spiral protection: cadence" << Cadence.value()
<< "< 50, blocking resistance increase"
<< m_lastErgResistance << "->" << newR;
} else {
qDebug() << "continuous ERG: cadence" << Cadence.value()
<< "target" << lastRequestedPower().value()
<< "resistance" << m_lastErgResistance << "->" << newR;
forceResistance(newR);
m_lastErgResistance = newR;
}
}
}
if (requestStart != -1) {
emit debug(QStringLiteral("starting..."));
// btinit();
requestStart = -1;
emit bikeStarted();
}
if (requestStop != -1) {
emit debug(QStringLiteral("stopping..."));
// writeCharacteristic(initDataF0C800B8, sizeof(initDataF0C800B8), "stop tape");
requestStop = -1;
QSettings settings;
if (settings.value(QZSettings::ss2k_peloton, QZSettings::default_ss2k_peloton).toBool()) {
uint8_t write[] = {FTMS_SET_INDOOR_BIKE_SIMULATION_PARAMS, 0x00, 0x00, 0x00, 0x00, 0x28, 0x19};
writeCharacteristic(write, sizeof(write), QStringLiteral("init SS2K"));
}
}
}
}
void ftmsbike::serviceDiscovered(const QBluetoothUuid &gatt) {
emit debug(QStringLiteral("serviceDiscovered ") + gatt.toString());
}
bool ftmsbike::shouldUseCalculatedResistanceFallback(const QDateTime &now) {
if (native_resistance_received) {
return false;
}
if (!calculatedResistanceFallbackSince.isValid()) {
calculatedResistanceFallbackSince = now;
return false;
}
// Some FTMS bikes send native resistance on a later packet than cadence/power.
// Wait briefly before promoting the calculated Peloton value into Resistance.
return calculatedResistanceFallbackSince.msecsTo(now) >= 3000;
}
void ftmsbike::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
if (isWriting && currentWriteWaitingForResponse && sender() == currentWriteService) {
completeCurrentWrite();
}
QDateTime now = QDateTime::currentDateTime();
// qDebug() << "characteristicChanged" << characteristic.uuid() << newValue << newValue.length();
Q_UNUSED(characteristic);
QSettings settings;
QString heartRateBeltName =
settings.value(QZSettings::heart_rate_belt_name, QZSettings::default_heart_rate_belt_name).toString();
bool disable_hr_frommachinery =
settings.value(QZSettings::heart_ignore_builtin, QZSettings::default_heart_ignore_builtin).toBool();
bool heart = false;
bool watt_ignore_builtin =
settings.value(QZSettings::watt_ignore_builtin, QZSettings::default_watt_ignore_builtin).toBool();
bool externalCadenceSensorEnabled =
!settings.value(QZSettings::cadence_sensor_name, QZSettings::default_cadence_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"));
bool externalPowerSensorEnabled =
!settings.value(QZSettings::power_sensor_name, QZSettings::default_power_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"));
bool useMachineCadence = !externalCadenceSensorEnabled && !externalPowerSensorEnabled;
qDebug() << characteristic.uuid() << newValue.length() << QStringLiteral(" << ") << newValue.toHex(' ');
lastPacket = newValue;
if (DU30_bike && characteristic.uuid() == QBluetoothUuid(QStringLiteral("0000fff1-0000-1000-8000-00805f9b34fb")) && newValue.length() >= 14) {
resistance_received = true;
native_resistance_received = true;
calculatedResistanceFallbackSince = QDateTime();
Resistance = (double)(newValue.at(5));
emit resistanceRead(Resistance.value());
emit debug(QStringLiteral("Current Resistance: ") + QString::number(Resistance.value()));
return;
}
if (characteristic.uuid() == QBluetoothUuid((quint16)0x2A19) && !D2RIDE) { // Battery Service
if(newValue.length() > 0) {
uint8_t b = (uint8_t)newValue.at(0);
if(b != battery_level)
if(homeform::singleton())
homeform::singleton()->setToastRequested(bluetoothDevice.name() + QStringLiteral(" Battery Level ") + QString::number(b) + " %");
battery_level = b;
}
return;
}
if (characteristic.uuid() == QBluetoothUuid((quint16)0x2AD9) && newValue.length() >= 3) {
const uint8_t responseCode = (uint8_t)newValue.at(0);
const uint8_t requestCode = (uint8_t)newValue.at(1);
const uint8_t resultCode = (uint8_t)newValue.at(2);
if (DOMYOS && responseCode == FTMS_RESPONSE_CODE && requestCode == FTMS_SET_TARGET_RESISTANCE_LEVEL) {
if (resultCode == FTMS_CONTROL_NOT_PERMITTED) {
domyosResistanceRetryAfter = now.addMSecs(3000);
initDone = false;
qDebug() << "DOMYOS resistance command rejected with CONTROL_NOT_PERMITTED"
<< "lastRequestedResistance:" << lastDomyosRequestedResistance
<< "backoffUntil:" << domyosResistanceRetryAfter;
} else if (resultCode == FTMS_SUCCESS) {
domyosResistanceRetryAfter = now;
}
}
}
if(characteristic.uuid() == QBluetoothUuid(QStringLiteral("00000002-19ca-4651-86e5-fa29dcdd09d1")) && newValue.at(0) == 0x03) {
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
m_watt = lockscreen::zwift_hub_getPowerFromBuffer(newValue.mid(1));
qDebug() << "Current power: " << m_watt.value();
if (useMachineCadence) {
Cadence = lockscreen::zwift_hub_getCadenceFromBuffer(newValue.mid(1));
}
qDebug() << "Current cadence: " << Cadence.value();
#endif
#endif
return;
}
if(T2 && characteristic.uuid() == QBluetoothUuid(QStringLiteral("6e400003-b5a3-f393-e0a9-e50e24dcca9e")) && newValue.length() == 62) {
int16_t gears = ((int16_t)(((int16_t)((uint8_t)newValue.at(55)) << 8) |
(int16_t)((uint8_t)newValue.at(54))));
qDebug() << QStringLiteral("T2 gears event, actual gear") << gears << QStringLiteral("previous value") << T2_lastGear;
if (gears < T2_lastGear) {
for (int i = 0; i < T2_lastGear - gears; ++i) {
gearDown();
}
} else if (gears > T2_lastGear) {
for (int i = 0; i < gears - T2_lastGear; ++i) {
gearUp();
}
}
T2_lastGear = gears;
return;
}
// Wattbike Atom First Generation - Display Gears
if(WATTBIKE && characteristic.uuid() == QBluetoothUuid(QStringLiteral("b4cc1224-bc02-4cae-adb9-1217ad2860d1")) &&
newValue.length() > 3 && newValue.at(1) == 0x03 && (uint8_t)newValue.at(2) == 0xb6) {
uint8_t gear = newValue.at(3);
qDebug() << "watt bike gears" << gear;
setGears(gear);
}
if (characteristic.uuid() == QBluetoothUuid((quint16)0x2AD2)) {
union flags {
struct {
uint16_t moreData : 1;
uint16_t avgSpeed : 1;
uint16_t instantCadence : 1;
uint16_t avgCadence : 1;
uint16_t totDistance : 1;
uint16_t resistanceLvl : 1;
uint16_t instantPower : 1;
uint16_t avgPower : 1;
uint16_t expEnergy : 1;
uint16_t heartRate : 1;
uint16_t metabolic : 1;
uint16_t elapsedTime : 1;
uint16_t remainingTime : 1;
uint16_t spare : 3;
};
uint16_t word_flags;
};
// clean time in case for a long period we don't receive values
if(lastRefreshCharacteristicChanged2AD2.secsTo(now) > secondsToResetTimer) {
qDebug() << "clearing lastRefreshCharacteristicChanged2AD2" << lastRefreshCharacteristicChanged2AD2 << now;
lastRefreshCharacteristicChanged2AD2 = now;
}
flags Flags;
int index = 0;
// potential bug, a casting to uint8 is required for the single byte values to avoid negative values
if (newValue.length() < 2) {
qDebug() << "Invalid FTMS 0x2AD2 packet length" << newValue.length();
return;
}
Flags.word_flags = (((uint16_t)((uint8_t)newValue.at(1))) << 8) |
((uint16_t)((uint8_t)newValue.at(0)));
index += 2;
if (!Flags.moreData) {
if (!settings.value(QZSettings::speed_power_based, QZSettings::default_speed_power_based).toBool()) {
Speed = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index)))) /
100.0;
} else {
Speed = metric::calculateSpeedFromPower(
watts(), Inclination.value(), Speed.value(),
fabs(now.msecsTo(Speed.lastChanged()) / 1000.0), this->speedLimit());
}
index += 2;
emit debug(QStringLiteral("Current Speed: ") + QString::number(Speed.value()));
}
if (Flags.avgSpeed) {
double avgSpeed;
avgSpeed = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index)))) /
100.0;
index += 2;
emit debug(QStringLiteral("Current Average Speed: ") + QString::number(avgSpeed));
// Use average speed if instant speed is not available (moreData flag set)
if (Flags.moreData) {
if (!settings.value(QZSettings::speed_power_based, QZSettings::default_speed_power_based).toBool()) {
Speed = avgSpeed;
emit debug(QStringLiteral("Current Speed (from average): ") + QString::number(Speed.value()));
}
}
}
if (Flags.instantCadence) {
if (useMachineCadence) {
Cadence = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index)))) /
2.0;
}
index += 2;
emit debug(QStringLiteral("Current Cadence: ") + QString::number(Cadence.value()));
}
if (Flags.avgCadence) {
double avgCadence;
avgCadence = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index)))) /
2.0;
index += 2;
emit debug(QStringLiteral("Current Average Cadence: ") + QString::number(avgCadence));
// Use average cadence if instant cadence is not available
if (!Flags.instantCadence) {
if (useMachineCadence) {
Cadence = avgCadence;
emit debug(QStringLiteral("Current Cadence (from average): ") + QString::number(Cadence.value()));
}
}
}
if (Flags.totDistance) {
/*
* the distance sent from the most trainers is a total distance, so it's useless for QZ
*
Distance = ((double)((((uint32_t)((uint8_t)newValue.at(index + 2)) << 16) |
(uint32_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint32_t)((uint8_t)newValue.at(index)))) /
1000.0;*/
index += 3;
}
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCharacteristicChanged2AD2.msecsTo(now)));
emit debug(QStringLiteral("Current Distance: ") + QString::number(Distance.value()));
if (Flags.resistanceLvl) {
double d = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index))));
index += 2;
if(d > 0) {
if(BIKE_)
d = d / 10.0;
// for this bike, i will use the resistance that I set directly because the bike sends a different ratio.
if(!SL010 && !TITAN_7000 && !SPORT01) {
Resistance = d;
native_resistance_received = true;
calculatedResistanceFallbackSince = QDateTime();
}
emit debug(QStringLiteral("Current Resistance: ") + QString::number(Resistance.value()));
emit resistanceRead(Resistance.value());
resistance_received = true;
}
}
double ac = 0.01243107769;
double bc = 1.145964912;
double cc = -23.50977444;
double ar = 0.1469553975;
double br = -5.841344538;
double cr = 97.62165482;
if (Cadence.value() && m_watt.value()) {
double res =
(((sqrt(pow(br, 2.0) - 4.0 * ar *
(cr - (m_watt.value() * 132.0 /
(ac * pow(Cadence.value(), 2.0) + bc * Cadence.value() + cc)))) -
br) /
(2.0 * ar)) *
settings.value(QZSettings::peloton_gain, QZSettings::default_peloton_gain).toDouble()) +
settings.value(QZSettings::peloton_offset, QZSettings::default_peloton_offset).toDouble();
if (isnan(res)) {
if (Cadence.value() > 0) {
// let's keep the last good value
} else {
m_pelotonResistance = 0;
}
} else {
m_pelotonResistance = res;
}
if (!resistance_received && !DU30_bike && !SL010 &&
shouldUseCalculatedResistanceFallback(now)) {
Resistance = m_pelotonResistance;
emit resistanceRead(Resistance.value());
emit debug(QStringLiteral("Current Resistance (calculated fallback): ") +
QString::number(Resistance.value()));
}
}
if (Flags.instantPower) {
// power table from an user
if(DU30_bike) {
m_watt = wattsFromResistance(Resistance.value());
emit debug(QStringLiteral("Current Watt: ") + QString::number(m_watt.value()));
} else if (SPORT01 && settings.value(QZSettings::toputure_teb1, QZSettings::default_toputure_teb1).toBool()) {
// Custom power calculation for SPORT01
// Resistance multipliers for levels 1-10
const double k[10] = {0.60, 0.75, 0.85, 0.95, 1.00, 1.18, 1.40, 1.70, 2.00, 2.40};
// Baseline power curve coefficients (MyWhoosh cadence-power at resistance 5)
double ac = 0.01243107769;
double bc = 1.145964912;
double cc = -23.50977444;
// Calculate baseline power from cadence (resistance level 5 baseline)
double baseline_watt = ac * pow(Cadence.value(), 2.0) + bc * Cadence.value() + cc;
// Get current resistance level (1-10) and apply multiplier
int resistance_level = (int)Resistance.value();
if(resistance_level < 1) resistance_level = 1;
if(resistance_level > 10) resistance_level = 10;
// Apply resistance multiplier
m_watt = baseline_watt * k[resistance_level - 1];
if(m_watt.value() < 0) m_watt = 0;
emit debug(QStringLiteral("Current Watt (SPORT01 formula - R%1 x%2): %3")
.arg(resistance_level).arg(k[resistance_level - 1]).arg(m_watt.value()));
} else if (MRK_S26C) {
m_watt = Cadence.value() * (Resistance.value() * 1.16);
emit debug(QStringLiteral("Current Watt (MRK-S26C formula): ") + QString::number(m_watt.value()));
} else if ((LYDSTO || DMASUN) && watt_ignore_builtin) {
m_watt = wattFromHR(true);
emit debug(QStringLiteral("Current Watt: ") + QString::number(m_watt.value()));
} else {
double ftms_watt = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index))));
m_rawWatt = ftms_watt; // Always update rawWatt from FTMS bike data
if (settings.value(QZSettings::power_sensor_name, QZSettings::default_power_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"))) {
m_watt = ftms_watt; // Only update watt if no external power sensor
}
if(!wattReceived && m_watt.value() > 0) {
wattReceived = true;
}
}
index += 2;
emit debug(QStringLiteral("Current Watt: ") + QString::number(m_watt.value()));
} else if(DOMYOS) {
// doesn't send power at all and the resistance either
m_watt = wattFromHR(true);
emit debug(QStringLiteral("Current Watt: ") + QString::number(m_watt.value()));
}
if (Flags.avgPower && newValue.length() > index + 1) {
double avgPower;
avgPower = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index))));
index += 2;
emit debug(QStringLiteral("Current Average Watt: ") + QString::number(avgPower));
// Use average power if instant power is zero or not available
if ((!Flags.instantPower || m_watt.value() == 0) && avgPower > 0 && !wattReceived) {
if (settings.value(QZSettings::power_sensor_name, QZSettings::default_power_sensor_name)
.toString()
.startsWith(QStringLiteral("Disabled"))) {
m_watt = avgPower;
emit debug(QStringLiteral("Current Watt (from average): ") + QString::number(m_watt.value()));
}
}
}
if (Flags.expEnergy && newValue.length() > index + 1) {
/*KCal = ((double)(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) |
(uint16_t)((uint8_t)newValue.at(index))));*/
index += 2;
// energy per hour
index += 2;
// energy per minute
index += 1;
}
if (watts())
KCal += ((((0.048 * ((double)watts()) + 1.19) *
settings.value(QZSettings::weight, QZSettings::default_weight).toFloat() * 3.5) /
200.0) /
(60000.0 /
((double)lastRefreshCharacteristicChanged2AD2.msecsTo(
now)))); //(( (0.048* Output in watts +1.19) * body weight in
// kg * 3.5) / 200 ) / 60
emit debug(QStringLiteral("Current KCal: ") + QString::number(KCal.value()));
#ifdef Q_OS_ANDROID