-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathcscbike.cpp
More file actions
728 lines (632 loc) · 31 KB
/
Copy pathcscbike.cpp
File metadata and controls
728 lines (632 loc) · 31 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
#include "cscbike.h"
#include "virtualdevices/virtualbike.h"
#include "virtualdevices/virtualrower.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;
cscbike::cscbike(bool noWriteResistance, bool noHeartService, bool noVirtualDevice) {
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, &cscbike::update);
refresh->start(200ms);
}
void cscbike::enableManualResistancePowerAdjustment(resistance_t resistance) {
if (!jorotoBike && !useCustomResistancePowerTable()) {
return;
}
resistance_t clampedResistance =
jorotoBike ? qBound<resistance_t>(1, resistance, 15) : clampedCustomResistance(resistance);
manualResistanceTarget = clampedResistance;
manualResistancePowerAdjustmentActive = true;
Resistance = clampedResistance;
emit resistanceRead(Resistance.value());
if (!manualResistancePowerAdjustmentToastShown && homeform::singleton()) {
homeform::singleton()->setToastRequested(
jorotoBike
? QStringLiteral(
"Manual resistance power adjustment enabled: power now scales with the Resistance tile value.")
: QStringLiteral(
"Custom CSC power table enabled: power now follows the configured resistance/watt points."));
manualResistancePowerAdjustmentToastShown = true;
}
}
void cscbike::onManualResistanceAdjusted(resistance_t resistance) {
enableManualResistancePowerAdjustment(resistance);
}
uint16_t cscbike::manualResistanceAdjustedWatts() {
if (currentCadence().value() == 0) {
return 0;
}
const double cadenceOnlyWatts = currentCadence().value() * 1.2;
return qRound(cadenceOnlyWatts * manualResistancePowerMultiplier());
}
uint16_t cscbike::customResistanceAdjustedWatts() {
if (currentCadence().value() == 0) {
return 0;
}
QSettings settings;
const double resistanceLevel1 =
settings.value(QZSettings::cscbike_custom_resistance_level_1,
QZSettings::default_cscbike_custom_resistance_level_1)
.toDouble();
const double watt1 =
settings.value(QZSettings::cscbike_custom_watt_1, QZSettings::default_cscbike_custom_watt_1).toDouble();
const double resistanceLevel2 =
settings.value(QZSettings::cscbike_custom_resistance_level_2,
QZSettings::default_cscbike_custom_resistance_level_2)
.toDouble();
const double watt2 =
settings.value(QZSettings::cscbike_custom_watt_2, QZSettings::default_cscbike_custom_watt_2).toDouble();
const double resistance = clampedCustomResistance(manualResistanceTarget);
if (resistanceLevel1 == resistanceLevel2) {
return qMax(0, qRound((watt1 + watt2) / 2.0));
}
const double slope = (watt2 - watt1) / (resistanceLevel2 - resistanceLevel1);
const double watts = watt1 + ((resistance - resistanceLevel1) * slope);
return qMax(0, qRound(watts));
}
double cscbike::manualResistancePowerMultiplier() {
const double normalizedResistance = (qBound(1, static_cast<int>(manualResistanceTarget), 15) - 1) / 14.0;
return 1.0 + (normalizedResistance * normalizedResistance * 2.0);
}
bool cscbike::useCustomResistancePowerTable() const {
QSettings settings;
return settings
.value(QZSettings::cscbike_custom_resistance_power_table,
QZSettings::default_cscbike_custom_resistance_power_table)
.toBool();
}
resistance_t cscbike::clampedCustomResistance(resistance_t resistance) const {
QSettings settings;
int resistanceMin =
qRound(settings.value(QZSettings::zwift_erg_resistance_down,
QZSettings::default_zwift_erg_resistance_down)
.toDouble());
int resistanceMax =
qRound(settings.value(QZSettings::zwift_erg_resistance_up,
QZSettings::default_zwift_erg_resistance_up)
.toDouble());
if (resistanceMin > resistanceMax) {
qSwap(resistanceMin, resistanceMax);
}
return qBound(static_cast<resistance_t>(resistanceMin), resistance, static_cast<resistance_t>(resistanceMax));
}
/*
void cscbike::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 cscbike::update() {
QSettings settings;
QString heartRateBeltName =
settings.value(QZSettings::heart_rate_belt_name, QZSettings::default_heart_rate_belt_name).toString();
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"))) {
update_hr_from_external();
}
}
bool rogue_echo_bike = settings.value(QZSettings::rogue_echo_bike, QZSettings::default_rogue_echo_bike).toBool();
if (manualResistancePowerAdjustmentActive && jorotoBike) {
m_watt = manualResistanceAdjustedWatts();
} else if (manualResistancePowerAdjustmentActive && useCustomResistancePowerTable()) {
m_watt = customResistanceAdjustedWatts();
} else if (rogue_echo_bike) {
double rpm = currentCadence().value();
m_watt = 0.000602337 * pow(rpm, 3.11762) + 32.6404;
} else {
// When cadence is zero, watts should be zero regardless of HR
if (currentCadence().value() == 0) {
m_watt = 0;
} else {
m_watt = wattFromHR(false);
}
}
emit debug(QStringLiteral("Current Watt: ") + QString::number(m_watt.value()));
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*/) {
bool cadence_sensor_as_bike =
settings.value(QZSettings::cadence_sensor_as_bike, QZSettings::default_cadence_sensor_as_bike).toBool();
update_metrics(false, watts(), !cadence_sensor_as_bike);
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);
}
// updating the treadmill console every second
if (sec1Update++ == (500 / refresh->interval())) {
sec1Update = 0;
// updateDisplay(elapsed);
}
if (requestResistance != -1) {
if (requestResistance > 15) {
requestResistance = 15;
} else if (requestResistance == 0) {
requestResistance = 1;
}
if (requestResistance != currentResistance().value()) {
emit debug(QStringLiteral("writing resistance ") + QString::number(requestResistance));
// forceResistance(requestResistance);
}
requestResistance = -1;
}
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;
}
}
}
void cscbike::serviceDiscovered(const QBluetoothUuid &gatt) {
emit debug(QStringLiteral("serviceDiscovered ") + gatt.toString());
}
void cscbike::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
QDateTime now = QDateTime::currentDateTime();
qDebug() << "characteristicChanged << " << characteristic.uuid() << newValue.toHex(' ') << newValue.length();
Q_UNUSED(characteristic);
QSettings settings;
// QString heartRateBeltName = //unused QString
// settings.value(QZSettings::heart_rate_belt_name, QZSettings::default_heart_rate_belt_name).toString();
uint16_t _LastCrankEventTime = 0;
double _CrankRevs = 0;
uint16_t _LastWheelEventTime = 0;
double _WheelRevs = 0;
uint8_t battery = 0;
charNotified = true;
if (characteristic.uuid() == QBluetoothUuid((quint16)0x2A19)) {
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((quint16)0x2A5B)) {
return;
}
lastPacket = newValue;
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));
}
// CSC Combo Sensor Fallback Logic
//
// Some combo sensors (e.g., Giant Combo) advertise both speed and cadence capabilities
// by setting CrankPresent=true in the CSC flags byte, but only transmit valid wheel data
// while sending crank data as zeros. This happens when:
// 1. The sensor supports dual mode (speed+cadence) but only speed sensor is mounted
// 2. The cadence sensor is not activated/calibrated
// 3. Firmware always sets CrankPresent flag regardless of actual crank sensor status
//
// In these cases, we use wheel revolutions as a fallback to calculate cadence.
// This works when the wheel circumference is set to a small value (e.g., 20cm for
// indoor trainers), which effectively converts wheel RPM to a cadence-like metric.
//
// Note: When using wheel revs as cadence, the calculated RPM can exceed 256 (the
// typical limit for real crank cadence). For example, with 20cm wheel circumference
// at 12.5 km/h, wheel RPM ≈ 1000. The validation logic below accounts for this.
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;
// Cadence Validation Logic
//
// Normal cadence validation applies a 256 RPM limit for real crank sensors (no human
// can pedal faster than 256 RPM). However, when using wheel revs as fallback
// (_CrankRevs == 0), we bypass this limit because:
// - Wheel RPM with small circumferences (e.g., 20cm) can legitimately exceed 256
// - Example: 12.5 km/h with 20cm circumference = ~1042 wheel RPM
// - This high RPM represents wheel rotation rate, not actual pedaling cadence
//
// The condition breakdown:
// Part 1: (cadence >= 0 && (cadence < 256 || _CrankRevs == 0) && CrankPresent)
// - For real crank data: applies 256 RPM limit
// - For wheel fallback: no limit when _CrankRevs == 0
// Part 2: (!CrankPresent && WheelPresent)
// - Pure speed sensors with no crank capability
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 (!settings.value(QZSettings::speed_power_based, QZSettings::default_speed_power_based).toBool()) {
Speed = Cadence.value() *
settings.value(QZSettings::cadence_sensor_speed_ratio, QZSettings::default_cadence_sensor_speed_ratio)
.toDouble();
} else {
Speed = metric::calculateSpeedFromPower(
watts(), Inclination.value(), Speed.value(),
fabs(now.msecsTo(Speed.lastChanged()) / 1000.0), this->speedLimit());
}
emit debug(QStringLiteral("Current Speed: ") + QString::number(Speed.value()));
Distance += ((Speed.value() / 3600000.0) *
((double)lastRefreshCharacteristicChanged.msecsTo(now)));
emit debug(QStringLiteral("Current Distance: ") + QString::number(Distance.value()));
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() > 0) {
m_pelotonResistance =
(((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 (manualResistancePowerAdjustmentActive) {
Resistance = manualResistanceTarget;
} else {
Resistance = m_pelotonResistance;
}
} else {
m_pelotonResistance = 0;
Resistance = manualResistancePowerAdjustmentActive ? manualResistanceTarget : 0;
}
emit resistanceRead(Resistance.value());
if (watts())
KCal +=
((((0.048 * ((double)watts()) + 1.19) *
settings.value(QZSettings::weight, QZSettings::default_weight).toFloat() * 3.5) /
200.0) /
(60000.0 / ((double)lastRefreshCharacteristicChanged.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()));
if (Cadence.value() > 0) {
CrankRevs++;
LastCrankEventTime += (uint16_t)(1024.0 / (((double)(Cadence.value())) / 60.0));
}
lastRefreshCharacteristicChanged = now;
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
}
emit debug(QStringLiteral("Current CrankRevs: ") + QString::number(CrankRevs));
emit debug(QStringLiteral("Last CrankEventTime: ") + QString::number(LastCrankEventTime));
if (m_control->error() != QLowEnergyController::NoError) {
qDebug() << QStringLiteral("QLowEnergyController ERROR!!") << m_control->errorString();
}
}
void cscbike::stateChanged(QLowEnergyService::ServiceState state) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceState>();
emit debug(QStringLiteral("BTLE stateChanged ") + QString::fromLocal8Bit(metaEnum.valueToKey(state)));
QBluetoothUuid CyclingSpeedAndCadence(QBluetoothUuid::CyclingSpeedAndCadence);
QBluetoothUuid Battery(QBluetoothUuid::BatteryService);
for (QLowEnergyService *s : qAsConst(gattCommunicationChannelService)) {
qDebug() << QStringLiteral("stateChanged") << s->serviceUuid() << s->state();
#ifdef Q_OS_WINDOWS
qDebug() << "windows workaround, check only CyclingSpeedAndCadence ftms service"
<< (s->serviceUuid() == CyclingSpeedAndCadence);
if (s->serviceUuid() == CyclingSpeedAndCadence)
#endif
{
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) {
if(s->serviceUuid() == CyclingSpeedAndCadence) {
qDebug() << "CyclingSpeedAndCadence found";
cadenceService = s;
}
if(s->serviceUuid() != CyclingSpeedAndCadence && s->serviceUuid() != Battery) {
// No data from sensors and avatar won’t move in Zwift (even when data showed on first try) (Issue #2178)
qDebug() << "avoid unwaned service";
continue;
}
// establish hook into notifications
connect(s, &QLowEnergyService::characteristicChanged, this, &cscbike::characteristicChanged);
connect(s, &QLowEnergyService::characteristicWritten, this, &cscbike::characteristicWritten);
connect(s, &QLowEnergyService::characteristicRead, this, &cscbike::characteristicRead);
connect(
s, static_cast<void (QLowEnergyService::*)(QLowEnergyService::ServiceError)>(&QLowEnergyService::error),
this, &cscbike::errorService);
connect(s, &QLowEnergyService::descriptorWritten, this, &cscbike::descriptorWritten);
connect(s, &QLowEnergyService::descriptorRead, this, &cscbike::descriptorRead);
qDebug() << s->serviceUuid() << QStringLiteral("connected!");
auto characteristics_list = s->characteristics();
for (const QLowEnergyCharacteristic &c : qAsConst(characteristics_list)) {
if(c.uuid() == QBluetoothUuid((quint16)0x2A5B)) {
qDebug() << "CyclingSpeedAndCadence char found";
cadenceChar = c;
}
qDebug() << QStringLiteral("char uuid") << c.uuid() << QStringLiteral("handle") << c.handle() << QStringLiteral("properties") << c.properties();
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 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_rower =
settings.value(QZSettings::virtual_device_rower, QZSettings::default_virtual_device_rower).toBool();
#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) {
qDebug() << "ios_peloton_workaround activated!";
h = new lockscreen();
h->virtualbike_ios();
} else
#endif
#endif
if (virtual_device_enabled) {
if (virtual_device_rower) {
emit debug(QStringLiteral("creating virtual rower interface..."));
auto virtualRower = new virtualrower(this, noWriteResistance, noHeartService);
this->setVirtualDevice(virtualRower, VIRTUAL_DEVICE_MODE::ALTERNATIVE);
} else {
emit debug(QStringLiteral("creating virtual bike interface..."));
auto virtualBike = new virtualbike(this, noWriteResistance, noHeartService);
connect(virtualBike, &virtualbike::changeInclination, this, &cscbike::changeInclination);
// connect(virtualBike,&virtualbike::debug ,this,&cscbike::debug);
this->setVirtualDevice(virtualBike, VIRTUAL_DEVICE_MODE::PRIMARY);
}
}
}
firstStateChanged = 1;
// ********************************************************************************************************
}
void cscbike::descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
emit debug(QStringLiteral("descriptorWritten ") + descriptor.name() + QStringLiteral(" ") + newValue.toHex(' '));
initRequest = true;
emit connectedAndDiscovered();
}
void cscbike::descriptorRead(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
qDebug() << QStringLiteral("descriptorRead ") << descriptor.name() << descriptor.uuid() << newValue.toHex(' ');
}
void cscbike::characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
Q_UNUSED(characteristic);
emit debug(QStringLiteral("characteristicWritten ") + newValue.toHex(' '));
}
void cscbike::characteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
qDebug() << QStringLiteral("characteristicRead ") << characteristic.uuid() << newValue.toHex(' ');
characteristicChanged(characteristic, newValue);
}
void cscbike::serviceScanDone(void) {
emit debug(QStringLiteral("serviceScanDone"));
#ifdef Q_OS_ANDROID
QLowEnergyConnectionParameters c;
c.setIntervalRange(24, 40);
c.setLatency(0);
c.setSupervisionTimeout(420);
m_control->requestConnectionUpdate(c);
#endif
auto services_list = m_control->services();
for (const QBluetoothUuid &s : qAsConst(services_list)) {
#ifdef Q_OS_WINDOWS
QBluetoothUuid CyclingSpeedAndCadence(QBluetoothUuid::CyclingSpeedAndCadence);
qDebug() << "windows workaround, check only the CyclingSpeedAndCadence service" << s << CyclingSpeedAndCadence
<< (s == CyclingSpeedAndCadence);
if (s == CyclingSpeedAndCadence)
#endif
{
gattCommunicationChannelService.append(m_control->createServiceObject(s));
connect(gattCommunicationChannelService.constLast(), &QLowEnergyService::stateChanged, this,
&cscbike::stateChanged);
gattCommunicationChannelService.constLast()->discoverDetails();
}
}
}
void cscbike::errorService(QLowEnergyService::ServiceError err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyService::ServiceError>();
emit debug(QStringLiteral("cscbike::errorService") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void cscbike::error(QLowEnergyController::Error err) {
QMetaEnum metaEnum = QMetaEnum::fromType<QLowEnergyController::Error>();
emit debug(QStringLiteral("cscbike::error") + QString::fromLocal8Bit(metaEnum.valueToKey(err)) +
m_control->errorString());
}
void cscbike::deviceDiscovered(const QBluetoothDeviceInfo &device) {
emit debug(QStringLiteral("Found new device: ") + device.name() + QStringLiteral(" (") +
device.address().toString() + ')');
{
bluetoothDevice = device;
jorotoBike = bluetoothDevice.name().toUpper().startsWith(QStringLiteral("JOROTO-BK-"));
m_control = QLowEnergyController::createCentral(bluetoothDevice, this);
connect(m_control, &QLowEnergyController::serviceDiscovered, this, &cscbike::serviceDiscovered);
connect(m_control, &QLowEnergyController::discoveryFinished, this, &cscbike::serviceScanDone);
connect(m_control,
static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, &cscbike::error);
connect(m_control, &QLowEnergyController::stateChanged, this, &cscbike::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 cscbike::connected() {
if (!m_control) {
return false;
}
return m_control->state() == QLowEnergyController::DiscoveredState;
}
uint16_t cscbike::watts() {
if (currentCadence().value() == 0) {
return 0;
}
return m_watt.value();
}
void cscbike::controllerStateChanged(QLowEnergyController::ControllerState state) {
qDebug() << "controllerStateChanged" << state;
if (state == QLowEnergyController::UnconnectedState && m_control) {
qDebug() << "trying to connect back again...";
initDone = false;
m_control->connectToDevice();
}
}