summaryrefslogtreecommitdiffstats
path: root/src/plugins/canbus/peakcan/peakcanbackend.cpp
blob: 6e1af1c23bae1908607d6e8e8d792e86833cc7d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
/****************************************************************************
**
** Copyright (C) 2017 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtSerialBus module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "peakcanbackend.h"
#include "peakcanbackend_p.h"
#include "peakcan_symbols_p.h"

#include <QtSerialBus/qcanbusdevice.h>

#include <QtCore/qtimer.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qloggingcategory.h>

#include <algorithm>

#ifdef Q_OS_WIN32
#   include <QtCore/qwineventnotifier.h>
#else
#   include <QtCore/qsocketnotifier.h>
#endif

QT_BEGIN_NAMESPACE

Q_DECLARE_LOGGING_CATEGORY(QT_CANBUS_PLUGINS_PEAKCAN)

#ifndef LINK_LIBPCANBASIC
Q_GLOBAL_STATIC(QLibrary, pcanLibrary)
#endif

bool PeakCanBackend::canCreate(QString *errorReason)
{
#ifdef LINK_LIBPCANBASIC
    return true;
#else
    static bool symbolsResolved = resolvePeakCanSymbols(pcanLibrary());
    if (Q_UNLIKELY(!symbolsResolved)) {
        qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot load library: %ls",
                qUtf16Printable(pcanLibrary()->errorString()));
        *errorReason = pcanLibrary()->errorString();
        return false;
    }
    return true;
#endif
}

struct PcanChannel{
    char        name[6];
    TPCANHandle index;
};
static const PcanChannel pcanChannels[] = {
    { "usb0",  PCAN_USBBUS1  },
    { "usb1",  PCAN_USBBUS2  },
    { "usb2",  PCAN_USBBUS3  },
    { "usb3",  PCAN_USBBUS4  },
    { "usb4",  PCAN_USBBUS5  },
    { "usb5",  PCAN_USBBUS6  },
    { "usb6",  PCAN_USBBUS7  },
    { "usb7",  PCAN_USBBUS8  },
    { "usb8",  PCAN_USBBUS9  },
    { "usb9",  PCAN_USBBUS10 },
    { "usb10", PCAN_USBBUS11 },
    { "usb11", PCAN_USBBUS12 },
    { "usb12", PCAN_USBBUS13 },
    { "usb13", PCAN_USBBUS14 },
    { "usb14", PCAN_USBBUS15 },
    { "usb15", PCAN_USBBUS16 },
    { "pci0",  PCAN_PCIBUS1  },
    { "pci1",  PCAN_PCIBUS2  },
    { "pci2",  PCAN_PCIBUS3  },
    { "pci3",  PCAN_PCIBUS4  },
    { "pci4",  PCAN_PCIBUS5  },
    { "pci5",  PCAN_PCIBUS6  },
    { "pci6",  PCAN_PCIBUS7  },
    { "pci7",  PCAN_PCIBUS8  },
    { "pci8",  PCAN_PCIBUS9  },
    { "pci9",  PCAN_PCIBUS10 },
    { "pci10", PCAN_PCIBUS11 },
    { "pci11", PCAN_PCIBUS12 },
    { "pci12", PCAN_PCIBUS13 },
    { "pci13", PCAN_PCIBUS14 },
    { "pci14", PCAN_PCIBUS15 },
    { "pci15", PCAN_PCIBUS16 },
    { "none",  PCAN_NONEBUS  }
};

QList<QCanBusDeviceInfo> PeakCanBackend::interfaces()
{
    QList<QCanBusDeviceInfo> result;

    for (int i = 0; pcanChannels[i].index != PCAN_NONEBUS; ++i) {
        uint value = 0;
        const TPCANHandle index = pcanChannels[i].index;
        const TPCANStatus stat = ::CAN_GetValue(index, PCAN_CHANNEL_CONDITION,
                                                &value, sizeof(value));
        if ((stat == PCAN_ERROR_OK) && (value & PCAN_CHANNEL_AVAILABLE)) {
            const TPCANStatus fdStat = ::CAN_GetValue(index, PCAN_CHANNEL_FEATURES,
                                                      &value, sizeof(value));
            const bool isFd = (fdStat == PCAN_ERROR_OK) && (value & FEATURE_FD_CAPABLE);

            char description[256] = {0};
            const TPCANStatus descStat = ::CAN_GetValue(index, PCAN_HARDWARE_NAME,
                                                        description, sizeof(description));
            if (descStat != PCAN_ERROR_OK)
                description[0] = 0;

            int channel = 0;
            const TPCANStatus chnStat = ::CAN_GetValue(index, PCAN_CONTROLLER_NUMBER,
                                                       &channel, sizeof(channel));
            if (chnStat != PCAN_ERROR_OK)
                channel = 0;

            result.append(std::move(createDeviceInfo(QLatin1String(pcanChannels[i].name),
                                                     QString(), QLatin1String(description),
                                                     channel, false, isFd)));
        }
    }

    return result;
}

#if defined(Q_OS_WIN32)
class PeakCanReadNotifier : public QWinEventNotifier
{
    // no Q_OBJECT macro!
public:
    explicit PeakCanReadNotifier(PeakCanBackendPrivate *d, QObject *parent)
        : QWinEventNotifier(parent)
        , dptr(d)
    {
        setHandle(dptr->readHandle);
    }

protected:
    bool event(QEvent *e) override
    {
        if (e->type() == QEvent::WinEventAct) {
            dptr->startRead();
            return true;
        }
        return QWinEventNotifier::event(e);
    }

private:
    PeakCanBackendPrivate * const dptr;
};
#else
class PeakCanReadNotifier : public QSocketNotifier
{
    // no Q_OBJECT macro!
public:
    explicit PeakCanReadNotifier(PeakCanBackendPrivate *d, QObject *parent)
        : QSocketNotifier(d->readHandle, QSocketNotifier::Read, parent)
        , dptr(d)
    {
    }

protected:
    bool event(QEvent *e) override
    {
        if (e->type() == QEvent::SockAct) {
            dptr->startRead();
            return true;
        }
        return QSocketNotifier::event(e);
    }

private:
    PeakCanBackendPrivate * const dptr;
};
#endif

class PeakCanWriteNotifier : public QTimer
{
    // no Q_OBJECT macro!
public:
    PeakCanWriteNotifier(PeakCanBackendPrivate *d, QObject *parent)
        : QTimer(parent)
        , dptr(d)
    {
    }

protected:
    void timerEvent(QTimerEvent *e) override
    {
        if (e->timerId() == timerId()) {
            dptr->startWrite();
            return;
        }
        QTimer::timerEvent(e);
    }

private:
    PeakCanBackendPrivate * const dptr;
};

PeakCanBackendPrivate::PeakCanBackendPrivate(PeakCanBackend *q)
    : q_ptr(q)
{
}

struct BitrateItem
{
    int bitrate;
    TPCANBaudrate code;
};

struct BitrateLessFunctor
{
    bool operator()( const BitrateItem &item1, const BitrateItem &item2) const
    {
        return item1.bitrate < item2.bitrate;
    }
};

static TPCANBaudrate bitrateCodeFromBitrate(int bitrate)
{
    static const BitrateItem bitratetable[] = {
        { 5000, PCAN_BAUD_5K },
        { 10000, PCAN_BAUD_10K },
        { 20000, PCAN_BAUD_20K },
        { 33000, PCAN_BAUD_33K },
        { 47000, PCAN_BAUD_47K },
        { 50000, PCAN_BAUD_50K },
        { 83000, PCAN_BAUD_83K },
        { 95000, PCAN_BAUD_95K },
        { 100000, PCAN_BAUD_100K },
        { 125000, PCAN_BAUD_125K },
        { 250000, PCAN_BAUD_250K },
        { 500000, PCAN_BAUD_500K },
        { 800000, PCAN_BAUD_800K },
        { 1000000, PCAN_BAUD_1M }
    };

    static const BitrateItem *endtable = bitratetable + (sizeof(bitratetable) / sizeof(*bitratetable));

    const BitrateItem item = { bitrate , 0 };
    const BitrateItem *where = std::lower_bound(bitratetable, endtable, item, BitrateLessFunctor());
    return where != endtable ? where->code : PCAN_BAUD_INVALID;
}

static QByteArray nominalBitrateString(int nominalBitrate)
{
    switch (nominalBitrate) {
    case 125000:
        return "f_clock=80000000, nom_brp=40, nom_tseg1=12, nom_tseg2=3, nom_sjw=1";
    case 250000:
        return "f_clock=80000000, nom_brp=20, nom_tseg1=12, nom_tseg2=3, nom_sjw=1";
    case 500000:
        return "f_clock=80000000, nom_brp=10, nom_tseg1=12, nom_tseg2=3, nom_sjw=1";
    case 1000000:
        return "f_clock=80000000, nom_brp=10, nom_tseg1=5,  nom_tseg2=2, nom_sjw=1";
    default:
        return QByteArray();
    }
}

static QByteArray dataBitrateString(int dataBitrate)
{
    switch (dataBitrate) {
    case 2000000:
        return ", data_brp=4, data_tseg1=7, data_tseg2=2, data_sjw=1";
    case 4000000:
        return ", data_brp=2, data_tseg1=7, data_tseg2=2, data_sjw=1";
    case 8000000:
        return ", data_brp=1, data_tseg1=7, data_tseg2=2, data_sjw=1";
    case 10000000:
        return ", data_brp=1, data_tseg1=5, data_tseg2=2, data_sjw=1";
    default:
        return QByteArray();
    }
}

static QByteArray bitrateStringFromBitrate(int nominalBitrate, int dataBitrate)
{
    QByteArray result = nominalBitrateString(nominalBitrate);

    if (result.isEmpty())
        return QByteArray();

    result += dataBitrateString(dataBitrate);

    return result;
}

bool PeakCanBackendPrivate::open()
{
    Q_Q(PeakCanBackend);

    const int nominalBitrate = q->configurationParameter(QCanBusDevice::BitRateKey).toInt();
    TPCANStatus st = PCAN_ERROR_OK;

    if (isFlexibleDatarateEnabled) {
        const int dataBitrate = q->configurationParameter(QCanBusDevice::DataBitRateKey).toInt();
        const QByteArray bitrateStr = bitrateStringFromBitrate(nominalBitrate, dataBitrate);
        st = ::CAN_InitializeFD(channelIndex, const_cast<char *>(bitrateStr.data()));
    } else {
        const TPCANBaudrate bitrateCode = bitrateCodeFromBitrate(nominalBitrate);
        st = ::CAN_Initialize(channelIndex, bitrateCode, 0, 0, 0);
    }

    if (Q_UNLIKELY(st != PCAN_ERROR_OK)) {
        const QString errorString = systemErrorString(st);
        qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot initialize hardware: %ls",
                   qUtf16Printable(errorString));
        q->setError(errorString, QCanBusDevice::ConnectionError);
        return false;
    }

#if defined(Q_OS_WIN32)
    if (readHandle == INVALID_HANDLE_VALUE) {
        readHandle = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
        if (Q_UNLIKELY(!readHandle)) {
            const QString errorString = qt_error_string(int(::GetLastError()));
            qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot create receive event handler: %ls",
                       qUtf16Printable(errorString));
            q->setError(errorString, QCanBusDevice::ConnectionError);
            return false;
        }
    }

    const TPCANStatus err = ::CAN_SetValue(channelIndex, PCAN_RECEIVE_EVENT, &readHandle, sizeof(readHandle));
    if (Q_UNLIKELY(err != PCAN_ERROR_OK)) {
        q->setError(systemErrorString(err), QCanBusDevice::ConnectionError);
        return false;
    }

#else
    const TPCANStatus err = ::CAN_GetValue(channelIndex, PCAN_RECEIVE_EVENT, &readHandle, sizeof(readHandle));
    if (Q_UNLIKELY(err != PCAN_ERROR_OK)) {
        const QString errorString = systemErrorString(err);
        qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot create receive event handler: %ls",
                   qUtf16Printable(errorString));
        q->setError(errorString, QCanBusDevice::ConnectionError);
        return false;
    }
#endif

    writeNotifier = new PeakCanWriteNotifier(this, q);
    writeNotifier->setInterval(0);

    readNotifier = new PeakCanReadNotifier(this, q);
    readNotifier->setEnabled(true);

    isOpen = true;
    return true;
}

void PeakCanBackendPrivate::close()
{
    Q_Q(PeakCanBackend);

    delete readNotifier;
    readNotifier = nullptr;

    delete writeNotifier;
    writeNotifier = nullptr;

    quint32 value = 0;
    const TPCANStatus err = ::CAN_SetValue(channelIndex, PCAN_RECEIVE_EVENT, &value, sizeof(value));
    if (Q_UNLIKELY(err != PCAN_ERROR_OK)) {
        const QString errorString = systemErrorString(err);
        qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot unregister receive event handler: %ls",
                   qUtf16Printable(errorString));
        q->setError(errorString, QCanBusDevice::ConnectionError);
    }

    const TPCANStatus st = ::CAN_Uninitialize(channelIndex);
    if (Q_UNLIKELY(st != PCAN_ERROR_OK))
        q->setError(systemErrorString(st), QCanBusDevice::ConnectionError);

#if defined(Q_OS_WIN32)
    if (readHandle && (readHandle != INVALID_HANDLE_VALUE)) {
        const QString errorString = qt_error_string(int(::GetLastError()));
        if (Q_UNLIKELY(!::CloseHandle(readHandle))) {
            qCCritical(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot close read handle: %ls",
                       qUtf16Printable(errorString));
            q->setError(errorString, QCanBusDevice::ConnectionError);
        }
        readHandle = INVALID_HANDLE_VALUE;
    }
#else
    readHandle = -1;
#endif

    isOpen = false;
}

bool PeakCanBackendPrivate::setConfigurationParameter(int key, const QVariant &value)
{
    Q_Q(PeakCanBackend);

    switch (key) {
    case QCanBusDevice::BitRateKey:
        return verifyBitRate(value.toInt());
    case QCanBusDevice::CanFdKey:
        isFlexibleDatarateEnabled = value.toBool();
        return true;
    case QCanBusDevice::DataBitRateKey: {
        const int dataBitrate = value.toInt();
        if (Q_UNLIKELY(dataBitrateString(dataBitrate).isEmpty())) {
            qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Unsupported data bitrate value: %d", dataBitrate);
            q->setError(PeakCanBackend::tr("Unsupported data bitrate value: %1.").arg(dataBitrate),
                        QCanBusDevice::ConfigurationError);
            return false;
        }
        return true;
    }
    default:
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Unsupported configuration key: %d", key);
        q->setError(PeakCanBackend::tr("Unsupported configuration key: %1").arg(key),
                    QCanBusDevice::ConfigurationError);
        return false;
    }
}

void PeakCanBackendPrivate::setupChannel(const QByteArray &interfaceName)
{
    const PcanChannel *chn = pcanChannels;
    while (chn->index != PCAN_NONEBUS && chn->name != interfaceName)
        ++chn;
    channelIndex = chn->index;
}

// Calls only when the device is closed
void PeakCanBackendPrivate::setupDefaultConfigurations()
{
    Q_Q(PeakCanBackend);

    q->setConfigurationParameter(QCanBusDevice::BitRateKey, 500000);
}

QString PeakCanBackendPrivate::systemErrorString(TPCANStatus errorCode)
{
    QByteArray buffer(256, 0);
    if (Q_UNLIKELY(::CAN_GetErrorText(errorCode, 0, buffer.data()) != PCAN_ERROR_OK))
        return PeakCanBackend::tr("Unable to retrieve an error string");
    return QString::fromLatin1(buffer);
}

enum CanFrameDlc {
    Dlc00 =  0,
    Dlc01 =  1,
    Dlc02 =  2,
    Dlc03 =  3,
    Dlc04 =  4,
    Dlc05 =  5,
    Dlc06 =  6,
    Dlc07 =  7,
    Dlc08 =  8,
    Dlc12 =  9,
    Dlc16 = 10,
    Dlc20 = 11,
    Dlc24 = 12,
    Dlc32 = 13,
    Dlc48 = 14,
    Dlc64 = 15
};

static CanFrameDlc sizeToDlc(int size)
{
    switch (size) {
    case 12:
        return Dlc12;
    case 16:
        return Dlc16;
    case 20:
        return Dlc20;
    case 24:
        return Dlc24;
    case 32:
        return Dlc32;
    case 48:
        return Dlc48;
    case 64:
        return Dlc64;
    default:
        if (size >= 0 && size <= 8)
            return static_cast<CanFrameDlc>(size);

        return Dlc00;
    }
}

static int dlcToSize(CanFrameDlc dlc)
{
    switch (dlc) {
    case Dlc00:
    case Dlc01:
    case Dlc02:
    case Dlc03:
    case Dlc04:
    case Dlc05:
    case Dlc06:
    case Dlc07:
    case Dlc08:
        return static_cast<int>(dlc);
    case Dlc12:
        return 12;
    case Dlc16:
        return 16;
    case Dlc20:
        return 20;
    case Dlc24:
        return 24;
    case Dlc32:
        return 32;
    case Dlc48:
        return 48;
    case Dlc64:
        return 64;
    }
    return 0;
}

void PeakCanBackendPrivate::startWrite()
{
    Q_Q(PeakCanBackend);

    if (!q->hasOutgoingFrames()) {
        writeNotifier->stop();
        return;
    }

    const QCanBusFrame frame = q->dequeueOutgoingFrame();
    const QByteArray payload = frame.payload();
    TPCANStatus st = PCAN_ERROR_OK;

    if (isFlexibleDatarateEnabled) {
        const int size = payload.size();
        TPCANMsgFD message = {};
        message.ID = frame.frameId();
        message.DLC = sizeToDlc(size);
        message.MSGTYPE = frame.hasExtendedFrameFormat() ? PCAN_MESSAGE_EXTENDED
                                                         : PCAN_MESSAGE_STANDARD;

        if (frame.hasFlexibleDataRateFormat())
            message.MSGTYPE |= PCAN_MESSAGE_FD;
        if (frame.hasBitrateSwitch())
            message.MSGTYPE |= PCAN_MESSAGE_BRS;

        if (frame.frameType() == QCanBusFrame::RemoteRequestFrame)
            message.MSGTYPE |= PCAN_MESSAGE_RTR; // we do not care about the payload
        else
            ::memcpy(message.DATA, payload.constData(), sizeof(message.DATA));
        st = ::CAN_WriteFD(channelIndex, &message);
    } else if (frame.hasFlexibleDataRateFormat()) {
        const char errorString[] = "Cannot send CAN FD frame format as CAN FD is not enabled.";
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN(), errorString);
        q->setError(PeakCanBackend::tr(errorString), QCanBusDevice::WriteError);
    } else {
        TPCANMsg message = {};
        message.ID = frame.frameId();
        message.LEN = static_cast<quint8>(payload.size());
        message.MSGTYPE = frame.hasExtendedFrameFormat() ? PCAN_MESSAGE_EXTENDED
                                                         : PCAN_MESSAGE_STANDARD;

        if (frame.frameType() == QCanBusFrame::RemoteRequestFrame)
            message.MSGTYPE |= PCAN_MESSAGE_RTR; // we do not care about the payload
        else
            ::memcpy(message.DATA, payload.constData(), sizeof(message.DATA));
        st = ::CAN_Write(channelIndex, &message);
    }

    if (Q_UNLIKELY(st != PCAN_ERROR_OK)) {
        const QString errorString = systemErrorString(st);
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot write frame: %ls",
                  qUtf16Printable(errorString));
        q->setError(errorString, QCanBusDevice::WriteError);
    } else {
        emit q->framesWritten(qint64(1));
    }

    if (q->hasOutgoingFrames() && !writeNotifier->isActive())
        writeNotifier->start();
}

void PeakCanBackendPrivate::startRead()
{
    Q_Q(PeakCanBackend);

    QVector<QCanBusFrame> newFrames;

    for (;;) {
        if (isFlexibleDatarateEnabled) {
            TPCANMsgFD message = {};
            TPCANTimestampFD timestamp = {};

            const TPCANStatus st = ::CAN_ReadFD(channelIndex, &message, &timestamp);
            if (st != PCAN_ERROR_OK) {
                if (Q_UNLIKELY(st != PCAN_ERROR_QRCVEMPTY))
                    q->setError(systemErrorString(st), QCanBusDevice::ReadError);
                break;
            }

            // Filter out PCAN status frames, to avoid turning them
            // into QCanBusFrame::DataFrames with random canId
            if (Q_UNLIKELY(message.MSGTYPE & PCAN_MESSAGE_STATUS))
                continue;

            const int size = dlcToSize(static_cast<CanFrameDlc>(message.DLC));
            QCanBusFrame frame(TPCANLongToFrameID(message.ID),
                               QByteArray(reinterpret_cast<const char *>(message.DATA), size));
            frame.setTimeStamp(QCanBusFrame::TimeStamp::fromMicroSeconds(static_cast<qint64>(timestamp)));
            frame.setExtendedFrameFormat(message.MSGTYPE & PCAN_MESSAGE_EXTENDED);
            frame.setFrameType((message.MSGTYPE & PCAN_MESSAGE_RTR)
                               ? QCanBusFrame::RemoteRequestFrame : QCanBusFrame::DataFrame);
            frame.setFlexibleDataRateFormat(message.MSGTYPE & PCAN_MESSAGE_FD);
            frame.setBitrateSwitch(message.MSGTYPE & PCAN_MESSAGE_BRS);
            frame.setErrorStateIndicator(message.MSGTYPE & PCAN_MESSAGE_ESI);

            newFrames.append(std::move(frame));
        } else {
            TPCANMsg message = {};
            TPCANTimestamp timestamp = {};

            const TPCANStatus st = ::CAN_Read(channelIndex, &message, &timestamp);
            if (st != PCAN_ERROR_OK) {
                if (Q_UNLIKELY(st != PCAN_ERROR_QRCVEMPTY))
                    q->setError(systemErrorString(st), QCanBusDevice::ReadError);
                break;
            }

            // Filter out PCAN status frames, to avoid turning them
            // into QCanBusFrame::DataFrames with random canId
            if (Q_UNLIKELY(message.MSGTYPE & PCAN_MESSAGE_STATUS))
                continue;

            const int size = static_cast<int>(message.LEN);
            QCanBusFrame frame(TPCANLongToFrameID(message.ID),
                               QByteArray(reinterpret_cast<const char *>(message.DATA), size));
            const quint64 millis = timestamp.millis + Q_UINT64_C(0xFFFFFFFF) * timestamp.millis_overflow;
            const quint64 micros = Q_UINT64_C(1000) * millis + timestamp.micros;
            frame.setTimeStamp(QCanBusFrame::TimeStamp::fromMicroSeconds(static_cast<qint64>(micros)));
            frame.setExtendedFrameFormat(message.MSGTYPE & PCAN_MESSAGE_EXTENDED);
            frame.setFrameType((message.MSGTYPE & PCAN_MESSAGE_RTR)
                               ? QCanBusFrame::RemoteRequestFrame : QCanBusFrame::DataFrame);

            newFrames.append(std::move(frame));
        }
    }

    q->enqueueReceivedFrames(newFrames);
}

bool PeakCanBackendPrivate::verifyBitRate(int bitrate)
{
    Q_Q(PeakCanBackend);

    if (Q_UNLIKELY(isOpen)) {
        const char errorString[] = "Cannot change bitrate for already opened device.";
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, errorString);
        q->setError(PeakCanBackend::tr(errorString), QCanBusDevice::ConfigurationError);
        return false;
    }

    bool isValidBitrate = false;
    if (q->configurationParameter(QCanBusDevice::CanFdKey).toBool())
        isValidBitrate = !nominalBitrateString(bitrate).isEmpty();
    else
        isValidBitrate = bitrateCodeFromBitrate(bitrate) != PCAN_BAUD_INVALID;

    if (Q_UNLIKELY(!isValidBitrate)) {
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Unsupported bitrate value: %d.", bitrate);
        q->setError(PeakCanBackend::tr("Unsupported bitrate value: %1.").arg(bitrate),
                    QCanBusDevice::ConfigurationError);
    }

    return isValidBitrate;
}

PeakCanBackend::PeakCanBackend(const QString &name, QObject *parent)
    : QCanBusDevice(parent)
    , d_ptr(new PeakCanBackendPrivate(this))
{
    Q_D(PeakCanBackend);

    d->setupChannel(name.toLatin1());
    d->setupDefaultConfigurations();

    std::function<void()> f = std::bind(&PeakCanBackend::resetController, this);
    setResetControllerFunction(f);

    std::function<CanBusStatus()> g = std::bind(&PeakCanBackend::busStatus, this);
    setCanBusStatusGetter(g);
}

PeakCanBackend::~PeakCanBackend()
{
    Q_D(PeakCanBackend);

    if (d->isOpen)
        close();

    delete d_ptr;
}

bool PeakCanBackend::open()
{
    Q_D(PeakCanBackend);

    if (!d->isOpen) {
        if (Q_UNLIKELY(!d->open()))
            return false;

        // Apply all stored configurations except bitrate, because
        // the bitrate cannot be changed after opening the device
        const auto keys = configurationKeys();
        for (int key : keys) {
            if (key == QCanBusDevice::BitRateKey || key == QCanBusDevice::DataBitRateKey)
                continue;
            const QVariant param = configurationParameter(key);
            const bool success = d->setConfigurationParameter(key, param);
            if (Q_UNLIKELY(!success)) {
                qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Cannot apply parameter: %d with value: %ls.",
                          key, qUtf16Printable(param.toString()));
            }
        }
    }

    setState(QCanBusDevice::ConnectedState);
    return true;
}

void PeakCanBackend::close()
{
    Q_D(PeakCanBackend);

    d->close();

    setState(QCanBusDevice::UnconnectedState);
}

void PeakCanBackend::setConfigurationParameter(int key, const QVariant &value)
{
    Q_D(PeakCanBackend);

    if (d->setConfigurationParameter(key, value))
        QCanBusDevice::setConfigurationParameter(key, value);
}

bool PeakCanBackend::writeFrame(const QCanBusFrame &newData)
{
    Q_D(PeakCanBackend);

    if (Q_UNLIKELY(state() != QCanBusDevice::ConnectedState))
        return false;

    if (Q_UNLIKELY(!newData.isValid())) {
        setError(tr("Cannot write invalid QCanBusFrame"), QCanBusDevice::WriteError);
        return false;
    }

    if (Q_UNLIKELY(newData.frameType() != QCanBusFrame::DataFrame
                   && newData.frameType() != QCanBusFrame::RemoteRequestFrame)) {
        setError(tr("Unable to write a frame with unacceptable type"),
                 QCanBusDevice::WriteError);
        return false;
    }

    enqueueOutgoingFrame(newData);

    if (!d->writeNotifier->isActive())
        d->writeNotifier->start();

    return true;
}

// TODO: Implement me
QString PeakCanBackend::interpretErrorFrame(const QCanBusFrame &errorFrame)
{
    Q_UNUSED(errorFrame);

    return QString();
}

void PeakCanBackend::resetController()
{
    close();
    open();
}

QCanBusDevice::CanBusStatus PeakCanBackend::busStatus() const
{
    const TPCANStatus status = ::CAN_GetStatus(d_ptr->channelIndex);

    switch (status & PCAN_ERROR_ANYBUSERR) {
    case PCAN_ERROR_OK:
        return QCanBusDevice::CanBusStatus::Good;
    case PCAN_ERROR_BUSWARNING:
        return QCanBusDevice::CanBusStatus::Warning;
    case PCAN_ERROR_BUSPASSIVE:
        return QCanBusDevice::CanBusStatus::Error;
    case PCAN_ERROR_BUSOFF:
        return QCanBusDevice::CanBusStatus::BusOff;
    default:
        qCWarning(QT_CANBUS_PLUGINS_PEAKCAN, "Unknown CAN bus status: %lu.", ulong(status));
        return QCanBusDevice::CanBusStatus::Unknown;
    }
}

QT_END_NAMESPACE