summaryrefslogtreecommitdiffstats
path: root/src/plugins/canbus/passthrucan/passthrucanio.cpp
blob: 4482aa1a0eab3e966bc8d6d8af14d75f1f10cd93 (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
// Copyright (C) 2017 Ford Motor Company.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "passthrucanio.h"

#include <QLoggingCategory>
#include <QtEndian>

#include <cstring>

PassThruCanIO::PassThruCanIO(QObject *parent)
    : QObject(parent)
    , m_ioBuffer (8, J2534::Message(J2534::Protocol::CAN))
{
}

PassThruCanIO::~PassThruCanIO()
{
}

void PassThruCanIO::open(const QString &library, const QByteArray &subDev, uint bitRate)
{
    if (Q_UNLIKELY(m_passThru)) {
        qCCritical(QT_CANBUS_PLUGINS_PASSTHRU, "Pass-thru interface already open");
        emit openFinished(false);
        return;
    }
    qCDebug(QT_CANBUS_PLUGINS_PASSTHRU, "Loading interface library: %ls",
            qUtf16Printable(library));

    m_passThru = new J2534::PassThru(library, this);
    J2534::PassThru::Status openStatus = m_passThru->lastError();

    if (openStatus == J2534::PassThru::NoError)
        openStatus = m_passThru->open(subDev, &m_deviceId);

    if (openStatus == J2534::PassThru::NoError
            && m_passThru->connect(m_deviceId, J2534::Protocol::CAN,
                                   J2534::PassThru::CAN29BitID | J2534::PassThru::CANIDBoth,
                                   bitRate, &m_channelId) == J2534::PassThru::NoError) {
        emit openFinished(true);
        return;
    }
    emit errorOccurred(m_passThru->lastErrorString(),
                       QCanBusDevice::ConnectionError);

    if (openStatus == J2534::PassThru::NoError
            && m_passThru->close(m_deviceId) != J2534::PassThru::NoError)
        qCWarning(QT_CANBUS_PLUGINS_PASSTHRU, "Failed to close pass-thru device");

    delete m_passThru;
    m_passThru = nullptr;

    emit openFinished(false);
}

void PassThruCanIO::close()
{
    if (Q_LIKELY(m_passThru)) {
        delete m_idleNotifier;
        m_idleNotifier = nullptr;

        if (m_passThru->disconnect(m_channelId) != J2534::PassThru::NoError
                || m_passThru->close(m_deviceId) != J2534::PassThru::NoError) {

            qCWarning(QT_CANBUS_PLUGINS_PASSTHRU, "Failed to close pass-thru device");
            emit errorOccurred(m_passThru->lastErrorString(),
                               QCanBusDevice::ConnectionError);
        }
        delete m_passThru;
        m_passThru = nullptr;
    }
    emit closeFinished();
}

void PassThruCanIO::applyConfig(QCanBusDevice::ConfigurationKey key, const QVariant &value)
{
    if (Q_UNLIKELY(!m_passThru)) {
        qCCritical(QT_CANBUS_PLUGINS_PASSTHRU, "Pass-thru interface not open");
        return;
    }
    bool success = true;

    switch (key) {
    case QCanBusDevice::RawFilterKey:
        success = setMessageFilters(qvariant_cast<QList<QCanBusDevice::Filter>>(value));
        break;
    case QCanBusDevice::LoopbackKey:
        success = setConfigValue(J2534::Config::Loopback, value.toBool());
        break;
    case QCanBusDevice::BitRateKey:
        success = setConfigValue(J2534::Config::DataRate, value.toUInt());
        break;
    default:
        emit errorOccurred(tr("Unsupported configuration key: %1").arg(key),
                           QCanBusDevice::ConfigurationError);
        break;
    }
    if (!success) {
        emit errorOccurred(tr("Configuration failed: %1").arg(m_passThru->lastErrorString()),
                           QCanBusDevice::ConfigurationError);
    }
}

void PassThruCanIO::listen()
{
    if (Q_UNLIKELY(!m_passThru)) {
        qCCritical(QT_CANBUS_PLUGINS_PASSTHRU, "Pass-thru interface not open");
        return;
    }
    if (Q_UNLIKELY(m_idleNotifier)) {
        qCCritical(QT_CANBUS_PLUGINS_PASSTHRU, "Idle notifier already created");
        return;
    }
    m_idleNotifier = new QTimer(this);
    connect(m_idleNotifier, &QTimer::timeout, this, &PassThruCanIO::pollForMessages);

    m_idleNotifier->start(0);
}

bool PassThruCanIO::enqueueMessage(const QCanBusFrame &frame)
{
    const QMutexLocker lock (&m_writeGuard);
    m_writeQueue.append(frame);
    return true;
}

bool PassThruCanIO::setMessageFilters(const QList<QCanBusDevice::Filter> &filters)
{
    if (m_passThru->clear(m_channelId, J2534::PassThru::MsgFilters) != J2534::PassThru::NoError)
        return false;

    J2534::Message pattern {J2534::Protocol::CAN};
    pattern.setSize(4);
    J2534::Message mask {J2534::Protocol::CAN};
    mask.setSize(4);

    for (const auto &filter : filters) {
        if (filter.type != QCanBusFrame::DataFrame
                && filter.type != QCanBusFrame::InvalidFrame) {
            emit errorOccurred(tr("Configuration failed: unsupported filter type"),
                               QCanBusDevice::ConfigurationError);
            break;
        }
        if (filter.format & QCanBusDevice::Filter::MatchExtendedFormat)
            pattern.setRxStatus(J2534::Message::InCAN29BitID);
        else
            pattern.setRxStatus({});

        if (filter.format != QCanBusDevice::Filter::MatchBaseAndExtendedFormat)
            mask.setRxStatus(J2534::Message::InCAN29BitID);
        else
            mask.setRxStatus({});

        qToBigEndian<QCanBusFrame::FrameId>(filter.frameId & filter.frameIdMask, pattern.data());
        qToBigEndian<QCanBusFrame::FrameId>(filter.frameIdMask, mask.data());

        if (m_passThru->startMsgFilter(m_channelId, J2534::PassThru::PassFilter,
                                       mask, pattern) != J2534::PassThru::NoError)
            return false;
    }
    return true;
}

bool PassThruCanIO::setConfigValue(J2534::Config::Parameter param, ulong value)
{
    const J2534::Config config {param, value};

    return (m_passThru->setConfig(m_channelId, &config) == J2534::PassThru::NoError);
}

void PassThruCanIO::pollForMessages()
{
    if (Q_UNLIKELY(!m_passThru)) {
        qCCritical(QT_CANBUS_PLUGINS_PASSTHRU, "Pass-thru interface not open");
        return;
    }
    const bool writePending = writeMessages();
    readMessages(writePending);
}

bool PassThruCanIO::writeMessages()
{
    ulong numMsgs = m_ioBuffer.size();
    {
        const QMutexLocker lock (&m_writeGuard);
        numMsgs = qMin<ulong>(m_writeQueue.size(), numMsgs);

        for (ulong i = 0; i < numMsgs; ++i) {
            const QCanBusFrame &frame = m_writeQueue.at(i);
            J2534::Message &msg = m_ioBuffer[i];

            const QByteArray payload = frame.payload();
            const ulong payloadSize = qMin<ulong>(payload.size(),
                                                  J2534::Message::maxSize - 4);
            msg.setRxStatus({});
            msg.setTimestamp(0);
            msg.setSize(4 + payloadSize);
            msg.setExtraDataIndex(0);

            if (frame.hasExtendedFrameFormat())
                msg.setTxFlags(J2534::Message::OutCAN29BitID);
            else
                msg.setTxFlags({});

            qToBigEndian<QCanBusFrame::FrameId>(frame.frameId(), msg.data());
            std::memcpy(msg.data() + 4, payload.data(), payloadSize);
        }
    }
    if (numMsgs == 0)
        return false;

    const auto status = m_passThru->writeMsgs(m_channelId, m_ioBuffer.constData(),
                                              &numMsgs, pollTimeout);
    if (status == J2534::PassThru::BufferFull)
        return false;

    if (status != J2534::PassThru::NoError && status != J2534::PassThru::Timeout) {
        emit errorOccurred(tr("Message write failed: %1").arg(m_passThru->lastErrorString()),
                           QCanBusDevice::WriteError);
        return false;
    }
    if (numMsgs == 0)
        return false;

    bool morePending;
    {
        const QMutexLocker lock (&m_writeGuard);
        // De-queue successfully written frames.
        m_writeQueue.erase(m_writeQueue.begin(), m_writeQueue.begin() + numMsgs);
        morePending = !m_writeQueue.isEmpty();
    }
    emit messagesSent(numMsgs);

    return morePending;
}

void PassThruCanIO::readMessages(bool writePending)
{
    // If there are outgoing messages waiting to be written, just check
    // for already received messages but do not block waiting for more.
    const uint timeout = (writePending) ? 0 : pollTimeout;

    ulong numMsgs = m_ioBuffer.size();
    const auto status = m_passThru->readMsgs(m_channelId, m_ioBuffer.data(),
                                             &numMsgs, timeout);
    if (status == J2534::PassThru::BufferEmpty)
        return;

    if (status != J2534::PassThru::NoError && status != J2534::PassThru::Timeout) {
        emit errorOccurred(tr("Message read failed: %1").arg(m_passThru->lastErrorString()),
                           QCanBusDevice::ReadError);
        if (status != J2534::PassThru::BufferOverflow)
            return;
    }
    const int numFrames = qMin<ulong>(m_ioBuffer.size(), numMsgs);
    QList<QCanBusFrame> frames;
    frames.reserve(numFrames);

    for (int i = 0; i < numFrames; ++i) {
        const J2534::Message &msg = m_ioBuffer.at(i);
        if (Q_UNLIKELY(msg.size() < 4)
                || Q_UNLIKELY(msg.size() > J2534::Message::maxSize)) {
            // This normally shouldn't happen, so a log message is appropriate.
            qCWarning(QT_CANBUS_PLUGINS_PASSTHRU,
                      "Message with invalid size %lu received", msg.size());
            continue;
        }
        const QCanBusFrame::FrameId msgId = qFromBigEndian<QCanBusFrame::FrameId>(msg.data());
        const QByteArray payload (msg.data() + 4, msg.size() - 4);

        QCanBusFrame frame (msgId, payload);
        frame.setExtendedFrameFormat((msg.rxStatus() & J2534::Message::InCAN29BitID) != 0);
        frame.setLocalEcho((msg.rxStatus() & J2534::Message::InTxMsgType) != 0);
        frame.setTimeStamp(QCanBusFrame::TimeStamp::fromMicroSeconds(msg.timestamp()));

        frames.append(std::move(frame));
    }
    if (!frames.isEmpty())
        emit messagesReceived(std::move(frames));
}