-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMonarkConnection.cpp
528 lines (447 loc) · 12.6 KB
/
MonarkConnection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*
* Copyright (c) 2015 Erik Botö (erik.boto@gmail.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "MonarkConnection.h"
#include <QByteArray>
#include <QDebug>
#include <QtSerialPort/QSerialPortInfo>
MonarkConnection::MonarkConnection() :
m_serial(0),
m_pollInterval(1000),
m_readTimer(0),
m_writeTimer(0),
m_load(0),
m_loadToWrite(0),
m_type(MONARK_UNKNOWN),
m_power(0),
m_cadence(0),
m_pulse(0)
{
}
void MonarkConnection::setSerialPort(const QString serialPortName)
{
if (! this->isRunning())
{
m_serialPortName = serialPortName;
} else {
qWarning() << "MonarkConnection: Cannot set serialPortName while running";
}
}
void MonarkConnection::setPollInterval(int interval)
{
if (interval != m_pollInterval)
{
m_pollInterval = interval;
m_readTimer->setInterval(m_pollInterval);
}
}
int MonarkConnection::pollInterval()
{
return m_pollInterval;
}
/**
* Private function that reads a complete reply and prepares if for
* processing by replacing \r with \0
*/
QString MonarkConnection::readAnswer(int timeoutMs)
{
QByteArray data;
do
{
if (m_serial->waitForReadyRead(timeoutMs))
{
data.append(m_serial->readAll());
} else {
data.append('\r');
}
} while (data.indexOf('\r') == -1);
data.replace("\r", "\0");
return QString(data);
}
/**
* QThread::run()
*
* Open the serial port and set it up, then starts polling.
*
*/
void MonarkConnection::run()
{
// Open and configure serial port
m_serial = new QSerialPort();
m_startupTimer = new QTimer();
m_startupTimer->setInterval(200);
m_startupTimer->setSingleShot(true);
m_startupTimer->start();
m_readTimer = new QTimer();
m_writeTimer = new QTimer();
m_writeTimer->setInterval(250);
m_writeTimer->setSingleShot(false);
connect(m_startupTimer, SIGNAL(timeout()), this, SLOT(identifySerialPort()), Qt::DirectConnection);
connect(m_readTimer, SIGNAL(timeout()), this, SLOT(requestAll()), Qt::DirectConnection);
connect(m_writeTimer, SIGNAL(timeout()), this, SLOT(sendTargetWattOrKp()), Qt::DirectConnection);
qDebug() << "Started Monark Thread";
exec();
}
void MonarkConnection::requestAll()
{
// If something else is blocking mutex, don't start another round of requests
if (! m_mutex.tryLock())
return;
requestPower();
requestPulse();
requestCadence();
m_mutex.unlock();
sendTargetWattOrKp();
}
void MonarkConnection::sendTargetWattOrKp()
{
// Only proceed if there seems to be enough time to be sure it's done before next read request
if (m_readTimer->remainingTime() < 150)
return;
// If something else is blocking mutex, don't start another round of requests
if (! m_mutex.tryLock())
return;
// We have a new target power to write
if ((m_loadToWrite != m_load) && m_mode == MONARK_MODE_WATT && canDoLoad())
{
QString cmd = QString("power %1\r").arg(m_loadToWrite);
m_serial->write(cmd.toStdString().c_str());
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
m_load = m_loadToWrite;
QByteArray data = m_serial->readAll();
}
// We have a new kp to write to a bike than does kp-targets (e.g. LC6)
if ((m_kpToWrite != m_kp) && m_mode == MONARK_MODE_KP && canDoKp())
{
QString cmd = QString("kp %1\r").arg(QString::number(m_kpToWrite, 'f', 1 ));
m_serial->write(cmd.toStdString().c_str());
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
m_kp = m_kpToWrite;
QByteArray data = m_serial->readAll();
}
// We're in kp-target mode on a bike that only does target power (e.g. LC4)
if ((m_mode == MONARK_MODE_KP) && canDoLoad() && !canDoKp())
{
// Calculate what wattage to request to simulate selected kp
// watt = kp * cadence * 0.98
unsigned int load = (m_kpToWrite * m_cadence) * 0.98;
QString cmd = QString("power %1\r").arg(load);
m_serial->write(cmd.toStdString().c_str());
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
QByteArray data = m_serial->readAll();
}
m_mutex.unlock();
}
void MonarkConnection::requestPower()
{
// Always empty read buffer first
m_serial->readAll();
m_serial->write("power\r");
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
QString data = readAnswer(500);
m_power = data.toInt();
emit power(m_power);
}
void MonarkConnection::requestPulse()
{
// Always empty read buffer first
m_serial->readAll();
m_serial->write("pulse\r");
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
QString data = readAnswer(500);
m_pulse = data.toInt();
emit pulse(m_pulse);
}
void MonarkConnection::requestCadence()
{
// Always empty read buffer first
m_serial->readAll();
m_serial->write("pedal\r");
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
QString data = readAnswer(500);
m_cadence = data.toInt();
emit cadence(m_cadence);
}
void MonarkConnection::identifyModel()
{
m_serial->write("id\r");
if (!m_serial->waitForBytesWritten(500))
{
// failure to write to device, bail out
emit connectionStatus(false);
m_startupTimer->start();
}
QString data = readAnswer(500);
m_id = QString(data);
if (m_id.toLower().startsWith("lc"))
{
m_type = MONARK_LC;
} else if (m_id.toLower().startsWith("novo")) {
m_type = MONARK_LC_NOVO;
} else if (m_id.toLower().startsWith("mec")) {
m_type = MONARK_839E;
} else if (m_id.toLower().startsWith("lt")) {
m_type = MONARK_LT2;
}
if (canDoLoad())
{
setLoad(100);
}
emit typeIdentified();
qDebug() << "Connected to bike: " << m_id;
}
void MonarkConnection::setLoad(unsigned int load)
{
if (m_loadToWrite != load)
{
emit targetPowerChanged(load);
}
m_loadToWrite = load;
if (m_mode != MONARK_MODE_WATT)
{
m_mode = MONARK_MODE_WATT;
emit modeChanged(m_mode);
}
}
void MonarkConnection::setKp(double kp)
{
if (kp < 0)
kp = 0;
if (kp > 7)
kp = 7;
if (m_kpToWrite != kp)
{
emit targetKpChanged(kp);
}
m_kpToWrite = kp;
if (m_mode != MONARK_MODE_KP)
{
m_mode = MONARK_MODE_KP;
emit modeChanged(m_mode);
}
}
/*
* Configures a serialport for communicating with a Monark bike.
*/
void MonarkConnection::configurePort(QSerialPort *serialPort)
{
if (!serialPort)
{
qFatal("Trying to configure null port, start debugging.");
}
serialPort->setBaudRate(QSerialPort::Baud4800);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setFlowControl(QSerialPort::SoftwareControl);
serialPort->setParity(QSerialPort::NoParity);
// Send empty \r after configuring port, otherwise first command might not
// be interpreted correctly
serialPort->write("\r");
}
/**
* This functions takes a serial port and tries if it can find a Monark bike connected
* to it.
*/
bool MonarkConnection::discover(QString portName)
{
bool found = false;
QSerialPort sp;
sp.setPortName(portName);
if (sp.open(QSerialPort::ReadWrite))
{
configurePort(&sp);
// Discard any existing data
QByteArray data = sp.readAll();
// Read id from bike
sp.write("id\r");
sp.waitForBytesWritten(2000);
QByteArray id;
do
{
bool readyToRead = sp.waitForReadyRead(1000);
if (readyToRead)
{
id.append(sp.readAll());
} else {
id.append('\r');
}
} while ((id.indexOf('\r') == -1));
id.replace("\r", "\0");
// Should check for all bike ids known to use this protocol
if (QString(id).toLower().contains("lt") ||
QString(id).toLower().contains("lc") ||
QString(id).toLower().contains("mec") ||
QString(id).toLower().contains("novo")) {
found = true;
}
qDebug() << "Connected to bike: " << id;
}
sp.close();
return found;
}
void MonarkConnection::identifySerialPort()
{
qDebug() << __func__;
bool found = false;
// Make sure the port is closed to start with
m_serial->close();
m_readTimer->stop();
m_writeTimer->stop();
do {
qDebug() << "Refreshing list of serial ports...";
// Look for test interface
if (discover("/tmp/monark-test"))
{
// found monark
qDebug() << "FOUND!";
m_serialPortName = "/tmp/monark-test";
found = true;
break;
}
QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
foreach (QSerialPortInfo port, ports)
{
#ifdef RASPBERRYPI
if (port.systemLocation() == "/dev/ttyAMA0")
continue;
#endif
if (port.systemLocation().startsWith("/dev/ttyACM"))
continue;
qDebug() << "Looking for Monark at " << port.systemLocation();
if (discover(port.systemLocation()))
{
// found monark
qDebug() << "FOUND!";
m_serialPortName = port.systemLocation();
found = true;
break;
}
}
msleep(500);
} while (!found);
m_serial->setPortName(m_serialPortName);
if (!m_serial->open(QSerialPort::ReadWrite))
{
qDebug() << "Error opening serial";
m_startupTimer->start();
} else {
configurePort(m_serial);
// Discard any existing data
QByteArray data = m_serial->readAll();
}
identifyModel();
m_readTimer->setInterval(1000);
m_readTimer->start();
m_writeTimer->start();
emit connectionStatus(true);
}
bool MonarkConnection::canDoLoad()
{
bool result = false;
switch (m_type)
{
case MONARK_LC: // fall through
case MONARK_LC_NOVO: // fall through
case MONARK_839E:
result = true;
break;
case MONARK_LT2: // fall through
default:
result = false;
break;
}
return result;
}
bool MonarkConnection::canDoKp()
{
bool result = false;
switch (m_type)
{
case MONARK_839E: // fall through
case MONARK_LC_NOVO:
result = true;
break;
case MONARK_LC: // fall through
case MONARK_LT2: // fall through
default:
result = false;
break;
}
return result;
}
void MonarkConnection::setMode(MonarkMode mode)
{
if (mode == m_mode)
{
return;
}
if (mode == MONARK_MODE_KP)
{
if (m_cadence != 0)
{
setKp(m_power / (m_cadence * 0.98));
} else {
setKp(1);
}
}
if (mode == MONARK_MODE_WATT)
{
setLoad(m_power);
}
}
void MonarkConnection::setFecMode(FECDevice::FecMode mode)
{
m_fecMode = mode;
}
bool MonarkConnection::isFecErg()
{
return (m_fecMode == FECDevice::FEC_ERG);
}
bool MonarkConnection::isFecSimulation()
{
return (m_fecMode == FECDevice::FEC_SIMULATION);
}