-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathicsneocanbackend.cpp
624 lines (519 loc) · 20.5 KB
/
icsneocanbackend.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
/****************************************************************************
** Copyright (C) 2021 Tomasz Ziobrowski <[email protected]>
****************************************************************************/
#include "icsneocanbackend.h"
#include "icsneocanbackend_p.h"
#include "icsneo/icsneocpp.h"
#include "include/qticsneo_keys.h"
#include <QtSerialBus/qcanbusdevice.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qdebug.h>
#include <QtCore/qloggingcategory.h>
#include <QtCore/qregularexpression.h>
#include <QtCore/qtimer.h>
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(QT_CANBUS_PLUGINS_ICSNEOCAN)
class OutgoingEventNotifier : public QTimer
{
public:
OutgoingEventNotifier(IcsNeoCanBackendPrivate *d, QObject *parent) :
QTimer(parent),
dptr(d)
{
}
protected:
void timerEvent(QTimerEvent *e) override
{
if (e->timerId() == timerId()) {
dptr->startWrite();
return;
}
QTimer::timerEvent(e);
}
private:
IcsNeoCanBackendPrivate * const dptr;
};
/*-----------------------------------------------------------------------------------------
B A C K E N D P R I V A T E
-----------------------------------------------------------------------------------------*/
QMap<QString, std::shared_ptr<icsneo::Device>> IcsNeoCanBackendPrivate::m_devices;
IcsNeoCanBackendPrivate::IcsNeoCanBackendPrivate(IcsNeoCanBackend *q) :
q_ptr(q),
incomingEventHandler(new IncomingEventHandler(this, q))
{
}
bool IcsNeoCanBackendPrivate::setupDevice()
{
Q_Q(IcsNeoCanBackend);
if(!m_device)
return false;
if (!m_device->settings->refresh())
resetController();
QVariant value;
bool res = m_device!=nullptr;
// Loopback
value = q->configurationParameter(QCanBusDevice::LoopbackKey);
if (value.isValid() && res)
{
CAN_SETTINGS * set = m_device->settings->getMutableCANSettingsFor(m_network);
if (set)
value.toBool() ? set->Mode = LOOPBACK : set->Mode = NORMAL;
else
res = false;
}
// BitRate
value = q->configurationParameter(QCanBusDevice::BitRateKey);
if (value.isValid() && res)
res &= m_device->settings->setBaudrateFor(m_network, value.toInt()) ;
// CanFD Settings
value = q->configurationParameter(QCanBusDevice::CanFdKey);
if (value.toBool() && res)
{
/* NO_CANFD = 0 , CANFD_ENABLED=1, CANFD_BRS_ENABLED=2, CANFD_ENABLED_ISO=3, CANFD_BRS_ENABLED_ISO=4 */
CANFD_SETTINGS * canFD = m_device->settings->getMutableCANFDSettingsFor(m_network);
if (!canFD)
res = false;
// Iso
value = q->configurationParameter(ParameterIsoKey);
if (value.isValid() && res)
value.toBool() ? canFD->FDMode = CANFD_BRS_ENABLED_ISO : canFD->FDMode = CANFD_BRS_ENABLED;
//res&=m_device->settings->apply();
// FD-Bitrate
value = q->configurationParameter(QCanBusDevice::DataBitRateKey);
if (value.isValid() && res)
res &= m_device->settings->setFDBaudrateFor(m_network, value.toInt()) ;
//res&=m_device->settings->apply();
// Termination
value = q->configurationParameter(ParameterTerminationKey);
if (value.isValid() && res && m_device->settings->canTerminationBeEnabledFor(m_network))
m_device->settings->setTerminationFor(m_network,value.toBool());
//res&=m_device->settings->apply();
}
else
if (res) m_device->settings->getMutableCANFDSettingsFor(m_network)->FDMode = NO_CANFD;
value = q->configurationParameter(ParameterFlashKey);
if (res ) res &=m_device->settings->apply() ; // !value.toBool());
return res;
}
bool IcsNeoCanBackendPrivate::open()
{
Q_Q(IcsNeoCanBackend);
if (!m_device.get()) // device does not exist anymore
return false;
bool res = m_device->open();
if (res) res &= setupDevice();
if (res) res &= m_device->goOnline();
if (nullptr == m_device)
return false;
if (!res)
{
m_device->close();
q->setError(QString::fromStdString(icsneo::GetLastError().describe()),
QCanBusDevice::ConnectionError);
}
else
{
m_messageCallbackId = m_device->addMessageCallback(icsneo::MessageCallback([=](std::shared_ptr<icsneo::Message> m)
{
QVector<QCanBusFrame> newFrames;
auto msg = std::static_pointer_cast<icsneo::CANMessage>(m);
QCanBusFrame frame = interpretFrame(msg.get());
if (frame.isValid())
{
newFrames.append(frame);
q->enqueueReceivedFrames(newFrames);
}
} ));
}
return res;
}
void IcsNeoCanBackendPrivate::close()
{
Q_Q(IcsNeoCanBackend);
enableWriteNotification(false);
if (outgoingEventNotifier) {
delete outgoingEventNotifier;
outgoingEventNotifier = nullptr;
}
if (m_messageCallbackId)
m_device->removeMessageCallback(m_messageCallbackId);
bool res = m_device->goOffline() && m_device->close();
if (!res)
q->setError(QString::fromStdString(icsneo::GetLastError().describe()),
QCanBusDevice::OperationError);
}
bool IcsNeoCanBackendPrivate::setConfigurationParameter(int key, const QVariant &value)
{
Q_Q(IcsNeoCanBackend);
switch (key)
{
case QCanBusDevice::BitRateKey: return true;
case QCanBusDevice::DataBitRateKey: return true;
case QCanBusDevice::CanFdKey: return true;
case QCanBusDevice::LoopbackKey: return true;
case ParameterIsoKey : return true;
case ParameterTerminationKey: return true;
case ParameterFlashKey: return true;
case QCanBusDevice::ReceiveOwnKey:
{
if (Q_UNLIKELY(q->state() != QCanBusDevice::UnconnectedState))
{
q->setError(IcsNeoCanBackend::tr("Cannot configure TxEcho for open device"),
QCanBusDevice::ConfigurationError);
return false;
}
return true;
}
default:
{
q->setError(IcsNeoCanBackend::tr("Unsupported configuration key: %1").arg(key),
QCanBusDevice::ConfigurationError);
return false;
}
}
}
bool IcsNeoCanBackendPrivate::setupChannel(const QString &interfaceName)
{
Q_Q(IcsNeoCanBackend);
const QRegularExpression re(QStringLiteral("can(\\d)\\.(\\d)"));
const QRegularExpressionMatch match = re.match(interfaceName);
if (Q_LIKELY(match.hasMatch()) && m_device)
{
device = quint8(match.captured(1).toUShort());
channel = quint8(match.captured(2).toUShort());
m_network = m_device->getNetworkByNumber(icsneo::Network::Type::CAN, channel+1);
}
else
{
q->setError(IcsNeoCanBackend::tr("Invalid interface '%1'.")
.arg(interfaceName), QCanBusDevice::ConnectionError);
return false;
}
return true;
}
void IcsNeoCanBackendPrivate::setupDefaultConfigurations()
{
Q_Q(IcsNeoCanBackend);
if (!m_device)
return;
bool open = m_device->open();
Q_UNUSED(open);
int bitrate = m_device->settings->getBaudrateFor(m_network);
int fdbitrate = m_device->settings->getFDBaudrateFor(m_network);
const CANFD_SETTINGS * canFD = m_device->settings->getCANFDSettingsFor(m_network);
const CAN_SETTINGS * can = m_device->settings->getCANSettingsFor(m_network);
if (can && canFD)
{
bool hasloopback = can->Mode & LOOPBACK;
q->setConfigurationParameter(QCanBusDevice::LoopbackKey, hasloopback);
bool hasCanFD = canFD->FDMode!= NO_CANFD;
q->setConfigurationParameter(QCanBusDevice::CanFdKey, hasCanFD);
bool hasIso = CANFD_BRS_ENABLED_ISO & canFD->FDMode;
q->setConfigurationParameter(ParameterIsoKey, hasIso);
q->setConfigurationParameter(ParameterFlashKey,false);
if (m_device->settings->canTerminationBeEnabledFor(m_network))
{
bool hasTermination = m_device->settings->isTerminationEnabledFor(m_network).value();
q->setConfigurationParameter(ParameterTerminationKey, hasTermination);
}
q->setConfigurationParameter(QCanBusDevice::BitRateKey, bitrate); // standard BitRate
q->setConfigurationParameter(QCanBusDevice::DataBitRateKey, fdbitrate);
}
m_device->close();
}
void IcsNeoCanBackendPrivate::enableWriteNotification(bool enable)
{
Q_Q(IcsNeoCanBackend);
if (outgoingEventNotifier) {
if (enable) {
if (!outgoingEventNotifier->isActive())
outgoingEventNotifier->start();
} else {
outgoingEventNotifier->stop();
}
} else if (enable) {
outgoingEventNotifier = new OutgoingEventNotifier(this, q);
outgoingEventNotifier->start(0);
}
}
void IcsNeoCanBackendPrivate::startWrite()
{
Q_Q(IcsNeoCanBackend);
if (!q->hasOutgoingFrames()) {
enableWriteNotification(false);
return;
}
const QCanBusFrame frame = q->dequeueOutgoingFrame();
const QByteArray payload = frame.payload();
auto msg = std::make_shared<icsneo::CANMessage>();
msg->network = m_network;
msg->arbid = frame.frameId();
msg->isRemote = frame.frameType() == QCanBusFrame::RemoteRequestFrame;
msg->isCANFD = m_hasFD;
msg->isExtended = frame.hasExtendedFrameFormat();
msg->baudrateSwitch = frame.hasBitrateSwitch();
msg->errorStateIndicator = frame.hasErrorStateIndicator();
msg->data.insert(msg->data.end(), payload.begin(), payload.end()) ;
if(m_device->transmit(msg))
q->framesWritten(qint64(1));
else
q->setError(QString::fromStdString(icsneo::GetLastError().describe()),
QCanBusDevice::WriteError) ;
if (q->hasOutgoingFrames())
enableWriteNotification(true);
}
void IcsNeoCanBackendPrivate::readAllReceivedMessages()
{
//@TODO this is generic implementation based on Qt CanBus module will not work till polling is not enabled
// Attempt to get messages, limiting the number of messages at once to 50,000
// A third parameter of type std::chrono::milliseconds is also accepted if a timeout is desired
Q_Q(IcsNeoCanBackend);
QVector<QCanBusFrame> newFrames;
std::vector<std::shared_ptr<icsneo::Message>> msgs;
if(!m_device->getMessages(msgs, 50000, std::chrono::milliseconds(500)))
{
q->setError(QString::fromStdString(icsneo::GetLastError().describe()),
QCanBusDevice::ReadError) ;
return;
}
for (auto m: msgs)
{
auto msg = std::static_pointer_cast<icsneo::CANMessage>(m);
QCanBusFrame frame = interpretFrame(msg.get());
if (frame.isValid())
newFrames.append(std::move(frame));
}
q->enqueueReceivedFrames(newFrames);
}
void IcsNeoCanBackendPrivate::resetController()
{
auto uniqDevString =[=](const std::shared_ptr<icsneo::Device> & device ) {
QString str = QString::fromStdString(device->describe()) + QString(" - %1").arg(typeid(m_device).name());
str+= QString::fromStdString(device->getSerial());
return str;
};
qCWarning(QT_CANBUS_PLUGINS_ICSNEOCAN, "Reseting controller");
Q_Q(IcsNeoCanBackend);
QString description = uniqDevString(m_device);
this->close(); // Close current connection
m_device->settings->applyDefaults(); // setupd default settings
m_device->settings->apply(); // write into device EEPROM memory
delete m_device.get(); // Delete current device
m_device.reset(); // Reset variable
// Restore device handler
std::vector<std::shared_ptr<icsneo::Device>> devices = icsneo::FindAllDevices();
for (auto dev : devices)
{
QString dev_description = uniqDevString(dev);
if (dev_description == description )
{
m_device = dev ;
dev.reset();
break;
}
}
if (nullptr == m_device )
{
q->setError(IcsNeoCanBackend::tr("Cannot reset controller. Try unplug and plug deivce again"),
QCanBusDevice::UnknownError);
return;
}
// Resored opened state;
if (q->state() == QCanBusDevice::ConnectedState)
{
q->setState(QCanBusDevice::UnconnectedState);
q->open();
}
}
QCanBusFrame IcsNeoCanBackendPrivate::interpretFrame( icsneo::CANMessage * msg )
{
if (!(icsneo::Network::Type::CAN == msg->network.getType() &&
msg->network.getNetID() == m_network.getNetID() ) )
return QCanBusFrame(QCanBusFrame::InvalidFrame);
QByteArray data;
for (auto b : msg->data)
data.append(b);
QCanBusFrame frame(msg->arbid, data);
//qDebug() << "Message timestamp:" << msg->timestamp << " Sec:" << msg->timestamp / 1000000 << "." << msg->timestamp % 1000000;
frame.setTimeStamp(QCanBusFrame::TimeStamp::fromMicroSeconds(msg->timestamp));
frame.setExtendedFrameFormat(msg->isExtended);
frame.setFlexibleDataRateFormat(msg->isCANFD);
frame.setErrorStateIndicator(msg->errorStateIndicator);
//frame.setLocalEcho(msg->transmited); What does it do?
if (msg->error)
frame.setFrameType(QCanBusFrame::ErrorFrame);
else if (msg->isRemote)
frame.setFrameType(QCanBusFrame::RemoteRequestFrame);
else
frame.setFrameType(QCanBusFrame::DataFrame);
return frame;
}
QCanBusDevice::CanBusStatus IcsNeoCanBackendPrivate::busStatus()
{
Q_Q(IcsNeoCanBackend);
icsneo::APIEvent event = icsneo::GetLastError();
if (event.getDevice() == m_device.get() && event.getSeverity() == icsneo::APIEvent::Severity::Error)
{
QString error = QString::fromStdString(event.describe());
q->setError(error, QCanBusDevice::ConfigurationError);
return QCanBusDevice::CanBusStatus::Error;
}
QStringList warnings;
for( auto & event : GetEvents(icsneo::EventFilter()) )
warnings << QString::fromStdString(event.describe());
// if (q->configurationParameter(ParameterOmitKey).toBool())
// warnings << "Configuration ommited - using device defaults";
if (!warnings.isEmpty())
{
for(auto msg: warnings)
qCWarning(QT_CANBUS_PLUGINS_ICSNEOCAN, "Warning: %ls", qUtf16Printable(msg));
q->setError(warnings.join("\n"), QCanBusDevice::ConfigurationError);
return QCanBusDevice::CanBusStatus::Warning;
}
if (m_device->isOnline())
return QCanBusDevice::CanBusStatus::Good;
else
return QCanBusDevice::CanBusStatus::BusOff;
return QCanBusDevice::CanBusStatus::Unknown;
}
void IcsNeoCanBackendPrivate::interfaces( QList<QCanBusDeviceInfo> & list)
{
m_devices.clear();
std::vector<std::shared_ptr<icsneo::Device>> devices = icsneo::FindAllDevices();
for (unsigned int i = 0 ; i < devices.size() ; i++)
{
std::shared_ptr<icsneo::Device> & device = devices[i];
int channels = device->getNetworkCountByType(icsneo::Network::Type::CAN);
for (int channel = 0 ; channel < channels ; channel++)
{
QString description = QString::fromStdString(device->describe()) + QString(" - %1").arg(typeid(*device).name());
QString serial = QString::fromStdString(device->getSerial());
QCanBusDeviceInfo info = IcsNeoCanBackend::createDeviceInfo(serial, description, i, channel);
m_devices[info.name()] = device;
list.append(std::move(info));
}
}
}
/*-----------------------------------------------------------------------------------------
B A C K E N D
-----------------------------------------------------------------------------------------*/
IcsNeoCanBackend::IcsNeoCanBackend(const QString &name, QObject *parent) :
QCanBusDevice(parent),
d_ptr(new IcsNeoCanBackendPrivate(this))
{
Q_D(IcsNeoCanBackend);
d_ptr->m_device = IcsNeoCanBackendPrivate::m_devices[name];
d->setupChannel(name);
d->setupDefaultConfigurations();
std::function<void()> f = std::bind(&IcsNeoCanBackend::resetController, this);
setResetControllerFunction(f);
std::function<CanBusStatus()> g = std::bind(&IcsNeoCanBackend::busStatus, this);
setCanBusStatusGetter(g);
}
IcsNeoCanBackend::~IcsNeoCanBackend()
{
if (state() == QCanBusDevice::ConnectedState)
close();
d_ptr->m_device.reset(); // static table is for deleting it
delete d_ptr;
}
QCanBusDeviceInfo IcsNeoCanBackend::createDeviceInfo(const QString &serialNumber,
const QString &description,
uint deviceNumber,
int channelNumber)
{
const QString name = QString::fromLatin1("can%1.%2").arg(deviceNumber).arg(channelNumber);
qDebug() <<" Device name:serial:description" << name << ":" << serialNumber << ":" << name ;
return QCanBusDevice::createDeviceInfo(name, serialNumber, description, channelNumber, false, true);
}
QList<QCanBusDeviceInfo> IcsNeoCanBackend::interfaces()
{
QList<QCanBusDeviceInfo> list;
IcsNeoCanBackendPrivate::interfaces(list);
return list;
}
QString IcsNeoCanBackend::interpretErrorFrame(const QCanBusFrame &errorFrame)
{
//@TODO - this is stupid ... and not usable as error frame is not set anywhere
switch (errorFrame.error())
{
case QCanBusFrame::TransmissionTimeoutError : return "Transmission timeout";
case QCanBusFrame::LostArbitrationError : return "Lost arbitration";
case QCanBusFrame::ControllerError : return "Controller error";
case QCanBusFrame::ProtocolViolationError : return "Protocol violation";
case QCanBusFrame::TransceiverError : return "Trensceiver error";
case QCanBusFrame::MissingAcknowledgmentError : return "Missing Acknowledgment";
case QCanBusFrame::BusOffError : return "Bus off";
case QCanBusFrame::BusError : return "Bus error";
case QCanBusFrame::ControllerRestartError : return "Controller restart fail";
case QCanBusFrame::UnknownError : return "Unknown error";
case QCanBusFrame::AnyError : return "AnyError";
}
return QString();
}
bool IcsNeoCanBackend::open()
{
Q_D(IcsNeoCanBackend);
if (!d->open())
return false;
setState(QCanBusDevice::ConnectingState);
// Apply all stored configurations except bitrate and receive own,
// because these cannot be applied after opening the device
const QVector<int> keys = configurationKeys();
for (int key : keys) {
if (key == BitRateKey || key == ReceiveOwnKey)
continue;
const QVariant param = configurationParameter(key);
const bool success = d->setConfigurationParameter(key, param);
if (Q_UNLIKELY(!success)) {
qCWarning(QT_CANBUS_PLUGINS_ICSNEOCAN, "Cannot apply parameter %d with value %ls.",
key, qUtf16Printable(param.toString()));
}
}
setState(QCanBusDevice::ConnectedState);
return true;
}
void IcsNeoCanBackend::close()
{
Q_D(IcsNeoCanBackend);
setState(QCanBusDevice::ClosingState);
d->close();
setState(QCanBusDevice::UnconnectedState);
}
void IcsNeoCanBackend::setConfigurationParameter(int key, const QVariant &value)
{
Q_D(IcsNeoCanBackend);
if (d->setConfigurationParameter(key, value))
QCanBusDevice::setConfigurationParameter(key, value);
}
bool IcsNeoCanBackend::writeFrame(const QCanBusFrame &newData)
{
Q_D(IcsNeoCanBackend);
if (Q_UNLIKELY(state() != QCanBusDevice::ConnectedState))
return false;
if (Q_UNLIKELY(!newData.isValid())) {
setError(tr("Cannot write invalid QCanBusFrame"), QCanBusDevice::WriteError);
return false;
}
const QCanBusFrame::FrameType type = newData.frameType();
if (Q_UNLIKELY(type != QCanBusFrame::DataFrame && type != QCanBusFrame::RemoteRequestFrame)) {
setError(tr("Unable to write a frame with unacceptable type"),
QCanBusDevice::WriteError);
return false;
}
enqueueOutgoingFrame(newData);
d->enableWriteNotification(true);
return true;
}
void IcsNeoCanBackend::resetController()
{
Q_D(IcsNeoCanBackend);
d->resetController();
}
QCanBusDevice::CanBusStatus IcsNeoCanBackend::busStatus()
{
Q_D(IcsNeoCanBackend);
return d->busStatus();
}
QT_END_NAMESPACE