File: socketcand.cpp

package info (click to toggle)
savvycan 220-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,456 kB
  • sloc: cpp: 61,803; sh: 293; javascript: 91; python: 44; makefile: 8
file content (453 lines) | stat: -rw-r--r-- 13,962 bytes parent folder | download
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
#include <QObject>
#include <QDebug>
#include <QCanBusFrame>
#include <QSerialPortInfo>
#include <QSettings>
#include <QStringBuilder>
#include <QtNetwork>
#include <QMetaObject>

#include "socketcand.h"

SocketCANd::SocketCANd(QString portName) :
    CANConnection(portName, "kayak", CANCon::KAYAK, 0, 0, false, 0, 1, 4000, true),
    mTimer(this) /*NB: set this as parent of timer to manage it from working thread */
{

    mTimer.setInterval(2000); //tick every 2 seconds
    mTimer.setSingleShot(false); //keep ticking
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(checkConnection()));

    sendDebug("SocketCANd()");
    hostCanIDs = portName.left(portName.indexOf("@")).split(',');
    QString hostIPandPort = portName.mid(portName.indexOf("can://")+6, portName.length() - portName.indexOf("can://") - 6); //6 is lenght of 'can://'
    hostIP = QHostAddress(hostIPandPort.left(hostIPandPort.indexOf(":")));
    hostPort = (hostIPandPort.right(hostIPandPort.length() - hostIPandPort.lastIndexOf(":") -1)).toInt();
    mNumBuses = hostCanIDs.length();
    mBusData.resize(mNumBuses);

    // initial nullptr clients
    tcpClient = QVarLengthArray<QTcpSocket*>(mNumBuses, nullptr);

    reconnecting = false;
    setStatus(CANCon::NOT_CONNECTED);
    CANConStatus stats;
    stats.conStatus = getStatus();
    stats.numHardwareBuses = mNumBuses;
    emit status(stats);

    for (int i = 0; i < mNumBuses; i++)
    {
        rx_state.append(IDLE);
        unprocessedData.append("");
        CANBus bus_info;

        bus_info.setActive(true);
        bus_info.setListenOnly(false);
        bus_info.setSpeed(500000);
        setBusConfig(i, bus_info);
    }
}


SocketCANd::~SocketCANd()
{
    stop();
    for (int i = 0; i < tcpClient.length(); i++)
    {
        if (tcpClient[i])
        {
            if (tcpClient[i]->isOpen())
            {
                tcpClient[i]->close();
            }
            tcpClient[i]->disconnect();
            delete tcpClient[i];
            tcpClient[i] = nullptr;
        }
    }
    tcpClient.clear();
    sendDebug("~SocketCANd()");
}

void SocketCANd::sendDebug(const QString debugText)
{
    qDebug() << debugText;
    debugOutput(debugText);
}

void SocketCANd::sendBytesToTCP(const QByteArray &bytes, int busNum)
{
    if (tcpClient[busNum] && !tcpClient[busNum]->isOpen())
    {
        sendDebug("Attempt to write to TCP/IP port when it is not open!");
        return;
    }

    QString buildDebug;
    buildDebug = "Send data to " + hostIP.toString() + ":" + QString::number(hostPort) + " -> ";
    foreach (int byt, bytes) {
        byt = (unsigned char)byt;
        buildDebug = buildDebug % QString::number(byt, 16) % " ";
    }
    //sendDebug(buildDebug);

    if (tcpClient[busNum]) tcpClient[busNum]->write(bytes);
}

void SocketCANd::sendStringToTCP(const char* data, int busNum)
{
    if (tcpClient[busNum] && !tcpClient[busNum]->isOpen())
    {
        sendDebug("Attempt to write to TCP/IP port when it is not open!");
        return;
    }

    //QString buildDebug;
    //buildDebug = "Send data to " + hostIP.toString() + ":" + QString::number(hostPort) + " -> " + data;
    //sendDebug(buildDebug);
    //qInfo() << buildDebug;

    if (tcpClient[busNum]) tcpClient[busNum]->write(data);
}

void SocketCANd::piStarted()
{
    connectDevice();
    checkConnection();
    mTimer.start();
}


void SocketCANd::piSuspend(bool pSuspend)
{
    /* update capSuspended */
    setCapSuspended(pSuspend);

    /* flush queue if we are suspended */
    if(isCapSuspended())
        getQueue().flush();
}


void SocketCANd::piStop()
{
    mTimer.stop();
    disconnectDevice();
}


bool SocketCANd::piGetBusSettings(int pBusIdx, CANBus& pBus)
{
    return getBusConfig(pBusIdx, pBus);
}


void SocketCANd::piSetBusSettings(int pBusIdx, CANBus bus)
{
    setBusConfig(pBusIdx, bus);
    bus.setSpeed(250000);
}


