-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathstrydrunpowersensor.cpp
More file actions
834 lines (731 loc) · 38 KB
/
Copy pathstrydrunpowersensor.cpp
File metadata and controls
834 lines (731 loc) · 38 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
#include "strydrunpowersensor.h"
#include "virtualdevices/virtualtreadmill.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 "keepawakehelper.h"
#include <QLowEnergyConnectionParameters>
#endif
#include <chrono>
#include "homeform.h"
using namespace std::chrono_literals;
#ifdef Q_OS_IOS
extern quint8 QZ_EnableDiscoveryCharsAndDescripttors;
#endif
strydrunpowersensor::strydrunpowersensor(bool noWriteResistance, bool noHeartService, bool noVirtualDevice) {
#ifdef Q_OS_IOS
QZ_EnableDiscoveryCharsAndDescripttors = true;
#endif
m_watt.setType(metric::METRIC_WATT, deviceType());
Speed.setType(metric::METRIC_SPEED);
refresh = new QTimer(this);
this->noWriteResistance = noWriteResistance;
this->noHeartService = noHeartService;
this->noVirtualDevice = noVirtualDevice;
initDone = false;
connect(refresh, &QTimer::timeout, this, &strydrunpowersensor::update);
refresh->start(200ms);
}
/*
void strydrunpowersensor::writeCharacteristic(uint8_t* data, uint8_t data_len, QString info, bool disable_log, bool
wait_for_response)
{
QEventLoop loop;
QTimer timeout;
if(wait_for_response)
{
connect(gattCommunicationChannelService, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
&loop, SLOT(quit()));
timeout.singleShot(300, &loop, SLOT(quit()));
}
else
{
connect(gattCommunicationChannelService, SIGNAL(characteristicWritten(QLowEnergyCharacteristic,QByteArray)),
&loop, SLOT(quit()));
timeout.singleShot(300, &loop, SLOT(quit()));
}
gattCommunicationChannelService->writeCharacteristic(gattWriteCharacteristic, QByteArray((const char*)data,
data_len));
if(!disable_log)
debug(" >> " + QByteArray((const char*)data, data_len).toHex(' ') + " // " + info);
loop.exec();
}*/
void strydrunpowersensor::update() {
if (m_control->state() == QLowEnergyController::UnconnectedState) {
emit disconnected();
return;
}
if (initRequest) {
initRequest = false;
} else if (bluetoothDevice.isValid() &&
m_control->state() == QLowEnergyController::DiscoveredState //&&
// gattCommunicationChannelService &&
// gattWriteCharacteristic.isValid() &&
// gattNotify1Characteristic.isValid() &&
/*initDone*/) {
QSettings settings;
bool cadence_as_treadmill = settings
.value(QZSettings::cadence_sensor_as_treadmill,
QZSettings::default_cadence_sensor_as_treadmill)
.toBool();
bool power_as_treadmill =
settings.value(QZSettings::power_sensor_as_treadmill, QZSettings::default_power_sensor_as_treadmill)
.toBool();
update_metrics(false, watts(), !(power_as_treadmill || cadence_as_treadmill));
if (lastGoodCadence.secsTo(QDateTime::currentDateTime()) > 5 && !charNotified) {
readMethod = true;
qDebug() << "no cadence for 5 secs, switching to reading method";
}
if (readMethod && cadenceService) {
cadenceService->readCharacteristic(cadenceChar);
}
if (requestInclination != -100) {
Inclination = treadmillInclinationOverrideReverse(requestInclination);
emit inclinationChanged(Inclination.value(), Inclination.value());
qDebug() << QStringLiteral("writing incline ") << requestInclination;
requestInclination = -100;
}
// updating the treadmill console every second
if (sec1Update++ == (500 / refresh->interval())) {
sec1Update = 0;
// updateDisplay(elapsed);
}
if (strydIndoorModeRequested && !strydIndoorModeConfirmed && strydIndoorModeRetries < 3 &&
strydIndoorModeRequestedAt.msecsTo(QDateTime::currentDateTime()) > 1000) {
qDebug() << QStringLiteral("Stryd5: no ack for Indoor mode switch, retrying");
requestStrydIndoorMode();
}
}
}
void strydrunpowersensor::requestStrydIndoorMode() {
if (!strydIndoorModeService || !strydIndoorModeChar.isValid())
return;
qDebug() << QStringLiteral("Stryd5: switching power mode to Indoor");
strydIndoorModeService->writeCharacteristic(strydIndoorModeChar, QByteArray::fromHex("1500"));
strydIndoorModeRequested = true;
strydIndoorModeRequestedAt = QDateTime::currentDateTime();
strydIndoorModeRetries++;
}
void strydrunpowersensor::serviceDiscovered(const QBluetoothUuid &gatt) {
emit debug(QStringLiteral("serviceDiscovered ") + gatt.toString());
}
void strydrunpowersensor::characteristicChanged(const QLowEnergyCharacteristic &characteristic,
const QByteArray &newValue) {
qDebug() << "<<" << characteristic.uuid() << newValue.toHex(' ') << newValue.length();
Q_UNUSED(characteristic);
QDateTime now = QDateTime::currentDateTime();
QSettings settings;
bool cadence_as_treadmill = settings
.value(QZSettings::cadence_sensor_as_treadmill,
QZSettings::default_cadence_sensor_as_treadmill)
.toBool();
bool power_as_treadmill =
settings.value(QZSettings::power_sensor_as_treadmill, QZSettings::default_power_sensor_as_treadmill)
.toBool();
QString heartRateBeltName =
settings.value(QZSettings::heart_rate_belt_name, QZSettings::default_heart_rate_belt_name).toString();
bool treadmill_from_sensor = power_as_treadmill || cadence_as_treadmill;
charNotified = true;
if (characteristic.uuid() == QBluetoothUuid((quint16)0x2A19)) {
uint8_t battery = newValue.at(0);
if (battery != battery_level) {
if (homeform::singleton()) {
homeform::singleton()->setToastRequested(bluetoothDevice.name() + QStringLiteral(" Battery Level ") +
QString::number(battery) + " %");
}
}
battery_level = battery;
qDebug() << QStringLiteral("battery: ") << battery;
return;
}
if (characteristic.uuid() == QBluetoothUuid::CyclingPowerMeasurement) {
lastPacket = newValue;
uint16_t flags = (((uint16_t)((uint8_t)newValue.at(1)) << 8) | (uint16_t)((uint8_t)newValue.at(0)));
bool cadence_present = false;
bool wheel_revs = false;
uint16_t time_division = 1024;
uint8_t index = 4;
if (newValue.length() > 3) {
powerReceived = true;
double weight = settings.value(QZSettings::weight, QZSettings::default_weight).toFloat();
double vwatts = ((9.8 * weight) * (currentInclination().value() / 100.0));
m_watt = (((uint16_t)((uint8_t)newValue.at(3)) << 8) | (uint16_t)((uint8_t)newValue.at(2))) + vwatts;
}
emit powerChanged(m_watt.value());
emit debug(QStringLiteral("Current watt: ") + QString::number(m_watt.value()));
if ((flags & 0x1) == 0x01) // Pedal Power Balance Present
{
index += 1;
}
if ((flags & 0x2) == 0x02) // Pedal Power Balance Reference
{
}
if ((flags & 0x4) == 0x04) // Accumulated Torque Present
{
index += 2;
}
if ((flags & 0x8) == 0x08) // Accumulated Torque Source
{
}
if ((flags & 0x10) == 0x10) // Wheel Revolution Data Present
{
cadence_present = true;
wheel_revs = true;
time_division = 2048;
} else if ((flags & 0x20) == 0x20) // Crank Revolution Data Present
{
cadence_present = true;
}
if (watts())
KCal += ((((0.048 * ((double)watts()) + 1.19) *
settings.value(QZSettings::weight, QZSettings::default_weight).toFloat() * 3.5) /
200.0) /
(60000.0 / ((double)lastRefreshPowerChanged.msecsTo(now))));
emit debug(QStringLiteral("Current KCal: ") + QString::number(KCal.value()));
lastRefreshPowerChanged = now;
} else if (characteristic.uuid() == QBluetoothUuid::HeartRateMeasurement) {
if (newValue.length() > 1) {
Heart = (uint8_t)newValue[1];
emit onHeartRate((uint8_t)Heart.value());
}
emit debug(QStringLiteral("Current heart: ") + QString::number(Heart.value()));
} else if (characteristic.uuid() == QBluetoothUuid((quint16)0x2ACD)) {
lastPacket = newValue;
// inclination for NPE RUNN
union flags {
struct {
uint16_t moreData : 1;
uint16_t avgSpeed : 1;
uint16_t totalDistance : 1;
uint16_t inclination : 1;
uint16_t elevation : 1;
uint16_t instantPace : 1;
uint16_t averagePace : 1;
uint16_t expEnergy : 1;
uint16_t heartRate : 1;
uint16_t metabolic : 1;
uint16_t elapsedTime : 1;
uint16_t remainingTime : 1;
uint16_t forceBelt : 1;
uint16_t spare : 3;
};
uint16_t word_flags;
};
flags Flags;
int index = 0;
Flags.word_flags = (newValue.at(1) << 8) | newValue.at(0);
index += 2;
if (!Flags.moreData) {
/*Speed = ((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 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));
}
if (Flags.totalDistance) {
// ignoring the distance, because it's a total life odometer
// 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;
}
// else
{
/*
if (firstDistanceCalculated)
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCharacteristicChanged.msecsTo(QDateTime::currentDateTime())));
distanceEval = true;*/
}
emit debug(QStringLiteral("Current Distance: ") + QString::number(Distance.value()));
if (Flags.inclination) {
double inc =
((double)(((int16_t)((int8_t)newValue.at(index + 1)) << 8) | (int16_t)((uint8_t)newValue.at(index)))) /
10.0;
// steps of 0.5 only to send to the Inclination override function
if(!areInclinationSettingsDefault()) {
inc = qRound(inc * 2.0) / 2.0;
Inclination = treadmillInclinationOverride(inc);
} else {
Inclination = inc;
}
index += 4; // the ramo value is useless
emit debug(QStringLiteral("Current Inclination: ") + QString::number(Inclination.value()));
bool stryd_inclination_instead_treadmill = settings.value(QZSettings::stryd_inclination_instead_treadmill, QZSettings::default_stryd_inclination_instead_treadmill).toBool();
if(stryd_inclination_instead_treadmill)
emit inclinationChanged(Inclination.value(), Inclination.value());
}
if (Flags.elevation) {
index += 4; // TODO
}
if (Flags.instantPace) {
index += 1; // TODO
}
if (Flags.averagePace) {
index += 1; // TODO
}
if (Flags.expEnergy) {
/*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;
} else {
/*
if (firstDistanceCalculated &&
watts(settings.value(QZSettings::weight, QZSettings::default_weight).toFloat()))
KCal +=
((((0.048 *
((double)watts(settings.value(QZSettings::weight, QZSettings::default_weight).toFloat())) +
1.19) *
settings.value(QZSettings::weight, QZSettings::default_weight).toFloat() * 3.5) /
200.0) /
(60000.0 /
((double)lastRefreshCharacteristicChanged.msecsTo(
QDateTime::currentDateTime())))); //(( (0.048* Output in watts +1.19) * body weight in
// kg * 3.5) / 200 ) / 60
distanceEval = true;
*/
}
emit debug(QStringLiteral("Current KCal: ") + QString::number(KCal.value()));
if (Flags.heartRate) {
if (index < newValue.length()) {
double heart = ((double)(((uint8_t)newValue.at(index))));
emit debug(QStringLiteral("Current Heart: ") + QString::number(heart));
} else {
emit debug(QStringLiteral("Error on parsing heart!"));
}
// index += 1; //NOTE: clang-analyzer-deadcode.DeadStores
}
if (Flags.metabolic) {
// todo
}
if (Flags.elapsedTime) {
// todo
}
if (Flags.remainingTime) {
// todo
}
if (Flags.forceBelt) {
// todo
}
} else if (characteristic.uuid() == QBluetoothUuid::RSCMeasurement) {
uint8_t flags = (uint8_t)newValue.at(0);
bool InstantaneousStrideLengthPresent = (flags & 0x01);
bool TotalDistancePresent = (flags & 0x02) ? true : false;
bool WalkingorRunningStatusbits = (flags & 0x04) ? true : false;
bool double_cadence = settings
.value(QZSettings::powr_sensor_running_cadence_double,
QZSettings::default_powr_sensor_running_cadence_double)
.toBool();
double cadence_multiplier = 1.0;
if (double_cadence)
cadence_multiplier = 2.0;
// Unit is in m/s with a resolution of 1/256
uint16_t speedMs = (((uint16_t)((uint8_t)newValue.at(2)) << 8) | (uint16_t)((uint8_t)newValue.at(1)));
double speed = (((double)speedMs) / 256.0) * 3.6; // km/h
bool stryd_speed_instead_treadmill = settings.value(QZSettings::stryd_speed_instead_treadmill, QZSettings::default_stryd_speed_instead_treadmill).toBool();
if(stryd_speed_instead_treadmill)
emit speedChanged(speed);
double cadence = (uint8_t)newValue.at(3) * cadence_multiplier;
if (newValue.length() >= 6 && InstantaneousStrideLengthPresent) {
instantaneousStrideLengthCMAvailableFromDevice = true;
InstantaneousStrideLengthCM =
(((uint16_t)((uint8_t)newValue.at(5)) << 8) | (uint16_t)((uint8_t)newValue.at(4))) / 2;
emit instantaneousStrideLengthChanged(InstantaneousStrideLengthCM.value());
qDebug() << QStringLiteral("Current InstantaneousStrideLengthCM:") << InstantaneousStrideLengthCM.value();
if (InstantaneousStrideLengthCM.value() == 0) {
GroundContactMS.setValue(0);
VerticalOscillationMM.setValue(0);
emit groundContactChanged(GroundContactMS.value());
emit verticalOscillationChanged(VerticalOscillationMM.value());
qDebug() << QStringLiteral("Current GroundContactMS:") << GroundContactMS.value();
qDebug() << QStringLiteral("Current VerticalOscillationMM:") << VerticalOscillationMM.value();
}
}
Cadence = cadence;
emit cadenceChanged(cadence);
if (treadmill_from_sensor) {
Speed = speed;
emit speedChanged(speed);
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCadenceChanged.msecsTo(now)));
emit debug(QStringLiteral("Current Distance: ") + QString::number(Distance.value()));
emit debug(QStringLiteral("Current Speed: ") + QString::number(speed));
if (powerReceived == false) {
m_watt = wattsCalc(settings.value(QZSettings::weight, QZSettings::default_weight).toFloat(),
Speed.value(), Inclination.value());
emit debug(QStringLiteral("Current watt: ") + QString::number(m_watt.value()));
}
}
emit debug(QStringLiteral("Current Cadence: ") + QString::number(cadence));
lastRefreshCadenceChanged = now;
} else if (characteristic.uuid() == QBluetoothUuid::CSCMeasurement) {
uint16_t _LastCrankEventTime = 0;
double _CrankRevs = 0;
uint16_t _LastWheelEventTime = 0;
double _WheelRevs = 0;
uint8_t battery = 0;
bool CrankPresent = (newValue.at(0) & 0x02) == 0x02;
bool WheelPresent = (newValue.at(0) & 0x01) == 0x01;
qDebug() << QStringLiteral("CrankPresent: ") << CrankPresent;
qDebug() << QStringLiteral("WheelPresent: ") << WheelPresent;
uint8_t index = 1;
if (WheelPresent) {
_WheelRevs =
(((uint32_t)((uint8_t)newValue.at(index + 3)) << 24) | ((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)));
emit debug(QStringLiteral("Current Wheel Revs: ") + QString::number(_WheelRevs));
index += 4;
_LastWheelEventTime =
(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) | (uint16_t)((uint8_t)newValue.at(index)));
emit debug(QStringLiteral("Current Wheel Event Time: ") + QString::number(_LastWheelEventTime));
index += 2;
}
if (CrankPresent) {
_CrankRevs = (((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) | (uint16_t)((uint8_t)newValue.at(index)));
emit debug(QStringLiteral("Current Crank Revs: ") + QString::number(_CrankRevs));
index += 2;
_LastCrankEventTime =
(((uint16_t)((uint8_t)newValue.at(index + 1)) << 8) | (uint16_t)((uint8_t)newValue.at(index)));
emit debug(QStringLiteral("Current Crank Event Time: ") + QString::number(_LastCrankEventTime));
}
if ((!CrankPresent || _CrankRevs == 0) && WheelPresent) {
CrankRevs = _WheelRevs;
LastCrankEventTime = _LastWheelEventTime;
} else {
CrankRevs = _CrankRevs;
LastCrankEventTime = _LastCrankEventTime;
}
int16_t deltaT = LastCrankEventTime - oldLastCrankEventTime;
if (deltaT < 0) {
deltaT = LastCrankEventTime + 65535 - oldLastCrankEventTime;
}
if (CrankRevs != oldCrankRevs && deltaT) {
double cadence = ((CrankRevs - oldCrankRevs) / deltaT) * 1024 * 60;
if ((cadence >= 0 && (cadence < 256 || _CrankRevs == 0) && CrankPresent) ||
(!CrankPresent && WheelPresent))
Cadence = cadence;
lastGoodCadence = now;
} else if (lastGoodCadence.msecsTo(now) > 2000) {
Cadence = 0;
}
emit cadenceChanged(Cadence.value());
emit debug(QStringLiteral("Current Cadence: ") + QString::number(Cadence.value()));
oldLastCrankEventTime = LastCrankEventTime;
oldCrankRevs = CrankRevs;
if (treadmill_from_sensor) {
Speed =
Cadence.value() *
settings.value(QZSettings::cadence_sensor_speed_ratio, QZSettings::default_cadence_sensor_speed_ratio)
.toDouble();
emit speedChanged(Speed.value());
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCadenceChanged.msecsTo(now)));
emit debug(QStringLiteral("Current Distance: ") + QString::number(Distance.value()));
emit debug(QStringLiteral("Current Speed: ") + QString::number(Speed.value()));
}
lastRefreshCadenceChanged = now;
} else if (characteristic.uuid() == QBluetoothUuid(QStringLiteral("0000ff00-0000-1000-8000-00805f9b34fb"))) {
if (newValue.length() == 5 && newValue.at(0) == 0x0f) {
GroundContactMS = (((uint16_t)((uint8_t)newValue.at(2)) << 8) | (uint16_t)((uint8_t)newValue.at(1)));
emit groundContactChanged(GroundContactMS.value());
VerticalOscillationMM = (((uint16_t)((uint8_t)newValue.at(4)) << 8) | (uint16_t)((uint8_t)newValue.at(3)));
emit verticalOscillationChanged(VerticalOscillationMM.value());
qDebug() << QStringLiteral("Current GroundContactMS:") << GroundContactMS.value();
qDebug() << QStringLiteral("Current VerticalOscillationMM:") << VerticalOscillationMM.value();
}
} else if (characteristic.uuid() == QBluetoothUuid(QStringLiteral("7e78aa19-72cd-d3b8-a81f-5b7e589bea0f"))) {
if (newValue.length() == 20 && newValue.at(0) == 0x32) {
GroundContactMS = (((uint16_t)((uint8_t)newValue.at(5)) << 8) | (uint16_t)((uint8_t)newValue.at(4)));
emit groundContactChanged(GroundContactMS.value());
//VerticalOscillationMM = (((uint16_t)((uint8_t)newValue.at(4)) << 8) | (uint16_t)((uint8_t)newValue.at(3)));
//emit verticalOscillationChanged(VerticalOscillationMM.value());
qDebug() << QStringLiteral("Current GroundContactMS:") << GroundContactMS.value();
qDebug() << QStringLiteral("Current VerticalOscillationMM:") << VerticalOscillationMM.value();
} else if (strydIndoorModeRequested && newValue.length() >= 3 && (uint8_t)newValue.at(0) == 0x15 &&
(uint8_t)newValue.at(1) == 0x00) {
// ack of the 15 00/15 01 mode switch written to 7e78aa20: byte 2 echoes back the confirmed
// mode (0x00 = Indoor, 0x01 = Outdoor)
uint8_t confirmedMode = (uint8_t)newValue.at(2);
if (confirmedMode == 0x00) {
strydIndoorModeConfirmed = true;
qDebug() << QStringLiteral("Stryd5: Indoor mode confirmed by the pod");
} else {
qDebug() << QStringLiteral("Stryd5: pod acked mode ") << confirmedMode
<< QStringLiteral(" instead of Indoor, will retry");
}
}
}
if (!noVirtualDevice) {
#ifdef Q_OS_ANDROID
if (settings.value(QZSettings::ant_heart, QZSettings::default_ant_heart).toBool()) {
Heart = (uint8_t)KeepAwakeHelper::heart();
debug("Current Heart: " + QString::number(Heart.value()));
}
#endif
if (heartRateBeltName.startsWith(QStringLiteral("Disabled")) && Heart.value() == 0) {
update_hr_from_external();
}
}
if (!noVirtualDevice) {
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
bool cadence =
settings.value(QZSettings::bike_cadence_sensor, QZSettings::default_bike_cadence_sensor).toBool();
bool ios_peloton_workaround =
settings.value(QZSettings::ios_peloton_workaround, QZSettings::default_ios_peloton_workaround).toBool();
if (ios_peloton_workaround && cadence && h && firstStateChanged) {
h->virtualbike_setCadence(currentCrankRevolutions(), lastCrankEventTime());
h->virtualbike_setHeartRate((uint8_t)metrics_override_heartrate());
}
#endif
#endif
}
_ergTable.collectTreadmillData(Speed.value(), watts(), Inclination.value());
if (m_control->error() != QLowEnergyController::NoError) {
qDebug() << QStringLiteral("QLowEnergyController ERROR!!") << m_control->errorString();
}
}
void strydrunpowersensor::stateChanged(QLowEnergyService::ServiceState state) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceState>();
emit debug(QStringLiteral("BTLE stateChanged ") + QString::fromLocal8Bit(metaEnum.valueToKey(state)));
for (QLowEnergyService *s : qAsConst(gattCommunicationChannelService)) {
qDebug() << QStringLiteral("stateChanged") << s->serviceUuid() << s->state();
if (s->state() != QLowEnergyService::ServiceDiscovered && s->state() != QLowEnergyService::InvalidService) {
qDebug() << QStringLiteral("not all services discovered");
return;
}
}
qDebug() << QStringLiteral("all services discovered!");
for (QLowEnergyService *s : qAsConst(gattCommunicationChannelService)) {
if (s->state() == QLowEnergyService::ServiceDiscovered) {
// establish hook into notifications
connect(s, &QLowEnergyService::characteristicChanged, this, &strydrunpowersensor::characteristicChanged);
connect(s, &QLowEnergyService::characteristicWritten, this, &strydrunpowersensor::characteristicWritten);
connect(s, &QLowEnergyService::characteristicRead, this, &strydrunpowersensor::characteristicRead);
connect(
s, static_cast<void (QLowEnergyService::*)(QLowEnergyService::ServiceError)>(&QLowEnergyService::error),
this, &strydrunpowersensor::errorService);
connect(s, &QLowEnergyService::descriptorWritten, this, &strydrunpowersensor::descriptorWritten);
connect(s, &QLowEnergyService::descriptorRead, this, &strydrunpowersensor::descriptorRead);
if(FORERUNNER && s->serviceUuid() != QBluetoothUuid::HeartRate && s->serviceUuid() != QBluetoothUuid::RunningSpeedAndCadence) {
qDebug() << "skipping garmin services!" << s->serviceUuid();
continue;
}
if (s->serviceUuid() == QBluetoothUuid::CyclingSpeedAndCadence) {
cadenceService = s;
}
qDebug() << s->serviceUuid() << QStringLiteral("connected!");
auto characteristics_list = s->characteristics();
for (const QLowEnergyCharacteristic &c : qAsConst(characteristics_list)) {
if (c.uuid() == QBluetoothUuid::CSCMeasurement) {
cadenceChar = c;
}
// Stryd 5 broadcasts a power value that already reacts to the incline it detects on its own
// (confirmed via BLE sniffing, see #4480), which conflicts with QZ's own inclination gain
// formula. Switching the pod to Indoor mode makes it stop compensating for incline on its
// own, leaving QZ's formula as the only source of the incline adjustment.
if (bluetoothDevice.name().startsWith(QStringLiteral("Stryd5"), Qt::CaseInsensitive) &&
c.uuid() == QBluetoothUuid(QStringLiteral("7e78aa20-72cd-d3b8-a81f-5b7e589bea0f")) &&
(c.properties() & QLowEnergyCharacteristic::Write)) {
strydIndoorModeService = s;
strydIndoorModeChar = c;
requestStrydIndoorMode();
}
qDebug() << QStringLiteral("char uuid") << c.uuid() << QStringLiteral("handle") << c.handle();
auto descriptors_list = c.descriptors();
for (const QLowEnergyDescriptor &d : qAsConst(descriptors_list)) {
qDebug() << QStringLiteral("descriptor uuid") << d.uuid() << QStringLiteral("handle") << d.handle();
}
if ((c.properties() & QLowEnergyCharacteristic::Notify) == QLowEnergyCharacteristic::Notify) {
QByteArray descriptor;
descriptor.append((char)0x01);
descriptor.append((char)0x00);
if (c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).isValid()) {
s->writeDescriptor(c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration), descriptor);
} else {
qDebug() << QStringLiteral("ClientCharacteristicConfiguration") << c.uuid()
<< c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).uuid()
<< c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).handle()
<< QStringLiteral(" is not valid");
}
qDebug() << s->serviceUuid() << c.uuid() << QStringLiteral("notification subscribed!");
} else if ((c.properties() & QLowEnergyCharacteristic::Indicate) ==
QLowEnergyCharacteristic::Indicate) {
QByteArray descriptor;
descriptor.append((char)0x02);
descriptor.append((char)0x00);
if (c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).isValid()) {
s->writeDescriptor(c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration), descriptor);
} else {
qDebug() << QStringLiteral("ClientCharacteristicConfiguration") << c.uuid()
<< c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).uuid()
<< c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration).handle()
<< QStringLiteral(" is not valid");
}
qDebug() << s->serviceUuid() << c.uuid() << QStringLiteral("indication subscribed!");
} else if ((c.properties() & QLowEnergyCharacteristic::Read) == QLowEnergyCharacteristic::Read) {
// s->readCharacteristic(c);
// qDebug() << s->serviceUuid() << c.uuid() << "reading!";
}
}
}
}
// ******************************************* virtual treadmill/bike init *************************************
if (!firstStateChanged && !this->hasVirtualDevice() && !noVirtualDevice
#ifdef Q_OS_IOS
#ifndef IO_UNDER_QT
&& !h
#endif
#endif
) {
QSettings settings;
bool virtual_device_enabled =
settings.value(QZSettings::virtual_device_enabled, QZSettings::default_virtual_device_enabled).toBool();
bool virtual_device_force_bike =
settings.value(QZSettings::virtual_device_force_bike, QZSettings::default_virtual_device_force_bike)
.toBool();
if (virtual_device_enabled) {
if (!virtual_device_force_bike) {
debug("creating virtual treadmill interface...");
auto virtualTreadmill = new virtualtreadmill(this, noHeartService);
connect(virtualTreadmill, &virtualtreadmill::debug, this, &strydrunpowersensor::debug);
connect(virtualTreadmill, &virtualtreadmill::changeInclination, this,
&strydrunpowersensor::changeInclinationRequested);
this->setVirtualDevice(virtualTreadmill, VIRTUAL_DEVICE_MODE::PRIMARY);
} else {
debug("creating virtual bike interface...");
auto virtualBike = new virtualbike(this, noWriteResistance, noHeartService,
settings.value(QZSettings::bike_resistance_offset, QZSettings::default_bike_resistance_offset).toInt(),
settings.value(QZSettings::bike_resistance_gain_f, QZSettings::default_bike_resistance_gain_f).toDouble());
connect(virtualBike, &virtualbike::changeInclination, this,
&strydrunpowersensor::changeInclinationRequested);
this->setVirtualDevice(virtualBike, VIRTUAL_DEVICE_MODE::ALTERNATIVE);
}
}
}
firstStateChanged = 1;
// ********************************************************************************************************
}
void strydrunpowersensor::changeInclinationRequested(double grade, double percentage) {
if (percentage < 0)
percentage = 0;
if (grade < 0)
grade = 0;
changeInclination(grade, percentage);
}
void strydrunpowersensor::descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
emit debug(QStringLiteral("descriptorWritten ") + descriptor.name() + QStringLiteral(" ") + newValue.toHex(' '));
initRequest = true;
emit connectedAndDiscovered();
}
void strydrunpowersensor::descriptorRead(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
qDebug() << QStringLiteral("descriptorRead ") << descriptor.name() << descriptor.uuid() << newValue.toHex(' ');
}
void strydrunpowersensor::characteristicWritten(const QLowEnergyCharacteristic &characteristic,
const QByteArray &newValue) {
Q_UNUSED(characteristic);
emit debug(QStringLiteral("characteristicWritten ") + newValue.toHex(' '));
}
void strydrunpowersensor::characteristicRead(const QLowEnergyCharacteristic &characteristic,
const QByteArray &newValue) {
qDebug() << QStringLiteral("characteristicRead ") << characteristic.uuid() << newValue.toHex(' ');
characteristicChanged(characteristic, newValue);
}
void strydrunpowersensor::serviceScanDone(void) {
emit debug(QStringLiteral("serviceScanDone"));
auto services_list = m_control->services();
bool isZwiftPod = bluetoothDevice.name().contains(QStringLiteral("Zwift RunPod"), Qt::CaseInsensitive);
for (const QBluetoothUuid &s : qAsConst(services_list)) {
// For Zwift RunPod, skip both fff0 and ffc0 services that cause discovery issues
if (isZwiftPod && (s.toString() == QStringLiteral("{0000fff0-0000-1000-8000-00805f9b34fb}") ||
s.toString() == QStringLiteral("{f000ffc0-0451-4000-b000-000000000000}"))) {
qDebug() << QStringLiteral("Skipping problematic services for Zwift RunPod:") << s.toString();
continue;
}
gattCommunicationChannelService.append(m_control->createServiceObject(s));
connect(gattCommunicationChannelService.constLast(), &QLowEnergyService::stateChanged, this,
&strydrunpowersensor::stateChanged);
gattCommunicationChannelService.constLast()->discoverDetails();
}
}
void strydrunpowersensor::errorService(QLowEnergyService::ServiceError err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceError>();
emit debug(QStringLiteral("strydrunpowersensor::errorService") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void strydrunpowersensor::error(QLowEnergyController::Error err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyController::Error>();
emit debug(QStringLiteral("strydrunpowersensor::error") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void strydrunpowersensor::deviceDiscovered(const QBluetoothDeviceInfo &device) {
emit debug(QStringLiteral("Found new device: ") + device.name() + QStringLiteral(" (") +
device.address().toString() + ')');
{
bluetoothDevice = device;
if(bluetoothDevice.name().toUpper().startsWith("FORERUNNER")) {
FORERUNNER = true;
qDebug() << "FORERUNNER WORKAROUND!";
}
m_control = QLowEnergyController::createCentral(bluetoothDevice, this);
connect(m_control, &QLowEnergyController::serviceDiscovered, this, &strydrunpowersensor::serviceDiscovered);
connect(m_control, &QLowEnergyController::discoveryFinished, this, &strydrunpowersensor::serviceScanDone);
connect(m_control,
static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, &strydrunpowersensor::error);
connect(m_control, &QLowEnergyController::stateChanged, this, &strydrunpowersensor::controllerStateChanged);
connect(m_control,
static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, [this](QLowEnergyController::Error error) {
Q_UNUSED(error);
Q_UNUSED(this);
emit debug(QStringLiteral("Cannot connect to remote device."));
emit disconnected();
});
connect(m_control, &QLowEnergyController::connected, this, [this]() {
Q_UNUSED(this);
emit debug(QStringLiteral("Controller connected. Search services..."));
m_control->discoverServices();
});
connect(m_control, &QLowEnergyController::disconnected, this, [this]() {
Q_UNUSED(this);
emit debug(QStringLiteral("LowEnergy controller disconnected"));
emit disconnected();
});
// Connect
m_control->connectToDevice();
return;
}
}
bool strydrunpowersensor::connected() {
if (!m_control) {
return false;
}
return m_control->state() == QLowEnergyController::DiscoveredState;
}
uint16_t strydrunpowersensor::watts() { return m_watt.value(); }
void strydrunpowersensor::controllerStateChanged(QLowEnergyController::ControllerState state) {
qDebug() << QStringLiteral("controllerStateChanged") << state;
if (state == QLowEnergyController::UnconnectedState && m_control) {
qDebug() << QStringLiteral("trying to connect back again...");
initDone = false;
m_control->connectToDevice();
}
}