bool SocketCANd::piSendFrame(const CANFrame& frame)
{
    QByteArray buffer;
    int c;
    int ID;

//    //calculate bus number offset (in case of multiple connections)
//    //useless since SavvyCAN already delivers the right index in frame.bus
//    QList<CANConnection*> connList = CANConManager::getInstance()->getConnections();
//    int currentConnPos = connList.indexOf(this);
//    int busOffset = 0;
//    for (int i = 0; i < currentConnPos; i++)
//    {
//        busOffset += connList[i]->getNumBuses();
//    }
//    int busNum = frame.bus - busOffset;

    int busNum = frame.bus;

    framesRapid++;

    if (tcpClient[busNum] && !tcpClient[busNum]->isOpen()) return false;
    // rx not ready
    if(rx_state[busNum] != RAWMODE) return false;

    // Doesn't make sense to send an error frame
    // to an adapter
    if (frame.frameId() & 0x20000000) {
        return true;
    }
    ID = frame.frameId();
    if (frame.hasExtendedFrameFormat()) ID |= 1 << 31;

    QString sendStr = "< send " + QString::number(ID, 16) + " " + QString::number(frame.payload().length()) + " ";
    for (c = 0; c < frame.payload().length(); c++)
    {
       sendStr.append(QString::number(frame.payload()[c], 16) + " ");
    }
    sendStr.append(">");
    std::string str = sendStr.toStdString();
    const char* sendCmd = str.c_str();
    sendStringToTCP(sendCmd, busNum);

    return true;
}



/****************************************************************/

void SocketCANd::connectDevice()
{
    for (int i = 0; i < tcpClient.length(); i++)
    {
        if (tcpClient[i])
        {
            if(tcpClient[i]->state() == QAbstractSocket::ConnectedState || tcpClient[i]->state() == QAbstractSocket::ConnectingState)
                continue;

            if (tcpClient[i]->isOpen())
            {
                tcpClient[i]->close();
            }
            tcpClient[i]->disconnect();
            delete tcpClient[i];
            tcpClient[i] = nullptr;
        }
        rx_state[i] = IDLE;
        tcpClient[i] = new QTcpSocket();
        tcpClient[i]->connectToHost(hostIP, hostPort);
        connect(tcpClient[i], SIGNAL(readyRead()), this, SLOT(invokeReadTCPData()));
        sendDebug("Created TCP Socket to Kayak device " + hostCanIDs.at(i) + ", host: " + hostIP.toString() + ":" + QString::number(hostPort));
    }
}

void SocketCANd::deviceConnected(int busNum)
{
    sendDebug("Opening CAN on Kayak Device!");
    QString openCanCmd("< open " % hostCanIDs[busNum] % " >");
    sendStringToTCP(openCanCmd.toUtf8().data(), busNum);

    QCoreApplication::processEvents();
}

void SocketCANd::checkConnection()
{
    bool connected = tcpClient.length() > 0;
    for (int i = 0; i < tcpClient.length(); i++)
    {
        connected &= tcpClient[i] && tcpClient[i]->state() == QAbstractSocket::ConnectedState;
    }

    if (!connected)
    {
        reconnecting = true;
        setStatus(CANCon::NOT_CONNECTED);
        connectDevice();
        sendDebug("Reconnecting to TCP Host " + hostIP.toString() + ":" + QString::number(hostPort));
    } else {
        setStatus(CANCon::CONNECTED);
        if (reconnecting) {
            CANConStatus stats;
            stats.conStatus = getStatus();
            stats.numHardwareBuses = mNumBuses;
            emit status(stats);
        }
        reconnecting = false;
    }
}

void SocketCANd::switchToRawMode(int busNum)
{
    sendDebug("Switching to rawmode...");
    const char* rawmodeCmd = "< rawmode >";
    sendStringToTCP(rawmodeCmd, busNum);
    QCoreApplication::processEvents();
}

QString SocketCANd::decodeFrames(QString data, int busNum)
{
    if (data.indexOf("<") == -1)
        return "";
    else if(data.length() >= 8 && data.indexOf("< frame ") == -1)
        return "";

    int firstIndex = data.indexOf("< frame ");
    if(firstIndex > 0)
    {
        QString framePartial = data.left(firstIndex);
        qDebug() << "Received datagramm that starts with fragment (missing '< frame'), this should only occur on startup, removing...: " << framePartial;
    }
    QString framePart = data.mid(firstIndex); //remove starting beginning of payload if not < frame >
    const QString frameStrConst = framePart.left(framePart.indexOf(">")+1);
    QString frameStr = frameStrConst;
    QStringList frameParsed = (frameStr.remove(QRegularExpression("^<")).remove(QRegularExpression(">$"))).simplified().split(' ');

    if(frameParsed.length() < 3)
    {
        //qDebug() << "Received datagramm is an incomplete frame: " << data;

        //ok great, need to leave it in the buffer in case it can be combined with what comes next
        //but if there was a fragment that did not have a starting token then we don't want it so only return
        //known good data...again this should only happen on startup, but just in case we need to remove it
        //so the data buffer doesn't grow uncontrolled.
        return framePart;
    }

    buildFrame.setFrameId(frameParsed[1].toUInt(nullptr, 16));
    buildFrame.bus = busNum;

    if (buildFrame.frameId() > 0x7FF) buildFrame.setExtendedFrameFormat(true);
    else buildFrame.setExtendedFrameFormat(false);

    buildFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, frameParsed[2].toDouble() * 1000000l));
    //buildFrame.len =  frameParsed[3].length() * 0.5;

    int framelength = 0;

    if(frameParsed.length() == 4)
    {
        framelength = frameParsed[3].length() * 0.5;
    }

    QByteArray buildData;
    buildData.resize(framelength);

    int c;
    for (c = 0; c < framelength; c++)
    {
        bool ok;
        unsigned char byteVal = frameParsed[3].mid(c*2, 2).toUInt(&ok, 16);
        buildData[c] = byteVal;
    }
    buildFrame.setPayload(buildData);
//        buildFrame.isReceived = true;

    if (!isCapSuspended())
    {
        /* get frame from queue */
        CANFrame* frame_p = getQueue().get();
        if(frame_p) {
            /* copy frame */
            *frame_p = buildFrame;
            //frame_p->remote = false;
            frame_p->setFrameType(QCanBusFrame::DataFrame);
            checkTargettedFrame(buildFrame);
            /* enqueue frame */
            getQueue().queue();
        }
    }
    //else
    //    qDebug() << "can't get a frame, capture suspended";

    //take out the data that we just processed and anything that is in front of it
    //this should keep broken frames from accumulating at in the data buffer
    if (framePart.length() > frameStrConst.length())
    {
        return decodeFrames(framePart.right(framePart.length() - frameStrConst.length()), busNum);
    }

    return "";
}

void SocketCANd::disconnectDevice() {
    for (int i = 0; i < tcpClient.length(); i++)
    {
        if (tcpClient[i])
        {
            if (tcpClient[i]->isOpen())
            {
                tcpClient[i]->close();
            }
            tcpClient[i]->disconnect();
            delete tcpClient[i];
            tcpClient[i] = nullptr;
        }
    }

    setStatus(CANCon::NOT_CONNECTED);
    CANConStatus stats;
    stats.conStatus = getStatus();
    stats.numHardwareBuses = mNumBuses;
    emit status(stats);
}

void SocketCANd::invokeReadTCPData()
{
    QTcpSocket* signalSender = qobject_cast<QTcpSocket*>(QObject::sender());
    int busNum = tcpClient.indexOf(signalSender);
    QMetaObject::invokeMethod(this, "readTCPData", Qt::QueuedConnection, Q_ARG(int, busNum));
}

void SocketCANd::readTCPData(int busNum)
{
    QString data;

    if (QTcpSocket* socket = tcpClient.value(busNum))
        data = QString(socket->readAll());
    //sendDebug("Got data from TCP. Len = " % QString::number(data.length()));
    //qDebug() << "Received datagramm: " << data;
    procRXData(data, busNum);
}

void SocketCANd::procRXData(QString data, int busNum)
{
    switch (rx_state.at(busNum))
    {
    case IDLE:
        qDebug() << "Received datagramm: " << data;
        if (data == "< hi >")
        {
            deviceConnected(busNum);
            rx_state[busNum] = BCM;
        }
        else qInfo() << hostCanIDs[busNum] << ": Could not open bus. Host did not greet with ""< hi >"": " << data;
        break;
    case BCM:
        qDebug() << "Received datagramm: " << data;
        if (data == "< ok >")
        {
            switchToRawMode(busNum);
            rx_state[busNum] = SWITCHING2RAW;
            unprocessedData[busNum].clear();
        }
        else qInfo() << hostCanIDs[busNum] << ": Could not open bus. Host did not respond with ""< ok >"": " << data;
        break;
    case SWITCHING2RAW:
        qDebug() << "Received datagramm: " << data;
        if (data == "< ok >")
        {
            rx_state[busNum] = RAWMODE;
        }
        else if(data.indexOf("< ok >", 0, Qt::CaseSensitivity::CaseInsensitive) == 0)
        {
            qDebug() << "Ok found at start of compound message, switching to RAW and decoding immediately";
            rx_state[busNum] = RAWMODE;
            unprocessedData[busNum] = decodeFrames(data, busNum);
        }
        else if(data.indexOf("< ok >", 0, Qt::CaseSensitivity::CaseInsensitive) > 0)
        {
            qDebug() << "Ok found at in middle of compound message, switching to RAW and decoding immediately";
            rx_state[busNum] = RAWMODE;
            unprocessedData[busNum] = decodeFrames(data, busNum);
        }
        break;
    case RAWMODE:
        unprocessedData[busNum] = decodeFrames(unprocessedData[busNum] + data, busNum);

        if(unprocessedData[busNum].length() > 128)
        {
            //the buffer has grown too much we need to clear it out, but what is good logic for that?
            //the decodeFrames function strips out datat that doesn't have a '< frame' starting token, and in its
            //recursive calling of itself it strips out data that preceedes valid frames, so this should never happen
            qDebug() << "busNum: " << busNum << "- " << unprocessedData[busNum].length() << " bytes in unprocessedData, something is wrong, clearing...";
            unprocessedData[busNum].clear();
        }
        break;
    case ISOTP:
        break;
    }
}