diff --git a/.travis.yml b/.travis.yml index 6923721..7f6721a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,8 @@ language: cpp -# Any time a commit is done to either master or WIP we do a CI build on all three platforms to make sure it really builds. The linux version will be saved to the continuous tag -# and thus available for testing. All three platforms will get a proper release upon a tagged commit. +# Any time a commit is done to either master or WIP we do a CI build on all three platforms to make +# sure it really builds. The linux version will be saved to the continuous tag and thus available +# for testing. All three platforms will get a proper release upon a tagged commit. matrix: include: @@ -10,11 +11,11 @@ matrix: compiler: gcc sudo: require before_install: - - sudo add-apt-repository ppa:beineri/opt-qt-5.12.3-xenial -y + - sudo add-apt-repository ppa:beineri/opt-qt-5.14.1-xenial -y - sudo apt-get update -qq install: - - sudo apt-get -y install qt512base qt512connectivity qt512imageformats qt512serialport qt512serialbus qt512doc qt512tools libgl1-mesa-dev + - sudo apt-get -y install qt514base qt514connectivity qt514imageformats qt514serialport qt514serialbus qt514doc qt514tools libgl1-mesa-dev - source /opt/qt*/bin/qt*-env.sh script: @@ -42,56 +43,27 @@ matrix: tags: true #deploy is only done on tagged builds draft: false - - os: osx - osx_image: xcode10 - before_install: - - brew install qt5 - - brew link qt5 --force - script: - - qmake CONFIG+=release -spec macx-xcode SavvyCAN.pro - - xcodebuild - - mkdir Release/SavvyCAN.app/Contents/MacOS/help - - cp -R help/*.* Release/SavvyCAN.app/Contents/MacOS/help - - cd Release - - ls SavvyCAN.app/Contents/MacOS - - macdeployqt SavvyCAN.app -dmg - deploy: - provider: releases - skip_cleanup: true - api_key: $GITHUB_TOKEN - file: SavvyCAN.dmg - on: - tags: true - draft: false - - - os: windows - before_install: - - cmd.exe /C 'cd && "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build/vcvars32.bat"' - - choco install zip - - curl -vLO http://download.qt.io/official_releases/online_installers/qt-unified-windows-x86-online.exe - - "./qt-unified-windows-x86-online.exe --verbose --script qt-installer-windows.qs" - script: - - cmd.exe /C 'cd && "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build/vcvars32.bat" && cd && "C:/Qt/5.12.3/msvc2017/bin/qmake" CONFIG+=RELEASE SavvyCAN.pro && cd && nmake' - - ls - - cmd.exe /C 'cd release && "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build/vcvars32.bat" && "C:/Qt/5.12.3/msvc2017/bin/windeployqt.exe" ./SavvyCAN.exe' - - cd release - - ls - - rm *.cpp - - rm *.h - - rm *.obj - - mkdir help - - cp -R ../help/*.* ./help - - cp -r ../examples . - - 7z a -tzip SavvyCAN32.zip -r * - - deploy: - provider: releases - skip_cleanup: true - api_key: $GITHUB_TOKEN - file: SavvyCAN32.zip - on: - tags: true - draft: false +# - os: osx +# osx_image: xcode10 +# before_install: +# - brew install qt5 +# - brew link qt5 --force +# script: +# - qmake CONFIG+=release -spec macx-xcode SavvyCAN.pro +# - xcodebuild +# - mkdir Release/SavvyCAN.app/Contents/MacOS/help +# - cp -R help/*.* Release/SavvyCAN.app/Contents/MacOS/help +# - cd Release +# - ls SavvyCAN.app/Contents/MacOS +# - macdeployqt SavvyCAN.app -dmg +# deploy: +# provider: releases +# skip_cleanup: true +# api_key: $GITHUB_TOKEN +# file: SavvyCAN.dmg +# on: +# tags: true +# draft: false branches: except: diff --git a/README.md b/README.md index 9040884..4566633 100644 --- a/README.md +++ b/README.md @@ -97,3 +97,18 @@ when you installed Qt. ### What to do if `qmake` fails with error `Project ERROR: Unknown module(s) in QT: qml serialbus help` on Ubuntu? : `sudo apt install libqt5serialbus5-dev qtdeclarative5-dev qttools5-dev` + +### Used Items Requiring Attribution + +nodes by Adrien Coquet from the Noun Project + +message by Vectorstall from the Noun Project + +signal by shashank singh from the Noun Project + +signal by juli from the Noun Project + +signal by yudi from the Noun Project + +Death by Adrien Coquet from the Noun Project + diff --git a/SavvyCAN.pro b/SavvyCAN.pro index 605b90b..d52b170 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -4,11 +4,12 @@ # #------------------------------------------------- -QT = core gui printsupport qml serialbus serialport widgets help +QT = core gui printsupport qml serialbus serialport widgets help network CONFIG(release, debug|release):DEFINES += QT_NO_DEBUG_OUTPUT CONFIG += c++11 +CONFIG += NO_UNIT_TESTS DEFINES += QCUSTOMPLOT_USE_OPENGL @@ -16,8 +17,23 @@ TARGET = SavvyCAN TEMPLATE = app SOURCES += main.cpp\ + connections/mqtt_bus.cpp \ + mqtt/qmqtt_client.cpp \ + mqtt/qmqtt_client_p.cpp \ + mqtt/qmqtt_frame.cpp \ + mqtt/qmqtt_message.cpp \ + mqtt/qmqtt_network.cpp \ + mqtt/qmqtt_router.cpp \ + mqtt/qmqtt_routesubscription.cpp \ + mqtt/qmqtt_socket.cpp \ + mqtt/qmqtt_ssl_socket.cpp \ + mqtt/qmqtt_timer.cpp \ + mqtt/qmqtt_websocket.cpp \ + mqtt/qmqtt_websocketiodevice.cpp \ + re/dbccomparatorwindow.cpp \ mainwindow.cpp \ canframemodel.cpp \ + simplecrypt.cpp \ utility.cpp \ qcustomplot.cpp \ frameplaybackwindow.cpp \ @@ -39,10 +55,12 @@ SOURCES += main.cpp\ re/sniffer/snifferitem.cpp \ re/sniffer/sniffermodel.cpp \ re/sniffer/snifferwindow.cpp \ + dbc/dbcmessageeditor.cpp \ dbc/dbc_classes.cpp \ dbc/dbchandler.cpp \ dbc/dbcloadsavewindow.cpp \ dbc/dbcmaineditor.cpp \ + dbc/dbcnodeeditor.cpp \ dbc/dbcsignaleditor.cpp \ re/discretestatewindow.cpp \ re/filecomparatorwindow.cpp \ @@ -73,7 +91,29 @@ SOURCES += main.cpp\ HEADERS += mainwindow.h \ can_structs.h \ - canframemodel.h \ + canframemodel.h \ \ + connections/mqtt_bus.h \ + mqtt/qmqtt.h \ + mqtt/qmqtt_client.h \ + mqtt/qmqtt_client_p.h \ + mqtt/qmqtt_frame.h \ + mqtt/qmqtt_global.h \ + mqtt/qmqtt_message.h \ + mqtt/qmqtt_message_p.h \ + mqtt/qmqtt_network_p.h \ + mqtt/qmqtt_networkinterface.h \ + mqtt/qmqtt_routedmessage.h \ + mqtt/qmqtt_router.h \ + mqtt/qmqtt_routesubscription.h \ + mqtt/qmqtt_socket_p.h \ + mqtt/qmqtt_socketinterface.h \ + mqtt/qmqtt_ssl_socket_p.h \ + mqtt/qmqtt_timer_p.h \ + mqtt/qmqtt_timerinterface.h \ + mqtt/qmqtt_websocket_p.h \ + mqtt/qmqtt_websocketiodevice_p.h \ + re/dbccomparatorwindow.h \ + simplecrypt.h \ utility.h \ qcustomplot.h \ frameplaybackwindow.h \ @@ -103,6 +143,8 @@ HEADERS += mainwindow.h \ dbc/dbcloadsavewindow.h \ dbc/dbcmaineditor.h \ dbc/dbcsignaleditor.h \ + dbc/dbcmessageeditor.h \ + dbc/dbcnodeeditor.h \ re/discretestatewindow.h \ re/filecomparatorwindow.h \ re/flowviewwindow.h \ @@ -132,10 +174,13 @@ HEADERS += mainwindow.h \ filterutility.h FORMS += ui/candatagrid.ui \ + ui/dbccomparatorwindow.ui \ + ui/dbcmessageeditor.ui \ ui/connectionwindow.ui \ ui/dbcloadsavewindow.ui \ ui/dbcmaineditor.ui \ ui/dbcsignaleditor.ui \ + ui/dbcnodeeditor.ui \ ui/discretestatewindow.ui \ ui/filecomparatorwindow.ui \ ui/firmwareuploaderwindow.ui \ diff --git a/bisectwindow.cpp b/bisectwindow.cpp index 22d3e78..d86fc3c 100644 --- a/bisectwindow.cpp +++ b/bisectwindow.cpp @@ -64,9 +64,12 @@ bool BisectWindow::eventFilter(QObject *obj, QEvent *event) void BisectWindow::refreshIDList() { int id; + foundID.clear(); + ui->cbIDLower->clear(); + ui->cbIDUpper->clear(); for (int i = 0; i < modelFrames->count(); i++) { - id = modelFrames->at(i).ID; + id = modelFrames->at(i).frameId(); if (!foundID.contains(id)) { foundID.append(id); @@ -129,7 +132,7 @@ void BisectWindow::handleCalculateButton() uint32_t upperID = Utility::ParseStringToNum2(ui->cbIDUpper->currentText()); for (int i = 0; i < modelFrames->count(); i++) { - if (modelFrames->at(i).ID >= lowerID && modelFrames->at(i).ID <= upperID) splitFrames.append(modelFrames->at(i)); + if (modelFrames->at(i).frameId() >= lowerID && modelFrames->at(i).frameId() <= upperID) splitFrames.append(modelFrames->at(i)); } } refreshFrameNumbers(); @@ -137,7 +140,12 @@ void BisectWindow::handleCalculateButton() void BisectWindow::handleReplaceButton() { - + CANFrameModel *model; + model = MainWindow::getReference()->getCANFrameModel(); + model->clearFrames(); + model->insertFrames(splitFrames); + refreshFrameNumbers(); + refreshIDList(); } void BisectWindow::handleSaveButton() diff --git a/blfhandler.cpp b/blfhandler.cpp index 7dde7b3..b0a845a 100644 --- a/blfhandler.cpp +++ b/blfhandler.cpp @@ -67,7 +67,7 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) qDebug() << "Container is not compressed"; uncompressedData = fileData; } - if (objHeader.containerObj.compressionMethod == BLF_CONT_ZLIB_COMPRESSION) + else if (objHeader.containerObj.compressionMethod == BLF_CONT_ZLIB_COMPRESSION) { qDebug() << "Compressed container. Unpacking it."; fileData.prepend(objHeader.containerObj.uncompressedSize & 0xFF); @@ -76,9 +76,14 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) fileData.prepend((objHeader.containerObj.uncompressedSize >> 24) & 0xFF); uncompressedData += qUncompress(fileData); } + else + { + qDebug() << "Dunno what this is... " << objHeader.containerObj.compressionMethod; + } qDebug() << "Uncompressed size: " << uncompressedData.count(); + qDebug() << "Currently loaded frames at this point: " << frames->count(); pos = 0; - bool foundHeader = false; + //bool foundHeader = false; //first skip forward to find a header signature - usually not necessary while ( (int)(pos + sizeof(BLF_OBJ_HEADER)) < uncompressedData.count()) { @@ -91,7 +96,8 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) { memcpy(&obj.header.base, (uncompressedData.constData() + pos), sizeof(BLF_OBJ_HEADER_BASE)); memcpy(&obj.header.v1Obj, (uncompressedData.constData() + pos) + sizeof(BLF_OBJ_HEADER_BASE), sizeof(BLF_OBJ_HEADER_V1)); - qDebug() << "Pos: " << pos << " Type: " << obj.header.base.objType << "Obj Size: " << obj.header.base.objSize; + //if (obj.header.base.objType != 1) + //qDebug() << "Pos: " << pos << " Type: " << obj.header.base.objType << "Obj Size: " << obj.header.base.objSize; if (qFromLittleEndian(objHeader.base.sig) == 0x4A424F4C) { fileData = uncompressedData.mid(pos + sizeof(BLF_OBJ_HEADER_BASE) + sizeof(BLF_OBJ_HEADER_V1), obj.header.base.objSize - sizeof(BLF_OBJ_HEADER_BASE) - sizeof(BLF_OBJ_HEADER_V1)); @@ -100,19 +106,20 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) memcpy(&canObject, fileData.constData(), sizeof(BLF_CAN_OBJ)); CANFrame frame; frame.bus = canObject.channel; - frame.extended = (canObject.id & 0x80000000ull)?true:false; - frame.ID = canObject.id & 0x1FFFFFFFull; + frame.setExtendedFrameFormat((canObject.id & 0x80000000ull)?true:false); + frame.setFrameId(canObject.id & 0x1FFFFFFFull); frame.isReceived = true; - frame.len = canObject.dlc; + QByteArray bytes(canObject.dlc, 0); if (canObject.flags & BLF_REMOTE_FLAG) { - frame.remote = true; + frame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - frame.remote = false; - for (int i = 0; i < 8; i++) frame.data[i] = canObject.data[i]; + frame.setFrameType(QCanBusFrame::DataFrame); + for (int i = 0; i < canObject.dlc; i++) bytes[i] = canObject.data[i]; } + frame.setPayload(bytes); //Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds? - frame.timestamp = obj.header.v1Obj.uncompSize / 1000.0; //uncompsize field also used for timestamp oddly enough + frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough frames->append(frame); } else if (obj.header.base.objType == BLF_CAN_MSG2) @@ -120,24 +127,24 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) memcpy(&canObject2, fileData.constData(), sizeof(BLF_CAN_OBJ2)); CANFrame frame; frame.bus = canObject2.channel; - frame.extended = (canObject2.id & 0x80000000ull)?true:false; - frame.ID = canObject2.id & 0x1FFFFFFFull; + frame.setExtendedFrameFormat((canObject2.id & 0x80000000ull)?true:false); + frame.setFrameId(canObject2.id & 0x1FFFFFFFull); frame.isReceived = true; - frame.len = canObject2.dlc; + QByteArray bytes(canObject2.dlc, 0); if (canObject2.flags & BLF_REMOTE_FLAG) { - frame.remote = true; + frame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - frame.remote = false; - for (int i = 0; i < 8; i++) frame.data[i] = canObject2.data[i]; + frame.setFrameType(QCanBusFrame::DataFrame); + for (int i = 0; i < canObject2.dlc; i++) bytes[i] = canObject2.data[i]; } //Should we divide by a thousand or a million? Unsure here. It appears some logs are stamped in microseconds and some in milliseconds? - frame.timestamp = obj.header.v1Obj.uncompSize / 1000.0; //uncompsize field also used for timestamp oddly enough + frame.setTimeStamp(QCanBusFrame::TimeStamp(0, obj.header.v1Obj.uncompSize / 1000.0)); //uncompsize field also used for timestamp oddly enough frames->append(frame); } else { - //qDebug() << "Not a can frame! ObjType: " << obj.header.objType; + qDebug() << "Not a can frame! ObjType: " << obj.header.base.objType; if (obj.header.base.objType > 0xFFFF) return false; } @@ -162,5 +169,7 @@ bool BLFHandler::loadBLF(QString filename, QVector* frames) bool BLFHandler::saveBLF(QString filename, QVector *frames) { + Q_UNUSED(filename) + Q_UNUSED(frames) return false; } diff --git a/bus_protocols/isotp_handler.cpp b/bus_protocols/isotp_handler.cpp index db05824..553bd91 100644 --- a/bus_protocols/isotp_handler.cpp +++ b/bus_protocols/isotp_handler.cpp @@ -7,6 +7,7 @@ ISOTP_HANDLER::ISOTP_HANDLER() isReceiving = false; issueFlowMsgs = false; processAll = false; + sendPartialMessages = false; lastSenderBus = 0; lastSenderID = 0; @@ -47,10 +48,10 @@ void ISOTP_HANDLER::setReception(bool mode) } } -void ISOTP_HANDLER::sendISOTPFrame(int bus, int ID, QVector data) +void ISOTP_HANDLER::sendISOTPFrame(int bus, int ID, QByteArray data) { CANFrame frame; - frame.remote = false; + frame.setFrameType(QCanBusFrame::DataFrame); int currByte = 0; int index = 0; if (bus < 0) return; @@ -59,29 +60,27 @@ void ISOTP_HANDLER::sendISOTPFrame(int bus, int ID, QVector data) lastSenderID = ID; lastSenderBus = bus; + frame.bus = bus; + frame.setFrameId(ID); + if (ID > 0x7FF) frame.setExtendedFrameFormat(true); + else frame.setExtendedFrameFormat(false); + if (data.length() < 8) { - frame.bus = bus; - frame.ID = ID; - if (ID > 0x7FF) frame.extended = true; - else frame.extended = false; - frame.len = 8; - for (int b = 0; b < 8; b++) frame.data[b] = 0x00; - frame.data[0] = data.length(); - for (int i = 0; i < frame.data[0]; i++) frame.data[i + 1] = data[i]; + QByteArray bytes(8,0); + bytes.resize(8); + bytes[0] = data.length(); + for (int i = 0; i < data.length(); i++) bytes[i + 1] = data[i]; + frame.setPayload(bytes); CANConManager::getInstance()->sendFrame(frame); } else //need to send a multi-part ISO_TP message - Respects timing and frame number based flow control { - frame.bus = bus; - frame.ID = ID; - if (ID > 0x7FF) frame.extended = true; - else frame.extended = false; - frame.len = 8; - for (int b = 0; b < 8; b++) frame.data[b] = 0x00; - frame.data[0] = 0x10 + (data.length() / 256); - frame.data[1] = data.length() & 0xFF; - for (int i = 0; i < 6; i++) frame.data[2 + i] = data[currByte++]; + QByteArray bytes(8, 0); + bytes[0] = 0x10 + (data.length() / 256); + bytes[1] = data.length() & 0xFF; + for (int i = 0; i < 6; i++) bytes[2 + i] = data[currByte++]; + frame.setPayload(bytes); CANConManager::getInstance()->sendFrame(frame); //Queue up the rest of the frames waitingForFlow = true; @@ -90,13 +89,13 @@ void ISOTP_HANDLER::sendISOTPFrame(int bus, int ID, QVector data) frameTimer.start(); while (currByte < data.length()) { - for (int b = 0; b < 8; b++) frame.data[b] = 0x00; - frame.data[0] = 0x20 + index; + for (int b = 0; b < 8; b++) bytes[b] = 0x00; + bytes[0] = 0x20 + index; index = (index + 1) & 0xF; int bytesToGo = data.length() - currByte; if (bytesToGo > 7) bytesToGo = 7; - for (int i = 0; i < bytesToGo; i++) frame.data[1 + i] = data[currByte++]; - frame.len = 8; + for (int i = 0; i < bytesToGo; i++) bytes[1 + i] = data[currByte++]; + frame.setPayload(bytes); sendingFrames.append(frame); //CANConManager::getInstance()->sendFrame(frame); } @@ -108,9 +107,11 @@ void ISOTP_HANDLER::updatedFrames(int numFrames) { if (numFrames == -1) //all frames deleted. Kill the display { + messageBuffer.clear(); } else if (numFrames == -2) //all new set of frames. Reset { + messageBuffer.clear(); for (int i = 0; i < modelFrames->length(); i++) processFrame(modelFrames->at(i)); } else //just got some new frames. See if they are relevant. @@ -127,7 +128,7 @@ void ISOTP_HANDLER::rapidFrames(const CANConnection* conn, const QVector(frame.payload().constData()); + //qDebug() << frame.payload().count(); + //int dataLen = frame.payload().count(); frameType = 0; frameLen = 0; @@ -165,14 +170,14 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) if (useExtendedAddressing) { ID = ID << 8; - ID += frame.data[0]; - frameType = frame.data[1] >> 4; - frameLen = frame.data[1] & 0xF; + ID += data[0]; + frameType = data[1] >> 4; + frameLen = data[1] & 0xF; } else { - frameType = frame.data[0] >> 4; - frameLen = frame.data[0] & 0xF; + frameType = data[0] >> 4; + frameLen = data[0] & 0xF; } switch(frameType) @@ -185,89 +190,106 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) if (frameLen > 7) return; msg.bus = frame.bus; - msg.extended = frame.extended; - msg.ID = ID; + msg.setFrameType(QCanBusFrame::FrameType::DataFrame); + msg.setExtendedFrameFormat( frame.hasExtendedFrameFormat() ); + msg.setFrameId(ID); msg.isReceived = frame.isReceived; - msg.len = frameLen; - msg.data.reserve(frameLen); - msg.timestamp = frame.timestamp; + dataBytes.reserve(frameLen); + msg.reportedLength = frameLen; + msg.setTimeStamp(frame.timeStamp()); msg.isMultiframe = false; - if (useExtendedAddressing) for (int j = 0; j < frameLen; j++) msg.data.append(frame.data[j+2]); - else for (int j = 0; j < frameLen; j++) msg.data.append(frame.data[j+1]); - //qDebug() << "Emitting single frame ISOTP message"; + if (useExtendedAddressing) + { + for (int j = 0; j < frameLen; j++) + { + if (frame.payload().count() > (j+2)) + dataBytes.append(data[j+2]); + } + } + else + { + for (int j = 0; j < frameLen; j++) + { + if (frame.payload().count() > (j+1)) + dataBytes.append(data[j+1]); + } + } + qDebug() << "Emitting single frame ISOTP message"; + msg.setPayload(dataBytes); emit newISOMessage(msg); break; case 1: //first frame of a multi-frame message checkNeedFlush(ID); msg.bus = frame.bus; - msg.extended = frame.extended; - msg.ID = ID; - msg.timestamp = frame.timestamp; + if (frame.payload().count() < 8) return; //MUST have all 8 data bytes in this first frame. + msg.setExtendedFrameFormat( frame.hasExtendedFrameFormat() ); + msg.setFrameId(ID); + msg.setTimeStamp(frame.timeStamp()); msg.isReceived = frame.isReceived; msg.isMultiframe = true; frameLen = frameLen << 8; if (useExtendedAddressing) { - frameLen += frame.data[2]; + frameLen += data[2]; frameLen = frameLen & 0xFFF; - msg.len = frameLen; - msg.data.reserve(frameLen); - for (int j = 0; j < 5; j++) msg.data.append(frame.data[3 + j]); + dataBytes.reserve(frameLen); + msg.reportedLength = frameLen; + for (int j = 0; j < 5; j++) dataBytes.append(frame.payload()[3 + j]); } else { - frameLen += frame.data[1]; + frameLen += data[1]; frameLen = frameLen & 0xFFF; - msg.len = frameLen; - msg.data.reserve(frameLen); - for (int j = 0; j < 6; j++) msg.data.append(frame.data[2 + j]); + msg.payload().reserve(frameLen); + msg.reportedLength = frameLen; + for (int j = 0; j < 6; j++) dataBytes.append(frame.payload()[2 + j]); } msg.lastSequence = -1; - messageBuffer.append(msg); + msg.setPayload(dataBytes); + messageBuffer.insert(msg.frameId(), msg); //The sending ID is set to the last ID we used to send from this class which is //very likely to be correct. But, caution, there is a chance that it isn't. Beware. if (issueFlowMsgs && lastSenderID > 0) { CANFrame outFrame; outFrame.bus = lastSenderBus; - outFrame.extended = false; - outFrame.ID = lastSenderID; - outFrame.len = 8; - for (int b = 0; b < 8; b++) outFrame.data[b] = 0x00; - outFrame.data[0] = 0x30; //flow control, go ahead and send - outFrame.data[1] = 0; //dont ask again about flow control - outFrame.data[2] = 3; //separation time in milliseconds between messages. + outFrame.setExtendedFrameFormat(false); + outFrame.setFrameId(lastSenderID); + QByteArray bytes(8, 0); + bytes[0] = 0x30; //flow control, go ahead and send + bytes[1] = 0; //dont ask again about flow control + bytes[2] = 3; //separation time in milliseconds between messages. + outFrame.setPayload(bytes); CANConManager::getInstance()->sendFrame(outFrame); } break; case 2: //subsequent frames for multi-frame messages pMsg = nullptr; - for (int i = 0; i < messageBuffer.length(); i++) + if (messageBuffer.contains(ID)) { - if (messageBuffer[i].ID == ID) - { - pMsg = &messageBuffer[i]; - break; - } + pMsg = &messageBuffer[ID]; } if (!pMsg) return; if (!pMsg->isMultiframe) return; //if we didn't get a frame type 1 (start of multiframe) first then ignore this frame. - ln = pMsg->len - pMsg->data.count(); + dataBytes.clear(); + dataBytes.append(pMsg->payload()); + ln = pMsg->reportedLength - pMsg->payload().count(); //offset = pMsg->data.count(); if (useExtendedAddressing) { if (ln > 6) ln = 6; - for (int j = 0; j < ln; j++) pMsg->data.append(frame.data[j+2]); + for (int j = 0; j < ln; j++) dataBytes.append(frame.payload()[j+2]); } else { if (ln > 7) ln = 7; - for (int j = 0; j < ln; j++) pMsg->data.append(frame.data[j+1]); + for (int j = 0; j < ln; j++) dataBytes.append(frame.payload()[j+1]); } - if (pMsg->len <= pMsg->data.count()) + pMsg->setPayload(dataBytes); + if (pMsg->reportedLength <= pMsg->payload().count()) { - //qDebug() << "Emitting multiframe ISOTP message"; - checkNeedFlush(pMsg->ID); + qDebug() << "Emitting multiframe ISOTP message"; + checkNeedFlush(pMsg->frameId()); } break; case 3: //flow control messages @@ -276,10 +298,10 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) case 0: //continue to send frames but maybe change inter-frame delay waitingForFlow = false; //data[1] contains number of frames to send before waiting for next flow control - framesUntilFlow = frame.data[1]; + framesUntilFlow = data[1]; if (framesUntilFlow == 0) framesUntilFlow = -1; //-1 means don't count frames and just keep going //data[2] contains the interframe delay to use (0xF1 through 0xF9 are special through) - if (frame.data[2] < 0xF1) frameTimer.start(frame.data[2]); //set proper delay between frames + if (data[2] < 0xF1) frameTimer.start(data[2]); //set proper delay between frames else frameTimer.start(1); //can't do sub-millisecond sending with this code so just use 1ms timing break; case 1: //wait - do not send any more frames until other side says so @@ -300,26 +322,25 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) void ISOTP_HANDLER::checkNeedFlush(uint64_t ID) { - for (int i = 0; i < messageBuffer.length(); i++) + ISOTP_MESSAGE *msg; + if (messageBuffer.contains(ID)) { - if (messageBuffer[i].ID == ID) + msg = &messageBuffer[ID]; + if (msg->reportedLength <= msg->payload().count()) { - //used to pass by reference but now newISOMessage should pass by value which makes it easier to use cross thread - if (messageBuffer[i].ID > 0x600 && messageBuffer[i].ID < 0x630) - { - if (messageBuffer[i].len <= messageBuffer[i].data.count()) - { - qDebug() << "Flushing full frame" << QString::number(messageBuffer[i].ID, 16) << " " << messageBuffer[i].len << " " << messageBuffer[i].data.count(); - } - else - { - qDebug() << "Flushing a partial frame " << QString::number(messageBuffer[i].ID, 16) << " " << messageBuffer[i].len << " " << messageBuffer[i].data.count(); - } - } - emit newISOMessage(messageBuffer[i]); - messageBuffer.removeAt(i); - return; + qDebug() << "Flushing full frame" << QString::number(msg->frameId(), 16) << " " << msg->reportedLength << " " << msg->payload().count(); + if (msg->reportedLength > 0) emit newISOMessage(*msg); } + else + { + if (sendPartialMessages) + { + qDebug() << "Flushing a partial frame " << QString::number(msg->frameId(), 16) << " " << msg->reportedLength << " " << msg->payload().count(); + if (msg->reportedLength > 0) emit newISOMessage(*msg); + } + else qDebug() << "Have a partial message but sending of such is disabled. Throwing it away"; + } + messageBuffer.remove(ID); } } @@ -356,7 +377,7 @@ void ISOTP_HANDLER::setProcessAll(bool state) processAll = state; } -void ISOTP_HANDLER::addFilter(uint32_t pBusId, uint32_t ID, uint32_t mask) +void ISOTP_HANDLER::addFilter(int pBusId, uint32_t ID, uint32_t mask) { CANFilter filt; filt.ID = ID; @@ -366,7 +387,7 @@ void ISOTP_HANDLER::addFilter(uint32_t pBusId, uint32_t ID, uint32_t mask) filters.append(filt); } -void ISOTP_HANDLER::removeFilter(uint32_t pBusId, uint32_t ID, uint32_t mask) +void ISOTP_HANDLER::removeFilter(int pBusId, uint32_t ID, uint32_t mask) { for (int i = 0; i < filters.count(); i++) { @@ -379,4 +400,4 @@ void ISOTP_HANDLER::clearAllFilters() filters.clear(); } - +void setEmitPartials(bool mode); diff --git a/bus_protocols/isotp_handler.h b/bus_protocols/isotp_handler.h index 611f63a..690e05e 100644 --- a/bus_protocols/isotp_handler.h +++ b/bus_protocols/isotp_handler.h @@ -1,5 +1,4 @@ -#ifndef ISOTP_HANDLER_H -#define ISOTP_HANDLER_H +#pragma once #include #include @@ -20,11 +19,12 @@ public: ~ISOTP_HANDLER(); void setExtendedAddressing(bool mode); void setReception(bool mode); //set whether to accept and forward frames or not - void sendISOTPFrame(int bus, int ID, QVector data); + void setEmitPartials(bool mode); + void sendISOTPFrame(int bus, int ID, QByteArray data); void setProcessAll(bool state); void setFlowCtrl(bool state); - void addFilter(uint32_t pBusId, uint32_t ID, uint32_t mask); - void removeFilter(uint32_t pBusId, uint32_t ID, uint32_t mask); + void addFilter(int pBusId, uint32_t ID, uint32_t mask); + void removeFilter(int pBusId, uint32_t ID, uint32_t mask); void clearAllFilters(); public slots: @@ -36,7 +36,7 @@ signals: void newISOMessage(ISOTP_MESSAGE msg); private: - QList messageBuffer; + QHash messageBuffer; QList sendingFrames; QList filters; const QVector *modelFrames; @@ -46,6 +46,7 @@ private: int framesUntilFlow; bool processAll; bool issueFlowMsgs; + bool sendPartialMessages; QTimer frameTimer; uint32_t lastSenderID; uint32_t lastSenderBus; @@ -53,5 +54,3 @@ private: void processFrame(const CANFrame &frame); void checkNeedFlush(uint64_t ID); }; - -#endif // ISOTP_HANDLER_H diff --git a/bus_protocols/isotp_message.h b/bus_protocols/isotp_message.h index f2d4c85..788a069 100644 --- a/bus_protocols/isotp_message.h +++ b/bus_protocols/isotp_message.h @@ -1,20 +1,18 @@ #ifndef ISOTP_MESSAGE_H #define ISOTP_MESSAGE_H -//the same as the CANFrame struct but with arbitrary data size. -class ISOTP_MESSAGE +#include +#include +#include + +//Now a child class of CANFrame. We just add the ability to track how long it was supposed to be and other +//ISOTP related details. But, mostly just CANFrame. +class ISOTP_MESSAGE : public CANFrame { public: - uint32_t ID; - int bus; - bool extended; - bool isReceived; - int len; //# of bytes this message should have (as reported) - int actualSize; //# we actually got + int reportedLength; int lastSequence; bool isMultiframe; - QVector data; - uint64_t timestamp; }; #endif // ISOTP_MESSAGE_H diff --git a/bus_protocols/uds_handler.cpp b/bus_protocols/uds_handler.cpp index 5508800..697f758 100644 --- a/bus_protocols/uds_handler.cpp +++ b/bus_protocols/uds_handler.cpp @@ -33,6 +33,14 @@ static QVector UDS_ROUTINE_SUB = { {3,"GET_ROUTINE_RESULTS", "Get results from routine specified by ID"}, }; +static QVector UDS_FILE_MODEOFOP = { + {1, "ADDFILE", "Add file to file system"}, + {2, "DELETEFILE", "Add file to file system"}, + {3, "REPLACEFILE", "Add file to file system"}, + {4, "READFILE", "Add file to file system"}, + {5, "READDIR", "Add file to file system"} +}; + static QVector UDS_SERVICE_DESC = { {1, "OBDII_SHOW_CURRENT", "OBDII - Show current data"}, {2, "OBDII_SHOW_FREEZE", "OBDII - Show freeze data"}, @@ -158,7 +166,6 @@ UDS_MESSAGE::UDS_MESSAGE() subFunc = 0; service = 0; subFuncLen = 1; - extended = false; isErrorReply = false; } @@ -178,39 +185,39 @@ UDS_HANDLER::~UDS_HANDLER() void UDS_HANDLER::gotISOTPFrame(ISOTP_MESSAGE msg) { qDebug() << "UDS handler got ISOTP frame"; + const unsigned char *data = reinterpret_cast(msg.payload().constData()); + int dataLen = msg.payload().count(); UDS_MESSAGE udsMsg; udsMsg.bus = msg.bus; - udsMsg.extended = msg.extended; - udsMsg.ID = msg.ID; + udsMsg.setExtendedFrameFormat(msg.hasExtendedFrameFormat()); + udsMsg.setFrameId(msg.frameId()); udsMsg.isReceived = msg.isReceived; - udsMsg.timestamp = msg.timestamp; - udsMsg.actualSize = msg.actualSize; + udsMsg.setTimeStamp(msg.timeStamp()); + udsMsg.reportedLength = msg.reportedLength; udsMsg.service = 0; udsMsg.subFunc = 0; udsMsg.subFuncLen = 0; udsMsg.isErrorReply = false; - udsMsg.len = msg.len; - if (msg.data.length() > 0) { - udsMsg.service = msg.data.at(0); + udsMsg.setPayload(msg.payload()); + if (dataLen > 0) { + udsMsg.service = data[0]; if (udsMsg.service == 0x7F) { udsMsg.isErrorReply = true; - if (msg.data.length() > 1) + if (dataLen > 1) { - udsMsg.service = msg.data.at(1); - if (msg.data.length() > 2) udsMsg.subFunc = msg.data.at(2); + udsMsg.service = data[1]; + if (dataLen > 2) udsMsg.subFunc = data[2]; else return; } else return; - udsMsg.data = msg.data.mid(2, -1); //don't copy error byte nor service byte - udsMsg.len -= 2; //and remove those bytes from the length reported too. + udsMsg.payload().remove(0, 2); } else { udsMsg.isErrorReply = false; - if (msg.data.length() > 1) udsMsg.subFunc = msg.data.at(1); - udsMsg.data = msg.data.mid(1, -1); //don't copy service byte - udsMsg.len -= 1; //and remove service byte from length too. + if (dataLen > 1) udsMsg.subFunc = data[1]; + udsMsg.payload().remove(0, 1); } } else return; @@ -245,7 +252,7 @@ void UDS_HANDLER::setReception(bool mode) void UDS_HANDLER::sendUDSFrame(const UDS_MESSAGE &msg) { - QVector data; + QByteArray data; if (msg.bus < 0) return; if (msg.bus >= CANConManager::getInstance()->getNumBuses()) return; if (msg.service > 0xFF) return; @@ -256,8 +263,10 @@ void UDS_HANDLER::sendUDSFrame(const UDS_MESSAGE &msg) data.append((msg.subFunc >> (8 * b)) & 0xFF); } - data.append(msg.data); - isoHandler->sendISOTPFrame(msg.bus, msg.ID, data); + data.append(msg.payload()); + isoHandler->sendISOTPFrame(msg.bus, msg.frameId(), data); + + //qDebug() << "Data sending: " << data; qDebug() << "Sent UDS service: " << getServiceShortDesc(msg.service) << " on bus " << msg.bus; } @@ -325,24 +334,23 @@ QString UDS_HANDLER::getNegativeResponseLong(int respCode) QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) { QString buildString; - bool isResponse = true; int dataSize; int addrSize; + int compType, encType; + const unsigned char *data = reinterpret_cast(msg.payload().constData()); + int dataLen = msg.payload().length(); if (msg.isErrorReply) { - isResponse = true; buildString.append("UDS ERROR Response\n"); buildString.append("Service: " + getServiceLongDesc(msg.service) + "\n"); } else if (msg.service < 0x3F || (msg.service > 0x7F && msg.service < 0xAF)) { - isResponse = false; buildString.append("UDS Request\n"); buildString.append("Service: " + getServiceLongDesc(msg.service) + "\n"); } else { - isResponse = true; buildString.append("UDS Positive Response\n"); buildString.append("Service: " + getServiceLongDesc(msg.service - 0x40) + "\n"); } @@ -363,15 +371,15 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) case UDS_SERVICES::DIAG_CONTROL + 0x40: //positive response buildString.append("Session Request: " + getLongDesc(UDS_DIAG_CTRL_SUB, msg.subFunc)); //there should be four extra bytes now - if (msg.data.length() < 5) //5 because subfunc codes are left in data so it starts with one subfunc byte + if (dataLen < 5) //5 because subfunc codes are left in data so it starts with one subfunc byte { //buildString.append("\nReturned data payload wasn't at least \n4 bytes like it should have been"); } else { - int p2 = msg.data[1] * 256 + msg.data[2]; + int p2 = data[1] * 256 + data[2]; buildString.append("\nP2MAX (Max Wait / Resp Time): " + QString::number(p2) + "ms"); - p2 = (msg.data[3] * 256 + msg.data[4]) * 10; + p2 = (data[3] * 256 + data[4]) * 10; buildString.append("\nP2 Ext MAX: " + QString::number(p2) + "ms"); } break; @@ -382,11 +390,11 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) case UDS_SERVICES::ECU_RESET + 0x40: buildString.append("Reset Type: " + getLongDesc(UDS_ECU_RESET_SUB, msg.subFunc)); //There should be one additional byte which encodes power down time - if (msg.data.length() > 1) + if (dataLen > 1) { - if (msg.data[1] < 0xFF) + if (data[1] < 0xFF) { - buildString.append("\nMinimum powered down time: " + QString::number(msg.data[1])); + buildString.append("\nMinimum powered down time: " + QString::number(data[1])); } else buildString.append("\nPowerdown time not available"); } @@ -395,11 +403,11 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) case UDS_SERVICES::COMM_CTRL: //Comm control has potentially a lot of parameters. control type, comm type, nodeID buildString.append("Control type: " + getLongDesc(UDS_COMM_CTRL_SUB, msg.subFunc)); - if (msg.data.length() > 1) - buildString.append("\nComm Type: " + QString::number(msg.data[1])); //TODO: no attempt to interpret yet - if (msg.data.length() > 3) + if (dataLen > 1) + buildString.append("\nComm Type: " + QString::number(data[1])); //TODO: no attempt to interpret yet + if (dataLen > 3) { - int nodeID = (msg.data[2] * 256 + msg.data[3]); + int nodeID = (data[2] * 256 + data[3]); buildString.append("\nNode ID: " + Utility::formatHexNum(nodeID)); } break; @@ -407,19 +415,19 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) if ((msg.subFunc % 2) == 1) { buildString.append("Seed request for security level: " + QString::number(msg.subFunc) + "\n"); - if (msg.data.length()> 1) + if (dataLen > 1) { buildString.append("Data payload: "); - for (int j = 1; j < msg.data.length(); j++) buildString.append(Utility::formatHexNum(msg.data[j]) + " "); + for (int j = 2; j < dataLen; j++) buildString.append(Utility::formatHexNum(data[j]) + " "); } } else { buildString.append("Key sending for security level: " + QString::number(msg.subFunc - 1)); - if (msg.data.length()> 1) //and it sure as hell should be! + if (dataLen > 1) //and it sure as hell should be! { - buildString.append("KEY: "); - for (int j = 1; j < msg.data.length(); j++) buildString.append(Utility::formatHexNum(msg.data[j]) + " "); + buildString.append(" KEY: "); + for (int j = 2; j < dataLen; j++) buildString.append(Utility::formatHexNum(data[j]) + " "); } } break; @@ -427,10 +435,10 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) if ((msg.subFunc % 2) == 1) { buildString.append("Seed response for security level: " + QString::number(msg.subFunc) + "\n"); - if (msg.data.length()> 1) //be kinda pointless if it weren't + if (dataLen > 1) //be kinda pointless if it weren't { buildString.append("SEED: "); - for (int j = 1; j < msg.data.length(); j++) buildString.append(Utility::formatHexNum(msg.data[j]) + " "); + for (int j = 2; j < dataLen; j++) buildString.append(Utility::formatHexNum(data[j]) + " "); } } else @@ -441,33 +449,33 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) break; case UDS_SERVICES::READ_BY_ID: //parameter is groups of two bytes, each of which specify an ID to read - if (msg.data.length() > 2) + if (dataLen > 2) { uint32_t id; - for (int i = 1; i < msg.data.length(); i = i + 2) + for (int i = 1; i < dataLen; i = i + 2) { - id = (msg.data[i] * 256) + msg.data[i+1]; + id = (data[i] * 256) + data[i+1]; buildString.append("\nID to read: " + Utility::formatHexNum(id)); } } break; case UDS_SERVICES::READ_BY_ID + 0x40: //reply buildString.append("Reply is non-standard and so no decoding is done. The format is (ID) followed by how ever much data that ID returns, followed by more ID/data pairs if applicable.\nPayload: "); - for (int i = 1; i < msg.data.length(); i++) + for (int i = 1; i < dataLen; i++) { - buildString.append(Utility::formatHexNum(msg.data[i]) + " "); + buildString.append(Utility::formatHexNum(data[i]) + " "); } break; case UDS_SERVICES::READ_BY_ADDR: //subfunc byte specifies address and length format, then address, then size dataSize = msg.subFunc >> 4; addrSize = msg.subFunc & 0xF; - if (msg.data.length() > (dataSize + addrSize)) + if (dataLen > (dataSize + addrSize)) { buildString.append("Address: 0x"); - for (int i = 0; i < addrSize; i++) buildString.append(QString::number(msg.data[1+i], 16).toUpper().rightJustified(2,'0')); + for (int i = 0; i < addrSize; i++) buildString.append(QString::number(data[1+i], 16).toUpper().rightJustified(2,'0')); buildString.append("\nSize: 0x"); - for (int i = 0; i < dataSize; i++) buildString.append(QString::number(msg.data[1+i+addrSize], 16).toUpper().rightJustified(2,'0')); + for (int i = 0; i < dataSize; i++) buildString.append(QString::number(data[1+i+addrSize], 16).toUpper().rightJustified(2,'0')); } else { @@ -476,54 +484,109 @@ QString UDS_HANDLER::getDetailedMessageAnalysis(const UDS_MESSAGE &msg) break; case UDS_SERVICES::READ_BY_ADDR + 0x40: buildString.append("Reply is a raw packet of data of the size requested.\nPayload: "); - for (int i = 1; i < msg.data.length(); i++) + for (int i = 1; i < dataLen; i++) { - buildString.append(Utility::formatHexNum(msg.data[i]) + " "); + buildString.append(Utility::formatHexNum(data[i]) + " "); } break; - case UDS_SERVICES::WRITE_BY_ID: + case UDS_SERVICES::WRITE_BY_ID: + if (dataLen > 3) + { + int writeID = (data[1] * 256 + data[2]); + buildString.append("ID to write to: " + Utility::formatHexNum(writeID) + "\nPayload: "); + for (int i = 3; i < dataLen; i++) + { + buildString.append(Utility::formatHexNum(data[i]) + " "); + } + } + break; + case UDS_SERVICES::WRITE_BY_ID + 0x40: + if (dataLen > 2) + { + int writeID = (data[1] * 256 + data[2]); + buildString.append("ID written to: " + Utility::formatHexNum(writeID)); + } break; case UDS_SERVICES::ROUTINE_CTRL: buildString.append("Routine Control: " + getLongDesc(UDS_ROUTINE_SUB, msg.subFunc)); - if (msg.data.length() > 2) + if (dataLen > 3) { int routineID; - routineID = (msg.data[1] * 256 + msg.data[2]); + routineID = (data[2] * 256 + data[3]); buildString.append("\nRoutine ID: " + Utility::formatHexNum(routineID)); } - if (msg.data.length() > 3) + if (dataLen > 4) { buildString.append("\nParameter bytes to routine: "); - for (int i = 4; i < msg.data.length(); i++) + for (int i = 4; i < dataLen; i++) { - buildString.append(Utility::formatHexNum(msg.data[i]) + " "); + buildString.append(Utility::formatHexNum(data[i]) + " "); } } break; case UDS_SERVICES::ROUTINE_CTRL + 0x40: buildString.append("Routine Control: " + getLongDesc(UDS_ROUTINE_SUB, msg.subFunc)); - if (msg.data.length() > 2) + if (dataLen > 2) { int routineID; - routineID = (msg.data[1] * 256 + msg.data[2]); + routineID = (data[2] * 256 + data[3]); buildString.append("\nRoutine ID: " + Utility::formatHexNum(routineID)); } - if (msg.data.length() > 3) + if (dataLen > 4) { buildString.append("\nBytes returned by routine: "); - for (int i = 4; i < msg.data.length(); i++) + for (int i = 4; i < dataLen; i++) { - buildString.append(Utility::formatHexNum(msg.data[i]) + " "); + buildString.append(Utility::formatHexNum(data[i]) + " "); } } break; case UDS_SERVICES::REQUEST_DOWNLOAD: - break; case UDS_SERVICES::REQUEST_UPLOAD: + compType = data[1] >> 4; + encType = data[1] & 0xF; + buildString.append("Compression Type: " + QString::number(compType)); + if (compType == 0) buildString.append(" (none)"); + buildString.append("\n"); + buildString.append("Encryption Type: " + QString::number(encType)); + if (encType == 0) buildString.append(" (none)"); + buildString.append("\n"); + //subfunc byte specifies address and length format, then address, then size + dataSize = data[2] >> 4; + addrSize = data[2] & 0xF; + if (dataLen > (dataSize + addrSize)) + { + buildString.append("Address: 0x"); + for (int i = 0; i < addrSize; i++) buildString.append(QString::number(data[3 + i], 16).toUpper().rightJustified(2,'0')); + buildString.append("\nSize: 0x"); + for (int i = 0; i < dataSize; i++) buildString.append(QString::number(data[3 + i + addrSize], 16).toUpper().rightJustified(2,'0')); + } + else + { + buildString.append("Message has insufficient bytes to properly decode address and size!"); + } + break; + case UDS_SERVICES::REQUEST_DOWNLOAD + 0x40: + case UDS_SERVICES::REQUEST_UPLOAD + 0x40: + dataSize = data[1] >> 4; + buildString.append("\nMax Size of data block: 0x"); + for (int i = 0; i < dataSize; i++) buildString.append(QString::number(data[2 + i], 16).toUpper().rightJustified(2,'0')); break; case UDS_SERVICES::TRANSFER_DATA: + case UDS_SERVICES::TRANSFER_DATA + 0x40: + buildString.append("\nBlock Sequence: " + QString::number(data[1], 16) + "\nPayload: "); + for (int i = 2; i < dataLen; i++) + { + buildString.append(Utility::formatHexNum(data[i]) + " "); + } break; case UDS_SERVICES::REQ_TRANS_EXIT: + case UDS_SERVICES::REQ_TRANS_EXIT + 0x40: + buildString.append("\nPayload: "); + for (int i = 1; i < dataLen; i++) + { + buildString.append(Utility::formatHexNum(data[i]) + " "); + } break; case UDS_SERVICES::REQ_FILE_TRANS: break; diff --git a/can_structs.h b/can_structs.h index d0b3063..6b8cdee 100644 --- a/can_structs.h +++ b/can_structs.h @@ -4,35 +4,32 @@ #include #include #include +#include -struct CANFrame +//Now inherits from the built-in CAN frame class from Qt. This should be more future proof and easier to integrate with other code + +struct CANFrame : public QCanBusFrame { public: - uint32_t ID; int bus; - bool extended; - bool remote; bool isReceived; //did we receive this or send it? - int len; - unsigned char data[8]; - uint64_t timestamp; uint64_t timedelta; uint32_t frameCount; //used in overwrite mode friend bool operator<(const CANFrame& l, const CANFrame& r) { - return l.timestamp < r.timestamp; + qint64 lStamp = l.timeStamp().seconds() * 1000000 + l.timeStamp().microSeconds(); + qint64 rStamp = r.timeStamp().seconds() * 1000000 + r.timeStamp().microSeconds(); + return lStamp < rStamp; } CANFrame() { - ID = 0; + setFrameId(0); bus = 0; - extended = false; - remote = false; + setExtendedFrameFormat(false); + setFrameType(QCanBusFrame::DataFrame); isReceived = true; - len = 0; - timestamp = 0; timedelta = 0; frameCount = 1; } diff --git a/candatagrid.cpp b/candatagrid.cpp index 25c4262..f46783f 100644 --- a/candatagrid.cpp +++ b/candatagrid.cpp @@ -14,6 +14,7 @@ CANDataGrid::CANDataGrid(QWidget *parent) : memset(data, 0, 8); memset(refData, 0, 8); memset(usedData, 0, 8); + memset(usedSignalNum, 0, 64); for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) textStates[x][y] = GridTextState::NORMAL; @@ -53,7 +54,7 @@ void CANDataGrid::setCellTextState(int x, int y, GridTextState state) this->update(); } -GridTextState CANDataGrid::geCellTextState(int x, int y) +GridTextState CANDataGrid::getCellTextState(int x, int y) { if (x < 0) return GridTextState::NORMAL; if (x > 7) return GridTextState::NORMAL; @@ -62,6 +63,21 @@ GridTextState CANDataGrid::geCellTextState(int x, int y) return textStates[x][y]; } +void CANDataGrid::setUsedSignalNum(int bit, unsigned char signal) +{ + if (bit < 0) return; + if (bit > 63) return; + usedSignalNum[bit] = signal; +} + +unsigned char CANDataGrid::getUsedSignalNum(int bit) +{ + if (bit < 0) return 0; + if (bit > 63) return 0; + return usedSignalNum[bit]; +} + + void CANDataGrid::paintEvent(QPaintEvent *event) { Q_UNUSED(event); @@ -161,7 +177,11 @@ void CANDataGrid::paintEvent(QPaintEvent *event) } else { - if ((usedData[y] & (1 << (7-x))) == (1 << (7-x))) painter.setBrush(grayBrush); + if ((usedData[y] & (1 << (7-x))) == (1 << (7-x))) + { + grayBrush = QBrush(QColor(0xB6, 0xB6, 0xB6), Qt::BDiagPattern); + painter.setBrush(grayBrush); + } else painter.setBrush(whiteBrush); } } diff --git a/candatagrid.h b/candatagrid.h index e3162c8..572e87f 100644 --- a/candatagrid.h +++ b/candatagrid.h @@ -19,6 +19,9 @@ class CANDataGrid; * Then, support was added for modifying the text color of each cell. This can be used for whatever the calling code wants. An example is * FlowView that uses all of the above functionality plus this functionality in order to show which bits are set as triggers for stopping * the flowview playback. + * + * Now the control also tracks which signal is using which bit. Currently this is not used for graphical output. I tried but couldn't make it look + * like I wanted. So, it's un-used as of yet. */ enum GridTextState @@ -41,7 +44,9 @@ public: void setUsed(unsigned char *, bool); void saveImage(QString filename, int width, int height); void setCellTextState(int x, int y, GridTextState state); - GridTextState geCellTextState(int x, int y); + GridTextState getCellTextState(int x, int y); + void setUsedSignalNum(int bit, unsigned char signal); + unsigned char getUsedSignalNum(int bit); protected: void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; @@ -54,6 +59,7 @@ private: unsigned char refData[8]; unsigned char data[8]; unsigned char usedData[8]; + unsigned char usedSignalNum[64]; //allows a full char per 64 bits we track so we can specify which signal claims this bit GridTextState textStates[8][8]; QPoint upperLeft, gridSize; }; diff --git a/canframemodel.cpp b/canframemodel.cpp index 95f30a2..1340918 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -133,23 +133,23 @@ void CANFrameModel::normalizeTiming() { mutex.lock(); if (frames.count() == 0) return; - timeOffset = frames[0].timestamp; + timeOffset = frames[0].timeStamp().microSeconds(); //find the absolute lowest timestamp in the whole time. Needed because maybe timestamp was reset in the middle. for (int j = 0; j < frames.count(); j++) { - if (frames[j].timestamp < timeOffset) timeOffset = frames[j].timestamp; + if (frames[j].timeStamp().microSeconds() < timeOffset) timeOffset = frames[j].timeStamp().microSeconds(); } for (int i = 0; i < frames.count(); i++) { - frames[i].timestamp -= timeOffset; + frames[i].setTimeStamp(QCanBusFrame::TimeStamp(0, frames[i].timeStamp().microSeconds() - timeOffset)); } this->beginResetModel(); for (int i = 0; i < filteredFrames.count(); i++) { - filteredFrames[i].timestamp -= timeOffset; + filteredFrames[i].setTimeStamp(QCanBusFrame::TimeStamp(0, filteredFrames[i].timeStamp().microSeconds() - timeOffset)); } this->endResetModel(); @@ -195,15 +195,15 @@ uint64_t CANFrameModel::getCANFrameVal(int row, Column col) { case Column::TimeStamp: if (overwriteDups) return frame.timedelta; - return frame.timestamp; + return frame.timeStamp().microSeconds(); case Column::FrameId: - return frame.ID; + return frame.frameId(); case Column::Extended: - if (frame.extended) return 1; + if (frame.hasExtendedFrameFormat()) return 1; return 0; case Column::Remote: if (overwriteDups) return frame.frameCount; - if (frame.remote) return 1; + if (frame.frameType() == QCanBusFrame::RemoteRequestFrame) return 1; return 0; case Column::Direction: if (frame.isReceived) return 1; @@ -211,10 +211,10 @@ uint64_t CANFrameModel::getCANFrameVal(int row, Column col) case Column::Bus: return static_cast(frame.bus); case Column::Length: - return static_cast(frame.len); + return static_cast(frame.payload().length()); case Column::ASCII: //sort both the same for now case Column::Data: - for (int i = 0; i < frame.len; i++) temp += (static_cast(frame.data[i]) << (56 - (8 * i))); + for (int i = 0; i < frame.payload().length(); i++) temp += (static_cast(frame.payload()[i]) << (56 - (8 * i))); //qDebug() << temp; return temp; case Column::NUM_COLUMN: @@ -311,7 +311,7 @@ void CANFrameModel::recalcOverwrite() uint64_t idAugmented; //id in lower 29 bits, bus number shifted up 29 bits foreach(CANFrame frame, frames) { - idAugmented = frame.ID; + idAugmented = frame.frameId(); idAugmented = idAugmented + (frame.bus << 29ull); if (!overWriteFrames.contains(idAugmented)) { @@ -321,7 +321,7 @@ void CANFrameModel::recalcOverwrite() } else { - frame.timedelta = frame.timestamp - overWriteFrames[idAugmented].timestamp; + frame.timedelta = frame.timeStamp().microSeconds() - overWriteFrames[idAugmented].timeStamp().microSeconds(); frame.frameCount = overWriteFrames[idAugmented].frameCount + 1; overWriteFrames[idAugmented] = frame; } @@ -335,7 +335,7 @@ void CANFrameModel::recalcOverwrite() for (int i = 0; i < frames.count(); i++) { - if (filters[frames[i].ID]) + if (filters[frames[i].frameId()]) { filteredFrames.append(frames[i]); } @@ -347,7 +347,6 @@ void CANFrameModel::recalcOverwrite() QVariant CANFrameModel::data(const QModelIndex &index, int role) const { - int dLen; QString tempString; CANFrame thisFrame; static bool rowFlip = false; @@ -361,6 +360,9 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const thisFrame = filteredFrames.at(index.row()); + const unsigned char *data = reinterpret_cast(thisFrame.payload().constData()); + int dataLen = thisFrame.payload().count(); + if (role == Qt::BackgroundColorRole) { if (dbcHandler != nullptr && interpretFrames) @@ -404,17 +406,17 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const if (timeSeconds) return QString::number(thisFrame.timedelta / 1000000.0, 'f', 5); return QString::number(thisFrame.timedelta); } - else ts = Utility::formatTimestamp(thisFrame.timestamp); + else ts = Utility::formatTimestamp(thisFrame.timeStamp().microSeconds()); if (ts.type() == QVariant::Double) return QString::number(ts.toDouble(), 'f', 5); //never scientific notation, 5 decimal places if (ts.type() == QVariant::LongLong) return QString::number(ts.toLongLong()); //never scientific notion, all digits shown if (ts.type() == QVariant::DateTime) return ts.toDateTime().toString(timeFormat); //custom set format for dates and times - return Utility::formatTimestamp(thisFrame.timestamp); + return Utility::formatTimestamp(thisFrame.timeStamp().microSeconds()); case Column::FrameId: - return Utility::formatCANID(thisFrame.ID, thisFrame.extended); + return Utility::formatCANID(thisFrame.frameId(), thisFrame.hasExtendedFrameFormat()); case Column::Extended: - return QString::number(thisFrame.extended); + return QString::number(thisFrame.hasExtendedFrameFormat()); case Column::Remote: - if (!overwriteDups) return QString::number(thisFrame.remote); + if (!overwriteDups) return QString::number(thisFrame.frameType() == QCanBusFrame::RemoteRequestFrame); return QString::number(thisFrame.frameCount); case Column::Direction: if (thisFrame.isReceived) return QString(tr("Rx")); @@ -422,40 +424,37 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const case Column::Bus: return QString::number(thisFrame.bus); case Column::Length: - return QString::number(thisFrame.len); + return QString::number(dataLen); case Column::ASCII: - if (thisFrame.ID >= 0x7FFFFFF0ull) + if (thisFrame.frameId() >= 0x7FFFFFF0ull) { tempString.append("MARK "); - tempString.append(QString::number(thisFrame.ID & 0x7)); + tempString.append(QString::number(thisFrame.frameId() & 0x7)); return tempString; } - dLen = thisFrame.len; - if (!thisFrame.remote) { - if (dLen < 0) dLen = 0; - if (dLen > 8) dLen = 8; - for (int i = 0; i < dLen; i++) + if (thisFrame.frameType() != QCanBusFrame::RemoteRequestFrame) { + if (dataLen < 0) dataLen = 0; + //if (dLen > 8) dLen = 8; + for (int i = 0; i < dataLen; i++) { - quint8 byt = thisFrame.data[i]; + char byt = thisFrame.payload()[i]; //0x20 through 0x7E are printable characters. Outside of that range they aren't. So use dots instead if (byt < 0x20) byt = 0x2E; //dot character if (byt > 0x7E) byt = 0x2E; - tempString.append(QString::fromUtf8((char *)&byt, 1)); + tempString.append(QString::fromUtf8(&byt, 1)); } } return tempString; case Column::Data: - dLen = thisFrame.len; - if (dLen < 0) dLen = 0; - if (dLen > 8) dLen = 8; + if (dataLen < 0) dataLen = 0; //if (useHexMode) tempString.append("0x "); - if (thisFrame.remote) { + if (thisFrame.frameType() == QCanBusFrame::RemoteRequestFrame) { return tempString; } - for (int i = 0; i < dLen; i++) + for (int i = 0; i < dataLen; i++) { - if (useHexMode) tempString.append( QString::number(thisFrame.data[i], 16).toUpper().rightJustified(2, '0')); - else tempString.append(QString::number(thisFrame.data[i], 10)); + if (useHexMode) tempString.append( QString::number(data[i], 16).toUpper().rightJustified(2, '0')); + else tempString.append(QString::number(data[i], 10)); tempString.append(" "); } //now, if we're supposed to interpret the data and the DBC handler is loaded then use it @@ -464,8 +463,8 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const DBC_MESSAGE *msg = dbcHandler->findMessage(thisFrame); if (msg != nullptr) { - tempString.append(" \n"); - tempString.append(msg->name + "\n" + msg->comment + "\n"); + tempString.append(" <" + msg->name + ">\n"); + if (msg->comment.length() > 1) tempString.append(msg->comment + "\n"); for (int j = 0; j < msg->sigHandler->getCount(); j++) { QString sigString; @@ -552,25 +551,26 @@ void CANFrameModel::addFrame(const CANFrame& frame, bool autoRefresh = false) mutex.lock(); CANFrame tempFrame; tempFrame = frame; - tempFrame.timestamp -= timeOffset; + + tempFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, tempFrame.timeStamp().microSeconds() - timeOffset)); lastUpdateNumFrames++; //if this ID isn't found in the filters list then add it and show it by default - if (!filters.contains(tempFrame.ID)) + if (!filters.contains(tempFrame.frameId())) { // if there are any filters already configured, leave the new filter disabled if (any_filters_are_configured()) - filters.insert(tempFrame.ID, false); + filters.insert(tempFrame.frameId(), false); else - filters.insert(tempFrame.ID, true); + filters.insert(tempFrame.frameId(), true); needFilterRefresh = true; } if (!overwriteDups) { frames.append(tempFrame); - if (filters[tempFrame.ID]) + if (filters[tempFrame.frameId()]) { if (autoRefresh) beginInsertRows(QModelIndex(), filteredFrames.count(), filteredFrames.count()); tempFrame.frameCount = 1; @@ -583,10 +583,10 @@ void CANFrameModel::addFrame(const CANFrame& frame, bool autoRefresh = false) bool found = false; for (int i = 0; i < frames.count(); i++) { - if ( (frames[i].ID == tempFrame.ID) && (frames[i].bus == tempFrame.bus) ) + if ( (frames[i].frameId() == tempFrame.frameId()) && (frames[i].bus == tempFrame.bus) ) { tempFrame.frameCount = frames[i].frameCount + 1; - tempFrame.timedelta = tempFrame.timestamp - frames[i].timestamp; + tempFrame.timedelta = tempFrame.timeStamp().microSeconds() - frames[i].timeStamp().microSeconds(); frames.replace(i, tempFrame); found = true; break; @@ -595,7 +595,7 @@ void CANFrameModel::addFrame(const CANFrame& frame, bool autoRefresh = false) if (!found) { frames.append(tempFrame); - if (filters[tempFrame.ID]) + if (filters[tempFrame.frameId()]) { if (autoRefresh) beginInsertRows(QModelIndex(), filteredFrames.count(), filteredFrames.count()); tempFrame.frameCount = 1; @@ -608,7 +608,7 @@ void CANFrameModel::addFrame(const CANFrame& frame, bool autoRefresh = false) { for (int j = 0; j < filteredFrames.count(); j++) { - if ( (filteredFrames[j].ID == tempFrame.ID) && (filteredFrames[j].bus == tempFrame.bus) ) + if ( (filteredFrames[j].frameId() == tempFrame.frameId()) && (filteredFrames[j].bus == tempFrame.bus) ) { if (autoRefresh) beginResetModel(); filteredFrames.replace(j, tempFrame); @@ -642,7 +642,7 @@ void CANFrameModel::sendRefresh() int count = frames.count(); for (int i = 0; i < count; i++) { - if (filters[frames[i].ID]) + if (filters[frames[i].frameId()]) { tempContainer.append(frames[i]); } @@ -718,12 +718,12 @@ void CANFrameModel::insertFrames(const QVector &newFrames) for (int i = 0; i < newFrames.count(); i++) { frames.append(newFrames[i]); - if (!filters.contains(newFrames[i].ID)) + if (!filters.contains(newFrames[i].frameId())) { - filters.insert(newFrames[i].ID, true); + filters.insert(newFrames[i].frameId(), true); needFilterRefresh = true; } - if (filters[newFrames[i].ID]) + if (filters[newFrames[i].frameId()]) { insertedFiltered++; filteredFrames.append(newFrames[i]); @@ -740,12 +740,12 @@ void CANFrameModel::insertFrames(const QVector &newFrames) int CANFrameModel::getIndexFromTimeID(unsigned int ID, double timestamp) { int bestIndex = -1; - uint64_t intTimeStamp = timestamp * 1000000l; + int64_t intTimeStamp = static_cast (timestamp * 1000000l); for (int i = 0; i < frames.count(); i++) { - if ((frames[i].ID == ID)) + if ((frames[i].frameId() == ID)) { - if (frames[i].timestamp <= intTimeStamp) bestIndex = i; + if (frames[i].timeStamp().microSeconds() <= intTimeStamp) bestIndex = i; else break; //drop out of loop as soon as we pass the proper timestamp } } diff --git a/canframemodel.h b/canframemodel.h index d01f03b..51762a1 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -88,7 +88,7 @@ private: bool timeSeconds; bool useSystemTime; bool needFilterRefresh; - uint64_t timeOffset; + int64_t timeOffset; int lastUpdateNumFrames; uint32_t preallocSize; bool sortDirAsc; diff --git a/config.h b/config.h index 163928a..3bbbd8a 100644 --- a/config.h +++ b/config.h @@ -1,7 +1,7 @@ #ifndef CONFIG #define CONFIG -#define VERSION 199 +#define VERSION 200 //try to keep this in sync. //SavvyCAN will complain if you connect a GVRET board with a revision diff --git a/connections/canbus.h b/connections/canbus.h index fb2d382..b127059 100644 --- a/connections/canbus.h +++ b/connections/canbus.h @@ -9,7 +9,8 @@ public: CANBus(); CANBus(const CANBus&); bool operator==(const CANBus&) const; - virtual ~CANBus(){}; + CANBus& operator=(const CANBus& other) = default; + //virtual ~CANBus(){} int speed; bool listenOnly; diff --git a/connections/canconconst.h b/connections/canconconst.h index f70ebd9..71dc3fd 100644 --- a/connections/canconconst.h +++ b/connections/canconconst.h @@ -18,6 +18,7 @@ namespace CANCon { KVASER, SERIALBUS, REMOTE, + MQTT, NONE }; } diff --git a/connections/canconfactory.cpp b/connections/canconfactory.cpp index d506524..345b0ef 100644 --- a/connections/canconfactory.cpp +++ b/connections/canconfactory.cpp @@ -2,6 +2,7 @@ #include "canconfactory.h" #include "serialbusconnection.h" #include "gvretserial.h" +#include "mqtt_bus.h" using namespace CANCon; @@ -14,6 +15,8 @@ CANConnection* CanConFactory::create(type pType, QString pPortName, QString pDri return new GVRetSerial(pPortName, false); case REMOTE: return new GVRetSerial(pPortName, true); //it's a special case of GVRET connected over TCP/IP so it uses the same class + case MQTT: + return new MQTT_BUS(pPortName); default: {} } diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 0154c03..a1e0cab 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -214,17 +214,17 @@ bool CANConManager::sendFrame(const CANFrame& pFrame) foreach (CANConnection* conn, mConns) { //check if this CAN connection is supposed to handle the requested bus - if (pFrame.bus < (uint32_t)(busBase + conn->getNumBuses())) + if (pFrame.bus < (busBase + conn->getNumBuses())) { workingFrame.bus -= busBase; workingFrame.isReceived = false; if (useSystemTime) { - workingFrame.timestamp = (QDateTime::currentMSecsSinceEpoch() * 1000); + workingFrame.setTimeStamp(QCanBusFrame::TimeStamp(0,QDateTime::currentMSecsSinceEpoch() * 1000)); } else { - workingFrame.timestamp = mElapsedTimer.nsecsElapsed() / 1000; + workingFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, mElapsedTimer.nsecsElapsed() / 1000)); //workingFrame.timestamp -= mTimestampBasis; } txFrame = conn->getQueue().get(); diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 9dfc0ff..ef6e176 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -8,8 +8,8 @@ CANConnection::CANConnection(QString pPort, int pNumBuses, int pQueueLen, bool pUseThread) : - mQueue(), mNumBuses(pNumBuses), + mQueue(), mPort(pPort), mDriver(pDriver), mType(pType), @@ -343,7 +343,7 @@ void CANConnection::checkTargettedFrame(CANFrame &frame) foreach (const CANFltObserver filt, mBusData[frame.bus].mTargettedFrames) { //qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask; - maskedID = frame.ID & filt.mask; + maskedID = frame.frameId() & filt.mask; if (maskedID == filt.id) { qDebug() << "In connection object I got a targetted frame. Forwarding it."; QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame)); diff --git a/connections/canconnection.h b/connections/canconnection.h index a450134..38d1160 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -77,6 +77,12 @@ public: */ CANCon::status getStatus(); + /** + * @brief setConsoleOutput + * @param state - set whether to send debugging info to the console or not + */ + void setConsoleOutput(bool state); + signals: /*not implemented yet */ @@ -194,6 +200,7 @@ public slots: protected: int mNumBuses; //protected to allow connected device to figure out how many buses are available QVector mBusData; + bool mConsoleOutput; //send debugging info to the console? //determine if the passed frame is part of a filter or not. void checkTargettedFrame(CANFrame &frame); diff --git a/connections/canconnectionmodel.cpp b/connections/canconnectionmodel.cpp index cbecb40..35a0c1e 100644 --- a/connections/canconnectionmodel.cpp +++ b/connections/canconnectionmodel.cpp @@ -70,10 +70,10 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const //qDebug() << "Row: " << index.row(); CANConnection *conn_p = getAtIdx(index.row()); - bool ret; + if (!conn_p) return QVariant(); - bool isSocketCAN = (conn_p->getType() == CANCon::SERIALBUS) ? true: false; + //bool isSocketCAN = (conn_p->getType() == CANCon::SERIALBUS) ? true: false; if (role == Qt::DisplayRole) { @@ -147,6 +147,8 @@ CANConnection* CANConnectionModel::getAtIdx(int pIdx) const void CANConnectionModel::refresh(int pIndex) { + Q_UNUSED(pIndex) + beginResetModel(); endResetModel(); /* diff --git a/connections/connectionwindow.cpp b/connections/connectionwindow.cpp index 56dff96..e63e72a 100644 --- a/connections/connectionwindow.cpp +++ b/connections/connectionwindow.cpp @@ -70,7 +70,7 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : rxBroadcast = new QUdpSocket(this); //Need to make sure it tries to share the address in case there are //multiple instances of SavvyCAN running. - rxBroadcast->bind(QHostAddress::AnyIPv4, 17222, QAbstractSocket::ShareAddress); + rxBroadcast->bind(QHostAddress::Any, 17222, QAbstractSocket::ShareAddress); connect(rxBroadcast, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); @@ -85,7 +85,7 @@ void ConnectionWindow::readPendingDatagrams() if (!remoteDeviceIP.contains(datagram.senderAddress().toString())) { remoteDeviceIP.append(datagram.senderAddress().toString()); - //qDebug() << "Add new remote IP " << datagram.senderAddress().toString(); + qDebug() << "Add new remote IP " << datagram.senderAddress().toString(); } } } @@ -312,8 +312,8 @@ void ConnectionWindow::populateBusDetails(int offset) } else { - bool ret; - int numBuses; + //bool ret; + //int numBuses; CANConnection* conn_p = connModel->getAtIdx(selIdx); CANBus bus; @@ -365,7 +365,7 @@ void ConnectionWindow::currentRowChanged(const QModelIndex ¤t, const QMode } else { - bool ret; + //bool ret; ui->groupBus->setEnabled(true); int numBuses; diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index 523c3a5..4da0f3a 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -9,9 +9,9 @@ #include "gvretserial.h" GVRetSerial::GVRetSerial(QString portName, bool useTcp) : - CANConnection(portName, "gvret", CANCon::GVRET_SERIAL, 3, 4000, true), - useTcp(useTcp), - mTimer(this) /*NB: set this as parent of timer to manage it from working thread */ + CANConnection(portName, "gvret", CANCon::GVRET_SERIAL, 3, 4000, true), + mTimer(this), /*NB: set this as parent of timer to manage it from working thread */ + useTcp(useTcp) { sendDebug("GVRetSerial()"); @@ -192,14 +192,14 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) sendDebug("Got signal to update bauds. 1: " + QString::number((can0Baud & 0xFFFFFFF)) + " 2: " + QString::number((can1Baud & 0xFFFFFFF))); buffer[0] = (char)0xF1; //start of a command over serial buffer[1] = 5; //setup canbus - buffer[2] = (unsigned char)(can0Baud & 0xFF); //four bytes of ID LSB first - buffer[3] = (unsigned char)(can0Baud >> 8); - buffer[4] = (unsigned char)(can0Baud >> 16); - buffer[5] = (unsigned char)(can0Baud >> 24); - buffer[6] = (unsigned char)(can1Baud & 0xFF); //four bytes of ID LSB first - buffer[7] = (unsigned char)(can1Baud >> 8); - buffer[8] = (unsigned char)(can1Baud >> 16); - buffer[9] = (unsigned char)(can1Baud >> 24); + buffer[2] = (char)(can0Baud & 0xFF); //four bytes of ID LSB first + buffer[3] = (char)(can0Baud >> 8); + buffer[4] = (char)(can0Baud >> 16); + buffer[5] = (char)(can0Baud >> 24); + buffer[6] = (char)(can1Baud & 0xFF); //four bytes of ID LSB first + buffer[7] = (char)(can1Baud >> 8); + buffer[8] = (char)(can1Baud >> 16); + buffer[9] = (char)(can1Baud >> 24); buffer[10] = 0; sendToSerial(buffer); } @@ -210,18 +210,18 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) sendDebug("Got signal to update extended bus speeds SWCAN: " + QString::number(swcanBaud) + " LIN1: " + QString::number(lin1Baud) + " LIN2: " + QString::number(lin2Baud)); buffer[0] = (char)0xF1; //start of a command over serial buffer[1] = 14; //setup extended buses - buffer[2] = (unsigned char)(swcanBaud & 0xFF); //four bytes of ID LSB first - buffer[3] = (unsigned char)(swcanBaud >> 8); - buffer[4] = (unsigned char)(swcanBaud >> 16); - buffer[5] = (unsigned char)(swcanBaud >> 24); - buffer[6] = (unsigned char)(lin1Baud & 0xFF); //four bytes of ID LSB first - buffer[7] = (unsigned char)(lin1Baud >> 8); - buffer[8] = (unsigned char)(lin1Baud >> 16); - buffer[9] = (unsigned char)(lin1Baud >> 24); - buffer[10] = (unsigned char)(lin2Baud & 0xFF); //four bytes of ID LSB first - buffer[11] = (unsigned char)(lin2Baud >> 8); - buffer[12] = (unsigned char)(lin2Baud >> 16); - buffer[13] = (unsigned char)(lin2Baud >> 24); + buffer[2] = (char)(swcanBaud & 0xFF); //four bytes of ID LSB first + buffer[3] = (char)(swcanBaud >> 8); + buffer[4] = (char)(swcanBaud >> 16); + buffer[5] = (char)(swcanBaud >> 24); + buffer[6] = (char)(lin1Baud & 0xFF); //four bytes of ID LSB first + buffer[7] = (char)(lin1Baud >> 8); + buffer[8] = (char)(lin1Baud >> 16); + buffer[9] = (char)(lin1Baud >> 24); + buffer[10] = (char)(lin2Baud & 0xFF); //four bytes of ID LSB first + buffer[11] = (char)(lin2Baud >> 8); + buffer[12] = (char)(lin2Baud >> 16); + buffer[13] = (char)(lin2Baud >> 24); buffer[14] = 0; sendToSerial(buffer); } @@ -231,8 +231,8 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) bool GVRetSerial::piSendFrame(const CANFrame& frame) { QByteArray buffer; - unsigned int c; - int ID; + int c; + quint32 ID; //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; @@ -246,25 +246,25 @@ bool GVRetSerial::piSendFrame(const CANFrame& frame) // Doesn't make sense to send an error frame // to an adapter - if (frame.ID & 0x20000000) { + if (frame.frameId() & 0x20000000) { return true; } - ID = frame.ID; - if (frame.extended) ID |= 1 << 31; + ID = frame.frameId(); + if (frame.hasExtendedFrameFormat()) ID |= 1u << 31; - buffer[0] = (unsigned char)0xF1; //start of a command over serial + buffer[0] = (char)0xF1; //start of a command over serial buffer[1] = 0; //command ID for sending a CANBUS frame - buffer[2] = (unsigned char)(ID & 0xFF); //four bytes of ID LSB first - buffer[3] = (unsigned char)(ID >> 8); - buffer[4] = (unsigned char)(ID >> 16); - buffer[5] = (unsigned char)(ID >> 24); - buffer[6] = (unsigned char)((frame.bus) & 3); - buffer[7] = (unsigned char)frame.len; - for (c = 0; c < frame.len; c++) + buffer[2] = (char)(ID & 0xFF); //four bytes of ID LSB first + buffer[3] = (char)(ID >> 8); + buffer[4] = (char)(ID >> 16); + buffer[5] = (char)(ID >> 24); + buffer[6] = (char)((frame.bus) & 3); + buffer[7] = (char)frame.payload().length(); + for (c = 0; c < frame.payload().length(); c++) { - buffer[8 + c] = frame.data[c]; + buffer[8 + c] = frame.payload()[c]; } - buffer[8 + frame.len] = 0; + buffer[8 + frame.payload().length()] = 0; sendToSerial(buffer); @@ -375,18 +375,18 @@ void GVRetSerial::deviceConnected() { sendDebug("Connecting to GVRET Device!"); QByteArray output; - output.append((unsigned char)0xE7); //this puts the device into binary comm mode - output.append((unsigned char)0xE7); + output.append((char)0xE7); //this puts the device into binary comm mode + output.append((char)0xE7); - output.append((unsigned char)0xF1); - output.append((unsigned char)0x0C); //get number of actually implemented buses. Not implemented except on M2RET + output.append((char)0xF1); + output.append((char)0x0C); //get number of actually implemented buses. Not implemented except on M2RET mNumBuses = 2; //the proper number if C/12 is not implemented - output.append((unsigned char)0xF1); //signal we want to issue a command - output.append((unsigned char)0x06); //request canbus stats from the board + output.append((char)0xF1); //signal we want to issue a command + output.append((char)0x06); //request canbus stats from the board - output.append((unsigned char)0xF1); //another command to the GVRET - output.append((unsigned char)0x07); //request device information + output.append((char)0xF1); //another command to the GVRET + output.append((char)0x07); //request device information /*output.append((char)0xF1); output.append((char)0x08); //setting singlewire mode @@ -399,11 +399,11 @@ void GVRetSerial::deviceConnected() output.append((char)0xFF); //signal we don't want single wire mode }*/ - output.append((unsigned char)0xF1); //and another command - output.append((unsigned char)0x01); //Time Sync - Not implemented until 333 but we can try + output.append((char)0xF1); //and another command + output.append((char)0x01); //Time Sync - Not implemented until 333 but we can try - output.append((unsigned char)0xF1); //yet another command - output.append((unsigned char)0x09); //comm validation command + output.append((char)0xF1); //yet another command + output.append((char)0x09); //comm validation command continuousTimeSync = true; @@ -659,57 +659,59 @@ void GVRetSerial::procRXChar(unsigned char c) switch (rx_step) { case 0: - buildFrame.timestamp = c; + buildTimestamp = c; break; case 1: - buildFrame.timestamp |= (uint)(c << 8); + buildTimestamp |= (uint)(c << 8); break; case 2: - buildFrame.timestamp |= (uint)c << 16; + buildTimestamp |= (uint)c << 16; break; case 3: - buildFrame.timestamp |= (uint)c << 24; + buildTimestamp |= (uint)c << 24; - buildFrame.timestamp += timeBasis; + buildTimestamp += timeBasis; if (useSystemTime) { - buildFrame.timestamp = QDateTime::currentMSecsSinceEpoch() * 1000l; + buildTimestamp = QDateTime::currentMSecsSinceEpoch() * 1000l; } + buildFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, buildTimestamp)); break; case 4: - buildFrame.ID = c; + buildId = c; break; case 5: - buildFrame.ID |= c << 8; + buildId |= c << 8; break; case 6: - buildFrame.ID |= c << 16; + buildId |= c << 16; break; case 7: - buildFrame.ID |= c << 24; - if ((buildFrame.ID & 1 << 31) == 1u << 31) + buildId |= c << 24; + if ((buildId & 1 << 31) == 1u << 31) { - buildFrame.ID &= 0x7FFFFFFF; - buildFrame.extended = true; + buildId &= 0x7FFFFFFF; + buildFrame.setExtendedFrameFormat(true); } - else buildFrame.extended = false; + else buildFrame.setExtendedFrameFormat(false); + buildFrame.setFrameId(buildId); break; case 8: - buildFrame.len = c & 0xF; - if (buildFrame.len > 8) buildFrame.len = 8; + buildData.resize(c & 0xF); buildFrame.bus = (c & 0xF0) >> 4; break; default: - if (rx_step < buildFrame.len + 9) + if (rx_step < buildData.length() + 9) { - buildFrame.data[rx_step - 9] = c; + buildData[rx_step - 9] = c; } else { rx_state = IDLE; rx_step = 0; buildFrame.isReceived = true; - + buildFrame.setPayload(buildData); + buildFrame.setFrameType(QCanBusFrame::FrameType::DataFrame); if (!isCapSuspended()) { /* get frame from queue */ @@ -717,8 +719,7 @@ void GVRetSerial::procRXChar(unsigned char c) if(frame_p) { //qDebug() << "GVRET got frame on bus " << frame_p->bus; /* copy frame */ - *frame_p = buildFrame; - frame_p->remote = false; + *frame_p = buildFrame; checkTargettedFrame(buildFrame); /* enqueue frame */ getQueue().queue(); @@ -818,11 +819,14 @@ void GVRetSerial::procRXChar(unsigned char c) qDebug() << "Baud 0 = " << can0Baud; qDebug() << "Baud 1 = " << can1Baud; mBusData[0].mBus.setSpeed(can0Baud); - mBusData[1].mBus.setSpeed(can1Baud); mBusData[0].mBus.setActive(can0Enabled); - mBusData[1].mBus.setActive(can1Enabled); mBusData[0].mConfigured = true; - mBusData[1].mConfigured = true; + if (mBusData.count() > 1) + { + mBusData[1].mBus.setSpeed(can1Baud); + mBusData[1].mBus.setActive(can1Enabled); + mBusData[1].mConfigured = true; + } can0Baud |= 0x80000000; if (can0Enabled) can0Baud |= 0x40000000; diff --git a/connections/gvretserial.h b/connections/gvretserial.h index dba664f..4dc5e47 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -91,8 +91,11 @@ protected: QUdpSocket *udpClient; int framesRapid; STATE rx_state; - uint32_t rx_step; + int rx_step; CANFrame buildFrame; + qint64 buildTimestamp; + quint32 buildId; + QByteArray buildData; int can0Baud, can1Baud, swcanBaud, lin1Baud, lin2Baud; bool can0Enabled, can1Enabled, swcanEnabled, lin1Enabled, lin2Enabled; bool can0ListenOnly, can1ListenOnly, swcanListenOnly; diff --git a/connections/mqtt_bus.cpp b/connections/mqtt_bus.cpp new file mode 100644 index 0000000..41f8df3 --- /dev/null +++ b/connections/mqtt_bus.cpp @@ -0,0 +1,251 @@ +#include +#include +#include +#include +#include +#include + +#include "utility.h" +#include "mqtt_bus.h" + +MQTT_BUS::MQTT_BUS(QString topicName) : + CANConnection(topicName, "mqtt_client", CANCon::MQTT, 1, 4000, true), + mTimer(this) /*NB: set this as parent of timer to manage it from working thread */ +{ + sendDebug("MQTT_BUS()"); + + crypto = new SimpleCrypt(Q_UINT64_C(0xdeadbeefface6285)); + + isAutoRestart = false; + this->topicName = topicName; + + timeBasis = 0; + lastSystemTimeBasis = 0; + + readSettings(); +} + + +MQTT_BUS::~MQTT_BUS() +{ + delete crypto; + stop(); + sendDebug("~MQTT_BUS"); +} + +void MQTT_BUS::sendDebug(const QString debugText) +{ + qDebug() << debugText; + debugOutput(debugText); +} + +void MQTT_BUS::piStarted() +{ + QSettings settings; + QString userName = settings.value("Remote/User", "Anonymous").toString(); + QString host = settings.value("Remote/Host", "api.savvycan.com").toString(); + int port = settings.value("Remote/Port", 8333).toInt(); + QByteArray encPass = settings.value("Remote/Pass", "").toByteArray(); + QByteArray password = crypto->decryptToByteArray(encPass); + + QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration(); + mqttClient = new QMQTT::Client(host, port, sslConfig); + + connect(mqttClient, &QMQTT::Client::connected, this, &MQTT_BUS::clientConnected); + connect(mqttClient, &QMQTT::Client::error, this, &MQTT_BUS::clientErrored); + + //qDebug() << "User: " << userName << " Pass: " << password; + mqttClient->setClientId(genRandomClientID()); + mqttClient->setUsername(userName); + mqttClient->setPassword(password); + mqttClient->connectToHost(); +} + +//MQTT required a client ID and they cannot be the same for any two clients. But, they really aren't super exciting +//or important to be named explicitly. Perhaps it might be nice to be able to see it for debugging though. +QString MQTT_BUS::genRandomClientID() +{ + QString output; + output.reserve(12); + QRandomGenerator gen; + for (int i = 0; i < 12; i++) + { + int val = gen.bounded(0, 62); + if (val < 26) output.append(QChar('A'+val)); + else if (val < 52) output.append(QChar('a'+val-26)); + else output.append(QChar('0'+val-52)); + } + qDebug() << "Client ID: " << output; + return output; +} + +void MQTT_BUS::clientErrored(const QMQTT::ClientError error) +{ + qDebug() << QString::number(error); +} + +void MQTT_BUS::piSuspend(bool pSuspend) +{ + /* update capSuspended */ + setCapSuspended(pSuspend); + + /* flush queue if we are suspended */ + if(isCapSuspended()) + getQueue().flush(); +} + + +void MQTT_BUS::piStop() +{ + mTimer.stop(); + disconnectDevice(); +} + + +bool MQTT_BUS::piGetBusSettings(int pBusIdx, CANBus& pBus) +{ + return getBusConfig(pBusIdx, pBus); +} + + +void MQTT_BUS::piSetBusSettings(int pBusIdx, CANBus bus) +{ + /* sanity checks */ + if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) + return; + + /* copy bus config */ + setBusConfig(pBusIdx, bus); + //we don't really update anything. We're just here to listen and perhaps send frames. +} + + +bool MQTT_BUS::piSendFrame(const CANFrame& frame) +{ + QByteArray buffer; + int c; + quint32 ID; + + //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; + + framesRapid++; + + // Doesn't make sense to send an error frame + // to an adapter + if (frame.frameId() & 0x20000000) { + return true; + } + + QMQTT::Message msg; + QByteArray bytes; + + msg.setTopic(topicName + "/s/" + QString::number(frame.frameId())); + uint8_t flags = 0; + if (frame.hasExtendedFrameFormat()) flags += 1; + if (frame.frameType() == QCanBusFrame::RemoteRequestFrame) flags += 2; + if (frame.hasFlexibleDataRateFormat()) flags += 4; + if (frame.frameType() == QCanBusFrame::ErrorFrame) flags += 8; + + uint64_t micros = QDateTime::currentMSecsSinceEpoch() * 1000ull; + for (int x = 0; x < 8; x++) + { + bytes.append(micros & 0xFF); + micros = micros / 256; + } + bytes.append(flags); + bytes.append(frame.payload()); + + msg.setPayload(bytes); + mqttClient->publish(msg); + + return true; +} + + + +/****************************************************************/ + +void MQTT_BUS::readSettings() +{ + QSettings settings; + +} + +void MQTT_BUS::clientMessageReceived(const QMQTT::Message& message) +{ + uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis(); + + + /* drop frame if capture is suspended */ + if(isCapSuspended()) + return; + + CANFrame* frame_p = getQueue().get(); + if(frame_p) + { + uint32_t frameID = message.topic().split("/")[1].toInt(); + uint64_t timeStamp = message.payload()[0] + (message.payload()[1] << 8) + (message.payload()[2] << 16) + (message.payload()[3] << 24) + + ((uint64_t)message.payload()[4] << 32ull) + ((uint64_t)message.payload()[5] << 40ull) + + ((uint64_t)message.payload()[6] << 48ull) + ((uint64_t)message.payload()[7] << 56ull); + int flags = message.payload()[8]; + frame_p->setPayload(message.payload().right(message.payload().count() - 9)); + frame_p->bus = 0; + frame_p->setExtendedFrameFormat(flags & 1); + frame_p->setFrameId(frameID); + frame_p->setFrameType(QCanBusFrame::DataFrame); + frame_p->isReceived = true; + if (useSystemTime) + { + frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, QDateTime::currentMSecsSinceEpoch() * 1000ul)); + } + else frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); + + checkTargettedFrame(*frame_p); + + /* enqueue frame */ + getQueue().queue(); + } +} + +void MQTT_BUS::clientConnected() +{ + sendDebug("Connecting to MQTT Broker!"); + + mqttClient->subscribe(topicName + "/+", 0); //subscribe to all sub topics to grab the frames. + connect(mqttClient, &QMQTT::Client::received, this, &MQTT_BUS::clientMessageReceived); + + setStatus(CANCon::CONNECTED); + CANConStatus stats; + stats.conStatus = getStatus(); + stats.numHardwareBuses = 1;//mNumBuses; + emit status(stats); +} + +void MQTT_BUS::disconnectDevice() { + + setStatus(CANCon::NOT_CONNECTED); + CANConStatus stats; + stats.conStatus = getStatus(); + stats.numHardwareBuses = mNumBuses; + emit status(stats); +} + +void MQTT_BUS::rebuildLocalTimeBasis() +{ + + //qDebug() << "Rebuilding GVRET time base. GVRET local base = " << buildTimeBasis; + + /* + our time basis is the value we have to modulate the main system basis by in order + to sync the GVRET timestamps to the rest of the system. + The rest of the system uses CANConManager::getInstance()->getTimeBasis as the basis. + GVRET returns to us the current time since boot up in microseconds. + timeAtGVRETSync stores the "system" timestamp when the GVRET timestamp was retrieved. + */ + /* + lastSystemTimeBasis = CANConManager::getInstance()->getTimeBasis(); + int64_t systemDelta = timeAtGVRETSync - lastSystemTimeBasis; + int32_t localDelta = buildTimeBasis - systemDelta; + timeBasis = -localDelta; + */ +} diff --git a/connections/mqtt_bus.h b/connections/mqtt_bus.h new file mode 100644 index 0000000..8e9c156 --- /dev/null +++ b/connections/mqtt_bus.h @@ -0,0 +1,67 @@ +#ifndef MQTTBUS_H +#define MQTTBUS_H + +#include +#include +#include +#include "mqtt/qmqtt.h" + +/*************/ +#include +/*************/ + +#include "canframemodel.h" +#include "canconnection.h" +#include "canconmanager.h" +#include "simplecrypt.h" + +class MQTT_BUS : public CANConnection +{ + Q_OBJECT + +public: + MQTT_BUS(QString topicName); + virtual ~MQTT_BUS(); + +protected: + + virtual void piStarted(); + virtual void piStop(); + virtual void piSetBusSettings(int pBusIdx, CANBus pBus); + virtual bool piGetBusSettings(int pBusIdx, CANBus& pBus); + virtual void piSuspend(bool pSuspend); + virtual bool piSendFrame(const CANFrame&) ; + + void disconnectDevice(); + +private slots: + void clientConnected(); + void clientErrored(const QMQTT::ClientError error); + void clientMessageReceived(const QMQTT::Message& message); + +private: + void readSettings(); + void rebuildLocalTimeBasis(); + void sendDebug(const QString debugText); + QString genRandomClientID(); + SimpleCrypt *crypto; + +protected: + QTimer mTimer; + QThread mThread; + + QMQTT::Client *mqttClient; + QString topicName; + + bool isAutoRestart; + int framesRapid; + CANFrame buildFrame; + qint64 buildTimestamp; + quint32 buildId; + QByteArray buildData; + uint32_t buildTimeBasis; + int32_t timeBasis; + uint64_t lastSystemTimeBasis; +}; + +#endif // MQTT_BUS_H diff --git a/connections/newconnectiondialog.cpp b/connections/newconnectiondialog.cpp index 1f03eba..25fa899 100644 --- a/connections/newconnectiondialog.cpp +++ b/connections/newconnectiondialog.cpp @@ -25,6 +25,8 @@ NewConnectionDialog::NewConnectionDialog(QVector* ips, QWidget *parent) connect(ui->rbGVRET, &QAbstractButton::clicked, this, &NewConnectionDialog::handleConnTypeChanged); connect(ui->rbSocketCAN, &QAbstractButton::clicked, this, &NewConnectionDialog::handleConnTypeChanged); connect(ui->rbRemote, &QAbstractButton::clicked, this, &NewConnectionDialog::handleConnTypeChanged); + connect(ui->rbMQTT, &QAbstractButton::clicked, this, &NewConnectionDialog::handleConnTypeChanged); + connect(ui->cbDeviceType, QOverload::of(&QComboBox::currentIndexChanged), this, &NewConnectionDialog::handleDeviceTypeChanged); connect(ui->btnOK, &QPushButton::clicked, this, &NewConnectionDialog::handleCreateButton); @@ -50,6 +52,7 @@ void NewConnectionDialog::handleConnTypeChanged() if (ui->rbGVRET->isChecked()) selectSerial(); if (ui->rbSocketCAN->isChecked()) selectSocketCan(); if (ui->rbRemote->isChecked()) selectRemote(); + if (ui->rbMQTT->isChecked()) selectMQTT(); } void NewConnectionDialog::handleDeviceTypeChanged() @@ -102,6 +105,14 @@ void NewConnectionDialog::selectRemote() } } +void NewConnectionDialog::selectMQTT() +{ + ui->lPort->setText("Topic Name:"); + ui->lblDeviceType->setHidden(true); + ui->cbDeviceType->setHidden(true); + ui->cbPort->clear(); +} + void NewConnectionDialog::setPortName(CANCon::type pType, QString pPortName, QString pDriver) { @@ -112,7 +123,12 @@ void NewConnectionDialog::setPortName(CANCon::type pType, QString pPortName, QSt break; case CANCon::SERIALBUS: ui->rbSocketCAN->setChecked(true); - //you can't configure any of the below three with socketcan so dim them out + break; + case CANCon::REMOTE: + ui->rbRemote->setChecked(true); + break; + case CANCon::MQTT: + ui->rbMQTT->setChecked(true); break; default: {} } @@ -146,6 +162,9 @@ void NewConnectionDialog::setPortName(CANCon::type pType, QString pPortName, QSt else ui->cbPort->addItem(pPortName); break; } + case CANCon::MQTT: + ui->cbPort->setCurrentText(pPortName); + break; default: {} } } @@ -156,6 +175,7 @@ QString NewConnectionDialog::getPortName() case CANCon::GVRET_SERIAL: case CANCon::SERIALBUS: case CANCon::REMOTE: + case CANCon::MQTT: return ui->cbPort->currentText(); default: qDebug() << "getPortName: can't get port"; @@ -178,6 +198,7 @@ CANCon::type NewConnectionDialog::getConnectionType() if (ui->rbGVRET->isChecked()) return CANCon::GVRET_SERIAL; if (ui->rbSocketCAN->isChecked()) return CANCon::SERIALBUS; if (ui->rbRemote->isChecked()) return CANCon::REMOTE; + if (ui->rbMQTT->isChecked()) return CANCon::MQTT; qDebug() << "getConnectionType: error"; return CANCon::NONE; diff --git a/connections/newconnectiondialog.h b/connections/newconnectiondialog.h index f826b70..52b43e5 100644 --- a/connections/newconnectiondialog.h +++ b/connections/newconnectiondialog.h @@ -40,6 +40,7 @@ private: void selectKvaser(); void selectSocketCan(); void selectRemote(); + void selectMQTT(); bool isSerialBusAvailable(); void setPortName(CANCon::type pType, QString pPortName, QString pDriver); }; diff --git a/connections/serialbusconnection.cpp b/connections/serialbusconnection.cpp index 6fa35f2..f628cb6 100644 --- a/connections/serialbusconnection.cpp +++ b/connections/serialbusconnection.cpp @@ -115,22 +115,11 @@ void SerialBusConnection::piSetBusSettings(int pBusIdx, CANBus bus) bool SerialBusConnection::piSendFrame(const CANFrame& pFrame) { /* sanity checks */ - if(0 != pFrame.bus || pFrame.len>8) + if(0 != pFrame.bus /*|| pFrame.len>8*/) return false; if (!mDev_p) return false; - /* fill frame */ - QCanBusFrame frame; - frame.setExtendedFrameFormat(pFrame.extended); - frame.setFrameId(pFrame.ID); - if (pFrame.remote) { - frame.setFrameType(QCanBusFrame::FrameType::RemoteRequestFrame); - } else { - frame.setFrameType(QCanBusFrame::FrameType::DataFrame); - } - frame.setPayload(QByteArray(reinterpret_cast(pFrame.data), - static_cast(pFrame.len))); - return mDev_p->writeFrame(frame); + return mDev_p->writeFrame(pFrame); } @@ -190,17 +179,19 @@ void SerialBusConnection::framesReceived() continue; /* check frame */ - if (recFrame.payload().length() <= 8) { + //if (recFrame.payload().length() <= 8) { CANFrame* frame_p = getQueue().get(); if(frame_p) { - frame_p->len = static_cast(recFrame.payload().length()); - frame_p->bus = 0; + frame_p->setPayload(recFrame.payload()); + frame_p->bus = 0; if (recFrame.frameType() == QCanBusFrame::ErrorFrame) { // Constants defined in include/uapi/linux/can/error.h + //since the whole program uses QCanBusFrame now we can just grab errors directly out of the proper place from now on + /* switch (recFrame.error()) { case QCanBusFrame::TransmissionTimeoutError: - frame_p->ID = 0x20000001; + frame_p->setFrameId(0x20000001); break; case QCanBusFrame::LostArbitrationError: frame_p->ID = 0x20000002; @@ -230,25 +221,27 @@ void SerialBusConnection::framesReceived() break; } frame_p->extended = true; + */ } else { - frame_p->extended = recFrame.hasExtendedFrameFormat(); - frame_p->ID = recFrame.frameId(); - frame_p->remote = (recFrame.frameType() == recFrame.RemoteRequestFrame); - memcpy(frame_p->data, recFrame.payload().data(), frame_p->len); + frame_p->setExtendedFrameFormat(recFrame.hasExtendedFrameFormat()); + frame_p->setFrameId(recFrame.frameId()); + frame_p->setTimeStamp(recFrame.timeStamp()); + frame_p->setFrameType(recFrame.frameType()); + frame_p->setError(recFrame.error()); frame_p->isReceived = true; } frame_p->isReceived = true; if (useSystemTime) { - frame_p->timestamp = QDateTime::currentMSecsSinceEpoch() * 1000ul; + frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, QDateTime::currentMSecsSinceEpoch() * 1000ul)); } - else frame_p->timestamp = (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis; + else frame_p->setTimeStamp(QCanBusFrame::TimeStamp(0, (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis)); checkTargettedFrame(*frame_p); /* enqueue frame */ getQueue().queue(); - } + //} #if 0 else qDebug() << "can't get a frame, ERROR"; diff --git a/dbc/dbc_classes.cpp b/dbc/dbc_classes.cpp index e9a1e3e..9dab43a 100644 --- a/dbc/dbc_classes.cpp +++ b/dbc/dbc_classes.cpp @@ -48,7 +48,7 @@ bool DBC_SIGNAL::processAsText(const CANFrame &frame, QString &outString, bool o QString buildString; int startByte = startBit / 8; int bytes = signalSize / 8; - for (int x = 0; x < bytes; x++) buildString.append(frame.data[startByte + x]); + for (int x = 0; x < bytes; x++) buildString.append(frame.payload().data()[startByte + x]); outString = buildString; cachedValue = outString; return true; @@ -69,7 +69,7 @@ bool DBC_SIGNAL::processAsText(const CANFrame &frame, QString &outString, bool o if (valType == SIGNED_INT) isSigned = true; if (valType == SIGNED_INT || valType == UNSIGNED_INT) { - result = Utility::processIntegerSignal(frame.data, startBit, signalSize, intelByteOrder, isSigned); + result = Utility::processIntegerSignal(frame.payload(), startBit, signalSize, intelByteOrder, isSigned); endResult = ((double)result * factor) + bias; result = (int64_t)endResult; // if factor is an integer, we don't need the possibly human-unreadable float representation @@ -82,19 +82,19 @@ bool DBC_SIGNAL::processAsText(const CANFrame &frame, QString &outString, bool o //that the bytes that make up the integer are instead treated as having made up //a 32 bit single precision float. That's evil incarnate but it is very fast and small //in terms of new code. - result = Utility::processIntegerSignal(frame.data, startBit, 32, intelByteOrder, false); + result = Utility::processIntegerSignal(frame.payload(), startBit, 32, intelByteOrder, false); endResult = (*((float *)(&result)) * factor) + bias; } else //double precision float { - if ( frame.len < 8 ) + if ( frame.payload().length() < 8 ) { result = 0; return false; } //like the above, this is rotten and evil and wrong in so many ways. Force //calculation of a 64 bit integer and then cast it into a double. - result = Utility::processIntegerSignal(frame.data, 0, 64, intelByteOrder, false); + result = Utility::processIntegerSignal(frame.payload(), 0, 64, intelByteOrder, false); endResult = (*((double *)(&result)) * factor) + bias; } @@ -158,13 +158,13 @@ bool DBC_SIGNAL::processAsInt(const CANFrame &frame, int32_t &outValue) } if (valType == SIGNED_INT) isSigned = true; - if ( static_cast(frame.len * 8) < (startBit + signalSize) ) + if ( static_cast(frame.payload().length() * 8) < (startBit + signalSize) ) { result = 0; return false; } - result = static_cast(Utility::processIntegerSignal(frame.data, startBit, signalSize, intelByteOrder, isSigned)); + result = static_cast(Utility::processIntegerSignal(frame.payload(), startBit, signalSize, intelByteOrder, isSigned)); double endResult = (result * factor) + bias; result = static_cast(endResult); @@ -203,19 +203,19 @@ bool DBC_SIGNAL::processAsDouble(const CANFrame &frame, double &outValue) if (valType == SIGNED_INT) isSigned = true; if (valType == SIGNED_INT || valType == UNSIGNED_INT) { - if ( frame.len*8 < (startBit+signalSize) ) + if ( frame.payload().length() * 8 < (startBit+signalSize) ) { result = 0; return false; } - result = Utility::processIntegerSignal(frame.data, startBit, signalSize, intelByteOrder, isSigned); + result = Utility::processIntegerSignal(frame.payload(), startBit, signalSize, intelByteOrder, isSigned); endResult = ((double)result * factor) + bias; result = (int64_t)endResult; } /*TODO: It should be noted that the below floating point has not even been tested. For shame! Test it!*/ else if (valType == SP_FLOAT) { - if ( frame.len*8 < (startBit+32) ) + if ( frame.payload().length() * 8 < (startBit + 32) ) { result = 0; return false; @@ -225,19 +225,19 @@ bool DBC_SIGNAL::processAsDouble(const CANFrame &frame, double &outValue) //that the bytes that make up the integer are instead treated as having made up //a 32 bit single precision float. That's evil incarnate but it is very fast and small //in terms of new code. - result = Utility::processIntegerSignal(frame.data, startBit, 32, false, false); + result = Utility::processIntegerSignal(frame.payload(), startBit, 32, false, false); endResult = (*((float *)(&result)) * factor) + bias; } else //double precision float { - if ( frame.len < 8 ) + if ( frame.payload().length() < 8 ) { result = 0; return false; } //like the above, this is rotten and evil and wrong in so many ways. Force //calculation of a 64 bit integer and then cast it into a double. - result = Utility::processIntegerSignal(frame.data, 0, 64, false, false); + result = Utility::processIntegerSignal(frame.payload(), 0, 64, false, false); endResult = (*((double *)(&result)) * factor) + bias; } cachedValue = endResult; diff --git a/dbc/dbc_classes.h b/dbc/dbc_classes.h index 6b56e02..3006737 100644 --- a/dbc/dbc_classes.h +++ b/dbc/dbc_classes.h @@ -74,6 +74,11 @@ public: DBC_ATTRIBUTE_VALUE *findAttrValByName(QString name); DBC_ATTRIBUTE_VALUE *findAttrValByIdx(int idx); + + friend bool operator<(const DBC_NODE& l, const DBC_NODE& r) + { + return (l.name.toLower() < r.name.toLower()); + } }; class DBC_MESSAGE; //forward reference so that DBC_SIGNAL can compile before we get to real definition of DBC_MESSAGE @@ -107,6 +112,11 @@ public: //TODO: this is sloppy. It shouldn't all be public! QString makePrettyOutput(double floatVal, int64_t intVal, bool outputName = true, bool isInteger = false); DBC_ATTRIBUTE_VALUE *findAttrValByName(QString name); DBC_ATTRIBUTE_VALUE *findAttrValByIdx(int idx); + + friend bool operator<(const DBC_SIGNAL& l, const DBC_SIGNAL& r) + { + return (l.name.toLower() < r.name.toLower()); + } }; class DBCSignalHandler; //forward declaration to keep from having to include dbchandler.h in this file and thus create a loop @@ -129,6 +139,11 @@ public: DBC_ATTRIBUTE_VALUE *findAttrValByName(QString name); DBC_ATTRIBUTE_VALUE *findAttrValByIdx(int idx); + + friend bool operator<(const DBC_MESSAGE& l, const DBC_MESSAGE& r) + { + return (l.name.toLower() < r.name.toLower()); + } }; diff --git a/dbc/dbchandler.cpp b/dbc/dbchandler.cpp index e10cb87..e88a658 100644 --- a/dbc/dbchandler.cpp +++ b/dbc/dbchandler.cpp @@ -8,6 +8,9 @@ #include #include #include +#include +#include +#include #include "utility.h" #include "connections/canconmanager.h" @@ -43,9 +46,16 @@ bool DBCSignalHandler::addSignal(DBC_SIGNAL &sig) bool DBCSignalHandler::removeSignal(DBC_SIGNAL *sig) { - Q_UNUSED(sig); - //if (sigs.removeAll(*sig) > 0) return true; - return false; + qDebug() << "Total # of signals: " << getCount(); + for (int i = 0; i < getCount(); i++) + { + if (sigs[i].name == sig->name) + { + sigs.removeAt(i); + qDebug() << "Removed signal at idx " << i; + } + } + return true; } bool DBCSignalHandler::removeSignal(int idx) @@ -82,6 +92,11 @@ int DBCSignalHandler::getCount() return sigs.count(); } +void DBCSignalHandler::sort() +{ + std::sort(sigs.begin(), sigs.end()); +} + DBC_MESSAGE* DBCMessageHandler::findMsgByID(uint32_t id) { if (messages.count() == 0) return nullptr; @@ -148,6 +163,20 @@ DBC_MESSAGE* DBCMessageHandler::findMsgByName(QString name) return nullptr; } +//allow for finding a message just by part of the name +DBC_MESSAGE* DBCMessageHandler::findMsgByPartialName(QString name) +{ + if (messages.count() == 0) return nullptr; + for (int i = 0; i < messages.count(); i++) + { + if (messages[i].name.contains(name, Qt::CaseInsensitive)) + { + return &messages[i]; + } + } + return nullptr; +} + bool DBCMessageHandler::addMessage(DBC_MESSAGE &msg) { messages.append(msg); @@ -156,9 +185,16 @@ bool DBCMessageHandler::addMessage(DBC_MESSAGE &msg) bool DBCMessageHandler::removeMessage(DBC_MESSAGE *msg) { - Q_UNUSED(msg); - //if (messages.removeAll(*msg) > 0) return true; - return false; + qDebug() << "Total # of messages: " << getCount(); + for (int i = 0; i < getCount(); i++) + { + if (messages[i].name == msg->name) + { + messages.removeAt(i); + qDebug() << "Removed message at idx " << i; + } + } + return true; } bool DBCMessageHandler::removeMessageByIndex(int idx) @@ -210,6 +246,15 @@ int DBCMessageHandler::getCount() return messages.count(); } +void DBCMessageHandler::sort() +{ + std::sort(messages.begin(), messages.end()); + for (int i = 0; i < messages.count(); i++) + { + messages[i].sigHandler->sort(); + } +} + bool DBCMessageHandler::filterLabeling() { return filterLabelingEnabled; @@ -235,6 +280,7 @@ DBCFile::DBCFile() messageHandler = new DBCMessageHandler; messageHandler->setMatchingCriteria(EXACT); messageHandler->setFilterLabeling(false); + isDirty = false; } DBCFile::DBCFile(const DBCFile& cpy) : QObject() @@ -252,6 +298,7 @@ DBCFile::DBCFile(const DBCFile& cpy) : QObject() dbc_nodes.append(cpy.dbc_nodes); dbc_attributes.clear(); dbc_attributes.append(cpy.dbc_attributes); + isDirty = cpy.isDirty; } DBCFile& DBCFile::operator=(const DBCFile& cpy) @@ -270,6 +317,12 @@ DBCFile& DBCFile::operator=(const DBCFile& cpy) return *this; } +void DBCFile::sort() +{ + std::sort(dbc_nodes.begin(), dbc_nodes.end()); //sort node names + messageHandler->sort(); //sort messages, each of which sorts its signals too +} + DBC_NODE* DBCFile::findNodeByIdx(int idx) { if (idx < 0) return nullptr; @@ -349,6 +402,17 @@ void DBCFile::findAttributesByType(DBC_ATTRIBUTE_TYPE typ, QList } } +//there's no external way to clear the flag. It is only cleared when the file is saved by this object. +void DBCFile::setDirtyFlag() +{ + isDirty = true; +} + +bool DBCFile::getDirtyFlag() +{ + return isDirty; +} + DBC_MESSAGE* DBCFile::parseMessageLine(QString line) { QRegularExpression regex; @@ -704,6 +768,7 @@ void DBCFile::loadFile(QString fileName) DBC_MESSAGE *currentMessage = nullptr; DBC_ATTRIBUTE attr; int numSigFaults = 0, numMsgFaults = 0; + int linesSinceYield = 0; bool inMultilineBU = false; @@ -730,6 +795,12 @@ void DBCFile::loadFile(QString fileName) rawLine = QString(inFile->readLine()); line = rawLine.simplified(); + linesSinceYield++; + if (linesSinceYield > 100) + { + qApp->processEvents(); + } + if (inMultilineBU) { if (rawLine.startsWith("\t") || rawLine.startsWith(" ")) @@ -967,6 +1038,7 @@ void DBCFile::loadFile(QString fileName) this->fileName = fileList[fileList.length() - 1]; //whoops... same name as parameter in this function. filePath = fileName.left(fileName.length() - this->fileName.length()); assocBuses = -1; + isDirty = false; } QVariant DBCFile::processAttributeVal(QString input, DBC_ATTRIBUTE_VAL_TYPE typ) @@ -1183,7 +1255,10 @@ void DBCFile::saveFile(QString fileName) msgNumber++; } - msgOutput.append("BO_ " + QString::number(msg->ID) + " " + msg->name + ": " + QString::number(msg->len) + + uint32_t ID = msg->ID; + if (msg->ID > 0x7FF) msg->ID += 0x80000000ul; //set bit 31 if this ID is extended. + + msgOutput.append("BO_ " + QString::number(ID) + " " + msg->name + ": " + QString::number(msg->len) + " " + msg->sender->name + "\n"); if (msg->comment.length() > 0) { @@ -1374,6 +1449,8 @@ void DBCFile::saveFile(QString fileName) outFile->close(); delete outFile; + isDirty = false; + QStringList fileList = fileName.split('/'); this->fileName = fileList[fileList.length() - 1]; //whoops... same name as parameter in this function. filePath = fileName.left(fileName.length() - this->fileName.length()); @@ -1417,6 +1494,7 @@ int DBCHandler::createBlankFile() //add our custom attributes to the new file so that we know they're already there. attr.attrType = MESSAGE; attr.defaultValue = QApplication::palette().color(QPalette::Base).name(); + qDebug() << attr.defaultValue; attr.enumVals.clear(); attr.lower = 0; attr.upper = 0; @@ -1426,6 +1504,7 @@ int DBCHandler::createBlankFile() attr.attrType = MESSAGE; attr.defaultValue = QApplication::palette().color(QPalette::WindowText).name(); + qDebug() << attr.defaultValue; attr.enumVals.clear(); attr.lower = 0; attr.upper = 0; @@ -1451,6 +1530,11 @@ int DBCHandler::createBlankFile() attr.valType = QINT; newFile.dbc_attributes.append(attr); + DBC_NODE falseNode; + falseNode.name = "Vector__XXX"; + falseNode.comment = "Default node if none specified"; + newFile.dbc_nodes.append(falseNode); + loadedFiles.append(newFile); return loadedFiles.count(); } @@ -1495,6 +1579,158 @@ DBCFile* DBCHandler::loadDBCFile(int idx) return nullptr; } +DBCFile* DBCHandler::loadJSONFile(QString filename) +{ + QSettings settings; + DBCFile *thisFile; + DBC_MESSAGE *pMsg; + + createBlankFile(); + thisFile = &loadedFiles.last(); + QFile *inFile = new QFile(filename); + if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) + { + qDebug() << "Could not open JSON file for reading."; + delete inFile; + return nullptr; + } + QByteArray wholeFileData = inFile->readAll(); + inFile->close(); + delete inFile; + //qDebug() << "Data Length: " << wholeFileData.length(); + QJsonDocument jsonDoc = QJsonDocument::fromJson(wholeFileData); + if (jsonDoc.isNull()) + { + qDebug() << "Couldn't load and parse the JSON file for some reason."; + return nullptr; + } + qDebug() << "Loaded JSON"; + + QJsonObject jsonObj = jsonDoc.object(); + QJsonObject jsonMessages = jsonObj["messages"].toObject(); + + QJsonObject::iterator iter; + for (iter = jsonMessages.begin(); iter != jsonMessages.end(); iter++) + { + qDebug() << iter.key(); + DBC_MESSAGE msg; + msg.ID = static_cast(iter->toObject().find("message_id").value().toInt()); + msg.name = QString(iter.key().toUtf8()); + msg.len = static_cast(iter->toObject().find("length_bytes").value().toInt()); + msg.sender = thisFile->findNodeByIdx(0); + QString nodeName = iter->toObject().find("originNode").value().toString(); + msg.sender = thisFile->findNodeByName(nodeName); + msg.bgColor = QColor(thisFile->findAttributeByName("GenMsgBackgroundColor")->defaultValue.toString()); + msg.fgColor = QColor(thisFile->findAttributeByName("GenMsgForegroundColor")->defaultValue.toString()); + if (!msg.sender && nodeName.length() > 1) + { + DBC_NODE node; + node.name = nodeName; + thisFile->dbc_nodes.append(node); + msg.sender = thisFile->findNodeByName(nodeName); + } + if (nodeName.length() < 2) msg.sender = thisFile->findNodeByIdx(0); + thisFile->messageHandler->addMessage(msg); + pMsg = thisFile->messageHandler->findMsgByID(msg.ID); + if (!pMsg) + { + qDebug() << "pMsg was null... I have no idea how that is possible. DEBUG ME"; + return nullptr; + } + + QJsonObject jsonSigs = iter->toObject().find("signals").value().toObject(); + QJsonObject::iterator sigIter; + for (sigIter = jsonSigs.begin(); sigIter != jsonSigs.end(); sigIter++) + { + qDebug() << sigIter.key(); + DBC_SIGNAL sig; + QJsonObject sigObj = sigIter->toObject(); + if (sigObj.isEmpty()) + { + qDebug() << "EMPTY!?"; + } + sig.name = QString(sigIter.key().toUtf8()); + sig.factor = sigObj.find("scale").value().toDouble(); + sig.bias = sigObj.find("offset").value().toDouble(); + sig.max = sigObj.find("max").value().toDouble(); + sig.min = sigObj.find("min").value().toDouble(); + sig.startBit = sigObj.find("start_position").value().toInt(); + sig.unitName = sigObj.find("units").value().toString(); + sig.signalSize = sigObj.find("width").value().toInt(); + sig.isMultiplexed = false; + sig.isMultiplexor = false; + sig.parentMessage = pMsg; + if (!sigObj.find("mux_id")->isUndefined()) + { + QJsonValue muxVal = sigObj.find("mux_id").value(); + sig.multiplexValue = muxVal.toInt(); + sig.isMultiplexed = true; + } + else + { + sig.multiplexValue = 0; + } + QJsonValue muxerVal = sigObj.find("is_muxer").value(); + if (!muxerVal.isNull()) + { + if (muxerVal.toBool()) + { + sig.isMultiplexor = true; + } + } + + QJsonObject valuesObj = sigObj.find("value_description")->toObject(); + if (!valuesObj.isEmpty()) + { + QJsonObject::iterator valIter; + for (valIter = valuesObj.begin(); valIter != valuesObj.end(); valIter++) + { + DBC_VAL_ENUM_ENTRY valEnum; + valEnum.value = valIter.value().toInt(); + valEnum.descript = valIter.key().toUtf8(); + sig.valList.append(valEnum); + } + } + + QJsonArray rxArray = sigObj.find("receivers")->toArray(); + if (rxArray.size() < 1) sig.receiver = thisFile->findNodeByIdx(0); + else + { + qDebug() << rxArray[0].toString(); + sig.receiver = thisFile->findNodeByName(rxArray[0].toString()); + if (!sig.receiver && rxArray[0].toString().length() > 1) + { + DBC_NODE node; + node.name = rxArray[0].toString(); + thisFile->dbc_nodes.append(node); + sig.receiver = thisFile->findNodeByName(rxArray[0].toString()); + } + if (!sig.receiver) sig.receiver = thisFile->findNodeByIdx(0); + } + if (!sigObj.find("endianness").value().toString().compare("BIG")) + { + sig.intelByteOrder = false; + } + else sig.intelByteOrder = true; + + if (!sigObj.find("signedness").value().toString().compare("UNSIGNED")) + { + sig.valType = DBC_SIG_VAL_TYPE::UNSIGNED_INT; + } + else sig.valType = DBC_SIG_VAL_TYPE::SIGNED_INT; + + pMsg->sigHandler->addSignal(sig); + if (sig.isMultiplexor) //if this signal was the multiplexor then store that info + { + DBC_SIGNAL *pSig = pMsg->sigHandler->findSignalByName(sig.name); + if (pSig) pMsg->multiplexorSignal = pSig; + } + } + } + thisFile->setDirtyFlag(); + return thisFile; +} + void DBCHandler::removeDBCFile(int idx) { if (loadedFiles.count() == 0) return; @@ -1516,7 +1752,7 @@ void DBCHandler::swapFiles(int pos1, int pos2) if (pos2 < 0) return; if (pos2 >= loadedFiles.count()) return; - loadedFiles.swap(pos1, pos2); + loadedFiles.swapItemsAt(pos1, pos2); } /* @@ -1529,9 +1765,9 @@ DBC_MESSAGE* DBCHandler::findMessage(const CANFrame &frame) { for(int i = 0; i < loadedFiles.count(); i++) { - if (loadedFiles[i].getAssocBus() == -1 || frame.bus == (unsigned int)loadedFiles[i].getAssocBus()) + if (loadedFiles[i].getAssocBus() == -1 || frame.bus == loadedFiles[i].getAssocBus()) { - DBC_MESSAGE* msg = loadedFiles[i].messageHandler->findMsgByID(frame.ID); + DBC_MESSAGE* msg = loadedFiles[i].messageHandler->findMsgByID(frame.frameId()); if (msg != nullptr) return msg; } } diff --git a/dbc/dbchandler.h b/dbc/dbchandler.h index 9435ede..f2341eb 100644 --- a/dbc/dbchandler.h +++ b/dbc/dbchandler.h @@ -29,6 +29,8 @@ public: bool removeSignal(QString name); void removeAllSignals(); int getCount(); + void sort(); + private: QList sigs; //signals is a reserved word or I'd have used that }; @@ -40,6 +42,7 @@ public: DBC_MESSAGE *findMsgByID(uint32_t id); DBC_MESSAGE *findMsgByIdx(int idx); DBC_MESSAGE *findMsgByName(QString name); + DBC_MESSAGE *findMsgByPartialName(QString name); bool addMessage(DBC_MESSAGE &msg); bool removeMessage(DBC_MESSAGE *msg); bool removeMessageByIndex(int idx); @@ -51,6 +54,8 @@ public: void setMatchingCriteria(MatchingCriteria_t mc); void setFilterLabeling( bool labelFiltering ); bool filterLabeling(); + void sort(); + private: QList messages; MatchingCriteria_t matchingCriteria; @@ -78,6 +83,9 @@ public: QString getPath(); int getAssocBus(); void setAssocBus(int bus); + void setDirtyFlag(); + bool getDirtyFlag(); + void sort(); DBCMessageHandler *messageHandler; QList dbc_nodes; @@ -86,6 +94,7 @@ private: QString fileName; QString filePath; int assocBuses; //-1 = all buses, 0 = first bus, 1 = second bus, etc. + bool isDirty; //has the file been modified? bool parseAttribute(QString inpString, DBC_ATTRIBUTE &attr); QVariant processAttributeVal(QString input, DBC_ATTRIBUTE_VAL_TYPE typ); @@ -113,6 +122,7 @@ public: DBCFile* getFileByIdx(int idx); DBCFile* getFileByName(QString name); int createBlankFile(); + DBCFile* loadJSONFile(QString); static DBCHandler *getReference(); private: diff --git a/dbc/dbcloadsavewindow.cpp b/dbc/dbcloadsavewindow.cpp index aea39d6..cd47371 100644 --- a/dbc/dbcloadsavewindow.cpp +++ b/dbc/dbcloadsavewindow.cpp @@ -1,6 +1,7 @@ #include "dbcloadsavewindow.h" #include "ui_dbcloadsavewindow.h" #include +#include #include #include #include "helpwindow.h" @@ -152,7 +153,38 @@ void DBCLoadSaveWindow::newFile() void DBCLoadSaveWindow::loadFile() { - DBCFile *file = dbcHandler->loadDBCFile(-1); + DBCFile *file = nullptr; + QString filename; + QFileDialog dialog; + QSettings settings; + + QStringList filters; + filters.append(QString(tr("DBC File (*.dbc)"))); + filters.append(QString(tr("Tesla JSON File (*.json)"))); + + dialog.setDirectory(settings.value("DBC/LoadSaveDirectory", dialog.directory().path()).toString()); + dialog.setFileMode(QFileDialog::ExistingFile); + dialog.setNameFilters(filters); + dialog.setViewMode(QFileDialog::Detail); + + if (dialog.exec() == QDialog::Accepted) + { + filename = dialog.selectedFiles()[0]; + //right now there is only one file type that can be loaded here so just do it. + settings.setValue("DBC/LoadSaveDirectory", dialog.directory().path()); + + if (dialog.selectedNameFilter() == filters[0]) + { + if (!filename.contains('.')) filename += ".dbc"; + file = dbcHandler->loadDBCFile(filename); + } + if (dialog.selectedNameFilter() == filters[1]) + { + if (!filename.contains('.')) filename += ".json"; + file = dbcHandler->loadJSONFile(filename); + } + } + if(file) { inhibitCellProcessing=true; int idx = ui->tableFiles->rowCount(); @@ -184,6 +216,11 @@ void DBCLoadSaveWindow::loadFile() } } +void DBCLoadSaveWindow::loadJSON() +{ + +} + void DBCLoadSaveWindow::saveFile() { int idx = ui->tableFiles->currentRow(); @@ -247,6 +284,8 @@ void DBCLoadSaveWindow::editFile() void DBCLoadSaveWindow::matchingCriteriaChanged(int index) { + Q_UNUSED(index) + if (inhibitCellProcessing) return; // We don't know which combobox changed, so we just update all of them for (int row=0; rowtableFiles->rowCount(); row++) @@ -289,7 +328,7 @@ void DBCLoadSaveWindow::cellChanged(int row, int col) { DBCFile *file = dbcHandler->getFileByIdx(row); int bus = ui->tableFiles->item(row, col)->text().toInt(); - int numBuses = CANConManager::getInstance()->getNumBuses(); + //int numBuses = CANConManager::getInstance()->getNumBuses(); if (bus > -2) { file->setAssocBus(bus); diff --git a/dbc/dbcloadsavewindow.h b/dbc/dbcloadsavewindow.h index b671679..34961a3 100644 --- a/dbc/dbcloadsavewindow.h +++ b/dbc/dbcloadsavewindow.h @@ -21,6 +21,7 @@ public: private slots: void loadFile(); + void loadJSON(); void saveFile(); void removeFile(); void moveUp(); diff --git a/dbc/dbcmaineditor.cpp b/dbc/dbcmaineditor.cpp index f84b36d..2aa5825 100644 --- a/dbc/dbcmaineditor.cpp +++ b/dbc/dbcmaineditor.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include "helpwindow.h" @@ -19,38 +21,43 @@ DBCMainEditor::DBCMainEditor( const QVector *frames, QWidget *parent) dbcHandler = DBCHandler::getReference(); referenceFrames = frames; - QStringList headers; - headers << "Node Name" << "Comment"; - ui->NodesTable->setColumnCount(2); - ui->NodesTable->setColumnWidth(0, 240); - ui->NodesTable->setColumnWidth(1, 700); - ui->NodesTable->setHorizontalHeaderLabels(headers); - ui->NodesTable->horizontalHeader()->setStretchLastSection(true); - - QStringList headers2; - headers2 << "Msg ID" << "Msg Name" << "Data Len" << "Signals" << "Fg" << "Bg" << "Comment"; - ui->MessagesTable->setColumnCount(headers2.count()); - ui->MessagesTable->setColumnWidth(0, 80); - ui->MessagesTable->setColumnWidth(1, 200); - ui->MessagesTable->setColumnWidth(2, 80); - ui->MessagesTable->setColumnWidth(3, 80); - ui->MessagesTable->setColumnWidth(4, 40); - ui->MessagesTable->setColumnWidth(5, 40); - ui->MessagesTable->setColumnWidth(6, 300); - ui->MessagesTable->setHorizontalHeaderLabels(headers2); - ui->MessagesTable->horizontalHeader()->setStretchLastSection(true); - - connect(ui->NodesTable, SIGNAL(cellChanged(int,int)), this, SLOT(onCellChangedNode(int,int))); - connect(ui->NodesTable, SIGNAL(cellClicked(int,int)), this, SLOT(onCellClickedNode(int,int))); - connect(ui->NodesTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomMenuNode(QPoint))); - ui->NodesTable->setContextMenuPolicy(Qt::CustomContextMenu); - - connect(ui->MessagesTable, SIGNAL(cellChanged(int,int)), this, SLOT(onCellChangedMessage(int,int))); - connect(ui->MessagesTable, SIGNAL(cellClicked(int,int)), this, SLOT(onCellClickedMessage(int,int))); - connect(ui->MessagesTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomMenuMessage(QPoint))); - ui->MessagesTable->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->btnSearch, &QAbstractButton::clicked, this, &DBCMainEditor::handleSearch); + connect(ui->lineSearch, &QLineEdit::returnPressed, this, &DBCMainEditor::handleSearch); + connect(ui->btnSearchNext, &QAbstractButton::clicked, this, &DBCMainEditor::handleSearchForward); + connect(ui->btnSearchPrev, &QAbstractButton::clicked, this, &DBCMainEditor::handleSearchBackward); + connect(ui->treeDBC, &QTreeWidget::doubleClicked, this, &DBCMainEditor::onTreeDoubleClicked); + connect(ui->treeDBC, &QTreeWidget::currentItemChanged, this, &DBCMainEditor::currentItemChanged); + connect(ui->btnDelete, &QAbstractButton::clicked, this, &DBCMainEditor::deleteCurrentTreeItem); + connect(ui->btnNewNode, &QAbstractButton::clicked, this, &DBCMainEditor::newNode); + connect(ui->btnNewMessage, &QAbstractButton::clicked, this, &DBCMainEditor::newMessage); + connect(ui->btnNewSignal, &QAbstractButton::clicked, this, &DBCMainEditor::newSignal); sigEditor = new DBCSignalEditor(this); + msgEditor = new DBCMessageEditor(this); + nodeEditor = new DBCNodeEditor(this); + + //all three might potentially change the data stored and force the tree to be updated + connect(sigEditor, &DBCSignalEditor::updatedTreeInfo, this, &DBCMainEditor::updatedSignal); + connect(msgEditor, &DBCMessageEditor::updatedTreeInfo, this, &DBCMainEditor::updatedMessage); + connect(nodeEditor, &DBCNodeEditor::updatedTreeInfo, this, &DBCMainEditor::updatedNode); + + nodeIcon = QIcon(":/icons/images/node.png"); + messageIcon = QIcon(":/icons/images/message.png"); + signalIcon = QIcon(":/icons/images/signal.png"); + multiplexedSignalIcon = QIcon(":/icons/images/multiplexed-signal.png"); + multiplexorSignalIcon = QIcon(":/icons/images/multiplexor-signal.png"); + + //ui->btnDelete->setFixedSize(32,32); + ui->btnDelete->setIconSize(QSize(32, 32)); + + //ui->btnNewNode->setFixedSize(32,32); + ui->btnNewNode->setIconSize(QSize(32, 32)); + + //ui->btnNewMessage->setFixedSize(32,32); + ui->btnNewMessage->setIconSize(QSize(32, 32)); + + //ui->btnNewSignal->setFixedSize(32,32); + ui->btnNewSignal->setIconSize(QSize(32, 32)); installEventFilter(this); } @@ -59,13 +66,7 @@ void DBCMainEditor::showEvent(QShowEvent* event) { QDialog::showEvent(event); - inhibitCellChanged = true; - refreshNodesTable(); - if (dbcFile->dbc_nodes.count() > 0) - refreshMessagesTable(&dbcFile->dbc_nodes.at(0)); - - currRow = 0; - inhibitCellChanged = false; + refreshTree(); } DBCMainEditor::~DBCMainEditor() @@ -73,6 +74,8 @@ DBCMainEditor::~DBCMainEditor() removeEventFilter(this); delete ui; delete sigEditor; + delete msgEditor; + delete nodeEditor; } bool DBCMainEditor::eventFilter(QObject *obj, QEvent *event) @@ -84,6 +87,23 @@ bool DBCMainEditor::eventFilter(QObject *obj, QEvent *event) case Qt::Key_F1: HelpWindow::getRef()->showHelp("dbc_editor.html"); break; + case Qt::Key_F3: + handleSearchForward(); + break; + case Qt::Key_F4: + handleSearchBackward(); + break; + case Qt::Key_F5: + newNode(); + break; + case Qt::Key_F6: + newMessage(); + break; + case Qt::Key_F7: + newSignal(); + break; + case Qt::Key_Delete: + deleteCurrentTreeItem(); } return true; } else { @@ -102,7 +122,7 @@ void DBCMainEditor::setFileIdx(int idx) void DBCMainEditor::closeEvent(QCloseEvent *event) { - Q_UNUSED(event); + Q_UNUSED(event) writeSettings(); sigEditor->close(); } @@ -128,354 +148,152 @@ void DBCMainEditor::writeSettings() } } -void DBCMainEditor::onCustomMenuNode(QPoint point) -{ - QMenu *menu = new QMenu(this); - menu->setAttribute(Qt::WA_DeleteOnClose); - - menu->addAction(tr("Delete currently selected node"), this, SLOT(deleteCurrentNode())); - - menu->popup(ui->NodesTable->mapToGlobal(point)); - -} - -void DBCMainEditor::onCustomMenuMessage(QPoint point) +void DBCMainEditor::onCustomMenuTree(QPoint point) { QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); menu->addAction(tr("Delete currently selected message"), this, SLOT(deleteCurrentMessage())); - menu->popup(ui->MessagesTable->mapToGlobal(point)); + //menu->popup(ui->MessagesTable->mapToGlobal(point)); } -void DBCMainEditor::deleteCurrentNode() +void DBCMainEditor::handleSearch() { - int thisRow = ui->NodesTable->currentRow(); - QTableWidgetItem* thisItem = ui->NodesTable->item(thisRow, 0); - if (!thisItem) return; - QString nodeName = thisItem->text(); - if (nodeName.length() > 0 && nodeName.compare("Vector__XXX", Qt::CaseInsensitive) != 0) - { - ui->NodesTable->removeRow(thisRow); - dbcFile->dbc_nodes.removeAt(thisRow); - inhibitCellChanged = true; - refreshMessagesTable(&dbcFile->dbc_nodes[0]); - ui->NodesTable->selectRow(0); - inhibitCellChanged = false; - } -} - -void DBCMainEditor::deleteCurrentMessage() -{ - int thisRow = ui->MessagesTable->currentRow(); - QTableWidgetItem* thisItem = ui->MessagesTable->item(thisRow, 0); - if (!thisItem) return; - if (thisItem->text().length() > 0) + searchItems = ui->treeDBC->findItems(ui->lineSearch->text(),Qt::MatchContains | Qt::MatchRecursive); + qDebug() << "Search returned " << searchItems.count() << "items."; + if (searchItems.count() > 0) { - ui->MessagesTable->removeRow(thisRow); - dbcFile->messageHandler->removeMessageByIndex(thisRow); - } -} - -void DBCMainEditor::onCellChangedNode(int row,int col) -{ - if (inhibitCellChanged) return; - if (row == ui->NodesTable->rowCount() - 1) - { - //if this was the last row then it's new and we need to both - //create another potentially new record underneath and also - //add a node entry in the nodes list and store the record - //That is, so long as the node name was filled out - if (col == 0) - { - DBC_NODE newNode; - QString newName = ui->NodesTable->item(row, col)->text().simplified().replace(' ', '_'); - qDebug() << "new name: " << newName; - if (newName.length() == 0) return; - if (dbcFile->findNodeByName(newName) != nullptr) //duplicates an existing node! - { - QMessageBox msg; - msg.setParent(0); - msg.setText("An existing node with that name already exists! Aborting!"); - msg.exec(); - return; - } - newNode.name = newName; - dbcFile->dbc_nodes.append(newNode); - qDebug() << "# of nodes now " << dbcFile->dbc_nodes.count(); - QTableWidgetItem *widgetName = new QTableWidgetItem(newName); - inhibitCellChanged = true; - ui->NodesTable->setItem(row, col, widgetName); - ui->NodesTable->insertRow(ui->NodesTable->rowCount()); - inhibitCellChanged = false; - } + ui->treeDBC->setCurrentItem(searchItems[0]); + searchItemPos = 0; + ui->lblSearchPos->setText("Search Results: " + QString::number(searchItemPos + 1) + " of " + QString::number(searchItems.count())); } else { - if (col == 0) - { - DBC_NODE *oldNode = dbcFile->findNodeByIdx(row); - QString nodeName = ui->NodesTable->item(row, col)->text().simplified().replace(' ', '_'); - if (oldNode == nullptr) return; - if (row != 0) oldNode->name = nodeName; - else nodeName = oldNode->name; - inhibitCellChanged = true; - QTableWidgetItem *widgetName = new QTableWidgetItem(nodeName); - ui->NodesTable->setItem(row, col, widgetName); - inhibitCellChanged = false; - } - if (col == 1) //must have been col 1 then - { - QString nodeName = ui->NodesTable->item(row, 0)->text().simplified().replace(' ', '_'); - qDebug() << "searching for node " << nodeName; - DBC_NODE *thisNode = dbcFile->findNodeByName(nodeName); - if (thisNode == nullptr) return; - thisNode->comment = ui->NodesTable->item(row, col)->text().simplified(); - qDebug() << "New comment: " << thisNode->comment; - } + ui->lblSearchPos->setText("Search Results: 0 of 0"); } - ui->NodesTable->setCurrentCell(row, col); } -void DBCMainEditor::onCellChangedMessage(int row,int col) +void DBCMainEditor::handleSearchForward() { - QTableWidgetItem* item = nullptr; - bool ret = false; - DBC_MESSAGE *msg = nullptr; - uint msgID; + if (searchItems.count() == 0) return; + if (searchItemPos < searchItems.count() - 1) searchItemPos++; + else searchItemPos = 0; + ui->treeDBC->setCurrentItem(searchItems[searchItemPos]); + ui->lblSearchPos->setText("Search Results: " + QString::number(searchItemPos + 1) + " of " + QString::number(searchItems.count())); +} - if (inhibitCellChanged) return; +void DBCMainEditor::handleSearchBackward() +{ + if (searchItems.count() == 0) return; + if (searchItemPos > 0) searchItemPos--; + else searchItemPos = searchItems.count() - 1; + ui->treeDBC->setCurrentItem(searchItems[searchItemPos]); + ui->lblSearchPos->setText("Search Results: " + QString::number(searchItemPos + 1) + " of " + QString::number(searchItems.count())); +} - DBC_NODE *node = dbcFile->findNodeByIdx(ui->NodesTable->currentRow()); - if (node == nullptr) +void DBCMainEditor::currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *prev) +{ + Q_UNUSED(prev) + if (!current) { - qDebug() << "No node set?!? This is bad!"; + ui->btnNewMessage->setEnabled(false); + ui->btnNewSignal->setEnabled(false); + ui->btnDelete->setEnabled(false); return; } - - item = ui->MessagesTable->item(row, 0); - if(!item) return; - - msgID = Utility::ParseStringToNum2(item->text(), &ret); - msg = dbcFile->messageHandler->findMsgByID(msgID); - - switch(col) + switch (current->data(0, Qt::UserRole).toInt()) { - case 0: //msg id - { - /* sanity checks */ - if(!ret) - { - /* bad message id */ - ui->MessagesTable->item(row, 0)->setText(""); - return; - } - if (msg != nullptr) - { - QMessageBox msg; - msg.setParent(0); - msg.setText("An existing msg with that ID already exists! Aborting!"); - msg.exec(); - - ui->MessagesTable->item(row, 0)->setText(""); - return; - } - - /* insert row */ - DBC_MESSAGE newMsg; - newMsg.ID = msgID; - newMsg.name = ""; - newMsg.sender = node; - newMsg.len = 0; - newMsg.fgColor = ui->MessagesTable->item(row, 4)->backgroundColor(); - newMsg.bgColor = ui->MessagesTable->item(row, 5)->backgroundColor(); - - for (int i = 0; i < referenceFrames->length(); i++) - { - if ((uint) referenceFrames->at(i).ID == msgID) - { - newMsg.len = referenceFrames->at(i).len; - break; - } - } - dbcFile->messageHandler->addMessage(newMsg); - - /* insert message in table */ - inhibitCellChanged = true; - - item = ui->MessagesTable->item(row, 0); - item->setFlags(item->flags() & ~Qt::ItemIsEditable); - item->setText(Utility::formatCANID(msgID)); - - for(int i=1 ; i < ui->MessagesTable->columnCount(); i++) - { - item = ui->MessagesTable->item(row, i); - item->setFlags(item->flags() | Qt::ItemIsEditable); - } - - /* set length */ - item = ui->MessagesTable->item(row, 2); - item->setText(QString::number(newMsg.len)); - - inhibitCellChanged = false; - - /* insert a new row */ - insertBlankRow(); - break; - } - case 1: //msg name - { - QString msgName = ui->MessagesTable->item(row, 1)->text().simplified().replace(' ', '_'); - if (msgName.length() == 0) return; - if( ret && (msg!=nullptr) ) - msg->name = msgName; - break; - } - case 2: //data length - { - bool parseOk = false; - uint msgLen = ui->MessagesTable->item(row, col)->text().toUInt(&parseOk); - - /* sanity checks */ - if(!parseOk) - { - ui->MessagesTable->item(row, col)->setText(""); - return; - } - if (msgLen > 8) - { - msgLen = 8; - ui->MessagesTable->item(row, col)->setText(QString::number(msgLen)); - } - - if( ret && (msg!=nullptr) ) - msg->len = msgLen; - break; - } - case 3: //signals (number) - we don't handle anything here. User cannot directly change this value - break; - case 6: //comment - { - QString msgComment = ui->MessagesTable->item(row, col)->text().simplified(); - if( ret && (msgComment!=nullptr) ) - msg->comment = msgComment; - break; - } - } - - ui->MessagesTable->setCurrentCell(row, col); -} - -void DBCMainEditor::onCellClickedNode(int row, int col) -{ - //reload messages list if the currently selected row has changed. - qDebug() << "Clicked at row " << row << " col " << col; - if (row != currRow) - { - currRow = row; - QTableWidgetItem *item = ui->NodesTable->item(currRow, 0); - QString nodeName; - if (item == nullptr) return; - - nodeName = item->text(); - qDebug() << "Trying to find node with name " << nodeName; - DBC_NODE *node = dbcFile->findNodeByName(nodeName); - //qDebug() << "Address of node: " << (int)node; - inhibitCellChanged = true; - refreshMessagesTable(node); - inhibitCellChanged = false; + case 1: //node + ui->btnNewNode->setEnabled(true); + ui->btnNewMessage->setEnabled(true); + ui->btnNewSignal->setEnabled(false); + ui->btnDelete->setEnabled(true); + break; + case 2: //message + ui->btnNewNode->setEnabled(true); + ui->btnNewMessage->setEnabled(true); + ui->btnNewSignal->setEnabled(true); + ui->btnDelete->setEnabled(true); + break; + case 3: //signal + ui->btnNewNode->setEnabled(true); + ui->btnNewMessage->setEnabled(true); + ui->btnNewSignal->setEnabled(true); + ui->btnDelete->setEnabled(true); + break; + default: + ui->btnNewMessage->setEnabled(false); + ui->btnNewSignal->setEnabled(false); + ui->btnDelete->setEnabled(false); } } -void DBCMainEditor::onCellClickedMessage(int row, int col) +//Double clicking is interpreted as a desire to edit the given item. +void DBCMainEditor::onTreeDoubleClicked(const QModelIndex &index) { - QTableWidgetItem* thisItem = ui->MessagesTable->item(row, col); - QTableWidgetItem* firstCol = ui->MessagesTable->item(row, 0); + Q_UNUSED(index) + + QTreeWidgetItem* firstCol = ui->treeDBC->currentItem(); bool ret = false; DBC_MESSAGE *msg; - int msgID; + DBC_SIGNAL *sig; + DBC_NODE *node; + uint32_t msgID; + QString idString; - if (col == 3) //3 is the signals field. If clicked we go to the signals dialog + qDebug() << firstCol->data(0, Qt::UserRole) << " - " << firstCol->text(0); + + switch (firstCol->data(0, Qt::UserRole).toInt()) { - QTableWidgetItem* msg = ui->MessagesTable->item(row, 0); - if(msg) { - QString idString = msg->text(); - DBC_MESSAGE *message = dbcFile->messageHandler->findMsgByID(Utility::ParseStringToNum(idString)); - sigEditor->setMessageRef(message); - sigEditor->setFileIdx(fileIdx); - sigEditor->setWindowModality(Qt::WindowModal); - sigEditor->exec(); //blocks this window from being active until we're done - //now update the displayed # of signals - inhibitCellChanged = true; - QTableWidgetItem *replacement = new QTableWidgetItem(QString::number(message->sigHandler->getCount())); - ui->MessagesTable->setItem(row, col, replacement); - inhibitCellChanged = false; - } - } - if (col == 4) - { - QColor newColor = QColorDialog::getColor(thisItem->backgroundColor()); - thisItem->setBackgroundColor(newColor); - - if(!firstCol) return; - - msgID = Utility::ParseStringToNum2(firstCol->text(), &ret); + case 1: //a node + idString = firstCol->text(0).split(" ")[0]; + node = dbcFile->findNodeByName(idString); + nodeEditor->setFileIdx(fileIdx); + nodeEditor->setNodeRef(node); + nodeEditor->refreshView(); + nodeEditor->show(); + break; + case 2: //a message + idString = firstCol->text(0).split(" ")[0]; + msgID = static_cast(Utility::ParseStringToNum(idString)); msg = dbcFile->messageHandler->findMsgByID(msgID); - - if (msg) - { - msg->fgColor = newColor; - DBC_ATTRIBUTE_VALUE *val = msg->findAttrValByName("GenMsgForegroundColor"); - if (val) - { - val->value = newColor.name(); - } - else - { - DBC_ATTRIBUTE_VALUE newVal; - newVal.attrName = "GenMsgForegroundColor"; - newVal.value = newColor.name(); - msg->attributes.append(newVal); - } - } - } - if (col == 5) - { - QColor newColor = QColorDialog::getColor(thisItem->backgroundColor()); - thisItem->setBackgroundColor(newColor); - - if(!firstCol) return; - - msgID = Utility::ParseStringToNum2(firstCol->text(), &ret); + msgEditor->setMessageRef(msg); + msgEditor->setFileIdx(fileIdx); + //msgEditor->setWindowModality(Qt::WindowModal); + msgEditor->refreshView(); + msgEditor->show(); //show allows the rest of the forms to keep going + break; + case 3: //a signal + idString = firstCol->parent()->text(0).split(" ")[0]; + msgID = static_cast(Utility::ParseStringToNum(idString)); msg = dbcFile->messageHandler->findMsgByID(msgID); - - if (msg) - { - msg->bgColor = newColor; - DBC_ATTRIBUTE_VALUE *val = msg->findAttrValByName("GenMsgBackgroundColor"); - if (val) - { - val->value = newColor.name(); - } - else - { - DBC_ATTRIBUTE_VALUE newVal; - newVal.attrName = "GenMsgBackgroundColor"; - newVal.value = newColor.name(); - msg->attributes.append(newVal); - } - } + sig = msg->sigHandler->findSignalByName(firstCol->text(0).split(" ")[0]); + sigEditor->setSignalRef(sig); + sigEditor->setMessageRef(msg); + sigEditor->setFileIdx(fileIdx); + //sigEditor->setWindowModality(Qt::WindowModal); + sigEditor->refreshView(); + sigEditor->show(); + break; } } -void DBCMainEditor::refreshNodesTable() -{ - ui->NodesTable->clearContents(); //first step, clear out any previous crap - ui->NodesTable->setRowCount(0); - int rowIdx; +/* + * Recreate the whole tree with pretty icons and custom user roles that give the rest of code an easy way to figure out whether a given tree node + * is a node, message, or signal. +*/ +void DBCMainEditor::refreshTree() +{ + ui->treeDBC->clear(); + nodeToItem.clear(); + messageToItem.clear(); + signalToItem.clear(); + itemToNode.clear(); + itemToMessage.clear(); + itemToSignal.clear(); if (dbcFile->findNodeByName("Vector__XXX") == nullptr) { @@ -485,79 +303,393 @@ void DBCMainEditor::refreshNodesTable() dbcFile->dbc_nodes.append(newNode); } - for (int x = 0; x < dbcFile->dbc_nodes.count(); x++) - { - DBC_NODE node = dbcFile->dbc_nodes.at(x); - QTableWidgetItem *nodeName = new QTableWidgetItem(node.name); - QTableWidgetItem *nodeComment = new QTableWidgetItem(node.comment); - rowIdx = ui->NodesTable->rowCount(); - ui->NodesTable->insertRow(rowIdx); - ui->NodesTable->setItem(rowIdx, 0, nodeName); - ui->NodesTable->setItem(rowIdx, 1, nodeComment); - } - - //insert a fresh entry at the bottom that contains nothing - ui->NodesTable->insertRow(ui->NodesTable->rowCount()); - ui->NodesTable->selectRow(0); -} - -void DBCMainEditor::refreshMessagesTable(const DBC_NODE *node) -{ - ui->MessagesTable->clearContents(); - ui->MessagesTable->setRowCount(0); - - qDebug() << "In refreshMessagesTable"; - - int rowIdx; - - if (node != nullptr) + for (int n = 0; n < dbcFile->dbc_nodes.count(); n++) { + DBC_NODE *node = &dbcFile->dbc_nodes[n]; + QTreeWidgetItem *nodeItem = new QTreeWidgetItem(); + QString nodeInfo = node->name; + if (node->comment.count() > 0) nodeInfo.append(" - ").append(node->comment); + nodeItem->setText(0, nodeInfo); + nodeItem->setIcon(0, nodeIcon); + nodeItem->setData(0, Qt::UserRole, 1); + nodeToItem.insert(node, nodeItem); + itemToNode.insert(nodeItem, node); for (int x = 0; x < dbcFile->messageHandler->getCount(); x++) { DBC_MESSAGE *msg = dbcFile->messageHandler->findMsgByIdx(x); - if (msg->sender == node) + if (msg->sender->name == node->name) { - //many of these are simplistic first versions just to test functionality. - QTableWidgetItem *msgID = new QTableWidgetItem(Utility::formatCANID(msg->ID)); - QTableWidgetItem *msgName = new QTableWidgetItem(msg->name); - QTableWidgetItem *msgLen = new QTableWidgetItem(QString::number(msg->len)); - QTableWidgetItem *msgSignals = new QTableWidgetItem(QString::number(msg->sigHandler->getCount())); - QTableWidgetItem *fgColor = new QTableWidgetItem(""); - fgColor->setBackgroundColor(msg->fgColor); - QTableWidgetItem *bgColor = new QTableWidgetItem(""); - bgColor->setBackgroundColor(msg->bgColor); - QTableWidgetItem *msgComment = new QTableWidgetItem(msg->comment); - - rowIdx = ui->MessagesTable->rowCount(); - ui->MessagesTable->insertRow(rowIdx); - ui->MessagesTable->setItem(rowIdx, 0, msgID); - ui->MessagesTable->setItem(rowIdx, 1, msgName); - ui->MessagesTable->setItem(rowIdx, 2, msgLen); - ui->MessagesTable->setItem(rowIdx, 3, msgSignals); - ui->MessagesTable->setItem(rowIdx, 4, fgColor); - ui->MessagesTable->setItem(rowIdx, 5, bgColor); - ui->MessagesTable->setItem(rowIdx, 6, msgComment); - //note that there is a sending node field in the structure but we're - //not displaying it. It has to be the node we selected from the node list - //so no need to show that here. + QTreeWidgetItem *msgItem = new QTreeWidgetItem(nodeItem); + QString msgInfo = Utility::formatCANID(msg->ID) + " " + msg->name; + if (msg->comment.count() > 0) msgInfo.append(" - ").append(msg->comment); + msgItem->setText(0, msgInfo); + msgItem->setIcon(0, messageIcon); + msgItem->setData(0, Qt::UserRole, 2); + messageToItem.insert(msg, msgItem); + itemToMessage.insert(msgItem, msg); + for (int i = 0; i < msg->sigHandler->getCount(); i++) + { + DBC_SIGNAL *sig = msg->sigHandler->findSignalByIdx(i); + QTreeWidgetItem *sigItem = new QTreeWidgetItem(msgItem); + QString sigInfo = sig->name; + if (sig->comment.count() > 0) sigInfo.append(" - ").append(sig->comment); + sigItem->setText(0, sigInfo); + if (sig->isMultiplexed) sigItem->setIcon(0, multiplexedSignalIcon); + else if (sig->isMultiplexor) sigItem->setIcon(0, multiplexorSignalIcon); + else sigItem->setIcon(0, signalIcon); + sigItem->setData(0, Qt::UserRole, 3); + signalToItem.insert(sig, sigItem); + itemToSignal.insert(sigItem, sig); + } } } + ui->treeDBC->addTopLevelItem(nodeItem); } - - //insert blank record that can be used to add new messages - insertBlankRow(); + ui->treeDBC->sortItems(0, Qt::SortOrder::AscendingOrder); //sort the display list for ease in viewing by mere mortals, helps me a lot. } -void DBCMainEditor::insertBlankRow() +void DBCMainEditor::updatedNode(DBC_NODE *node) { - int rowIdx = ui->MessagesTable->rowCount(); - ui->MessagesTable->insertRow(rowIdx); - for(int i=1 ; i < ui->MessagesTable->columnCount(); i++) + if (nodeToItem.contains(node)) { - QTableWidgetItem *item = new QTableWidgetItem(""); - if (i == 4) item->setBackgroundColor(QApplication::palette().color(QPalette::WindowText)); //foreground color - if (i == 5) item->setBackgroundColor(QApplication::palette().color(QPalette::Base)); - item->setFlags(item->flags() & ~Qt::ItemIsEditable); - ui->MessagesTable->setItem(rowIdx, i, item); + QTreeWidgetItem *item = nodeToItem[node]; + QString nodeInfo = node->name; + if (node->comment.count() > 0) nodeInfo.append(" - ").append(node->comment); + item->setText(0, nodeInfo); + } + else qDebug() << "That node doesn't exist. That's a bug dude."; +} + +void DBCMainEditor::updatedMessage(DBC_MESSAGE *msg) +{ + if (messageToItem.contains(msg)) + { + QTreeWidgetItem *item = messageToItem.value(msg); + QString msgInfo = Utility::formatCANID(msg->ID) + " " + msg->name; + if (msg->comment.count() > 0) msgInfo.append(" - ").append(msg->comment); + item->setText(0, msgInfo); + //editor could have changed the parent Node too. Have to figure out which node + //is parent in the GUI and compare that to parent in the data. + DBC_NODE *oldParent = dbcFile->findNodeByName(item->parent()->text(0)); + if (oldParent != msg->sender) + { + qDebug() << "Changed parent of message. Trying to rehome it."; + QTreeWidgetItem *newParent = nullptr; + if (nodeToItem.contains(msg->sender)) newParent = nodeToItem.value(msg->sender); + else //new node created within message editor. Create the item and then use it + { + QTreeWidgetItem *newNodeItem = new QTreeWidgetItem(); + newNodeItem->setText(0, msg->sender->name); + newNodeItem->setIcon(0, nodeIcon); + newNodeItem->setData(0, Qt::UserRole, 1); + ui->treeDBC->addTopLevelItem(newNodeItem); + nodeToItem.insert(msg->sender, newNodeItem); + itemToNode.insert(newNodeItem, msg->sender); + newParent = newNodeItem; + } + + QTreeWidgetItem *prevParent = nodeToItem.value(oldParent); + prevParent->removeChild(item); + newParent->addChild(item); + ui->treeDBC->setCurrentItem(item); + ui->treeDBC->sortItems(0, Qt::AscendingOrder); //resort because we just moved an item + } + } + else qDebug() << "That mesage doesn't exist. That's a bug dude."; +} + +void DBCMainEditor::updatedSignal(DBC_SIGNAL *sig) +{ + if (signalToItem.contains(sig)) + { + QTreeWidgetItem *item = signalToItem.value(sig); + QString sigInfo = sig->name; + if (sig->comment.count() > 0) sigInfo.append(" - ").append(sig->comment); + item->setText(0, sigInfo); + } + else qDebug() << "That signal doesn't exist. That's a bug dude."; +} + +void DBCMainEditor::newNode() +{ + DBC_NODE node; + DBC_NODE *nodePtr; + node.name = "Unnamed" + QString::number(randGen.bounded(50000)); + dbcFile->dbc_nodes.append(node); + nodePtr = dbcFile->findNodeByName(node.name); + QTreeWidgetItem *nodeItem = new QTreeWidgetItem(); + nodeItem->setText(0, node.name); + nodeItem->setIcon(0, nodeIcon); + nodeItem->setData(0, Qt::UserRole, 1); + nodeToItem.insert(nodePtr, nodeItem); + itemToNode.insert(nodeItem, nodePtr); + ui->treeDBC->addTopLevelItem(nodeItem); + ui->treeDBC->setCurrentItem(nodeItem); + dbcFile->setDirtyFlag(); +} + + +//create a new message with it's parent being the node we're currently within +void DBCMainEditor::newMessage() +{ + QTreeWidgetItem *nodeItem = nullptr; + QTreeWidgetItem *msgItem = nullptr; + nodeItem = ui->treeDBC->currentItem(); + int typ = nodeItem->data(0, Qt::UserRole).toInt(); + if (!nodeItem) return; //nothing selected! + if (typ == 2) + { + msgItem = nodeItem; + nodeItem = nodeItem->parent(); + } + if (typ == 3) + { + msgItem = nodeItem->parent(); + nodeItem = msgItem->parent(); + } + + DBC_NODE *node = dbcFile->findNodeByName(nodeItem->data(0, Qt::DisplayRole).toString()); + DBC_MESSAGE msg; + DBC_MESSAGE *msgPtr; + if (msgItem) + { + QString idString = msgItem->text(0).split(" ")[0]; + int msgID = static_cast(Utility::ParseStringToNum(idString)); + DBC_MESSAGE *oldMsg = dbcFile->messageHandler->findMsgByID(msgID); + if (oldMsg) + { + msg.name = oldMsg->name + QString::number(randGen.bounded(1000)); + msg.ID = oldMsg->ID + 1; + msg.len = oldMsg->len; + msg.bgColor = oldMsg->bgColor; + msg.fgColor = oldMsg->fgColor; + msg.comment = oldMsg->comment; + } + else + { + msg.name = nodeItem->text(0) + "Msg" + QString::number(randGen.bounded(500)); + msg.ID = 0; + msg.len = 0; + } + } + else + { + msg.name = nodeItem->text(0) + "Msg" + QString::number(randGen.bounded(500)); + msg.ID = 0; + msg.len = 0; + } + msg.sender = node; + + dbcFile->messageHandler->addMessage(msg); + msgPtr = dbcFile->messageHandler->findMsgByIdx(dbcFile->messageHandler->getCount() - 1); + QTreeWidgetItem *newMsgItem = new QTreeWidgetItem(); + QString msgInfo = Utility::formatCANID(msg.ID) + " " + msg.name; + if (msg.comment.count() > 0) msgInfo.append(" - ").append(msg.comment); + newMsgItem->setText(0, msgInfo); + newMsgItem->setIcon(0, messageIcon); + newMsgItem->setData(0, Qt::UserRole, 2); + messageToItem.insert(msgPtr, newMsgItem); + itemToMessage.insert(newMsgItem, msgPtr); + nodeItem->addChild(newMsgItem); + ui->treeDBC->setCurrentItem(newMsgItem); + dbcFile->setDirtyFlag(); +} + +void DBCMainEditor::newSignal() +{ + QTreeWidgetItem *msgItem = nullptr; + QTreeWidgetItem *sigItem = nullptr; + msgItem = ui->treeDBC->currentItem(); + if (!msgItem) return; //nothing selected! + int typ = msgItem->data(0, Qt::UserRole).toInt(); + if (typ == 1) return; //can't add signals to a node! + if (typ == 3) + { + sigItem = msgItem; + msgItem = msgItem->parent(); + } + + QString idString = msgItem->text(0).split(" ")[0]; + int msgID = static_cast(Utility::ParseStringToNum(idString)); + DBC_MESSAGE *msg = dbcFile->messageHandler->findMsgByID(msgID); + DBC_SIGNAL sig; + DBC_SIGNAL *sigPtr; + if (sigItem) + { + DBC_SIGNAL *oldSig = msg->sigHandler->findSignalByName(sigItem->text(0).split(" ")[0]); + if (oldSig) + { + sig = *oldSig; //copy it all over + sig.name = sig.name + QString::number(randGen.bounded(100)); + } + else + { + sig.name = msgItem->text(0).split(" ")[1] + "Sig" + QString::number(randGen.bounded(500)); + } + } + else + { + sig.name = msgItem->text(0).split(" ")[1] + "Sig" + QString::number(randGen.bounded(500)); + } + + sig.parentMessage = msg; + msg->sigHandler->addSignal(sig); + sigPtr = msg->sigHandler->findSignalByIdx(msg->sigHandler->getCount() - 1); + QTreeWidgetItem *newSigItem = new QTreeWidgetItem(); + QString sigInfo = sig.name; + if (sig.comment.count() > 0) sigInfo.append(" - ").append(sig.comment); + newSigItem->setText(0, sigInfo); + if (sig.isMultiplexed) newSigItem->setIcon(0, multiplexedSignalIcon); + else if (sig.isMultiplexor) newSigItem->setIcon(0, multiplexorSignalIcon); + else newSigItem->setIcon(0, signalIcon); + newSigItem->setData(0, Qt::UserRole, 3); + signalToItem.insert(sigPtr, newSigItem); + itemToSignal.insert(newSigItem, sigPtr); + msgItem->addChild(newSigItem); + ui->treeDBC->setCurrentItem(newSigItem); + dbcFile->setDirtyFlag(); +} + +//gets confirmation before calling the real routines that delete things +void DBCMainEditor::deleteCurrentTreeItem() +{ + QTreeWidgetItem *currItem = ui->treeDBC->currentItem(); + int typ = currItem->data(0, Qt::UserRole).toInt(); + QString idString; + int msgID; + DBC_MESSAGE *msg; + DBC_NODE *node; + int numMsg = 0, numSig = 0; + + QMessageBox::StandardButton confirmDialog; + + switch (typ) + { + case 1: //deleting a node cascades deletion down to messages and signals + node = dbcFile->findNodeByName(currItem->text(0)); + if (!node) return; + for (int x = 0; x < dbcFile->messageHandler->getCount(); x++) + { + if (dbcFile->messageHandler->findMsgByIdx(x)->sender == node) + { + numMsg++; + numSig += dbcFile->messageHandler->findMsgByIdx(x)->sigHandler->getCount(); + } + } + confirmDialog = QMessageBox::question(this, "Really?", "Are you sure you want to delete this node, its\n" + + QString::number(numMsg) + " messages, and their " + QString::number(numSig) + " combined signals?", QMessageBox::Yes|QMessageBox::No); + if (confirmDialog == QMessageBox::Yes) + { + if (itemToNode.contains(currItem)) + { + DBC_NODE *node = itemToNode.value(currItem); + deleteNode(node); + } + else + { + qDebug() << "WTF, could not find the node in the map. That should not happen."; + } + } + + break; + case 2: //cascades to removing all signals too. + idString = currItem->text(0).split(" ")[0]; + msgID = static_cast(Utility::ParseStringToNum(idString)); + msg = dbcFile->messageHandler->findMsgByID(msgID); + + confirmDialog = QMessageBox::question(this, "Really?", "Are you sure you want to delete\nthis message and its " + + QString::number(msg->sigHandler->getCount()) + " signals?", QMessageBox::Yes|QMessageBox::No); + if (confirmDialog == QMessageBox::Yes) + { + QTreeWidgetItem *currItem = ui->treeDBC->currentItem(); + if (itemToMessage.contains(currItem)) + { + DBC_MESSAGE *msg = itemToMessage.value(currItem); + deleteMessage(msg); + } + else + { + qDebug() << "WTF, could not find the message in the map. That should not happen."; + } + } + break; + case 3: //no cascade, just this one signal. + confirmDialog = QMessageBox::question(this, "Really?", "Are you sure you want to delete this signal?", + QMessageBox::Yes|QMessageBox::No); + if (confirmDialog == QMessageBox::Yes) + { + QTreeWidgetItem *currItem = ui->treeDBC->currentItem(); + if (itemToSignal.contains(currItem)) + { + DBC_SIGNAL *sig = itemToSignal.value(currItem); + deleteSignal(sig); + } + else + { + qDebug() << "WTF, could not find the signal in the map. That should not happen."; + } + } + break; } } + +//these don't ask for permission. You call it, it disappears forever. +void DBCMainEditor::deleteNode(DBC_NODE *node) +{ + qDebug() << "Going through with it you mass deleter!"; + if (!nodeToItem.contains(node)) return; + QTreeWidgetItem *currItem = nodeToItem[node]; + //don't actually store which messages are associated to which nodes so just iterate through the messages list and whack the ones + //that claim to be associated to this node. + int numItems = dbcFile->messageHandler->getCount(); + for (int i = numItems - 1; i > -1; i--) + { + if (dbcFile->messageHandler->findMsgByIdx(i)->sender == node) deleteMessage(dbcFile->messageHandler->findMsgByIdx(i)); + } + + for (int j = 0; j < dbcFile->dbc_nodes.count(); j++) + { + if (dbcFile->dbc_nodes.at(j).name == node->name) dbcFile->dbc_nodes.removeAt(j); + } + + nodeToItem.remove(node); + itemToNode.remove(currItem); + ui->treeDBC->removeItemWidget(currItem, 0); + delete currItem; + dbcFile->setDirtyFlag(); +} + +void DBCMainEditor::deleteMessage(DBC_MESSAGE *msg) +{ + qDebug() << "Deleting the message and all signals. Bye bye!"; + if (!messageToItem.contains(msg)) return; + QTreeWidgetItem *currItem = messageToItem[msg]; + + int numItems = msg->sigHandler->getCount(); + for (int i = numItems - 1; i > -1; i--) + { + deleteSignal(msg->sigHandler->findSignalByIdx(i)); + } + + dbcFile->messageHandler->removeMessage(msg); + + itemToMessage.remove(currItem); + messageToItem.remove(msg); + ui->treeDBC->removeItemWidget(currItem, 0); + delete currItem; + dbcFile->setDirtyFlag(); +} + +void DBCMainEditor::deleteSignal(DBC_SIGNAL *sig) +{ + qDebug() << "Signal about to vanish."; + if (!signalToItem.contains(sig)) return; + QTreeWidgetItem *currItem = signalToItem[sig]; + sig->parentMessage->sigHandler->removeSignal(sig); + + itemToSignal.remove(currItem); + signalToItem.remove(sig); + ui->treeDBC->removeItemWidget(currItem, 0); + delete currItem; + dbcFile->setDirtyFlag(); +} diff --git a/dbc/dbcmaineditor.h b/dbc/dbcmaineditor.h index b92815d..02e8e1f 100644 --- a/dbc/dbcmaineditor.h +++ b/dbc/dbcmaineditor.h @@ -3,8 +3,13 @@ #include #include +#include +#include +#include #include "dbchandler.h" #include "dbcsignaleditor.h" +#include "dbcmessageeditor.h" +#include "dbcnodeeditor.h" #include "utility.h" namespace Ui { @@ -20,35 +25,57 @@ public: ~DBCMainEditor(); void setFileIdx(int idx); +public slots: + void updatedNode(DBC_NODE *node); + void updatedMessage(DBC_MESSAGE *msg); + void updatedSignal(DBC_SIGNAL *sig); + private slots: - void onCellChangedNode(int,int); - void onCellClickedNode(int, int); - void onCellClickedMessage(int, int); - void onCellChangedMessage(int,int); - void onCustomMenuNode(QPoint); - void onCustomMenuMessage(QPoint); - void deleteCurrentNode(); - void deleteCurrentMessage(); + void onTreeDoubleClicked(const QModelIndex &index); + void currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *prev); + void onCustomMenuTree(QPoint); + void deleteCurrentTreeItem(); + void deleteNode(DBC_NODE *node); + void deleteMessage(DBC_MESSAGE *msg); + void deleteSignal(DBC_SIGNAL *sig); + void handleSearch(); + void handleSearchForward(); + void handleSearchBackward(); + void newNode(); + void newMessage(); + void newSignal(); private: Ui::DBCMainEditor *ui; DBCHandler *dbcHandler; const QVector *referenceFrames; DBCSignalEditor *sigEditor; - int currRow; + DBCMessageEditor *msgEditor; + DBCNodeEditor *nodeEditor; DBCFile *dbcFile; int fileIdx; - bool inhibitCellChanged; + QIcon nodeIcon; + QIcon messageIcon; + QIcon signalIcon; + QIcon multiplexorSignalIcon; + QIcon multiplexedSignalIcon; + QList searchItems; + int searchItemPos; + //bidirectional mapping of QTreeWidget items back and forth to DBC objects + QMap nodeToItem; + QMap messageToItem; + QMap signalToItem; + QMap itemToNode; + QMap itemToMessage; + QMap itemToSignal; + QRandomGenerator randGen; - void refreshNodesTable(); - void refreshMessagesTable(const DBC_NODE *node); void showEvent(QShowEvent* event); void closeEvent(QCloseEvent *event); bool eventFilter(QObject *obj, QEvent *event); void readSettings(); void writeSettings(); - void insertBlankRow(); - + void refreshTree(); }; #endif // DBCMAINEDITOR_H diff --git a/dbc/dbcmessageeditor.cpp b/dbc/dbcmessageeditor.cpp new file mode 100644 index 0000000..2366696 --- /dev/null +++ b/dbc/dbcmessageeditor.cpp @@ -0,0 +1,266 @@ +#include "dbcmessageeditor.h" +#include "ui_dbcmessageeditor.h" + +#include +#include +#include +#include "helpwindow.h" +#include "utility.h" + +DBCMessageEditor::DBCMessageEditor(QWidget *parent) : + QDialog(parent), + ui(new Ui::DBCMessageEditor) +{ + ui->setupUi(this); + + readSettings(); + + dbcHandler = DBCHandler::getReference(); + dbcMessage = nullptr; + suppressEditCallbacks = false; + + connect(ui->lineComment, &QLineEdit::editingFinished, + [=]() + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + if (dbcMessage->comment != ui->lineComment->text()) dbcFile->setDirtyFlag(); + dbcMessage->comment = ui->lineComment->text(); + emit updatedTreeInfo(dbcMessage); + }); + + connect(ui->lineFrameID, &QLineEdit::editingFinished, + [=]() + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + if (dbcMessage->ID != Utility::ParseStringToNum(ui->lineFrameID->text())) dbcFile->setDirtyFlag(); + dbcMessage->ID = Utility::ParseStringToNum(ui->lineFrameID->text()); + emit updatedTreeInfo(dbcMessage); + }); + + connect(ui->lineMsgName, &QLineEdit::editingFinished, + [=]() + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + if (dbcMessage->name != ui->lineMsgName->text().simplified().replace(' ', '_')) dbcFile->setDirtyFlag(); + dbcMessage->name = ui->lineMsgName->text().simplified().replace(' ', '_'); + emit updatedTreeInfo(dbcMessage); + }); + + connect(ui->lineFrameLen, &QLineEdit::editingFinished, + [=]() + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + if (dbcMessage->len != Utility::ParseStringToNum(ui->lineFrameLen->text())) dbcFile->setDirtyFlag(); + dbcMessage->len = Utility::ParseStringToNum(ui->lineFrameLen->text()); + }); + + connect(ui->comboSender, &QComboBox::currentTextChanged, + [=](const QString newText) + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + DBC_NODE *node = dbcFile->findNodeByName(newText); + if (!node) return; + if (node != dbcMessage->sender) dbcFile->setDirtyFlag(); + dbcMessage->sender = node; + emit updatedTreeInfo(dbcMessage); + }); + + connect(ui->comboSender->lineEdit(), &QLineEdit::editingFinished, + [=]() + { + if (dbcMessage == nullptr) return; + if (suppressEditCallbacks) return; + QString newText = ui->comboSender->currentText(); + DBC_NODE *node = dbcFile->findNodeByName(newText); + if (!node) + { + DBC_NODE newNode; + newNode.name = newText; + dbcFile->dbc_nodes.append(newNode); + node = dbcFile->findNodeByName(newText); + ui->comboSender->addItem(newText); + } + if (node != dbcMessage->sender) dbcFile->setDirtyFlag(); + dbcMessage->sender = node; + emit updatedTreeInfo(dbcMessage); + }); + + connect(ui->btnTextColor, &QAbstractButton::clicked, + [=]() + { + if (suppressEditCallbacks) return; + QColor newColor = QColorDialog::getColor(dbcMessage->fgColor); + if (dbcMessage->fgColor != newColor) dbcFile->setDirtyFlag(); + dbcMessage->fgColor = newColor; + DBC_ATTRIBUTE_VALUE *val = dbcMessage->findAttrValByName("GenMsgForegroundColor"); + if (val) + { + val->value = newColor.name(); + } + else + { + DBC_ATTRIBUTE_VALUE newVal; + newVal.attrName = "GenMsgForegroundColor"; + newVal.value = newColor.name(); + dbcMessage->attributes.append(newVal); + } + generateSampleText(); + }); + + connect(ui->btnBackgroundColor, &QAbstractButton::clicked, + [=]() + { + if (suppressEditCallbacks) return; + QColor newColor = QColorDialog::getColor(dbcMessage->bgColor); + if (dbcMessage->bgColor != newColor) dbcFile->setDirtyFlag(); + dbcMessage->bgColor = newColor; + DBC_ATTRIBUTE_VALUE *val = dbcMessage->findAttrValByName("GenMsgBackgroundColor"); + if (val) + { + val->value = newColor.name(); + } + else + { + DBC_ATTRIBUTE_VALUE newVal; + newVal.attrName = "GenMsgBackgroundColor"; + newVal.value = newColor.name(); + dbcMessage->attributes.append(newVal); + } + generateSampleText(); + }); + + installEventFilter(this); +} + +DBCMessageEditor::~DBCMessageEditor() +{ + removeEventFilter(this); + delete ui; +} + +void DBCMessageEditor::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); + writeSettings(); +} + +bool DBCMessageEditor::eventFilter(QObject *obj, QEvent *event) +{ + if (event->type() == QEvent::KeyRelease) { + QKeyEvent *keyEvent = static_cast(event); + switch (keyEvent->key()) + { + case Qt::Key_F1: + HelpWindow::getRef()->showHelp("messageeditor.html"); + break; + } + return true; + } else { + // standard event processing + return QObject::eventFilter(obj, event); + } + return false; +} + +void DBCMessageEditor::setFileIdx(int idx) +{ + if (idx < 0 || idx > dbcHandler->getFileCount() - 1) return; + dbcFile = dbcHandler->getFileByIdx(idx); + + suppressEditCallbacks = true; + ui->comboSender->clear(); + for (int x = 0; x < dbcFile->dbc_nodes.count(); x++) + { + ui->comboSender->addItem(dbcFile->dbc_nodes[x].name); + } + suppressEditCallbacks = false; +} + +void DBCMessageEditor::readSettings() +{ + QSettings settings; + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + resize(settings.value("DBCMessageEditor/WindowSize", QSize(340, 400)).toSize()); + move(settings.value("DBCMessageEditor/WindowPos", QPoint(100, 100)).toPoint()); + } +} + +void DBCMessageEditor::writeSettings() +{ + QSettings settings; + + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + settings.setValue("DBCMessageEditor/WindowSize", size()); + settings.setValue("DBCMessageEditor/WindowPos", pos()); + } +} + + +void DBCMessageEditor::setMessageRef(DBC_MESSAGE *msg) +{ + dbcMessage = msg; +} + +void DBCMessageEditor::showEvent(QShowEvent* event) +{ + QDialog::showEvent(event); + + refreshView(); +} + +void DBCMessageEditor::refreshView() +{ + suppressEditCallbacks = true; + + ui->lineComment->setText(dbcMessage->comment); + ui->lineFrameID->setText(Utility::formatCANID(dbcMessage->ID)); + ui->lineMsgName->setText(dbcMessage->name); + ui->lineFrameLen->setText(QString::number(dbcMessage->len)); + for (int i = 0; i < ui->comboSender->count(); i++) + { + if (ui->comboSender->itemText(i) == dbcMessage->sender->name) + { + ui->comboSender->setCurrentIndex(i); + break; + } + } + + suppressEditCallbacks = false; + + generateSampleText(); +} + +void DBCMessageEditor::generateSampleText() +{ + QBrush fg, bg; + + if (dbcMessage->fgColor.isValid()) fg = QBrush(dbcMessage->fgColor); + else fg = QBrush(QColor(dbcFile->findAttributeByName("GenMsgForegroundColor")->defaultValue.toString())); + if (dbcMessage->bgColor.isValid()) bg = QBrush(dbcMessage->bgColor); + else bg = QBrush(QColor(dbcFile->findAttributeByName("GenMsgBackgroundColor")->defaultValue.toString())); + + ui->listSample->clear(); + QListWidgetItem *item = new QListWidgetItem("Test String"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("0x20F TestMsg"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("20 FF 10 A1 BB CC 4D"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("1024.3434"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); +} diff --git a/dbc/dbcmessageeditor.h b/dbc/dbcmessageeditor.h new file mode 100644 index 0000000..473b54d --- /dev/null +++ b/dbc/dbcmessageeditor.h @@ -0,0 +1,42 @@ +#ifndef DBCMESSAGEEDITOR_H +#define DBCMESSAGEEDITOR_H + +#include +#include "dbc_classes.h" +#include "dbchandler.h" + +namespace Ui { +class DBCMessageEditor; +} + +class DBCMessageEditor : public QDialog +{ + Q_OBJECT + +public: + explicit DBCMessageEditor(QWidget *parent = nullptr); + ~DBCMessageEditor(); + void showEvent(QShowEvent*); + void setMessageRef(DBC_MESSAGE *msg); + void setFileIdx(int idx); + void refreshView(); + +signals: + void updatedTreeInfo(DBC_MESSAGE *msg); + +private: + Ui::DBCMessageEditor *ui; + + DBCHandler *dbcHandler; + DBC_MESSAGE *dbcMessage; + DBCFile *dbcFile; + bool suppressEditCallbacks; + + void closeEvent(QCloseEvent *event); + bool eventFilter(QObject *obj, QEvent *event); + void readSettings(); + void writeSettings(); + void generateSampleText(); +}; + +#endif // DBCMESSAGEEDITOR_H diff --git a/dbc/dbcnodeeditor.cpp b/dbc/dbcnodeeditor.cpp new file mode 100644 index 0000000..0f25543 --- /dev/null +++ b/dbc/dbcnodeeditor.cpp @@ -0,0 +1,148 @@ +#include "dbcnodeeditor.h" +#include "ui_dbcnodeeditor.h" + +#include +#include +#include +#include "helpwindow.h" +#include "utility.h" + +DBCNodeEditor::DBCNodeEditor(QWidget *parent) : + QDialog(parent), + ui(new Ui::DBCNodeEditor) +{ + ui->setupUi(this); + + readSettings(); + + dbcHandler = DBCHandler::getReference(); + dbcNode = nullptr; + + connect(ui->lineComment, &QLineEdit::editingFinished, + [=]() + { + if (dbcNode == nullptr) return; + if (dbcNode->comment != ui->lineComment->text()) dbcFile->setDirtyFlag(); + dbcNode->comment = ui->lineComment->text(); + emit updatedTreeInfo(dbcNode); + }); + + connect(ui->lineMsgName, &QLineEdit::editingFinished, + [=]() + { + if (dbcNode == nullptr) return; + if (dbcNode->name != ui->lineMsgName->text()) dbcFile->setDirtyFlag(); + dbcNode->name = ui->lineMsgName->text(); + emit updatedTreeInfo(dbcNode); + }); + + installEventFilter(this); +} + +DBCNodeEditor::~DBCNodeEditor() +{ + removeEventFilter(this); + delete ui; +} + +void DBCNodeEditor::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); + writeSettings(); +} + +bool DBCNodeEditor::eventFilter(QObject *obj, QEvent *event) +{ + if (event->type() == QEvent::KeyRelease) { + QKeyEvent *keyEvent = static_cast(event); + switch (keyEvent->key()) + { + case Qt::Key_F1: + HelpWindow::getRef()->showHelp("nodeeditor.html"); + break; + } + return true; + } else { + // standard event processing + return QObject::eventFilter(obj, event); + } + return false; +} + +void DBCNodeEditor::setFileIdx(int idx) +{ + if (idx < 0 || idx > dbcHandler->getFileCount() - 1) return; + dbcFile = dbcHandler->getFileByIdx(idx); +} + +void DBCNodeEditor::readSettings() +{ + QSettings settings; + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + resize(settings.value("DBCNodeEditor/WindowSize", QSize(312, 128)).toSize()); + move(settings.value("DBCNodeEditor/WindowPos", QPoint(100, 100)).toPoint()); + } +} + +void DBCNodeEditor::writeSettings() +{ + QSettings settings; + + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + settings.setValue("DBCNodeEditor/WindowSize", size()); + settings.setValue("DBCNodeEditor/WindowPos", pos()); + } +} + + +void DBCNodeEditor::setNodeRef(DBC_NODE *node) +{ + dbcNode = node; +} + +void DBCNodeEditor::showEvent(QShowEvent* event) +{ + QDialog::showEvent(event); + + refreshView(); +} + +void DBCNodeEditor::refreshView() +{ + ui->lineComment->setText(dbcNode->comment); + ui->lineMsgName->setText(dbcNode->name); + + //generateSampleText(); +} + +void DBCNodeEditor::generateSampleText() +{ + /* + QBrush fg, bg; + + if (dbcMessage->fgColor.isValid()) fg = QBrush(dbcMessage->fgColor); + else fg = QBrush(QColor(dbcFile->findAttributeByName("GenMsgForegroundColor")->defaultValue.toString())); + if (dbcMessage->bgColor.isValid()) bg = QBrush(dbcMessage->bgColor); + else bg = QBrush(QColor(dbcFile->findAttributeByName("GenMsgBackgroundColor")->defaultValue.toString())); + + ui->listSample->clear(); + QListWidgetItem *item = new QListWidgetItem("Test String"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("0x20F TestMsg"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("20 FF 10 A1 BB CC 4D"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + item = new QListWidgetItem("1024.3434"); + item->setForeground(fg); + item->setBackground(bg); + ui->listSample->addItem(item); + */ +} diff --git a/dbc/dbcnodeeditor.h b/dbc/dbcnodeeditor.h new file mode 100644 index 0000000..3bd65e0 --- /dev/null +++ b/dbc/dbcnodeeditor.h @@ -0,0 +1,41 @@ +#ifndef DBCNODEEDITOR_H +#define DBCNODEEDITOR_H + +#include +#include "dbc_classes.h" +#include "dbchandler.h" + +namespace Ui { +class DBCNodeEditor; +} + +class DBCNodeEditor : public QDialog +{ + Q_OBJECT + +public: + explicit DBCNodeEditor(QWidget *parent = nullptr); + ~DBCNodeEditor(); + void showEvent(QShowEvent*); + void setNodeRef(DBC_NODE *node); + void setFileIdx(int idx); + void refreshView(); + +signals: + void updatedTreeInfo(DBC_NODE *node); + +private: + Ui::DBCNodeEditor *ui; + + DBCHandler *dbcHandler; + DBC_NODE *dbcNode; + DBCFile *dbcFile; + + void closeEvent(QCloseEvent *event); + bool eventFilter(QObject *obj, QEvent *event); + void readSettings(); + void writeSettings(); + void generateSampleText(); +}; + +#endif // DBCNODEEDITOR_H diff --git a/dbc/dbcsignaleditor.cpp b/dbc/dbcsignaleditor.cpp index 1ca3c2b..ce69871 100644 --- a/dbc/dbcsignaleditor.cpp +++ b/dbc/dbcsignaleditor.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include "helpwindow.h" @@ -15,8 +16,6 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : readSettings(); - qsrand(QDateTime::currentMSecsSinceEpoch()); - dbcHandler = DBCHandler::getReference(); dbcMessage = nullptr; currentSignal = nullptr; @@ -35,10 +34,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : ui->comboType->addItem("DOUBLE PRECISION"); ui->comboType->addItem("STRING"); - connect(ui->signalsList, SIGNAL(currentRowChanged(int)), this, SLOT(clickSignalList(int))); connect(ui->bitfield, SIGNAL(gridClicked(int,int)), this, SLOT(bitfieldClicked(int,int))); - connect(ui->signalsList, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomMenuSignals(QPoint))); - ui->signalsList->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->valuesTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onCustomMenuValues(QPoint))); ui->valuesTable->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->valuesTable, SIGNAL(cellChanged(int,int)), this, SLOT(onValuesCellChanged(int,int))); @@ -48,6 +44,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : [=]() { if (currentSignal == nullptr) return; + if (currentSignal->intelByteOrder != ui->cbIntelFormat->isChecked()) dbcFile->setDirtyFlag(); currentSignal->intelByteOrder = ui->cbIntelFormat->isChecked(); fillSignalForm(currentSignal); }); @@ -56,7 +53,9 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : [=]() { if (currentSignal == nullptr) return; - currentSignal->receiver = dbcFile->findNodeByName(ui->comboReceiver->currentText()); + DBC_NODE *node = dbcFile->findNodeByName(ui->comboReceiver->currentText()); + if (currentSignal->receiver != node) dbcFile->setDirtyFlag(); + currentSignal->receiver = node; }); connect(ui->comboType, &QComboBox::currentTextChanged, [=]() @@ -84,6 +83,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : currentSignal->valType = STRING; break; } + dbcFile->setDirtyFlag(); fillSignalForm(currentSignal); }); connect(ui->txtBias, &QLineEdit::editingFinished, @@ -93,7 +93,11 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : double temp; bool result; temp = ui->txtBias->text().toDouble(&result); - if (result) currentSignal->bias = temp; + if (result) + { + if (currentSignal->bias != temp) dbcFile->setDirtyFlag(); + currentSignal->bias = temp; + } }); connect(ui->txtMaxVal, &QLineEdit::editingFinished, @@ -103,7 +107,11 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : double temp; bool result; temp = ui->txtMaxVal->text().toDouble(&result); - if (result) currentSignal->max = temp; + if (result) + { + if (currentSignal->max != temp) dbcFile->setDirtyFlag(); + currentSignal->max = temp; + } }); connect(ui->txtMinVal, &QLineEdit::editingFinished, @@ -113,7 +121,11 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : double temp; bool result; temp = ui->txtMinVal->text().toDouble(&result); - if (result) currentSignal->min = temp; + if (result) + { + if (currentSignal->min != temp) dbcFile->setDirtyFlag(); + currentSignal->min = temp; + } }); connect(ui->txtScale, &QLineEdit::editingFinished, [=]() @@ -122,19 +134,26 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : double temp; bool result; temp = ui->txtScale->text().toDouble(&result); - if (result) currentSignal->factor = temp; + if (result) + { + if (currentSignal->factor != temp) dbcFile->setDirtyFlag(); + currentSignal->factor = temp; + } }); connect(ui->txtComment, &QLineEdit::editingFinished, [=]() { if (currentSignal == nullptr) return; + if (currentSignal->comment != ui->txtComment->text().simplified().replace(' ','_')) dbcFile->setDirtyFlag(); currentSignal->comment = ui->txtComment->text().simplified().replace(' ', '_'); + emit updatedTreeInfo(currentSignal); }); connect(ui->txtUnitName, &QLineEdit::editingFinished, [=]() { if (currentSignal == nullptr) return; + if (currentSignal->unitName != ui->txtUnitName->text().simplified().replace(' ','_')) dbcFile->setDirtyFlag(); currentSignal->unitName = ui->txtUnitName->text().simplified().replace(' ', '_'); }); connect(ui->txtBitLength, &QLineEdit::textChanged, @@ -143,8 +162,9 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : if (currentSignal == nullptr) return; int temp; temp = Utility::ParseStringToNum(ui->txtBitLength->text()); - if (temp < 0) return; - if (temp > 63) return; + if (temp < 1) return; + if (temp > 64) return; + if (currentSignal->signalSize != temp) dbcFile->setDirtyFlag(); if (currentSignal->valType != SP_FLOAT && currentSignal->valType != DP_FLOAT) currentSignal->signalSize = temp; fillSignalForm(currentSignal); @@ -154,9 +174,10 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : { if (currentSignal == nullptr) return; QString tempNameStr = ui->txtName->text().simplified().replace(' ', '_'); + if (currentSignal->name != tempNameStr) dbcFile->setDirtyFlag(); if (tempNameStr.length() > 0) currentSignal->name = tempNameStr; - //need to update the list too. - ui->signalsList->currentItem()->setText(currentSignal->name); + //need to update the tree too. + emit updatedTreeInfo(currentSignal); }); connect(ui->txtMultiplexValue, &QLineEdit::editingFinished, @@ -165,6 +186,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : if (currentSignal == nullptr) return; int temp; temp = Utility::ParseStringToNum(ui->txtMultiplexValue->text()); + if (currentSignal->multiplexValue != temp) dbcFile->setDirtyFlag(); //TODO: could look up the multiplexor and ensure that the value is within a range that the multiplexor could return currentSignal->multiplexValue = temp; }); @@ -178,6 +200,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : //if the set multiplexor for the message was this signal then clear it if (dbcMessage->multiplexorSignal == currentSignal) dbcMessage->multiplexorSignal = nullptr; } + dbcFile->setDirtyFlag(); }); connect(ui->rbMultiplexor, &QRadioButton::toggled, @@ -192,6 +215,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : //we just set that this is the multiplexor so update the message to show that as well. dbcMessage->multiplexorSignal = currentSignal; } + dbcFile->setDirtyFlag(); }); connect(ui->rbNotMulti, &QRadioButton::toggled, @@ -203,6 +227,7 @@ DBCSignalEditor::DBCSignalEditor(QWidget *parent) : currentSignal->isMultiplexor = false; if (dbcMessage->multiplexorSignal == currentSignal) dbcMessage->multiplexorSignal = nullptr; } + dbcFile->setDirtyFlag(); }); installEventFilter(this); @@ -229,9 +254,6 @@ bool DBCSignalEditor::eventFilter(QObject *obj, QEvent *event) case Qt::Key_F1: HelpWindow::getRef()->showHelp("signaleditor.html"); break; - case Qt::Key_F2: - cloneSignal(); - break; } return true; } else { @@ -279,12 +301,24 @@ void DBCSignalEditor::setMessageRef(DBC_MESSAGE *msg) dbcMessage = msg; } +void DBCSignalEditor::setSignalRef(DBC_SIGNAL *sig) +{ + currentSignal = sig; +} + + void DBCSignalEditor::showEvent(QShowEvent* event) { QDialog::showEvent(event); - currentSignal = nullptr; - refreshSignalsList(); + fillSignalForm(currentSignal); + fillValueTable(currentSignal); +} + +void DBCSignalEditor::refreshView() +{ + fillSignalForm(currentSignal); + fillValueTable(currentSignal); } void DBCSignalEditor::onValuesCellChanged(int row,int col) @@ -318,21 +352,6 @@ void DBCSignalEditor::onValuesCellChanged(int row,int col) } } -void DBCSignalEditor::onCustomMenuSignals(QPoint point) -{ - QMenu *menu = new QMenu(this); - menu->setAttribute(Qt::WA_DeleteOnClose); - - menu->addAction(tr("Add a new signal"), this, SLOT(addNewSignal())); - if (ui->signalsList->currentRow() != -1) - { - menu->addAction(tr("Clone currently selected signal"), this, SLOT(cloneSignal())); - menu->addAction(tr("Delete currently selected signal"), this, SLOT(deleteCurrentSignal())); - } - - menu->popup(ui->signalsList->mapToGlobal(point)); -} - void DBCSignalEditor::onCustomMenuValues(QPoint point) { QMenu *menu = new QMenu(this); @@ -343,86 +362,6 @@ void DBCSignalEditor::onCustomMenuValues(QPoint point) menu->popup(ui->valuesTable->mapToGlobal(point)); } -void DBCSignalEditor::addNewSignal() -{ - int num = qrand() % 70000; - QString newName = "SIGNAL" + QString::number(num); - DBC_SIGNAL newSig; - newSig.name = newName; - newSig.bias = 0.0; - newSig.factor = 1.0; - newSig.intelByteOrder = true; - newSig.max = 0.0; - newSig.min = 0.0; - newSig.receiver = dbcFile->findNodeByIdx(0); - newSig.signalSize = 1; - newSig.startBit = 0; - newSig.valType = UNSIGNED_INT; - newSig.isMultiplexed = false; - newSig.isMultiplexor = false; - newSig.multiplexValue = 0; - newSig.parentMessage = dbcMessage; - - dbcMessage->sigHandler->addSignal(newSig); - - /* add item at the end of the list and select it */ - /* this will call clickSignalList */ - ui->signalsList->addItem(newName); - ui->signalsList->setCurrentRow(ui->signalsList->count()-1); -} - -void DBCSignalEditor::cloneSignal() -{ - int num = qrand() % 100; - - int idx = ui->signalsList->currentRow(); - if (idx < 0) return; - - DBC_SIGNAL *oldSig = dbcMessage->sigHandler->findSignalByIdx(idx); - if (!oldSig) return; - - QString newName = oldSig->name + QString::number(num); - DBC_SIGNAL newSig; - newSig.name = newName; - newSig.bias = oldSig->bias; - newSig.factor = oldSig->factor; - newSig.intelByteOrder = oldSig->intelByteOrder; - newSig.max = oldSig->max; - newSig.min = oldSig->min; - newSig.receiver = oldSig->receiver; - newSig.signalSize = oldSig->signalSize; - newSig.startBit = oldSig->startBit; - newSig.valType = oldSig->valType; - newSig.valList.append(oldSig->valList); - newSig.isMultiplexed = oldSig->isMultiplexed; - newSig.isMultiplexor = oldSig->isMultiplexor; //maybe should force this false since you can't have two or more! - newSig.multiplexValue = oldSig->multiplexValue; - newSig.parentMessage = dbcMessage; - - dbcMessage->sigHandler->addSignal(newSig); - - /* add item at the end of the list */ - ui->signalsList->addItem(newName); - - //unlike adding a signal we don't want to select the new signal here. - //ui->signalsList->setCurrentRow(ui->signalsList->count()-1); -} - -void DBCSignalEditor::deleteCurrentSignal() -{ - int currIdx = ui->signalsList->currentRow(); - - //if(currIdx==ui->signalsList->count()-1) - //return; - - if (currIdx > -1) - { - delete(ui->signalsList->item(currIdx)); - dbcMessage->sigHandler->removeSignal(currIdx); - currentSignal = nullptr; - } -} - void DBCSignalEditor::deleteCurrentValue() { int currIdx = ui->valuesTable->currentRow(); @@ -433,25 +372,6 @@ void DBCSignalEditor::deleteCurrentValue() } } -void DBCSignalEditor::refreshSignalsList() -{ - ui->signalsList->clear(); - - - for (int x = 0; x < dbcMessage->sigHandler->getCount(); x++) - { - DBC_SIGNAL *sig = dbcMessage->sigHandler->findSignalByIdx(x); - ui->signalsList->addItem(sig->name); - } - - if( ui->signalsList->count()>0 ) { - /* click first element */ - ui->signalsList->setCurrentRow(0); - } - else - clickSignalList(-1); -} - /* fillSignalForm also handles group "enabled" state */ /* WARNING: fillSignalForm can be called recursively since it is in the listener of cbIntelFormat */ void DBCSignalEditor::fillSignalForm(DBC_SIGNAL *sig) @@ -585,7 +505,7 @@ void DBCSignalEditor::fillValueTable(DBC_SIGNAL *sig) for (int i = 0; i < sig->valList.count(); i++) { - QTableWidgetItem *val = new QTableWidgetItem(Utility::formatNumber(sig->valList[i].value)); + QTableWidgetItem *val = new QTableWidgetItem(Utility::formatNumber((uint64_t)sig->valList[i].value)); QTableWidgetItem *desc = new QTableWidgetItem(sig->valList[i].descript); rowIdx = ui->valuesTable->rowCount(); ui->valuesTable->insertRow(rowIdx); @@ -599,16 +519,6 @@ void DBCSignalEditor::fillValueTable(DBC_SIGNAL *sig) inhibitCellChanged = false; } -void DBCSignalEditor::clickSignalList(int row) -{ - //qDebug() << ui->signalsList->item(row)->text(); - - DBC_SIGNAL *thisSig = (row<0) ? nullptr : dbcMessage->sigHandler->findSignalByName(ui->signalsList->item(row)->text()); - currentSignal = thisSig; - fillSignalForm(thisSig); - fillValueTable(thisSig); -} - void DBCSignalEditor::bitfieldClicked(int x, int y) { int bit = (7 - x) + (y * 8); @@ -644,6 +554,7 @@ void DBCSignalEditor::generateUsedBits() { int byt = y / 8; usedBits[byt] |= 1 << (y % 8); + ui->bitfield->setUsedSignalNum(y, x); } } else //big endian / motorola format @@ -654,6 +565,7 @@ void DBCSignalEditor::generateUsedBits() { int byt = startBit / 8; usedBits[byt] |= 1 << (startBit % 8); + ui->bitfield->setUsedSignalNum(startBit, x); size--; if ((startBit % 8) == 0) startBit += 15; else startBit--; diff --git a/dbc/dbcsignaleditor.h b/dbc/dbcsignaleditor.h index e807f58..0c69ea3 100644 --- a/dbc/dbcsignaleditor.h +++ b/dbc/dbcsignaleditor.h @@ -16,19 +16,19 @@ class DBCSignalEditor : public QDialog public: explicit DBCSignalEditor(QWidget *parent = 0); void setMessageRef(DBC_MESSAGE *msg); - void showEvent(QShowEvent*); void setFileIdx(int idx); + void setSignalRef(DBC_SIGNAL *sig); + void showEvent(QShowEvent*); ~DBCSignalEditor(); + void refreshView(); + +signals: + void updatedTreeInfo(DBC_SIGNAL *sig); private slots: - void clickSignalList(int); void bitfieldClicked(int x, int y); void onValuesCellChanged(int row,int col); - void onCustomMenuSignals(QPoint); void onCustomMenuValues(QPoint); - void addNewSignal(); - void cloneSignal(); - void deleteCurrentSignal(); void deleteCurrentValue(); private: @@ -39,7 +39,6 @@ private: DBCFile *dbcFile; bool inhibitCellChanged; - void refreshSignalsList(); void fillSignalForm(DBC_SIGNAL *sig); void fillValueTable(DBC_SIGNAL *sig); void generateUsedBits(); diff --git a/docs/source/fuzzingwindow.rst b/docs/source/fuzzingwindow.rst index 36bdf48..a2a3a6f 100644 --- a/docs/source/fuzzingwindow.rst +++ b/docs/source/fuzzingwindow.rst @@ -13,12 +13,13 @@ Some people are big fans of fuzzing, some people have no use for it. There usual Fuzzing is Dangerous ==================== -You have now been warned. Sending random garbage over the CAN bus to see what happens could mess something up. It just might put your vehicle into gear and cause you to drive over a box full of kittens. Be careful! Never fuzz a car unless you're right there and you can stop it. Even better, don't do it unless your car is up on a hoist or something and can't drive over anyone. Even still, there is a small chance you could cause an adverse effect to your car. +You have now been warned. Sending random garbage over the CAN bus to see what happens could mess something up. It just might put your vehicle into gear and cause you to drive over a box full of kittens. Be careful! Never fuzz a car unless you're right there and you can stop it. Even better, don't do it unless your car is up on a hoist or jacks and can't drive over anyone. Even still, there is a small chance you could cause an adverse effect to your car. If you break something you own the pieces. Controlling the Fuzzy Beast =========================== -So, you want to give it a try? Let's do it! First of all, you can set the delay between frames and the burst rate. The burst rate can cause the program to send one than one frame each interval. This is useful as a CAN bus could potentially support 2000 to 8000 frames per second. Then you can set the number of bytes to send. Ordinarily this would be the full 8 but you can experiment with smaller frames. You can set to send on a specific bus. That's all the simple settings. It gets a bit more complicated now. +So, you want to give it a try? Let's do it! First of all, you can set the delay between frames and the burst rate. The delay is in milliseconds but can be set as low as 0. If the delay is set to 0 then the system will attempt to send frames as fast as it can. However, even then you may not get quite as many frames per second as you'd like. Even at 0 it will still be scheduled by your operating system and so might not quite get to the speed you want. The burst rate can cause the program to send one than one frame each interval. This is useful as a CAN bus could potentially support 2000 to 8000 frames per second. If you need rapid frame sending your best bet is to set the sending interval to 1-2ms and then adjust the burst +rate until you get your desired sending rate. Then you can set the number of bytes to send. Ordinarily this would be the full 8 but you can experiment with smaller frames. You can set to send on a specific bus. That's all the simple settings. It gets a bit more complicated now. The "ID Scanning" box has two radio buttons: @@ -36,9 +37,10 @@ The last box is "Bit Scanning" 2. Sweep causes the system to set the first one, then unset that one and set the second bit, then unset that, etc. Thus the fuzzed bit sweeps and only one fuzzed bit is set at once. 3. Random will randomly pick whether each fuzzed bit is set or not. -In order to fuzz bits you need to set which bits to fuzz and which not to. As listed at the bottom of the window, there is a color code to the 8x8 grid. Clicking cells in the grid will toggle them between their various values. White bits are never set, black bits are always set no matter what, green bits follow the fuzzing pattern you specified in "Bit Scanning" +In order to fuzz bits you need to set which bits to fuzz and which not to. As listed at the bottom of the window, there is a color code to the 8x8 grid. Clicking cells in the grid will toggle them between their various values. White bits are never set, black bits are always set no matter what, green bits follow the fuzzing pattern you specified in "Bit Scanning" You can also set the bytes directly with the text boxes above the 8x8 grid. Setting a hexadecimal value in these +boxes will set the relavent bits in the 8x8 grid. You must press the ENTER/RETURN key to set the values. Merely changing the value will not update it (as a safety measure). Pulling the Trigger =================== -Once you've configured everything click "Start Fuzzing" to give it a shot. You will see the number of frames sent so far listed below the button. You can stop the fuzzing by pushing the button again. +Once you've configured everything click "Start Fuzzing" to give it a shot. You will see the number of frames sent so far listed below the button. Approximately four times per second the current value for each byte is copied into the text boxes just above the 8x8 grid. This can be used to see what is going on and to ensure that it is working the way you want it to. You can stop the fuzzing by pushing the start button again. diff --git a/docs/source/images/FuzzingWindow.png b/docs/source/images/FuzzingWindow.png index 6a4950b..e863312 100644 Binary files a/docs/source/images/FuzzingWindow.png and b/docs/source/images/FuzzingWindow.png differ diff --git a/filterutility.cpp b/filterutility.cpp index a085993..72cc3ed 100644 --- a/filterutility.cpp +++ b/filterutility.cpp @@ -22,22 +22,22 @@ QString FilterUtility::getId( QListWidgetItem * item ) return getId(item->text()); } -uint32_t FilterUtility::getGMLanArbitrationId(uint32_t id) +uint32_t FilterUtility::getGMLanArbitrationId(int32_t id) { return (id >> 13) & 0x1FFF; } -uint32_t FilterUtility::getGMLanPriorityBits(uint32_t id) +uint32_t FilterUtility::getGMLanPriorityBits(int32_t id) { return (id >> 26) & 0x7; } -uint32_t FilterUtility::getGMLanSenderId(uint32_t id) +uint32_t FilterUtility::getGMLanSenderId(int32_t id) { return id & 0x1FFF; } -QListWidgetItem * FilterUtility::createCheckableFilterItem(uint32_t id, bool checked, QListWidget* parent) +QListWidgetItem * FilterUtility::createCheckableFilterItem(int32_t id, bool checked, QListWidget* parent) { QListWidgetItem * thisItem = createFilterItem(id,parent); thisItem->setFlags(thisItem->flags() | Qt::ItemIsUserCheckable); @@ -48,19 +48,22 @@ QListWidgetItem * FilterUtility::createCheckableFilterItem(uint32_t id, bool che return thisItem; } -QListWidgetItem * FilterUtility::createFilterItem(uint32_t id, QListWidget* parent) +QListWidgetItem * FilterUtility::createFilterItem(int32_t id, QListWidget* parent) { QSettings settings; DBCHandler * dbcHandler = DBCHandler::getReference(); QListWidgetItem *thisItem = new QListWidgetItem(parent); QString filterItemName = Utility::formatCANID(id); + //Note, there are multiple filter labeling preferences. There is one in main settings to globally + //enable or disable them all. Then each loaded DBC file also can be selected on/off + //Both must be enabled for you to see labeling. if (settings.value("Main/FilterLabeling", false).toBool()) - { + { // Filter labeling (show interpreted frame names next to the CAN addr ID) MatchingCriteria_t matchingCriteria; DBC_MESSAGE *msg = dbcHandler->findMessageForFilter(id,&matchingCriteria); - if (msg != NULL) + if (msg != nullptr) { filterItemName.append(" "); filterItemName.append(msg->name); @@ -77,4 +80,4 @@ QListWidgetItem * FilterUtility::createFilterItem(uint32_t id, QListWidget* pare thisItem->setText(filterItemName); return thisItem; -} \ No newline at end of file +} diff --git a/filterutility.h b/filterutility.h index 3e0eeaa..e346c31 100644 --- a/filterutility.h +++ b/filterutility.h @@ -8,16 +8,16 @@ class FilterUtility { public: - static QListWidgetItem * createFilterItem(uint32_t id, QListWidget* parent=NULL); // if parent is given, add item automatically to listwidget - static QListWidgetItem * createCheckableFilterItem(uint32_t id, bool checked, QListWidget* parent=NULL); + static QListWidgetItem * createFilterItem(int32_t id, QListWidget* parent=NULL); // if parent is given, add item automatically to listwidget + static QListWidgetItem * createCheckableFilterItem(int32_t id, bool checked, QListWidget* parent=NULL); static uint32_t getIdAsInt( QListWidgetItem * item ); static QString getId( QListWidgetItem * item ); static QString getId( QString itemText ); - static uint32_t getGMLanArbitrationId(uint32_t id); - static uint32_t getGMLanSenderId(uint32_t id); - static uint32_t getGMLanPriorityBits(uint32_t id); + static uint32_t getGMLanArbitrationId(int32_t id); + static uint32_t getGMLanSenderId(int32_t id); + static uint32_t getGMLanPriorityBits(int32_t id); }; -#endif // DBCLOADSAVEWINDOW_H \ No newline at end of file +#endif // DBCLOADSAVEWINDOW_H diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index 2b13746..44571d3 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -4,6 +4,13 @@ #include +//You might wonder: Collin, what in the hell is this for? Firmware uploader? For what? I'm interested! Well, it's a custom +//firmware uploader for a motor controller I built. Why would that be in this project. Cuz. It's not really relevant +//to anyone else but might serve as a decent reference for a few things: How to make an uploader interface that runs over CAN, +//how to lay out a screen like this, how to make a comm protocol for firmware updating over CAN. But, most things use UDS +//for firmware updates and wouldn't need this specific code. But, it might be able to be turned into a UDS firmware uploader or downloader. +//Note that this screen is specifically hidden by default because of it's oddball status. You have to re-enable it in mainwindow.cpp to see it. + FirmwareUploaderWindow::FirmwareUploaderWindow(const QVector *frames, QWidget *parent) : QDialog(parent), ui(new Ui::FirmwareUploaderWindow) @@ -70,17 +77,20 @@ void FirmwareUploaderWindow::updatedFrames(int numFrames) void FirmwareUploaderWindow::gotTargettedFrame(CANFrame frame) { - qDebug() << "FUW: Got targetted frame with id " << frame.ID; - if (frame.ID == (uint32_t)(baseAddress + 0x10)) { + const unsigned char *data = reinterpret_cast(frame.payload().constData()); + int dataLen = frame.payload().count(); + + qDebug() << "FUW: Got targetted frame with id " << frame.frameId(); + if (frame.frameId() == (uint32_t)(baseAddress + 0x10) && (dataLen == 8) ) { qDebug() << "Start firmware reply"; - if ((frame.data[0] == 0xAD) && (frame.data[1] == 0xDE)) + if ((data[0] == 0xAD) && (data[1] == 0xDE)) { - if ((frame.data[2] == 0xAF) && (frame.data[3] == 0xDE)) + if ((data[2] == 0xAF) && (data[3] == 0xDE)) { - qDebug() << "THere's dead beef here"; - if ((frame.data[4] == (token & 0xFF)) && (frame.data[5] == ((token >> 8) & 0xFF))) + qDebug() << "There's dead beef here"; + if ( (data[4] == (token & 0xFF)) && (data[5] == ((token >> 8) & 0xFF) ) ) { - if ((frame.data[6] == ((token >> 16) & 0xFF)) && (frame.data[7] == ((token >> 24) & 0xFF))) + if ((data[6] == ((token >> 16) & 0xFF)) && (data[7] == ((token >> 24) & 0xFF))) { qDebug() << "starting firmware process"; //MainWindow::getReference()->setTargettedID(baseAddress + 0x20); @@ -92,9 +102,9 @@ void FirmwareUploaderWindow::gotTargettedFrame(CANFrame frame) } } - if (frame.ID == (uint32_t)(baseAddress + 0x20)) { + if (frame.frameId() == (uint32_t)(baseAddress + 0x20)) { qDebug() << "Firmware reception success reply"; - int seq = frame.data[0] + (256 * frame.data[1]); + int seq = data[0] + (256 * data[1]); if (seq == currentSendingPosition) { currentSendingPosition++; @@ -126,18 +136,19 @@ void FirmwareUploaderWindow::sendFirmwareChunk() CANFrame *output = new CANFrame; int firmwareLocation = currentSendingPosition * 4; int xorByte = 0; - output->extended = false; - output->len = 7; + output->setExtendedFrameFormat(false); + QByteArray bytes(7,0); output->bus = bus; - output->ID = baseAddress + 0x16; - output->data[0] = currentSendingPosition & 0xFF; - output->data[1] = (currentSendingPosition >> 8) & 0xFF; - output->data[2] = firmwareData[firmwareLocation++]; - output->data[3] = firmwareData[firmwareLocation++]; - output->data[4] = firmwareData[firmwareLocation++]; - output->data[5] = firmwareData[firmwareLocation++]; - for (int i = 0; i < 6; i++) xorByte = xorByte ^ output->data[i]; - output->data[6] = xorByte; + output->setFrameId(baseAddress + 0x16); + output->payload()[0] = currentSendingPosition & 0xFF; + output->payload()[1] = (currentSendingPosition >> 8) & 0xFF; + output->payload()[2] = firmwareData[firmwareLocation++]; + output->payload()[3] = firmwareData[firmwareLocation++]; + output->payload()[4] = firmwareData[firmwareLocation++]; + output->payload()[5] = firmwareData[firmwareLocation++]; + for (int i = 0; i < 6; i++) xorByte = xorByte ^ static_cast(output->payload()[i]); + output->payload()[6] = xorByte; + output->setPayload(bytes); sendCANFrame(output); timer->start(); } @@ -145,14 +156,15 @@ void FirmwareUploaderWindow::sendFirmwareChunk() void FirmwareUploaderWindow::sendFirmwareEnding() { CANFrame *output = new CANFrame; - output->extended = false; + output->setExtendedFrameFormat(false); output->bus = bus; - output->len = 4; - output->ID = baseAddress + 0x30; - output->data[3] = 0xC0; - output->data[2] = 0xDE; - output->data[1] = 0xFA; - output->data[0] = 0xDE; + QByteArray bytes(4,0); + output->setFrameId(baseAddress + 0x30); + output->payload()[3] = 0xC0; + output->payload()[2] = 0xDE; + output->payload()[1] = 0xFA; + output->payload()[0] = 0xDE; + output->setPayload(bytes); //sendCANFrame(output, bus); } @@ -171,19 +183,19 @@ void FirmwareUploaderWindow::handleStartStopTransfer() CANConManager::getInstance()->addTargettedFrame(bus, baseAddress + 0x10, 0x7FF, this); CANConManager::getInstance()->addTargettedFrame(bus, baseAddress + 0x20, 0x7FF, this); CANFrame *output = new CANFrame; - output->extended = false; - output->len = 8; + output->setExtendedFrameFormat(false); + QByteArray bytes(8,0); output->bus = bus; - output->ID = baseAddress; + output->setFrameId(baseAddress); - output->data[0] = 0xEF; - output->data[1] = 0xBE; - output->data[2] = 0xAD; - output->data[3] = 0xDE; - output->data[4] = token & 0xFF; - output->data[5] = (token >> 8) & 0xFF; - output->data[6] = (token >> 16) & 0xFF; - output->data[7] = (token >> 24) & 0xFF; + output->payload()[0] = 0xEF; + output->payload()[1] = 0xBE; + output->payload()[2] = 0xAD; + output->payload()[3] = 0xDE; + output->payload()[4] = token & 0xFF; + output->payload()[5] = (token >> 8) & 0xFF; + output->payload()[6] = (token >> 16) & 0xFF; + output->payload()[7] = (token >> 24) & 0xFF; sendCANFrame(output); } else //stop anything in process diff --git a/framefileio.cpp b/framefileio.cpp index e704099..daf95c0 100644 --- a/framefileio.cpp +++ b/framefileio.cpp @@ -28,7 +28,7 @@ bool FrameFileIO::saveFrameFile(QString &fileName, const QVector* fram filters.append(QString(tr("CRTD Logs (*.crt *.crtd *.CRT *.CRTD)"))); filters.append(QString(tr("Generic ID/Data CSV (*.csv *.CSV)"))); filters.append(QString(tr("BusMaster Log (*.log *.LOG)"))); - filters.append(QString(tr("Microchip Log (*.can *.CAN)"))); + filters.append(QString(tr("Microchip Log (*.can *.CAN *.log *.LOG)"))); filters.append(QString(tr("Vector Trace Files (*.trace *.TRACE)"))); filters.append(QString(tr("IXXAT MiniLog (*.csv *.CSV)"))); filters.append(QString(tr("CAN-DO Log (*.can *.avc *.evc *.qcc *.CAN *.AVC *.EVC *.QCC)"))); @@ -148,7 +148,7 @@ bool FrameFileIO::loadFrameFile(QString &fileName, QVector* frameCache filters.append(QString(tr("GVRET Logs (*.csv *.CSV)"))); filters.append(QString(tr("CRTD Logs (*.crt *.crtd *.CRT *.CRTD)"))); filters.append(QString(tr("BusMaster Log (*.log *.LOG)"))); - filters.append(QString(tr("Microchip Log (*.can *.CAN)"))); + filters.append(QString(tr("Microchip Log (*.can *.CAN *.log *.LOG)"))); filters.append(QString(tr("Vector trace files (*.trace *.TRACE)"))); filters.append(QString(tr("IXXAT MiniLog (*.csv *.CSV)"))); filters.append(QString(tr("CAN-DO Log (*.avc *.can *.evc *.qcc *.AVC *.CAN *.EVC *.QCC)"))); @@ -219,9 +219,12 @@ bool FrameFileIO::loadFrameFile(QString &fileName, QVector* frameCache } else { - QMessageBox msgBox; - msgBox.setText("File load completed with errors.\r\nPerhaps you selected the wrong file type?"); - msgBox.exec(); + if (dialog.selectedNameFilter() != filters[0]) + { + QMessageBox msgBox; + msgBox.setText("File load completed with errors.\r\nPerhaps you selected the wrong file type?"); + msgBox.exec(); + } return false; } } @@ -229,7 +232,7 @@ bool FrameFileIO::loadFrameFile(QString &fileName, QVector* frameCache } -//Try every format by first uses the "is" functions which try to detect whether a given file is a good match to that +//Try every format by first using the "is" functions which try to detect whether a given file is a good match to that //file format or not. Those functions are much less tolerant than the load functions and so should help to discriminate //whether a file could be loaded or not by a given loader. The loader return is still used in case the guess was wrong. bool FrameFileIO::autoDetectLoadFile(QString filename, QVector* frames) @@ -430,6 +433,9 @@ bool FrameFileIO::autoDetectLoadFile(QString filename, QVector* frames } } + QMessageBox msgBox; + msgBox.setText("Could not autodetect the file type.\rPlease try to manually select the file format."); + msgBox.exec(); qDebug() << "Nothing worked... sorry..."; return false; } @@ -524,26 +530,25 @@ bool FrameFileIO::loadVehicleSpyFile(QString filename, QVector *frames if (tokens.length() > 20) { thisFrame.bus = 0; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); tempTime = now; tempTime = tempTime.addMSecs(static_cast(tokens[1].toDouble() * 1000.0)); - thisFrame.timestamp = static_cast(tempTime.toMSecsSinceEpoch() * 1000); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(tempTime.toMSecsSinceEpoch() * 1000))); if (tokens[5].startsWith("T")) thisFrame.isReceived = false; else thisFrame.isReceived = true; - thisFrame.ID = static_cast(tokens[9].toInt(nullptr, 16)); - if (tokens[11].startsWith("T")) thisFrame.extended = true; - else thisFrame.extended = false; - - thisFrame.len = 0; + thisFrame.setFrameId(static_cast(tokens[9].toInt(nullptr, 16))); + if (tokens[11].startsWith("T")) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); + QByteArray bytes; for (int i = 0; i < 8; i++) { if (tokens[12 + i].length() > 0) { - thisFrame.data[i] = static_cast(tokens[12 + i].toInt(nullptr, 16)); - thisFrame.len++; + bytes.append(static_cast(tokens[12 + i].toInt(nullptr, 16))); } else break; } + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -680,7 +685,7 @@ bool FrameFileIO::loadCRTDFile(QString filename, QVector* frames) multiplier = 1; //special case. Assume no decimal means microseconds } //qDebug() << "decimal places " << decimalPlaces; - thisFrame.timestamp = static_cast((tokens[0].toDouble() * multiplier)); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast((tokens[0].toDouble() * multiplier)))); thisFrame.bus = 0; char firstChar = tokens[1].left(1)[0]; if (firstChar >= '1' && firstChar <= '9') @@ -691,21 +696,22 @@ bool FrameFileIO::loadCRTDFile(QString filename, QVector* frames) } if (firstChar == 'R' || firstChar == 'T') { - thisFrame.ID = static_cast(tokens[2].toInt(nullptr, 16)); - if (tokens[1] == "R29" || tokens[1] == "T29") thisFrame.extended = true; - else thisFrame.extended = false; + thisFrame.setFrameId(static_cast(tokens[2].toInt(nullptr, 16))); + if (tokens[1] == "R29" || tokens[1] == "T29") thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); if (firstChar == 'T') thisFrame.isReceived = false; else thisFrame.isReceived = true; - thisFrame.len = tokens.length() - 3; - thisFrame.remote = false; - for (int d = 0; d < thisFrame.len; d++) + QByteArray bytes(tokens.length() - 3, 0); + thisFrame.setFrameType(QCanBusFrame::DataFrame); + for (int d = 0; d < bytes.length(); d++) { if (tokens[d + 3] != "") { - thisFrame.data[d] = static_cast(tokens[d + 3].toInt(nullptr, 16)); + bytes[d] = static_cast(tokens[d + 3].toInt(nullptr, 16)); } - else thisFrame.data[d] = 0; + else bytes[d] = 0; } + thisFrame.setPayload(bytes); frames->append(thisFrame); } } @@ -904,21 +910,23 @@ bool FrameFileIO::loadCANHackerFile(QString filename, QVector* frames) multiplier = 1; //special case. Assume no decimal means microseconds } //qDebug() << "decimal places " << decimalPlaces; - thisFrame.timestamp = static_cast(tokens[0].toDouble() * multiplier); - thisFrame.ID = static_cast(tokens[1].toInt(nullptr, 16)); - thisFrame.extended = (thisFrame.ID > 0x7FF); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(tokens[0].toDouble() * multiplier))); + thisFrame.setFrameId( static_cast(tokens[1].toInt(nullptr, 16)) ); + thisFrame.setExtendedFrameFormat((thisFrame.frameId() > 0x7FF)); thisFrame.isReceived = true; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); thisFrame.bus = 0; - thisFrame.len = tokens[2].toInt(nullptr, 16); - for (int d = 0; d < thisFrame.len; d++) + int numBytes = tokens[2].toInt(nullptr, 16); + QByteArray bytes( numBytes, 0); + for (int d = 0; d < numBytes; d++) { if (tokens[d + 3] != "") { - thisFrame.data[d] = static_cast(tokens[d + 3].toInt(nullptr, 16)); + bytes[d] = static_cast(tokens[d + 3].toInt(nullptr, 16)); } - else thisFrame.data[d] = 0; + else bytes[d] = 0; } + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -1020,22 +1028,23 @@ bool FrameFileIO::loadCANOpenFile(QString filename, QVector* frames) QList tokens = line.split(','); if (tokens.length() > 11) { - thisFrame.timestamp = static_cast(tokens[1].simplified().toDouble() * 1000.0); - thisFrame.ID = static_cast(Utility::ParseStringToNum(tokens[5].simplified())); - thisFrame.extended = (thisFrame.ID > 0x7FF); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(tokens[1].simplified().toDouble() * 1000.0))); + thisFrame.setFrameId(static_cast(Utility::ParseStringToNum(tokens[5].simplified()))); + thisFrame.setExtendedFrameFormat( (thisFrame.frameId() > 0x7FF) ); thisFrame.isReceived = true; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); thisFrame.bus = 0; QList dataTok = tokens[11].simplified().split(' '); - thisFrame.len = dataTok.length(); - for (int d = 0; d < thisFrame.len; d++) + QByteArray bytes(dataTok.length(), 0); + for (int d = 0; d < dataTok.length(); d++) { if (dataTok[d] != "") { - thisFrame.data[d] = static_cast(dataTok[d].simplified().toInt(nullptr, 16)); + bytes[d] = static_cast(dataTok[d].simplified().toInt(nullptr, 16)); } - else thisFrame.data[d] = 0; + else bytes[d] = 0; } + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -1051,6 +1060,10 @@ bool FrameFileIO::saveCRTDFile(QString filename, const QVector* frames QFile *outFile = new QFile(filename); int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) { delete outFile; @@ -1058,7 +1071,7 @@ bool FrameFileIO::saveCRTDFile(QString filename, const QVector* frames } //write in float format with 6 digits after the decimal point - outFile->write(QString::number(frames->at(0).timestamp / 1000000.0, 'f', 6).toUtf8() + tr(" CXX GVRET-PC Reverse Engineering Tool Output V").toUtf8() + QString::number(VERSION).toUtf8()); + outFile->write(QString::number(frames->at(0).timeStamp().microSeconds() / 1000000.0, 'f', 6).toUtf8() + tr(" CXX GVRET-PC Reverse Engineering Tool Output V").toUtf8() + QString::number(VERSION).toUtf8()); outFile->write("\n"); for (int c = 0; c < frames->count(); c++) @@ -1070,24 +1083,28 @@ bool FrameFileIO::saveCRTDFile(QString filename, const QVector* frames lineCounter = 0; } - outFile->write(QString::number(frames->at(c).timestamp / 1000000.0, 'f', 6).toUtf8()); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + outFile->write(QString::number(frame->timeStamp().microSeconds() / 1000000.0, 'f', 6).toUtf8()); outFile->putChar(' '); - outFile->write(QString::number(frames->at(c).bus + 1).toUtf8()); - if (frames->at(c).isReceived) outFile->putChar('R'); + outFile->write(QString::number(frame->bus + 1).toUtf8()); + if (frame->isReceived) outFile->putChar('R'); else outFile->putChar('T'); - if (frames->at(c).extended) + if (frame->hasExtendedFrameFormat()) { outFile->write("29 "); } else outFile->write("11 "); - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->putChar(' '); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); } @@ -1218,65 +1235,69 @@ bool FrameFileIO::loadPCANFile(QString filename, QVector* frames) { if (fileVersion == 1) { - thisFrame.timestamp = (uint64_t)(line.mid(10, 8).simplified().toDouble() * 1000.0); - thisFrame.ID = line.mid(28, 8).simplified().toUInt(nullptr, 16); - if (thisFrame.ID < 0x1FFFFFFF) + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, (uint64_t)(line.mid(10, 8).simplified().toDouble() * 1000.0))); + thisFrame.setFrameId(line.mid(28, 8).simplified().toUInt(nullptr, 16)); + if (thisFrame.frameId() < 0x1FFFFFFF) { - thisFrame.len = line.mid(38,1).toInt(); + int numBytes = line.mid(38,1).toInt(); + QByteArray bytes(numBytes, 0); thisFrame.isReceived = true; thisFrame.bus = 0; if (line.at(28) == ' ') { - thisFrame.extended = false; + thisFrame.setExtendedFrameFormat(false); } else { - thisFrame.extended = true; + thisFrame.setExtendedFrameFormat(true); } if (line.at(41) == 'R') { - thisFrame.remote = true; + thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - QList tokens = line.mid(41, thisFrame.len * 3).split(' '); - thisFrame.remote = false; - for (int d = 0; d < thisFrame.len; d++) + QList tokens = line.mid(41, thisFrame.payload().length() * 3).split(' '); + thisFrame.setFrameType(QCanBusFrame::DataFrame); + for (int d = 0; d < numBytes; d++) { if (tokens[d] != "") { - thisFrame.data[d] = static_cast(tokens[d].toInt(nullptr, 16)); + bytes[d] = static_cast(tokens[d].toInt(nullptr, 16)); } - else thisFrame.data[d] = 0; + else bytes[d] = 0; } } + thisFrame.setPayload(bytes); frames->append(thisFrame); } } else if (fileVersion == 2) { - thisFrame.timestamp = static_cast(line.mid(8, 13).simplified().toDouble() * 1000.0); - thisFrame.ID = line.mid(25, 8).simplified().toUInt(nullptr, 16); - if (thisFrame.ID < 0x1FFFFFFF) + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(line.mid(8, 13).simplified().toDouble() * 1000.0))); + thisFrame.setFrameId(line.mid(25, 8).simplified().toUInt(nullptr, 16)); + if (thisFrame.frameId() < 0x1FFFFFFF) { - thisFrame.len = line.mid(37,2).trimmed().toInt(); - qDebug() << thisFrame.len; + int numBytes = line.mid(37,2).trimmed().toInt(); + QByteArray bytes(numBytes, 0); + qDebug() << thisFrame.payload().length(); thisFrame.isReceived = true; thisFrame.bus = 0; if (line.at(25) == ' ') { - thisFrame.extended = false; + thisFrame.setExtendedFrameFormat(false); } else { - thisFrame.extended = true; + thisFrame.setExtendedFrameFormat(true); } if (line.at(40) == 'R') { - thisFrame.remote = true; + thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - QList tokens = line.mid(40, thisFrame.len * 3).split(' '); - thisFrame.remote = false; - for (int d = 0; d < thisFrame.len; d++) + QList tokens = line.mid(40, thisFrame.payload().length() * 3).split(' '); + thisFrame.setFrameType(QCanBusFrame::DataFrame); + for (int d = 0; d < numBytes; d++) { if (tokens[d] != "") { - thisFrame.data[d] = static_cast(tokens[d].toInt(nullptr, 16)); + bytes[d] = static_cast(tokens[d].toInt(nullptr, 16)); } - else thisFrame.data[d] = 0; + else bytes[d] = 0; } } + thisFrame.setPayload(bytes); frames->append(thisFrame); } } @@ -1361,7 +1382,7 @@ bool FrameFileIO::loadCanalyzerASC(QString filename, QVector* frames) int lineCounter = 0; bool foundErrors = false; bool inHeader = true; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); QList tokens; if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) @@ -1392,37 +1413,51 @@ bool FrameFileIO::loadCanalyzerASC(QString filename, QVector* frames) tokens = line.simplified().split(' '); if (tokens.length() > 5) { - thisFrame.timestamp = static_cast(tokens[0].toDouble() * 1000000.0); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(tokens[0].toDouble() * 1000000.0))); if (tokens[2].endsWith('x')) { QByteArray copied_id = tokens[2]; copied_id.chop(1); - thisFrame.ID = copied_id.toUInt(nullptr, 16); - thisFrame.extended = true; + thisFrame.setFrameId(copied_id.toUInt(nullptr, 16)); + thisFrame.setExtendedFrameFormat(true); } else { - thisFrame.ID = tokens[2].toUInt(nullptr, 16); - thisFrame.extended = false; + thisFrame.setFrameId(tokens[2].toUInt(nullptr, 16)); + thisFrame.setExtendedFrameFormat(false); + } + + int payloadLen = tokens[5].toInt(); + QByteArray bytes(payloadLen, 0); + + if (payloadLen > 8) + { + qDebug() << "Payload length too long. Original line: " << line; + return false; + } + if (payloadLen < 0) + { + qDebug() << "Payload length negative! Original line: " << line; + return false; } - thisFrame.len = tokens[5].toInt(); - if (thisFrame.len > 8) return false; - if (thisFrame.len < 0) return false; thisFrame.isReceived = tokens[3].toUpper().contains("RX"); thisFrame.bus = tokens[1].toInt(); - thisFrame.remote = tokens[4] == "r"; - for (int d = 6; d < (6 + static_cast(thisFrame.len)); d++) + if (tokens[4] == "r") thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); + for (int d = 6; d < (6 + payloadLen); d++) { if (tokens.count() > d) { - thisFrame.data[d - 6] = static_cast(tokens[d].toInt(nullptr, 16)); + bytes[d - 6] = static_cast(tokens[d].toInt(nullptr, 16)); } else //expected byte wasn't there to read. Set it zero and set error flag { - thisFrame.data[d - 6] = 0; - foundErrors = true; + bytes[d - 6] = 0; + foundErrors = true; + qDebug() << "D:" << d << " Count:" << tokens.count(); + qDebug() << "Expected byte missing! Original line: " << line; } } + thisFrame.setPayload(bytes); } frames->append(thisFrame); } @@ -1437,10 +1472,15 @@ bool FrameFileIO::saveCanalyzerASC(QString filename, const QVector* fr { QFile *outFile = new QFile(filename); int lineCounter = 0; - uint64_t offsetTime = frames->at(0).timestamp; + int64_t offsetTime = frames->at(0).timeStamp().microSeconds(); + + const unsigned char *data; + int dataLen; + const CANFrame *frame; + for (int c = 0; c < frames->count(); c++) { - if (frames->at(c).timestamp < offsetTime) offsetTime = frames->at(c).timestamp; + if (frames->at(c).timeStamp().microSeconds() < offsetTime) offsetTime = frames->at(c).timeStamp().microSeconds(); } if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -1470,24 +1510,28 @@ bool FrameFileIO::saveCanalyzerASC(QString filename, const QVector* fr lineCounter = 0; } - uint64_t timeStamp = (frames->at(c).timestamp - offsetTime) / 1000000ull; + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + uint64_t timeStamp = (frame->timeStamp().microSeconds() - offsetTime) / 1000000ull; int tsLen = QString::number(timeStamp).length(); int precision = 6; //vector seems to keep 10 bytes at the start of the line for the timestamp. It should never exceed this //and there should never be a precision over 6 digits after the decimal if (tsLen > 3) precision = 9 - tsLen; - outFile->write(QString::number((frames->at(c).timestamp - offsetTime) / 1000000.0, 'f', precision).rightJustified(10, ' ').toUtf8()); + outFile->write(QString::number((frame->timeStamp().microSeconds() - offsetTime) / 1000000.0, 'f', precision).rightJustified(10, ' ').toUtf8()); outFile->putChar(' '); - outFile->write(QString::number(frames->at(c).bus + 1).toUtf8()); + outFile->write(QString::number(frame->bus + 1).toUtf8()); outFile->write(" "); - if (frames->at(c).extended) + if (frames->at(c).hasExtendedFrameFormat()) { - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->write("x"); } else { - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(3, '0').toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(3, '0').toUtf8()); outFile->write(" "); } outFile->write(" "); @@ -1495,15 +1539,15 @@ bool FrameFileIO::saveCanalyzerASC(QString filename, const QVector* fr if (frames->at(c).isReceived) outFile->write("Rx "); else outFile->write("Tx "); - if (frames->at(c).remote) outFile->write("r "); + if (frames->at(c).frameType() == QCanBusFrame::RemoteRequestFrame) outFile->write("r "); else outFile->write("d "); - outFile->write(QString::number(frames->at(c).len).toUtf8()); + outFile->write(QString::number(dataLen).toUtf8()); outFile->write(" "); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->write(" "); } @@ -1612,7 +1656,7 @@ bool FrameFileIO::loadNativeCSVFile(QString filename, QVector* frames) uint64_t timeStamp = Utility::GetTimeMS(); int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -1639,44 +1683,48 @@ bool FrameFileIO::loadNativeCSVFile(QString filename, QVector* frames) { if (tokens[0].length() > 3) { - thisFrame.timestamp = tokens[0].toULongLong(); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, tokens[0].toULongLong())); } else { timeStamp += 5; - thisFrame.timestamp = timeStamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); } - thisFrame.ID = tokens[1].toUInt(nullptr, 16); - if (tokens[2].toUpper().contains("TRUE")) thisFrame.extended = 1; - else thisFrame.extended = 0; + thisFrame.setFrameId(tokens[1].toUInt(nullptr, 16)); + if (tokens[2].toUpper().contains("TRUE")) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (fileVersion == 1) { thisFrame.isReceived = true; thisFrame.bus = tokens[3].toInt(); - thisFrame.len = tokens[4].toInt(); - if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len < 0) thisFrame.len = 0; - for (int c = 0; c < 8; c++) thisFrame.data[c] = 0; - if (thisFrame.len + 5 > tokens.length()) thisFrame.len = tokens.length() - 5; - for (int d = 0; d < thisFrame.len; d++) - thisFrame.data[d] = static_cast(tokens[5 + d].toInt(nullptr, 16)); + int lng = tokens[4].toInt(); + if (lng > 8) lng = 8; + if (lng < 0) lng = 0; + if (lng + 5 > tokens.length()) lng = tokens.length() - 5; + QByteArray bytes(lng, 0); + for (int c = 0; c < 8; c++) bytes[c] = 0; + for (int d = 0; d < lng; d++) + bytes[d] = static_cast(tokens[5 + d].toInt(nullptr, 16)); + thisFrame.setPayload(bytes); } else if (fileVersion == 2) { if (tokens[3].at(0) == 'R') thisFrame.isReceived = true; else thisFrame.isReceived = false; - thisFrame.bus = tokens[4].toInt(); - thisFrame.len = tokens[5].toInt(); - if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len < 0) thisFrame.len = 0; - if (thisFrame.len + 6 > tokens.length()) thisFrame.len = tokens.length() - 6; - for (int c = 0; c < 8; c++) thisFrame.data[c] = 0; - for (int d = 0; d < thisFrame.len; d++) - thisFrame.data[d] = static_cast(tokens[6 + d].toInt(nullptr, 16)); + thisFrame.bus = tokens[4].toInt(); + int lng = tokens[5].toInt(); + if (lng > 8) lng = 8; + if (lng < 0) lng = 0; + if (lng + 6 > tokens.length()) lng = tokens.length() - 6; + QByteArray bytes(lng, 0); + for (int c = 0; c < 8; c++) bytes[c] = 0; + for (int d = 0; d < lng; d++) + bytes[d] = static_cast(tokens[6 + d].toInt(nullptr, 16)); + thisFrame.setPayload(bytes); } frames->append(thisFrame); @@ -1694,6 +1742,10 @@ bool FrameFileIO::saveNativeCSVFile(QString filename, const QVector* f QFile *outFile = new QFile(filename); int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) { delete outFile; @@ -1712,28 +1764,32 @@ bool FrameFileIO::saveNativeCSVFile(QString filename, const QVector* f lineCounter = 0; } - outFile->write(QString::number(frames->at(c).timestamp).toUtf8()); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + outFile->write(QString::number(frame->timeStamp().microSeconds()).toUtf8()); outFile->putChar(44); - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->putChar(44); - if (frames->at(c).extended) outFile->write("true,"); + if (frame->hasExtendedFrameFormat()) outFile->write("true,"); else outFile->write("false,"); - if (frames->at(c).isReceived) outFile->write("Rx,"); + if (frame->isReceived) outFile->write("Rx,"); else outFile->write("Tx,"); - outFile->write(QString::number(frames->at(c).bus).toUtf8()); + outFile->write(QString::number(frame->bus).toUtf8()); outFile->putChar(44); - outFile->write(QString::number(frames->at(c).len).toUtf8()); + outFile->write(QString::number(dataLen).toUtf8()); outFile->putChar(44); for (int temp = 0; temp < 8; temp++) { - if (temp < frames->at(c).len) - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + if (temp < dataLen) + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); else outFile->write("00"); outFile->putChar(44); @@ -1791,32 +1847,41 @@ bool FrameFileIO::closeContinuousNative() bool FrameFileIO::writeContinuousNative(const QVector* frames, int beginningFrame) { + + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!continuousFile.isOpen()) return false; qDebug() << "Bgn: " << beginningFrame << " Count: " << frames->count(); for (int c = beginningFrame; c < frames->count(); c++) { - continuousFile.write(QString::number(frames->at(c).timestamp).toUtf8()); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + continuousFile.write(QString::number(frame->timeStamp().microSeconds()).toUtf8()); continuousFile.putChar(44); - continuousFile.write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + continuousFile.write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); continuousFile.putChar(44); - if (frames->at(c).extended) continuousFile.write("true,"); + if (frame->hasExtendedFrameFormat()) continuousFile.write("true,"); else continuousFile.write("false,"); - if (frames->at(c).isReceived) continuousFile.write("Rx,"); + if (frame->isReceived) continuousFile.write("Rx,"); else continuousFile.write("Tx,"); - continuousFile.write(QString::number(frames->at(c).bus).toUtf8()); + continuousFile.write(QString::number(frame->bus).toUtf8()); continuousFile.putChar(44); - continuousFile.write(QString::number(frames->at(c).len).toUtf8()); + continuousFile.write(QString::number(dataLen).toUtf8()); continuousFile.putChar(44); for (int temp = 0; temp < 8; temp++) { - if (temp < frames->at(c).len) - continuousFile.write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + if (temp < dataLen) + continuousFile.write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); else continuousFile.write("00"); continuousFile.putChar(44); @@ -1894,7 +1959,7 @@ bool FrameFileIO::loadGenericCSVFile(QString filename, QVector* frames uint64_t timeStamp = Utility::GetTimeMS(); int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -1918,17 +1983,16 @@ bool FrameFileIO::loadGenericCSVFile(QString filename, QVector* frames QList tokens = line.split(','); timeStamp += 5000; - thisFrame.timestamp = timeStamp; - thisFrame.ID = tokens[0].toUInt(nullptr, 16); - if (thisFrame.ID > 0x7FF) thisFrame.extended = true; - else thisFrame.extended = false; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); + thisFrame.setFrameId(tokens[0].toUInt(nullptr, 16)); + if (thisFrame.frameId() > 0x7FF) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); thisFrame.bus = 0; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); QList dataTok = tokens[1].split(' '); - thisFrame.len = dataTok.length(); - if (thisFrame.len > 8) thisFrame.len = 8; - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = static_cast(dataTok[d].toInt(nullptr, 16)); - + QByteArray bytes(dataTok.length(), 0); + for (int d = 0; d < dataTok.length(); d++) bytes[d] = static_cast(dataTok[d].toInt(nullptr, 16)); + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -1944,6 +2008,10 @@ bool FrameFileIO::saveGenericCSVFile(QString filename, const QVector* QFile *outFile = new QFile(filename); int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) { delete outFile; @@ -1962,12 +2030,16 @@ bool FrameFileIO::saveGenericCSVFile(QString filename, const QVector* lineCounter = 0; } - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->putChar(44); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); } @@ -2098,31 +2170,34 @@ bool FrameFileIO::loadLogFile(QString filename, QVector* frames) QList timeToks = tokens[0].split(':'); timeStamp = (timeToks[0].toUInt() * (1000ul * 1000ul * 60ul * 60ul)) + (timeToks[1].toUInt() * (1000ul * 1000ul * 60ul)) + (timeToks[2].toUInt() * (1000ul * 1000ul)) + (timeToks[3].toUInt() * 100ul); - thisFrame.timestamp = timeStamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); if (tokens[1].at(0) == 'R') thisFrame.isReceived = true; else thisFrame.isReceived = false; - thisFrame.ID = tokens[3].right(tokens[3].length() - 2).toUInt(nullptr, 16); + thisFrame.setFrameId(tokens[3].right(tokens[3].length() - 2).toUInt(nullptr, 16)); if (tokens[4] == "S") { - thisFrame.extended = false; - thisFrame.remote = false; + thisFrame.setExtendedFrameFormat(false); + thisFrame.setFrameType(QCanBusFrame::DataFrame); } else if (tokens[4] == "X") { - thisFrame.extended = true; - thisFrame.remote = false; + thisFrame.setExtendedFrameFormat(true); + thisFrame.setFrameType(QCanBusFrame::DataFrame); } else if (tokens[4] == "SR") { - thisFrame.extended = false; - thisFrame.remote = true; + thisFrame.setExtendedFrameFormat(false); + thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { // XR - thisFrame.extended = true; - thisFrame.remote = true; + thisFrame.setExtendedFrameFormat(true); + thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); } - thisFrame.bus = tokens[2].toInt() - 1; - thisFrame.len = tokens[5].toInt(); - if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len < 0) thisFrame.len = 0; - if (!thisFrame.remote) { - for (int d = 0; d < thisFrame.len; d++) - thisFrame.data[d] = static_cast(tokens[d + 6].toInt(nullptr, 16)); + thisFrame.bus = tokens[2].toInt(); + + int lng = tokens[5].toInt(); + if (lng > 8) lng = 8; + if (lng < 0) lng = 0; + QByteArray bytes(lng, 0); + if (thisFrame.frameType() != QCanBusFrame::RemoteRequestFrame) { + for (int d = 0; d < lng; d++) + bytes[d] = static_cast(tokens[d + 6].toInt(nullptr, 16)); } + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -2139,6 +2214,10 @@ bool FrameFileIO::saveLogFile(QString filename, const QVector* frames) QDateTime timestamp, tempStamp; int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + //timestamp = QDateTime::currentDateTime(); if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -2172,28 +2251,32 @@ bool FrameFileIO::saveLogFile(QString filename, const QVector* frames) lineCounter = 0; } - tempStamp = QDateTime::fromMSecsSinceEpoch(frames->at(c).timestamp / 1000); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + tempStamp = QDateTime::fromMSecsSinceEpoch(frame->timeStamp().microSeconds() / 1000); outFile->write(tempStamp.toString("hh:mm:ss:zzz").toUtf8()); - if (frames->at(c).isReceived) outFile->write(" Rx "); + if (frame->isReceived) outFile->write(" Rx "); else outFile->write(" Tx "); // busmaster channel start at 1 - outFile->write(QString::number(frames->at(c).bus+1).toUtf8() + " "); + outFile->write(QString::number(frame->bus + 1).toUtf8() + " "); outFile->write("0x"); - if (frames->at(c).extended && frames->at(c).ID > 0x7FF) { - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); + if (frame->hasExtendedFrameFormat() && frame->frameId() > 0x7FF) { + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8()); } else { - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(3, '0').toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(3, '0').toUtf8()); } - if (frames->at(c).extended) outFile->write(" x"); + if (frame->hasExtendedFrameFormat()) outFile->write(" x"); else outFile->write(" s"); - if (frames->at(c).remote) outFile->write("r "); + if (frame->frameType() == QCanBusFrame::RemoteRequestFrame) outFile->write("r "); else outFile->write(" "); - outFile->write(QString::number(frames->at(c).len).toUtf8() + " "); + outFile->write(QString::number(dataLen).toUtf8() + " "); - if (!frames->at(c).remote) { - for (int temp = 0; temp < frames->at(c).len; temp++) + if (frame->frameType() != QCanBusFrame::RemoteRequestFrame) { + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); } } @@ -2250,7 +2333,7 @@ bool FrameFileIO::loadIXXATFile(QString filename, QVector* frames) uint64_t timeStamp = Utility::GetTimeMS(); int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -2287,29 +2370,31 @@ bool FrameFileIO::loadIXXATFile(QString filename, QVector* frames) foundErrors = true; return false; } - thisFrame.timestamp = timeStamp; - thisFrame.ID = Utility::unQuote(tokens[1]).toUInt(nullptr, 16); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); + thisFrame.setFrameId(Utility::unQuote(tokens[1]).toUInt(nullptr, 16)); QString tempStr = Utility::unQuote(tokens[2]).toUpper(); if (tempStr.length() > 0) { - if (tempStr.at(0) == 'S') thisFrame.extended = false; - else thisFrame.extended = true; + if (tempStr.at(0) == 'S') thisFrame.setExtendedFrameFormat(false); + else thisFrame.setExtendedFrameFormat(true); } else { - thisFrame.extended = false; + thisFrame.setExtendedFrameFormat(false); foundErrors = true; return false; } thisFrame.isReceived = true; thisFrame.bus = 0; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); QStringList dataToks = Utility::unQuote(tokens[4]).simplified().split(' '); - thisFrame.len = dataToks.length(); - if (thisFrame.len > 8) return false; - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = static_cast(dataToks[d].toInt(nullptr, 16)); + int numBytes = dataToks.length(); + QByteArray bytes(numBytes, 0); + if (numBytes > 8) return false; + for (int d = 0; d < numBytes; d++) bytes[d] = static_cast(dataToks[d].toInt(nullptr, 16)); + thisFrame.setPayload(bytes); frames->append(thisFrame); } else return false; @@ -2326,6 +2411,10 @@ bool FrameFileIO::saveIXXATFile(QString filename, const QVector* frame QDateTime timestamp, tempStamp; int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + timestamp = QDateTime::currentDateTime(); if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -2337,7 +2426,7 @@ bool FrameFileIO::saveIXXATFile(QString filename, const QVector* frame outFile->write("ASCII Trace IXXAT SavvyCAN V" + QString::number(VERSION).toUtf8() + "\n"); outFile->write("Date: " + timestamp.toString("d:M:yyyy").toUtf8() + "\n"); outFile->write("Start time: " + timestamp.toString("h:m:s").toUtf8() + "\n"); - timestamp = timestamp.addMSecs((frames->last().timestamp - frames->first().timestamp) / 1000); + timestamp = timestamp.addMSecs((frames->last().timeStamp().microSeconds() - frames->first().timeStamp().microSeconds()) / 1000); outFile->write("Stop time: " + timestamp.toString("h:m:s").toUtf8() + "\n"); outFile->write("Overruns: 0\n"); outFile->write("Baudrate: 500 kbit/s\n"); //could be a lie... this code has no way to know the baud rate (at the moment) @@ -2351,17 +2440,22 @@ bool FrameFileIO::saveIXXATFile(QString filename, const QVector* frame qApp->processEvents(); lineCounter = 0; } - tempStamp = QDateTime::fromMSecsSinceEpoch(frames->at(c).timestamp / 1000); + + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + tempStamp = QDateTime::fromMSecsSinceEpoch(frame->timeStamp().microSeconds() / 1000); outFile->write("\"" + tempStamp.toString("h:m:s.").toUtf8() + tempStamp.toString("z").rightJustified(3, '0').toUtf8() + "\""); - outFile->write(",\"" + QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8() + "\""); - if (frames->at(c).extended) outFile->write(",\"Ext\""); + outFile->write(",\"" + QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8() + "\""); + if (frame->hasExtendedFrameFormat()) outFile->write(",\"Ext\""); else outFile->write(",\"Std\""); outFile->write(",\"\",\""); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); } @@ -2428,9 +2522,9 @@ bool FrameFileIO::loadCANDOFile(QString filename, QVector* frames) int lineCounter = 0; QByteArray data; int timeOffset = 0; - uint64_t lastTimeStamp = 0; + int64_t lastTimeStamp = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly)) { @@ -2453,26 +2547,30 @@ bool FrameFileIO::loadCANDOFile(QString filename, QVector* frames) } data = inFile->read(12); + const unsigned char *uData = reinterpret_cast(data.constData()); thisFrame.bus = 0; thisFrame.isReceived = true; - thisFrame.extended = false; //format is incapable of extended frames - thisFrame.remote = false; - - thisFrame.timestamp = 1000000ul * ((unsigned char)data[0] >> 2); - thisFrame.timestamp += (((data[0] & 3) << 8) + (unsigned char)data[1]) * 1000; - thisFrame.timestamp += timeOffset; - if (thisFrame.timestamp < lastTimeStamp) + thisFrame.setExtendedFrameFormat(false); //format is incapable of extended frames + thisFrame.setFrameType(QCanBusFrame::DataFrame); + qint64 tempStamp; + tempStamp = 1000000ul * (uData[0] >> 2); + tempStamp += (((uData[0] & 3) << 8) + uData[1]) * 1000; + tempStamp += timeOffset; + if (tempStamp < lastTimeStamp) { timeOffset += 60000000ul; } - lastTimeStamp = thisFrame.timestamp; - thisFrame.ID = (((unsigned char)data[3] & 0x0F) * 256 + (unsigned char)data[2]) & 0x7FF; - thisFrame.len = (unsigned char)data[3] >> 4; + lastTimeStamp = tempStamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, tempStamp)); + thisFrame.setFrameId(((uData[3] & 0x0F) * 256 + uData[2]) & 0x7FF); + int numBytes = uData[3] >> 4; + QByteArray bytes(numBytes, 0); - if (thisFrame.len <= 8 && thisFrame.ID <= 0x7FF) + if (numBytes <= 8 && thisFrame.frameId() <= 0x7FF) { - for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)data[4 + d]; + for (int d = 0; d < numBytes; d++) bytes[d] = data[4 + d]; + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -2489,7 +2587,12 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame int lineCounter = 0; QByteArray data; CANFrame thisFrame; - int ms, id; + int id; + qint64 ms; + + const unsigned char *inData; + int inDataLen; + const CANFrame *frame; if (!outFile->open(QIODevice::WriteOnly)) { @@ -2501,7 +2604,7 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame //The initial frame in official files sets the global time but I don't care so it is set all zeros here. thisFrame = frames->at(0); - ms = (thisFrame.timestamp / 1000); + ms = (thisFrame.timeStamp().microSeconds() / 1000); data[0] = (((ms / 1000) % 60) << 2) + ((ms % 1000) >> 8); data[1] = (char)(ms & 0xFF); data[2] = (char)0xFF; @@ -2517,18 +2620,22 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame qApp->processEvents(); lineCounter = 0; } + + frame = &frames->at(c); + inData = reinterpret_cast(frame->payload().constData()); + inDataLen = frame->payload().count(); + for (int j = 0; j < 8; j++) data[4 + j] = (char)0xFF; - thisFrame = frames->at(c); - if (!thisFrame.extended) + if (!frame->hasExtendedFrameFormat()) { - ms = (thisFrame.timestamp / 1000); - id = thisFrame.ID & 0x7FF; + ms = (frame->timeStamp().microSeconds() / 1000); + id = frame->frameId() & 0x7FF; data[0] = (((ms / 1000) % 60) << 2) + ((ms % 1000) >> 8); data[1] = (char)(ms & 0xFF); data[2] = (char)(id & 0xFF); - data[3] = (char)((id >> 8) + (thisFrame.len << 4)); - for (unsigned int d = 0; d < thisFrame.len; d++) data[4 + d] = (char)thisFrame.data[d]; + data[3] = (char)((id >> 8) + (inDataLen << 4)); + for (int d = 0; d < inDataLen; d++) data[4 + d] = (char)inData[d]; outFile->write(data); } } @@ -2608,7 +2715,7 @@ bool FrameFileIO::loadMicrochipFile(QString filename, QVector* frames) long long timeStamp; int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -2641,18 +2748,20 @@ bool FrameFileIO::loadMicrochipFile(QString filename, QVector* frames) if (tokens.length() >= 4) { timeStamp = tokens[0].toInt() * 1000; - thisFrame.timestamp = timeStamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp)); if (tokens[1].at(0) == 'R') thisFrame.isReceived = true; else thisFrame.isReceived = false; - thisFrame.remote = false; - thisFrame.ID = Utility::ParseStringToNum(tokens[2]); - if (thisFrame.ID <= 0x7FF) thisFrame.extended = false; - else thisFrame.extended = true; + thisFrame.setFrameType(QCanBusFrame::DataFrame); + thisFrame.setFrameId(static_cast( Utility::ParseStringToNum(tokens[2])) ); + if (thisFrame.frameId() <= 0x7FF) thisFrame.setExtendedFrameFormat(false); + else thisFrame.setExtendedFrameFormat(true); thisFrame.bus = 0; - thisFrame.len = tokens[3].toUInt(); - if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len + 4 > (unsigned int) tokens.length()) thisFrame.len = tokens.length() - 4; - for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)Utility::ParseStringToNum(tokens[4 + d]); + int numBytes = tokens[3].toInt(); + QByteArray bytes(numBytes, 0); + if (thisFrame.payload().length() > 8) thisFrame.payload().resize(8); + if (thisFrame.payload().length() + 4 > tokens.length()) thisFrame.payload().resize( tokens.length() - 4 ); + for (int d = 0; d < numBytes; d++) bytes[d] = static_cast( Utility::ParseStringToNum(tokens[4 + d]) ); + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -2682,6 +2791,10 @@ bool FrameFileIO::saveMicrochipFile(QString filename, const QVector* f QDateTime timestamp, tempStamp; int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + timestamp = QDateTime::currentDateTime(); if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -2708,15 +2821,19 @@ bool FrameFileIO::saveMicrochipFile(QString filename, const QVector* f lineCounter = 0; } - outFile->write(QString::number((int)(frames->at(c).timestamp / 1000)).toUtf8()); - if (frames->at(c).isReceived) outFile->write(";RX;"); - else outFile->write(";TX;"); - outFile->write("0x" + QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8() + ";"); - outFile->write(QString::number(frames->at(c).len).toUtf8() + ";"); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); - for (unsigned int temp = 0; temp < frames->at(c).len; temp++) + outFile->write(QString::number((frame->timeStamp().microSeconds() / 1000)).toUtf8()); + if (frame->isReceived) outFile->write(";RX;"); + else outFile->write(";TX;"); + outFile->write("0x" + QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8() + ";"); + outFile->write(QString::number(dataLen).toUtf8() + ";"); + + for (int temp = 0; temp < dataLen; temp++) { - outFile->write("0x" + QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write("0x" + QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(';'); } @@ -2821,7 +2938,7 @@ bool FrameFileIO::loadTraceFile(QString filename, QVector* frames) long long timeStamp = 0; int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -2857,18 +2974,20 @@ bool FrameFileIO::loadTraceFile(QString filename, QVector* frames) timeStamp += timestampToks[2].toInt() * 1000000l; timeStamp += timestampToks[3].toInt() * 100; - thisFrame.timestamp = static_cast(timeStamp); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast(timeStamp))); - thisFrame.ID = static_cast(tokens[2].toLong(nullptr, 16)); - if (thisFrame.ID <= 0x7FF) thisFrame.extended = false; - else thisFrame.extended = true; + thisFrame.setFrameId(static_cast(tokens[2].toLong(nullptr, 16))); + if (thisFrame.frameId() <= 0x7FF) thisFrame.setExtendedFrameFormat(false); + else thisFrame.setExtendedFrameFormat(true); thisFrame.bus = 0; - thisFrame.remote = false; - thisFrame.len = tokens[3].toUInt(); - if (thisFrame.len > 8) thisFrame.len = 8; + thisFrame.setFrameType(QCanBusFrame::DataFrame); + int numBytes = tokens[3].toInt(); + if (numBytes > 8) numBytes = 8; + QByteArray bytes(numBytes, 0); QList dataToks = tokens[4].split(' '); - if (thisFrame.len > (unsigned int) dataToks.length()) thisFrame.len = static_cast(dataToks.length()); - for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)dataToks[d].toInt(nullptr, 16); + //if (numBytes > dataToks.length()) thisFrame.payload().resize(dataToks.length()); + for (int d = 0; d < numBytes; d++) bytes[d] = static_cast(dataToks[d].toInt(nullptr, 16)); + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -2885,9 +3004,13 @@ bool FrameFileIO::saveTraceFile(QString filename, const QVector * fram QFile *outFile = new QFile(filename); QDateTime timestamp; int lineCounter = 0; - uint64_t tempTime; + int64_t tempTime; int tempTimePiece; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + timestamp = QDateTime::currentDateTime(); if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -2926,38 +3049,41 @@ bool FrameFileIO::saveTraceFile(QString filename, const QVector * fram //lineCounter = 0; } + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); //1F D3 3F FF 08 FF E0 CB outFile->write(QString::number(lineCounter).rightJustified(10, ' ').toUtf8()); outFile->write("\t"); - tempTime = frames->at(c).timestamp; - tempTimePiece = tempTime / 1000000ul / 60 / 60; - tempTime -= tempTimePiece * 1000000ul * 60 * 60; + tempTime = frame->timeStamp().microSeconds(); + tempTimePiece = static_cast(tempTime / 1000000l / 60 / 60); + tempTime -= tempTimePiece * 1000000l * 60 * 60; outFile->write(QString::number(tempTimePiece).rightJustified(2, '0').toUtf8()); outFile->write(":"); - tempTimePiece = tempTime / 1000000ul / 60; - tempTime -= tempTimePiece * 1000000ul * 60; + tempTimePiece = static_cast(tempTime / 1000000l / 60); + tempTime -= tempTimePiece * 1000000l * 60; outFile->write(QString::number(tempTimePiece).rightJustified(2, '0').toUtf8()); outFile->write(":"); - tempTimePiece = tempTime / 1000000ul; - tempTime -= tempTimePiece * 1000000ul; + tempTimePiece = static_cast(tempTime / 1000000l); + tempTime -= tempTimePiece * 1000000l; outFile->write(QString::number(tempTimePiece).rightJustified(2, '0').toUtf8()); outFile->write(":"); - tempTimePiece = tempTime / 100; + tempTimePiece = static_cast(tempTime / 100); outFile->write(QString::number(tempTimePiece).rightJustified(4, '0').toUtf8()); outFile->write("\t"); - outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8() + "\t"); + outFile->write(QString::number(frame->frameId(), 16).toUpper().rightJustified(8, '0').toUtf8() + "\t"); - outFile->write(QString::number(frames->at(c).len).toUtf8() + "\t"); + outFile->write(QString::number(dataLen).toUtf8() + "\t"); - for (unsigned int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); } @@ -2976,6 +3102,10 @@ bool FrameFileIO::saveCanDumpFile(QString filename, const QVector * fr int lineCounter = 0; double tempTime; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + timestamp = QDateTime::currentDateTime(); if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) @@ -2992,27 +3122,31 @@ bool FrameFileIO::saveCanDumpFile(QString filename, const QVector * fr qApp->processEvents(); } + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + outFile->write("("); - tempTime = frames->at(c).timestamp / 1000000.0; + tempTime = frame->timeStamp().microSeconds() / 1000000.0; outFile->write(QString::number(tempTime,'f', 6).rightJustified(17, '0').toUtf8()); outFile->write(") vcan0 "); - if (frames->at(c).extended) { - outFile->write(QString::number(frames->at(c).ID, 16).rightJustified(8,'0').toUpper().toUtf8()); + if (frame->hasExtendedFrameFormat()) { + outFile->write(QString::number(frame->frameId(), 16).rightJustified(8,'0').toUpper().toUtf8()); } else { - outFile->write(QString::number(frames->at(c).ID, 16).rightJustified(3,'0').toUpper().toUtf8()); + outFile->write(QString::number(frame->frameId(), 16).rightJustified(3,'0').toUpper().toUtf8()); } outFile->write("#"); - if (frames->at(c).remote) { + if (frame->frameType() == QCanBusFrame::RemoteRequestFrame) { outFile->write("R"); - outFile->write(QString::number(frames->at(c).len).toUtf8()); + outFile->write(QString::number(dataLen).toUtf8()); } else { - for (unsigned int temp = 0; temp < frames->at(c).len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - outFile->write(QString::number(frames->at(c).data[temp], 16).rightJustified(2,'0').toUpper().toUtf8()); + outFile->write(QString::number(data[temp], 16).rightJustified(2,'0').toUpper().toUtf8()); } } @@ -3189,22 +3323,24 @@ bool FrameFileIO::loadCanDumpFile(QString filename, QVector* frames) ret = timeExp.exactMatch(tokens[0]); if(!ret) continue; - thisFrame.timestamp = (uint64_t)(timeExp.cap(1).toDouble(&ret) * (double)1000000.0); + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, (uint64_t)(timeExp.cap(1).toDouble(&ret) * (double)1000000.0))); if(!ret) continue; if (line.contains('[')) //the expanded format (second one from the above list) { //(1551774790.942758) can1 7A8 [8] F4 DC D1 83 0E 02 00 00 // 0 1 2 3 4 5 6 7 8 9 10 11 - thisFrame.ID = tokens[2].toULong(nullptr, 16); - if (thisFrame.ID > 0x7FF) thisFrame.extended = true; - else thisFrame.extended = false; - thisFrame.remote = false; - thisFrame.len = tokens[3].at(1) - '0'; - for (uint32_t c = 0; c < thisFrame.len; c++) + thisFrame.setFrameId(tokens[2].toLong(nullptr, 16)); + if (thisFrame.frameId() > 0x7FF) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); + thisFrame.setFrameType(QCanBusFrame::DataFrame); + int numBytes = tokens[3].at(1) - '0'; + QByteArray bytes(numBytes, 0); + for (int c = 0; c < numBytes; c++) { - thisFrame.data[c] = static_cast(tokens[4 + c].toInt(nullptr, 16)); + if ((4 + c) < tokens.size()) bytes[c] = static_cast(tokens[4 + c].toInt(nullptr, 16)); } + thisFrame.setPayload(bytes); } else //the more concise format (first one from list above) { @@ -3218,32 +3354,32 @@ bool FrameFileIO::loadCanDumpFile(QString filename, QVector* frames) } /* ID */ - thisFrame.ID = static_cast(IdValExp.cap(1).toInt(&ret, 16)); + thisFrame.setFrameId(static_cast(IdValExp.cap(1).toInt(&ret, 16))); if (IdValExp.cap(1).length() > 3) { - thisFrame.extended = true; + thisFrame.setExtendedFrameFormat(true); } else { - thisFrame.extended = false; + thisFrame.setExtendedFrameFormat(false); } QString val= IdValExp.cap(2); pos = 0; - thisFrame.len = 0; + QByteArray bytes; if (val.startsWith("R") && val.at(1).isDigit()) { - thisFrame.len = val.at(1).toLatin1() - '0'; - thisFrame.remote = true; + thisFrame.payload().resize( val.at(1).toLatin1() - '0' ); + thisFrame.setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); /* val byte per byte */ while ((pos = valExp.indexIn(val, pos)) != -1) { - thisFrame.data[thisFrame.len] = valExp.cap(1).toInt(&ret, 16); + bytes.append((char)valExp.cap(1).toInt(&ret, 16)); if(!ret) continue; - thisFrame.len++; pos += valExp.matchedLength(); } } + thisFrame.setPayload(bytes); } /*NB: should we make sure len <= 8? */ @@ -3263,7 +3399,6 @@ bool FrameFileIO::isLawicelFile(QString filename) QByteArray line; int lineCounter = 0; bool isMatch = false; - bool ret; if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -3328,18 +3463,20 @@ bool FrameFileIO::loadLawicelFile(QString filename, QVector* frames) line = inFile->readLine().simplified(); if (line.length() > 4 && !line.startsWith("S")) { - thisFrame.timestamp = (timeStamp += 100); - thisFrame.ID = line.mid(0, 3).toInt(nullptr, 16); - thisFrame.extended = false; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, timeStamp += 100)); + thisFrame.setFrameId( line.mid(0, 3).toInt(nullptr, 16) ); + thisFrame.setExtendedFrameFormat(false); thisFrame.isReceived = true; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); thisFrame.bus = 0; line.remove(0, 3); - thisFrame.len = line.length() / 2; - for (int d = 0; d < thisFrame.len; d++) + int numBytes = line.length() / 2; + QByteArray bytes(numBytes, 0); + for (int d = 0; d < numBytes; d++) { - thisFrame.data[d] = static_cast(line.mid(d * 2, 2).toInt(nullptr, 16)); + bytes[d] = static_cast(line.mid(d * 2, 2).toInt(nullptr, 16)); } + thisFrame.setPayload(bytes); frames->append(thisFrame); } } @@ -3402,7 +3539,7 @@ bool FrameFileIO::loadKvaserFile(QString filename, QVector *frames, bo int lineCounter = 0; int base = 10; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (useHex) base = 16; @@ -3432,18 +3569,19 @@ bool FrameFileIO::loadKvaserFile(QString filename, QVector *frames, bo //Chn Identifier Flg DLC D0...1...2...3...4...5...6..D7 Time Dir // 0 000000AD 8 FF FF 00 00 00 00 00 00 154.266550 R thisFrame.bus = line.mid(0,3).simplified().toInt(); - thisFrame.ID = line.mid(4,10).simplified().toInt(nullptr, base); - if (thisFrame.ID > 0x7FF) thisFrame.extended = true; - else thisFrame.extended = false; - thisFrame.remote = false; - thisFrame.len = line.mid(21, 3).simplified().toInt(); - for (int i = 0; i < 8; i++) { - thisFrame.data[i] = line.mid(25 + i * 4, 3).simplified().toInt(nullptr, base); + thisFrame.setFrameId(line.mid(4,10).simplified().toInt(nullptr, base)); + if (thisFrame.frameId() > 0x7FF) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); + thisFrame.setFrameType(QCanBusFrame::DataFrame); + int numBytes = line.mid(21, 3).simplified().toInt(); + QByteArray bytes(numBytes, 0); + for (int i = 0; i < numBytes; i++) { + bytes[i] = line.mid(25 + i * 4, 3).simplified().toInt(nullptr, base); } - thisFrame.timestamp = line.mid(57, 14).simplified().toDouble() * 1000000; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, line.mid(57, 14).simplified().toDouble() * 1000000)); if (line.mid(72, 1).toUpper() == "R") thisFrame.isReceived = true; else thisFrame.isReceived = false; - + thisFrame.setPayload(bytes); frames->append(thisFrame); } //else foundErrors = true; @@ -3514,7 +3652,7 @@ bool FrameFileIO::loadCabanaFile(QString filename, QVector* frames) uint64_t lastTimeStamp = 0; int lineCounter = 0; bool foundErrors = false; - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -3550,42 +3688,41 @@ bool FrameFileIO::loadCabanaFile(QString filename, QVector* frames) } if(timeStampBaseSet) { - thisFrame.timestamp = ((uint64_t)(temp) - timeStampBase); - lastTimeStamp = thisFrame.timestamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, ((uint64_t)(temp) - timeStampBase))); + lastTimeStamp = thisFrame.timeStamp().microSeconds(); } else { - thisFrame.timestamp = (lastTimeStamp + 1); - lastTimeStamp = thisFrame.timestamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, (lastTimeStamp + 1))); + lastTimeStamp = thisFrame.timeStamp().microSeconds(); } } else { - thisFrame.timestamp = (lastTimeStamp + 1); - lastTimeStamp = thisFrame.timestamp; + thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, (lastTimeStamp + 1))); + lastTimeStamp = thisFrame.timeStamp().microSeconds(); } - thisFrame.ID = tokens[1].toInt(); - if (thisFrame.ID > 0x7ff) thisFrame.extended = 1; - else thisFrame.extended = 0; + thisFrame.setFrameId(tokens[1].toInt()); + if (thisFrame.frameId() > 0x7ff) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); - thisFrame.remote = false; + thisFrame.setFrameType(QCanBusFrame::DataFrame); thisFrame.isReceived = true; thisFrame.bus = tokens[2].toInt(); - thisFrame.len = 8; - + QByteArray bytes(8,0); { unsigned long long int tempData = tokens[3].toULongLong(nullptr, 16); - thisFrame.data[0] = ((tempData >> 56) & 0xFF); - thisFrame.data[1] = ((tempData >> 48) & 0xFF); - thisFrame.data[2] = ((tempData >> 40) & 0xFF); - thisFrame.data[3] = ((tempData >> 32) & 0xFF); - thisFrame.data[4] = ((tempData >> 24) & 0xFF); - thisFrame.data[5] = ((tempData >> 16) & 0xFF); - thisFrame.data[6] = ((tempData >> 8) & 0xFF); - thisFrame.data[7] = (tempData & 0xFF); + bytes[0] = ((tempData >> 56) & 0xFF); + bytes[1] = ((tempData >> 48) & 0xFF); + bytes[2] = ((tempData >> 40) & 0xFF); + bytes[3] = ((tempData >> 32) & 0xFF); + bytes[4] = ((tempData >> 24) & 0xFF); + bytes[5] = ((tempData >> 16) & 0xFF); + bytes[6] = ((tempData >> 8) & 0xFF); + bytes[7] = (tempData & 0xFF); } - + thisFrame.setPayload(bytes); frames->append(thisFrame); } else foundErrors = true; @@ -3601,6 +3738,10 @@ bool FrameFileIO::saveCabanaFile(QString filename, const QVector* fram QFile *outFile = new QFile(filename); int lineCounter = 0; + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) { delete outFile; @@ -3619,23 +3760,27 @@ bool FrameFileIO::saveCabanaFile(QString filename, const QVector* fram lineCounter = 0; } - double tempTimeStamp = frames->at(c).timestamp; + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + + double tempTimeStamp = frame->timeStamp().microSeconds(); tempTimeStamp /= 1000000; outFile->write(QString::number(tempTimeStamp, 'f').toUtf8()); outFile->write(".0"); outFile->putChar(44); - outFile->write(QString::number(frames->at(c).ID, 10).toUpper().toUtf8()); + outFile->write(QString::number(frame->frameId(), 10).toUpper().toUtf8()); outFile->putChar(44); - outFile->write(QString::number(frames->at(c).bus).toUtf8()); + outFile->write(QString::number(frame->bus).toUtf8()); outFile->putChar(44); - for (unsigned int temp = 0; temp < 8; temp++) + for (int temp = 0; temp < 8; temp++) { - if (temp < frames->at(c).len) - outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); + if (temp < dataLen) + outFile->write(QString::number(data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); else outFile->write("00"); } diff --git a/frameplaybackobject.cpp b/frameplaybackobject.cpp index e990efe..b918b07 100644 --- a/frameplaybackobject.cpp +++ b/frameplaybackobject.cpp @@ -68,7 +68,7 @@ quint64 FramePlaybackObject::updatePosition(bool forward) //only send frame out if its ID is checked in the list. Otherwise discard it. CANFrame *thisFrame = ¤tSeqItem->data[currentPosition]; uint32_t originalBus = thisFrame->bus; - if (currentSeqItem->idFilters.find(thisFrame->ID).value()) + if (currentSeqItem->idFilters.find(thisFrame->frameId()).value()) { if (whichBusSend > -1) { @@ -90,7 +90,7 @@ quint64 FramePlaybackObject::updatePosition(bool forward) thisFrame->bus = originalBus; } - return thisFrame->timestamp; + return thisFrame->timeStamp().microSeconds(); } quint64 FramePlaybackObject::peekPosition(bool forward) @@ -113,7 +113,7 @@ quint64 FramePlaybackObject::peekPosition(bool forward) } } CANFrame *thisFrame = ¤tSeqItem->data[peekCurrentPosition]; - return thisFrame->timestamp; + return thisFrame->timeStamp().microSeconds(); } void FramePlaybackObject::piStart() @@ -197,8 +197,8 @@ void FramePlaybackObject::startPlaybackForward() { playbackTimer->setInterval(1); playbackElapsed.start(); - if (currentSeqItem->data[currentPosition].timestamp > 2000) - playbackLastTimeStamp = currentSeqItem->data[currentPosition].timestamp - 2000; + if (currentSeqItem->data[currentPosition].timeStamp().microSeconds() > 2000) + playbackLastTimeStamp = currentSeqItem->data[currentPosition].timeStamp().microSeconds() - 2000; else playbackLastTimeStamp = 0; } playbackTimer->start(); @@ -219,7 +219,7 @@ void FramePlaybackObject::startPlaybackBackward() { playbackElapsed.start(); playbackTimer->setInterval(1); - playbackLastTimeStamp = currentSeqItem->data[currentPosition].timestamp + 2000; + playbackLastTimeStamp = currentSeqItem->data[currentPosition].timeStamp().microSeconds() + 2000; } playbackTimer->start(); } @@ -350,8 +350,8 @@ void FramePlaybackObject::timerTriggered() if (peekPosition(true) == 0xFFFFFFFFFFFFFFFFull) { updatePosition(true); //this'll go to the next log (if there is one) - if (currentSeqItem->data[currentPosition].timestamp > 1000) - playbackLastTimeStamp = currentSeqItem->data[currentPosition].timestamp - 1000; + if (currentSeqItem->data[currentPosition].timeStamp().microSeconds() > 1000) + playbackLastTimeStamp = currentSeqItem->data[currentPosition].timeStamp().microSeconds() - 1000; else playbackLastTimeStamp = 0; } } @@ -367,7 +367,7 @@ void FramePlaybackObject::timerTriggered() if (peekPosition(false) == 0xFFFFFFFFFFFFFFFFull) { updatePosition(false); //this'll go to the next log (if there is one) - playbackLastTimeStamp = currentSeqItem->data[currentPosition].timestamp + 1000; + playbackLastTimeStamp = currentSeqItem->data[currentPosition].timeStamp().microSeconds() + 1000; } } statusCounter++; diff --git a/frameplaybackwindow.cpp b/frameplaybackwindow.cpp index 975df44..85fd517 100644 --- a/frameplaybackwindow.cpp +++ b/frameplaybackwindow.cpp @@ -297,7 +297,7 @@ void FramePlaybackWindow::refreshIDList() QHash::Iterator filterIter; for (filterIter = currentSeqItem->idFilters.begin(); filterIter != currentSeqItem->idFilters.end(); ++filterIter) { - QListWidgetItem* listItem = FilterUtility::createCheckableFilterItem(filterIter.key(), filterIter.value(), ui->listID); + /*QListWidgetItem* listItem = */ FilterUtility::createCheckableFilterItem(filterIter.key(), filterIter.value(), ui->listID); } //default is to sort in ascending order ui->listID->sortItems(); @@ -426,7 +426,7 @@ void FramePlaybackWindow::fillIDHash(SequenceItem &item) for (int i = 0; i < item.data.count(); i++) { - id = item.data[i].ID; + id = item.data[i].frameId(); if (!item.idFilters.contains(id)) { item.idFilters.insert(id, true); @@ -479,7 +479,7 @@ void FramePlaybackWindow::btnLoadFile() if (FrameFileIO::loadFrameFile(filename, &item.data)) { - qSort(item.data); //sort by timestamp to be sure it's in order + std::sort(item.data.begin(), item.data.end()); //sort by timestamp to be sure it's in order QStringList fileList = filename.split('/'); item.filename = fileList[fileList.length() - 1]; item.currentLoopCount = 0; @@ -513,7 +513,7 @@ void FramePlaybackWindow::btnLoadLive() item.currentLoopCount = 0; item.maxLoops = 1; item.data = QVector(*modelFrames); //create a copy of the current frames from the main view - qSort(item.data); //be sure it's all in time based order + std::sort(item.data.begin(), item.data.end()); //be sure it's all in time based order fillIDHash(item); if (ui->tblSequence->currentRow() == -1) { diff --git a/framesenderwindow.cpp b/framesenderwindow.cpp index fbd4093..622f729 100644 --- a/framesenderwindow.cpp +++ b/framesenderwindow.cpp @@ -130,13 +130,13 @@ void FrameSenderWindow::buildFrameCache() for (int i = 0; i < modelFrames->count(); i++) { thisFrame = modelFrames->at(i); - if (!frameCache.contains(thisFrame.ID)) + if (!frameCache.contains(thisFrame.frameId())) { - frameCache.insert(thisFrame.ID, thisFrame); + frameCache.insert(thisFrame.frameId(), thisFrame); } else { - frameCache[thisFrame.ID] = thisFrame; + frameCache[thisFrame.frameId()] = thisFrame; } } } @@ -160,13 +160,13 @@ void FrameSenderWindow::updatedFrames(int numFrames) for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { thisFrame = modelFrames->at(i); - if (!frameCache.contains(thisFrame.ID)) + if (!frameCache.contains(thisFrame.frameId())) { - frameCache.insert(thisFrame.ID, thisFrame); + frameCache.insert(thisFrame.frameId(), thisFrame); } else { - frameCache[thisFrame.ID] = thisFrame; + frameCache[thisFrame.frameId()] = thisFrame; } processIncomingFrame(&thisFrame); } @@ -182,10 +182,10 @@ void FrameSenderWindow::processIncomingFrame(CANFrame *frame) { Trigger *thisTrigger = &sendingData[sd].triggers[trig]; qDebug() << "Trigger ID: " << thisTrigger->ID; - qDebug() << "Frame ID: " << frame->ID; - if (thisTrigger->ID > 0 && (uint32_t)thisTrigger->ID == frame->ID) + qDebug() << "Frame ID: " << frame->frameId(); + if (thisTrigger->ID > 0 && (uint32_t)thisTrigger->ID == frame->frameId()) { - if ((uint32_t)thisTrigger->bus == frame->bus || thisTrigger->bus == -1) + if (thisTrigger->bus == frame->bus || thisTrigger->bus == -1) { if (thisTrigger->currCount < thisTrigger->maxCount) { @@ -511,7 +511,9 @@ void FrameSenderWindow::doModifiers(int idx) } } //Finally, drop the result into the proper data byte - sendData->data[mod->destByte] = (unsigned char) shadowReg; + QByteArray newArr(sendData->payload()); + newArr[mod->destByte] = (char) shadowReg; + sendData->setPayload(newArr); } } @@ -525,16 +527,16 @@ int FrameSenderWindow::fetchOperand(int idx, ModifierOperand op) } else if (op.ID == -2) //fetch data from a data byte within the output frame { - if (op.notOper) return ~sendingData.at(idx).data[op.databyte]; - else return sendingData.at(idx).data[op.databyte]; + if (op.notOper) return ~((unsigned char)sendingData.at(idx).payload()[op.databyte]); + else return (unsigned char)sendingData.at(idx).payload()[op.databyte]; } else //look up external data byte { tempFrame = lookupFrame(op.ID, op.bus); if (tempFrame != nullptr) { - if (op.notOper) return ~tempFrame->data[op.databyte]; - else return tempFrame->data[op.databyte]; + if (op.notOper) return ~((unsigned char)tempFrame->payload()[op.databyte]); + else return (unsigned char)tempFrame->payload()[op.databyte]; } else return 0; } @@ -550,7 +552,7 @@ CANFrame* FrameSenderWindow::lookupFrame(int ID, int bus) { if (!frameCache.contains(ID)) return nullptr; - if (bus == -1 || frameCache[ID].bus == (unsigned int)bus) return &frameCache[ID]; + if (bus == -1 || frameCache[ID].bus == bus) return &frameCache[ID]; return nullptr; } @@ -643,7 +645,7 @@ void FrameSenderWindow::processModifierText(int line) } else thisOp.second.notOper = false; thisOp.second.bus = sendingData[line].bus; - thisOp.second.ID = sendingData[line].ID; + thisOp.second.ID = sendingData[line].frameId(); parseOperandString(secondOp.split(":"), thisOp.second); thisMod.operations.append(thisOp); } @@ -786,17 +788,21 @@ ModifierOperationType FrameSenderWindow::parseOperation(QString op) void FrameSenderWindow::updateGridRow(int idx) { qDebug() << "updateGridRow"; + inhibitChanged = true; FrameSendData *temp = &sendingData[idx]; int gridLine = idx; QString dataString; QTableWidgetItem *item = ui->tableSender->item(gridLine, 9); + const unsigned char *data = reinterpret_cast(temp->payload().constData()); + int dataLen = temp->payload().length(); + if (item == nullptr) item = new QTableWidgetItem(); item->setText(QString::number(temp->count)); - if (!temp->remote) { - for (unsigned int i = 0; i < temp->len; i++) + if (temp->frameType() != QCanBusFrame::RemoteRequestFrame) { + for (int i = 0; i < dataLen; i++) { - dataString.append(Utility::formatNumber(temp->data[i])); + dataString.append(Utility::formatNumber(data[i])); dataString.append(" "); } ui->tableSender->item(gridLine, 6)->setText(dataString); @@ -818,14 +824,15 @@ void FrameSenderWindow::processCellChange(int line, int col) { FrameSendData tempData; tempData.enabled = false; - tempData.remote = false; - tempData.extended = false; + tempData.setFrameType(QCanBusFrame::DataFrame); + tempData.setExtendedFrameFormat(false); sendingData.append(tempData); } sendingData[line].count = 0; int numBuses = CANConManager::getInstance()->getNumBuses(); + QByteArray arr; switch (col) { @@ -848,9 +855,9 @@ void FrameSenderWindow::processCellChange(int line, int col) tempVal = Utility::ParseStringToNum(ui->tableSender->item(line, 2)->text()); if (tempVal < 0) tempVal = 0; if (tempVal > 0x7FFFFFFF) tempVal = 0x7FFFFFFF; - sendingData[line].ID = tempVal; - if (sendingData[line].ID > 0x7FF) { - sendingData[line].extended = true; + sendingData[line].setFrameId(tempVal); + if (sendingData[line].frameId() > 0x7FF) { + sendingData[line].setExtendedFrameFormat(true); ui->tableSender->blockSignals(true); ui->tableSender->item(line, 4)->setCheckState(Qt::Checked); ui->tableSender->blockSignals(false); @@ -860,31 +867,35 @@ void FrameSenderWindow::processCellChange(int line, int col) case 3: //length field tempVal = Utility::ParseStringToNum(ui->tableSender->item(line, 3)->text()); if (tempVal < 0) tempVal = 0; - if (tempVal > 8) tempVal = 8; - sendingData[line].len = tempVal; + if (tempVal > 8) tempVal = 8; + arr.resize(tempVal); + sendingData[line].setPayload(arr); break; case 4: // Ext if (ui->tableSender->item(line, 4)->checkState() == Qt::Checked) { - sendingData[line].extended = true; + sendingData[line].setExtendedFrameFormat(true); } else { - sendingData[line].extended = false; + sendingData[line].setExtendedFrameFormat(false); } break; case 5: // Rem if (ui->tableSender->item(line, 5)->checkState() == Qt::Checked) { - sendingData[line].remote = true; + sendingData[line].setFrameType(QCanBusFrame::RemoteRequestFrame); } else { - sendingData[line].remote = false; + sendingData[line].setFrameType(QCanBusFrame::DataFrame); } break; case 6: //Data bytes - for (int i = 0; i < 8; i++) sendingData[line].data[i] = 0; + for (int i = 0; i < 8; i++) sendingData[line].payload().data()[i] = 0; tokens = ui->tableSender->item(line, 6)->text().split(" "); + arr.clear(); + arr.reserve(tokens.count()); for (int j = 0; j < tokens.count(); j++) { - sendingData[line].data[j] = (uint8_t)Utility::ParseStringToNum(tokens[j]); + arr.append((uint8_t)Utility::ParseStringToNum(tokens[j])); } + sendingData[line].setPayload(arr); break; case 7: //triggers processTriggerText(line); diff --git a/help/_images/FuzzingWindow.png b/help/_images/FuzzingWindow.png index 6a4950b..e863312 100644 Binary files a/help/_images/FuzzingWindow.png and b/help/_images/FuzzingWindow.png differ diff --git a/help/_static/jquery.js b/help/_static/jquery.js index 00129ea..7e32910 100644 --- a/help/_static/jquery.js +++ b/help/_static/jquery.js @@ -9,7 +9,7 @@ * Released under the MIT license * https://jquery.org/license * - * Date: 2019-01-30T03:06Z + * Date: 2019-04-19T06:52Z */ ( function( global, factory ) { @@ -261,8 +261,9 @@ jQuery.extend = jQuery.fn.extend = function() { src = target[ name ]; copy = options[ name ]; + // Prevent Object.prototype pollution // Prevent never-ending loop - if ( target === copy ) { + if ( name === "__proto__" || target === copy ) { continue; } diff --git a/help/fuzzingwindow.html b/help/fuzzingwindow.html index 0eac95b..da838c7 100644 --- a/help/fuzzingwindow.html +++ b/help/fuzzingwindow.html @@ -25,11 +25,12 @@

60. Fuzzing is Dangerous

-

You have now been warned. Sending random garbage over the CAN bus to see what happens could mess something up. It just might put your vehicle into gear and cause you to drive over a box full of kittens. Be careful! Never fuzz a car unless you’re right there and you can stop it. Even better, don’t do it unless your car is up on a hoist or something and can’t drive over anyone. Even still, there is a small chance you could cause an adverse effect to your car.

+

You have now been warned. Sending random garbage over the CAN bus to see what happens could mess something up. It just might put your vehicle into gear and cause you to drive over a box full of kittens. Be careful! Never fuzz a car unless you’re right there and you can stop it. Even better, don’t do it unless your car is up on a hoist or jacks and can’t drive over anyone. Even still, there is a small chance you could cause an adverse effect to your car. If you break something you own the pieces.

61. Controlling the Fuzzy Beast

-

So, you want to give it a try? Let’s do it! First of all, you can set the delay between frames and the burst rate. The burst rate can cause the program to send one than one frame each interval. This is useful as a CAN bus could potentially support 2000 to 8000 frames per second. Then you can set the number of bytes to send. Ordinarily this would be the full 8 but you can experiment with smaller frames. You can set to send on a specific bus. That’s all the simple settings. It gets a bit more complicated now.

+

So, you want to give it a try? Let’s do it! First of all, you can set the delay between frames and the burst rate. The delay is in milliseconds but can be set as low as 0. If the delay is set to 0 then the system will attempt to send frames as fast as it can. However, even then you may not get quite as many frames per second as you’d like. Even at 0 it will still be scheduled by your operating system and so might not quite get to the speed you want. The burst rate can cause the program to send one than one frame each interval. This is useful as a CAN bus could potentially support 2000 to 8000 frames per second. If you need rapid frame sending your best bet is to set the sending interval to 1-2ms and then adjust the burst +rate until you get your desired sending rate. Then you can set the number of bytes to send. Ordinarily this would be the full 8 but you can experiment with smaller frames. You can set to send on a specific bus. That’s all the simple settings. It gets a bit more complicated now.

The “ID Scanning” box has two radio buttons:

  1. Sequential will go from “Start ID” to “End ID” then reset back to Start over and over.
  2. @@ -46,11 +47,12 @@
  3. Sweep causes the system to set the first one, then unset that one and set the second bit, then unset that, etc. Thus the fuzzed bit sweeps and only one fuzzed bit is set at once.
  4. Random will randomly pick whether each fuzzed bit is set or not.
-

In order to fuzz bits you need to set which bits to fuzz and which not to. As listed at the bottom of the window, there is a color code to the 8x8 grid. Clicking cells in the grid will toggle them between their various values. White bits are never set, black bits are always set no matter what, green bits follow the fuzzing pattern you specified in “Bit Scanning”

+

In order to fuzz bits you need to set which bits to fuzz and which not to. As listed at the bottom of the window, there is a color code to the 8x8 grid. Clicking cells in the grid will toggle them between their various values. White bits are never set, black bits are always set no matter what, green bits follow the fuzzing pattern you specified in “Bit Scanning” You can also set the bytes directly with the text boxes above the 8x8 grid. Setting a hexadecimal value in these +boxes will set the relavent bits in the 8x8 grid. You must press the ENTER/RETURN key to set the values. Merely changing the value will not update it (as a safety measure).

62. Pulling the Trigger

-

Once you’ve configured everything click “Start Fuzzing” to give it a shot. You will see the number of frames sent so far listed below the button. You can stop the fuzzing by pushing the button again.

+

Once you’ve configured everything click “Start Fuzzing” to give it a shot. You will see the number of frames sent so far listed below the button. Approximately four times per second the current value for each byte is copied into the text boxes just above the 8x8 grid. This can be used to see what is going on and to ensure that it is working the way you want it to. You can stop the fuzzing by pushing the start button again.

diff --git a/icons.qrc b/icons.qrc index cd68926..49ac17c 100644 --- a/icons.qrc +++ b/icons.qrc @@ -6,5 +6,14 @@ images/PlayHS.png images/ReverseHS.png images/StopHS.png + images/signal.png + images/node.png + images/message.png + images/multiplexed-signal.png + images/multiplexor-signal.png + images/skull.png + images/signal_new.png + images/node_new.png + images/message_new.png diff --git a/images/message.png b/images/message.png new file mode 100644 index 0000000..985a134 Binary files /dev/null and b/images/message.png differ diff --git a/images/message_new.png b/images/message_new.png new file mode 100644 index 0000000..15c8dc4 Binary files /dev/null and b/images/message_new.png differ diff --git a/images/multiplexed-signal.png b/images/multiplexed-signal.png new file mode 100644 index 0000000..55f66f9 Binary files /dev/null and b/images/multiplexed-signal.png differ diff --git a/images/multiplexor-signal.png b/images/multiplexor-signal.png new file mode 100644 index 0000000..afd11cd Binary files /dev/null and b/images/multiplexor-signal.png differ diff --git a/images/node.png b/images/node.png new file mode 100644 index 0000000..f2a52f5 Binary files /dev/null and b/images/node.png differ diff --git a/images/node_new.png b/images/node_new.png new file mode 100644 index 0000000..75ae0aa Binary files /dev/null and b/images/node_new.png differ diff --git a/images/signal.png b/images/signal.png new file mode 100644 index 0000000..dbfc714 Binary files /dev/null and b/images/signal.png differ diff --git a/images/signal_new.png b/images/signal_new.png new file mode 100644 index 0000000..3581a85 Binary files /dev/null and b/images/signal_new.png differ diff --git a/images/skull.png b/images/skull.png new file mode 100644 index 0000000..01453fc Binary files /dev/null and b/images/skull.png differ diff --git a/images/sourceImages/noun_Death_3194193.png b/images/sourceImages/noun_Death_3194193.png new file mode 100644 index 0000000..5d1825f Binary files /dev/null and b/images/sourceImages/noun_Death_3194193.png differ diff --git a/images/sourceImages/noun_Death_3194193.xcf b/images/sourceImages/noun_Death_3194193.xcf new file mode 100644 index 0000000..18605ba Binary files /dev/null and b/images/sourceImages/noun_Death_3194193.xcf differ diff --git a/images/sourceImages/noun_message_1977390.png b/images/sourceImages/noun_message_1977390.png new file mode 100644 index 0000000..5fd6b42 Binary files /dev/null and b/images/sourceImages/noun_message_1977390.png differ diff --git a/images/sourceImages/noun_message_1977390.xcf b/images/sourceImages/noun_message_1977390.xcf new file mode 100644 index 0000000..9dcab24 Binary files /dev/null and b/images/sourceImages/noun_message_1977390.xcf differ diff --git a/images/sourceImages/noun_nodes_2397529.png b/images/sourceImages/noun_nodes_2397529.png new file mode 100644 index 0000000..c14e1e0 Binary files /dev/null and b/images/sourceImages/noun_nodes_2397529.png differ diff --git a/images/sourceImages/noun_nodes_2397529.xcf b/images/sourceImages/noun_nodes_2397529.xcf new file mode 100644 index 0000000..8cfe1ab Binary files /dev/null and b/images/sourceImages/noun_nodes_2397529.xcf differ diff --git a/images/sourceImages/noun_signal_1402315.png b/images/sourceImages/noun_signal_1402315.png new file mode 100644 index 0000000..4ea4e8d Binary files /dev/null and b/images/sourceImages/noun_signal_1402315.png differ diff --git a/images/sourceImages/noun_signal_1402315.xcf b/images/sourceImages/noun_signal_1402315.xcf new file mode 100644 index 0000000..9007239 Binary files /dev/null and b/images/sourceImages/noun_signal_1402315.xcf differ diff --git a/images/sourceImages/noun_signal_1716563.png b/images/sourceImages/noun_signal_1716563.png new file mode 100644 index 0000000..cb29efa Binary files /dev/null and b/images/sourceImages/noun_signal_1716563.png differ diff --git a/images/sourceImages/noun_signal_1716563.xcf b/images/sourceImages/noun_signal_1716563.xcf new file mode 100644 index 0000000..2ccfc2f Binary files /dev/null and b/images/sourceImages/noun_signal_1716563.xcf differ diff --git a/images/sourceImages/noun_signal_1771815.png b/images/sourceImages/noun_signal_1771815.png new file mode 100644 index 0000000..c007970 Binary files /dev/null and b/images/sourceImages/noun_signal_1771815.png differ diff --git a/images/sourceImages/noun_signal_1771815.xcf b/images/sourceImages/noun_signal_1771815.xcf new file mode 100644 index 0000000..828dff5 Binary files /dev/null and b/images/sourceImages/noun_signal_1771815.xcf differ diff --git a/install-qt.sh b/install-qt.sh new file mode 100755 index 0000000..be953e7 --- /dev/null +++ b/install-qt.sh @@ -0,0 +1,319 @@ +#!/usr/bin/env bash +############################################################################# +## +## Copyright (C) 2019 Richard Weickelt. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of Qbs. +## +## $QT_BEGIN_LICENSE:LGPL$ +## 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 https://www.qt.io/terms-conditions. For further +## information use the contact form at https://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.LGPL3 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-3.0.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 (at your option) the GNU General +## Public license version 3 or any later version approved by the KDE Free +## Qt Foundation. The licenses are as published by the Free Software +## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +## included in the packaging of this file. Please review the following +## information to ensure the GNU General Public License requirements will +## be met: https://www.gnu.org/licenses/gpl-2.0.html and +## https://www.gnu.org/licenses/gpl-3.0.html. +## +## $QT_END_LICENSE$ +## +############################################################################# +set -eu + +function help() { + cat < + Root directory where to install the components. + Maps to C:/Qt on Windows, /opt/Qt on Linux, /usr/local/Qt on Mac + by default. + + -f, --force + Force download and do not attempt to re-use an existing installation. + + --host + The host operating system. Can be one of linux_x64, mac_x64, + windows_x86. Auto-detected by default. + + --target + The desired target platform. Can be one of desktop, android, ios. + The default value is desktop. + + --toolchain + The toolchain that has been used to build the binaries. + Possible values depend on --host and --target, respectively: + + linux_x64 + android + any, android_armv7, android_arm64_v8a + desktop + gcc_64 (default) + + mac_x64 + android + any, android_armv7, android_arm64_v8a + desktop + clang_64 (default), + ios + ios + + windows_x86 + android + any, android_armv7, android_arm64_v8a + desktop + win64_mingw73, win64_msvc2017_64 (default) + + --version + The desired Qt version. Currently supported are all versions + above 5.9.0. + +EOF +} + +TARGET_PLATFORM=desktop +COMPONENTS= +VERSION= +FORCE_DOWNLOAD=false +MD5_TOOL=md5sum + +case "$OSTYPE" in + *linux*) + HOST_OS=linux_x64 + INSTALL_DIR=/opt/Qt + TOOLCHAIN=gcc_64 + ;; + *darwin*) + HOST_OS=mac_x64 + INSTALL_DIR=/usr/local/Qt + TOOLCHAIN=clang_64 + MD5_TOOL="md5 -r" + ;; + msys) + HOST_OS=windows_x86 + INSTALL_DIR=/c/Qt + TOOLCHAIN=win64_msvc2015_64 + ;; + *) + HOST_OS= + INSTALL_DIR= + ;; +esac + +while [ $# -gt 0 ]; do + case "$1" in + --directory|-d) + INSTALL_DIR="$2" + shift + ;; + --force|-f) + FORCE_DOWNLOAD=true + ;; + --host) + HOST_OS="$2" + shift + ;; + --target) + TARGET_PLATFORM="$2" + shift + ;; + --toolchain) + TOOLCHAIN=$(echo $2 | tr '[A-Z]' '[a-z]') + shift + ;; + --version) + VERSION="$2" + shift + ;; + --help|-h) + help + exit 0 + ;; + *) + COMPONENTS="${COMPONENTS} $1" + ;; + esac + shift +done + +if [ -z "${HOST_OS}" ]; then + echo "No --host specified or auto-detection failed." >&2 + exit 1 +fi + +if [ -z "${INSTALL_DIR}" ]; then + echo "No --directory specified or auto-detection failed." >&2 + exit 1 +fi + +if [ -z "${VERSION}" ]; then + echo "No --version specified." >&2 + exit 1 +fi + +if [ -z "${COMPONENTS}" ]; then + echo "No components specified." >&2 + exit 1 +fi + +case "$TARGET_PLATFORM" in + android) + ;; + ios) + ;; + desktop) + ;; + *) + echo "Error: TARGET_PLATFORM=${TARGET_PLATFORM} is not valid." >&2 + exit 1 + ;; +esac + +HASH=$(echo "${OSTYPE} ${TARGET_PLATFORM} ${TOOLCHAIN} ${VERSION} ${INSTALL_DIR}" | ${MD5_TOOL} | head -c 16) +HASH_FILEPATH="${INSTALL_DIR}/${HASH}.manifest" +INSTALLATION_IS_VALID=false +if ! ${FORCE_DOWNLOAD} && [ -f "${HASH_FILEPATH}" ]; then + INSTALLATION_IS_VALID=true + while read filepath; do + if [ ! -e "${filepath}" ]; then + INSTALLATION_IS_VALID=false + break + fi + done <"${HASH_FILEPATH}" +fi + +if ${INSTALLATION_IS_VALID}; then + echo "Already installed. Skipping download." + exit 0 +fi + +DOWNLOAD_DIR=`mktemp -d 2>/dev/null || mktemp -d -t 'install-qt'` + +# +# The repository structure is a mess. Try different URL variants +# +function compute_url(){ + local COMPONENT=$1 + local CURL="curl -s -L" + local BASE_URL="http://download.qt.io/online/qtsdkrepository/${HOST_OS}/${TARGET_PLATFORM}" + + if [[ "${COMPONENT}" =~ "qtcreator" ]]; then + + REMOTE_BASE="tools_qtcreator/qt.tools.qtcreator" + REMOTE_PATH="$(${CURL} ${BASE_URL}/${REMOTE_BASE}/ | grep -o -E "${VERSION}[0-9\-]*${COMPONENT}\.7z" | tail -1)" + + if [ ! -z "${REMOTE_PATH}" ]; then + echo "${BASE_URL}/${REMOTE_BASE}/${REMOTE_PATH}" + return 0 + fi + + else + REMOTE_BASES=( + # New repository format (>=5.9.6) + "qt5_${VERSION//./}/qt.qt5.${VERSION//./}.${TOOLCHAIN}" + "qt5_${VERSION//./}/qt.qt5.${VERSION//./}.${COMPONENT}.${TOOLCHAIN}" + # Multi-abi Android since 5.14 + "qt5_${VERSION//./}/qt.qt5.${VERSION//./}.${TARGET_PLATFORM}" + "qt5_${VERSION//./}/qt.qt5.${VERSION//./}.${COMPONENT}.${TARGET_PLATFORM}" + # Older repository format (<5.9.0) + "qt5_${VERSION//./}/qt.${VERSION//./}.${TOOLCHAIN}" + "qt5_${VERSION//./}/qt.${VERSION//./}.${COMPONENT}.${TOOLCHAIN}" + ) + + for REMOTE_BASE in ${REMOTE_BASES[*]}; do + REMOTE_PATH="$(${CURL} ${BASE_URL}/${REMOTE_BASE}/ | grep -o -E "[[:alnum:]_.\-]*7z" | grep "${COMPONENT}" | tail -1)" + if [ ! -z "${REMOTE_PATH}" ]; then + echo "${BASE_URL}/${REMOTE_BASE}/${REMOTE_PATH}" + return 0 + fi + done + fi + + echo "Could not determine a remote URL for ${COMPONENT} with version ${VERSION}">&2 + exit 1 +} + +mkdir -p ${INSTALL_DIR} +rm -f "${HASH_FILEPATH}" + +for COMPONENT in ${COMPONENTS}; do + + URL="$(compute_url ${COMPONENT})" + echo "Downloading ${COMPONENT}..." >&2 + curl --progress-bar -L -o ${DOWNLOAD_DIR}/package.7z ${URL} >&2 + 7z x -y -o${INSTALL_DIR} ${DOWNLOAD_DIR}/package.7z >/dev/null 2>&1 + 7z l -ba -slt -y ${DOWNLOAD_DIR}/package.7z | tr '\\' '/' | sed -n -e "s|^Path\ =\ |${INSTALL_DIR}/|p" >> "${HASH_FILEPATH}" 2>/dev/null + rm -f ${DOWNLOAD_DIR}/package.7z + + # + # conf file is needed for qmake + # + if [ "${COMPONENT}" == "qtbase" ]; then + if [[ "${TOOLCHAIN}" =~ "win64_mingw" ]]; then + SUBDIR="${TOOLCHAIN/win64_/}_64" + elif [[ "${TOOLCHAIN}" =~ "win32_mingw" ]]; then + SUBDIR="${TOOLCHAIN/win32_/}_32" + elif [[ "${TOOLCHAIN}" =~ "win64_msvc" ]]; then + SUBDIR="${TOOLCHAIN/win64_/}" + elif [[ "${TOOLCHAIN}" =~ "win32_msvc" ]]; then + SUBDIR="${TOOLCHAIN/win32_/}" + elif [[ "${TOOLCHAIN}" =~ "any" ]] && [[ "${TARGET_PLATFORM}" == "android" ]]; then + SUBDIR="android" + else + SUBDIR="${TOOLCHAIN}" + fi + + CONF_FILE="${INSTALL_DIR}/${VERSION}/${SUBDIR}/bin/qt.conf" + echo "[Paths]" > ${CONF_FILE} + echo "Prefix = .." >> ${CONF_FILE} + + # Adjust the license to be able to run qmake + # sed with -i requires intermediate file on Mac OS + PRI_FILE="${INSTALL_DIR}/${VERSION}/${SUBDIR}/mkspecs/qconfig.pri" + sed -i.bak 's/Enterprise/OpenSource/g' "${PRI_FILE}" + sed -i.bak 's/licheck.*//g' "${PRI_FILE}" + rm "${PRI_FILE}.bak" + + # Print the directory so that the caller can + # adjust the PATH variable. + echo $(dirname "${CONF_FILE}") + elif [[ "${COMPONENT}" =~ "qtcreator" ]]; then + echo "${INSTALL_DIR}/Tools/QtCreator/bin" + fi + +done diff --git a/jsedit.cpp b/jsedit.cpp index 96c64cb..aff5f81 100644 --- a/jsedit.cpp +++ b/jsedit.cpp @@ -997,11 +997,11 @@ void JSEdit::updateSidebar() int maxLines = blockCount(); for (int number = 10; number < maxLines; number *= 10) ++digits; - sw += fontMetrics().width('w') * digits; + sw += fontMetrics().horizontalAdvance('w') * digits; } if (d->codeFolding) { int fh = fontMetrics().lineSpacing(); - int fw = fontMetrics().width('w'); + int fw = fontMetrics().horizontalAdvance('w'); d->sidebar->foldIndicatorWidth = qMax(fw, fh); sw += d->sidebar->foldIndicatorWidth; } diff --git a/mainsettingsdialog.cpp b/mainsettingsdialog.cpp index 149fef0..dd1764f 100644 --- a/mainsettingsdialog.cpp +++ b/mainsettingsdialog.cpp @@ -1,8 +1,13 @@ #include "mainsettingsdialog.h" #include "ui_mainsettingsdialog.h" #include "helpwindow.h" - #include +#include "simplecrypt.h" + +//using this simple encryption library to obfuscate stored password a bit. It's not super secure but better than +//storing a password in straight plaintext. You have the source to this application anyway, whatever algorithm used, +//whatever key, you'd see it. Just behave yourselves +SimpleCrypt crypto(Q_UINT64_C(0xdeadbeefface6285)); MainSettingsDialog::MainSettingsDialog(QWidget *parent) : QDialog(parent), @@ -11,6 +16,7 @@ MainSettingsDialog::MainSettingsDialog(QWidget *parent) : QSettings settings; ui->setupUi(this); + //TODO: This is still hard coded to support only two buses. Sometimes there is none, sometimes 1, sometimes much more than 2. Fix this. ui->comboSendingBus->addItem(tr("None")); ui->comboSendingBus->addItem(tr("0")); ui->comboSendingBus->addItem(tr("1")); @@ -30,8 +36,12 @@ MainSettingsDialog::MainSettingsDialog(QWidget *parent) : ui->spinPlaybackSpeed->setValue(settings.value("Playback/DefSpeed", 5).toInt()); ui->lineClockFormat->setText(settings.value("Main/TimeFormat", "MMM-dd HH:mm:ss.zzz").toString()); ui->lineRemoteHost->setText(settings.value("Remote/Host", "api.savvycan.com").toString()); - ui->lineRemotePort->setText(settings.value("Remote/Port", "21315").toString()); // = 0x5343 = SC. Yep, really creative port number - ui->cbAutoStartRemote->setChecked(settings.value("Remote/AutoStart", false).toBool()); + ui->lineRemotePort->setText(settings.value("Remote/Port", "8883").toString()); //default port for SSL enabled MQTT + ui->lineRemoteUser->setText(settings.value("Remote/User", "Anonymous").toString()); + QByteArray encPass = settings.value("Remote/Pass", "").toByteArray(); + QString decPass = crypto.decryptToString(encPass); + ui->lineRemotePassword->setText(decPass); + ui->cbLoadConnections->setChecked(settings.value("Main/SaveRestoreConnections", false).toBool()); ui->spinFontSize->setValue(settings.value("Main/FontSize", ui->cbDisplayHex->font().pointSize()).toUInt()); @@ -82,9 +92,10 @@ MainSettingsDialog::MainSettingsDialog(QWidget *parent) : connect(ui->cbUseFiltered, SIGNAL(toggled(bool)), this, SLOT(updateSettings())); connect(ui->lineClockFormat, SIGNAL(editingFinished()), this, SLOT(updateSettings())); connect(ui->cbUseOpenGL, SIGNAL(toggled(bool)), this, SLOT(updateSettings())); - connect(ui->cbAutoStartRemote, SIGNAL(toggled(bool)), this, SLOT(updateSettings())); connect(ui->lineRemoteHost, SIGNAL(editingFinished()), this, SLOT(updateSettings())); connect(ui->lineRemotePort, SIGNAL(editingFinished()), this, SLOT(updateSettings())); + connect(ui->lineRemoteUser, SIGNAL(editingFinished()), this, SLOT(updateSettings())); + connect(ui->lineRemotePassword, SIGNAL(editingFinished()), this, SLOT(updateSettings())); connect(ui->cbLoadConnections, SIGNAL(toggled(bool)), this, SLOT(updateSettings())); connect(ui->cbFilterLabeling, SIGNAL(toggled(bool)), this, SLOT(updateSettings())); installEventFilter(this); @@ -144,7 +155,9 @@ void MainSettingsDialog::updateSettings() settings.setValue("Main/FontSize", ui->spinFontSize->value()); settings.setValue("Remote/Host", ui->lineRemoteHost->text()); settings.setValue("Remote/Port", ui->lineRemotePort->text()); - settings.setValue("Remote/AutoStart", ui->cbAutoStartRemote->isChecked()); + settings.setValue("Remote/User", ui->lineRemoteUser->text()); + QByteArray encPass = crypto.encryptToByteArray(ui->lineRemotePassword->text()); + settings.setValue("Remote/Pass", encPass); settings.setValue("Main/FilterLabeling", ui->cbFilterLabeling->isChecked()); settings.sync(); diff --git a/mainwindow.cpp b/mainwindow.cpp index 641ea32..dc4ab13 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -51,9 +51,15 @@ MainWindow::MainWindow(QWidget *parent) : readSettings(); - //QHeaderView *verticalHeader = ui->canFramesView->verticalHeader(); - //verticalHeader->setSectionResizeMode(QHeaderView::Fixed); - //verticalHeader->setDefaultSectionSize(10); + QHeaderView *verticalHeader = ui->canFramesView->verticalHeader(); + verticalHeader->setSectionResizeMode(QHeaderView::Fixed); + QSettings settings; + int fontSize = settings.value("Main/FontSize", 9).toUInt(); + QFont sysFont = QFont(); //get default font + sysFont.setPointSize(fontSize); + verticalHeader->setDefaultSectionSize(sysFont.pixelSize()); + ui->canFramesView->setFont(sysFont); + QHeaderView *HorzHdr = ui->canFramesView->horizontalHeader(); HorzHdr->setStretchLastSection(true); //causes the data column to automatically fill the tableview connect(HorzHdr, SIGNAL(sectionClicked(int)), this, SLOT(headerClicked(int))); @@ -80,6 +86,7 @@ MainWindow::MainWindow(QWidget *parent) : bisectWindow = nullptr; signalViewerWindow = nullptr; temporalGraphWindow = nullptr; + dbcComparatorWindow = nullptr; dbcHandler = DBCHandler::getReference(); bDirty = false; inhibitFilterUpdate = false; @@ -111,6 +118,7 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionSave_Decoded_Frames, &QAction::triggered, this, &MainWindow::handleSaveDecoded); connect(ui->actionSingle_Multi_State_2, &QAction::triggered, this, &MainWindow::showSingleMultiWindow); connect(ui->actionFile_Comparison, &QAction::triggered, this, &MainWindow::showComparisonWindow); + connect(ui->actionDBC_Comparison, &QAction::triggered, this, &MainWindow::showDBCComparisonWindow); connect(ui->actionScripting_INterface, &QAction::triggered, this, &MainWindow::showScriptingWindow); connect(ui->btnNormalize, &QAbstractButton::clicked, this, &MainWindow::normalizeTiming); connect(ui->actionPreferences, &QAction::triggered, this, &MainWindow::showSettingsDialog); @@ -129,6 +137,8 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionSignal_Viewer, &QAction::triggered, this, &MainWindow::showSignalViewer); connect(ui->actionSave_Continuous_Logfile, &QAction::triggered, this, &MainWindow::handleContinousLogging); connect(ui->actionTemporal_Graph, &QAction::triggered, this, &MainWindow::showTemporalGraphWindow); + connect(ui->btnExpandAll, &QAbstractButton::clicked, this, &MainWindow::expandAllRows); + connect(ui->btnCollapseAll, &QAbstractButton::clicked, this, &MainWindow::collapseAllRows); connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames); @@ -168,12 +178,9 @@ MainWindow::MainWindow(QWidget *parent) : //of scaling or font differences between different computers. CANFrame temp; temp.bus = 0; - temp.ID = 0x100; - temp.len = 0; - temp.extended = false; + temp.setFrameId(0x100); temp.isReceived = true; - temp.remote = false; - temp.timestamp = 100000000; + temp.setTimeStamp(QCanBusFrame::TimeStamp(0, 100000000)); model->addFrame(temp, true); qApp->processEvents(); tickGUIUpdate(); //force a GUI refresh so that the row exists to measure @@ -258,12 +265,31 @@ void MainWindow::exitApp() QApplication::quit(); //forces the whole application to terminate when the main window is closed } + +//the close event can be trapped and ignored so put unsaved warnings in here so the user can abort the program closing if they forgot to save things. void MainWindow::closeEvent(QCloseEvent *event) { - Q_UNUSED(event); + + QMessageBox::StandardButton confirmDialog; + + for (int i = 0; i < dbcHandler->getFileCount(); i++) + { + DBCFile *file = dbcHandler->getFileByIdx(i); + if (file->getDirtyFlag()) + { + confirmDialog = QMessageBox::question(this, "Unsaved DBC", "DBC File:\n" + file->getFilename() + "\nAppears to have unsaved changes\nReally close without saving?", QMessageBox::Yes|QMessageBox::No); + if (confirmDialog != QMessageBox::Yes) + { + event->ignore(); + return; + } + } + } + removeEventFilter(this); writeSettings(); exitApp(); + event->accept(); } bool MainWindow::eventFilter(QObject *obj, QEvent *event) @@ -385,6 +411,48 @@ void MainWindow::headerClicked(int logicalIndex) model->sortByColumn(logicalIndex); } +void MainWindow::expandAllRows() +{ + bool goAhead = false; + int numRows = ui->canFramesView->model()->rowCount(); + + if (numRows > 20000) + { + QMessageBox::StandardButton confirmDialog; + confirmDialog = QMessageBox::question(this, "Really?", "It's not recommended to use this\non more than 20000 frames.\nIt can take a long time.\n\nYou have been warned!\nStill do it?", + QMessageBox::Yes|QMessageBox::No); + + if (confirmDialog == QMessageBox::Yes) goAhead = true; + } + else goAhead = true; + + if (goAhead) + { + ui->canFramesView->resizeRowsToContents(); + } +} + +void MainWindow::collapseAllRows() +{ + bool goAhead = false; + int numRows = ui->canFramesView->model()->rowCount(); + + if (numRows > 50000) + { + QMessageBox::StandardButton confirmDialog; + confirmDialog = QMessageBox::question(this, "Really?", "It's not recommended to use this\non more than 50000 frames.\nIt can take a long time.\n\nYou have been warned!\nStill do it?", + QMessageBox::Yes|QMessageBox::No); + + if (confirmDialog == QMessageBox::Yes) goAhead = true; + } + else goAhead = true; + + if (goAhead) + { + for (int i = 0; i < numRows; i++) ui->canFramesView->setRowHeight(i, normalRowHeight); + } +} + void MainWindow::gridClicked(QModelIndex idx) { //qDebug() << "Grid Clicked"; @@ -402,7 +470,7 @@ void MainWindow::gridDoubleClicked(QModelIndex idx) //qDebug() << "Grid double clicked"; //grab ID and timestamp and send them away CANFrame frame = model->getListReference()->at(idx.row()); - emit sendCenterTimeID(frame.ID, frame.timestamp / 1000000.0); + emit sendCenterTimeID(frame.frameId(), frame.timeStamp().microSeconds() / 1000000.0); } void MainWindow::interpretToggled(bool state) @@ -447,7 +515,7 @@ void MainWindow::updateFilterList() QMap::const_iterator filterIter; for (filterIter = filters->begin(); filterIter != filters->end(); ++filterIter) { - QListWidgetItem *thisItem = FilterUtility::createCheckableFilterItem(filterIter.key(), filterIter.value(), ui->listFilters); + /*QListWidgetItem *thisItem = */FilterUtility::createCheckableFilterItem(filterIter.key(), filterIter.value(), ui->listFilters); } inhibitFilterUpdate = false; } @@ -595,10 +663,13 @@ void MainWindow::handleLoadFile() if (!loadResult) { - confirmDialog = QMessageBox::question(this, "Error Loading", "Do you want to salvage what could be loaded?", + if (tempFrames.count() > 0) //only ask if at least one frame was decoded. + { + confirmDialog = QMessageBox::question(this, "Error Loading", "Do you want to salvage what could be loaded?", QMessageBox::Yes|QMessageBox::No); - if (confirmDialog == QMessageBox::Yes) { - loadResult = true; + if (confirmDialog == QMessageBox::Yes) { + loadResult = true; + } } } @@ -732,6 +803,10 @@ void MainWindow::saveDecodedTextFile(QString filename) QFile *outFile = new QFile(filename); const QVector *frames = model->getFilteredListReference(); + const unsigned char *data; + int dataLen; + const CANFrame *frame; + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) return; /* @@ -741,20 +816,23 @@ Data Bytes: 88 10 00 13 BB 00 06 00 */ for (int c = 0; c < frames->count(); c++) { - CANFrame thisFrame = frames->at(c); + frame = &frames->at(c); + data = reinterpret_cast(frame->payload().constData()); + dataLen = frame->payload().count(); + QString builderString; - builderString += tr("Time: ") + QString::number((thisFrame.timestamp / 1000000.0), 'f', 6); - builderString += tr(" ID: ") + Utility::formatCANID(thisFrame.ID, thisFrame.extended); - if (thisFrame.extended) builderString += tr(" Ext "); + builderString += tr("Time: ") + QString::number((frame->timeStamp().microSeconds() / 1000000.0), 'f', 6); + builderString += tr(" ID: ") + Utility::formatCANID(frame->frameId(), frame->hasExtendedFrameFormat()); + if (frame->hasExtendedFrameFormat()) builderString += tr(" Ext "); else builderString += tr(" Std "); - builderString += tr("Bus: ") + QString::number(thisFrame.bus); - builderString += " Len: " + QString::number(thisFrame.len) + "\n"; + builderString += tr("Bus: ") + QString::number(frame->bus); + builderString += " Len: " + QString::number(dataLen) + "\n"; outFile->write(builderString.toUtf8()); builderString = tr("Data Bytes: "); - for (unsigned int temp = 0; temp < thisFrame.len; temp++) + for (int temp = 0; temp < dataLen; temp++) { - builderString += Utility::formatNumber(thisFrame.data[temp]) + " "; + builderString += Utility::formatNumber(data[temp]) + " "; } builderString += "\n"; outFile->write(builderString.toUtf8()); @@ -762,14 +840,14 @@ Data Bytes: 88 10 00 13 BB 00 06 00 builderString = ""; if (dbcHandler != nullptr) { - DBC_MESSAGE *msg = dbcHandler->findMessage(thisFrame); + DBC_MESSAGE *msg = dbcHandler->findMessage(*frame); if (msg != nullptr) { for (int j = 0; j < msg->sigHandler->getCount(); j++) { QString temp; - if (msg->sigHandler->findSignalByIdx(j)->processAsText(thisFrame, temp)) + if (msg->sigHandler->findSignalByIdx(j)->processAsText(*frame, temp)) { builderString.append("\t" + temp); builderString.append("\n"); @@ -845,14 +923,14 @@ void MainWindow::showGraphingWindow() { if (!graphingWindow) { graphingWindow = new GraphingWindow(model->getListReference()); - connect(graphingWindow, SIGNAL(sendCenterTimeID(int32_t,double)), this, SLOT(gotCenterTimeID(int32_t,double))); - connect(this, SIGNAL(sendCenterTimeID(int32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(graphingWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), this, SLOT(gotCenterTimeID(int32_t,double))); + connect(this, SIGNAL(sendCenterTimeID(uint32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); } if (flowViewWindow) //connect the two external windows together { - connect(graphingWindow, SIGNAL(sendCenterTimeID(int32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); - connect(flowViewWindow, SIGNAL(sendCenterTimeID(int32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(graphingWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(flowViewWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); } graphingWindow->show(); } @@ -953,6 +1031,15 @@ void MainWindow::showComparisonWindow() comparatorWindow->show(); } +void MainWindow::showDBCComparisonWindow() +{ + if (!dbcComparatorWindow) + { + dbcComparatorWindow = new DBCComparatorWindow(); + } + dbcComparatorWindow->show(); +} + void MainWindow::showSingleMultiWindow() { if (!discreteStateWindow) @@ -1022,14 +1109,14 @@ void MainWindow::showFlowViewWindow() flowViewWindow = new FlowViewWindow(model->getListReference()); else flowViewWindow = new FlowViewWindow(model->getFilteredListReference()); - connect(flowViewWindow, SIGNAL(sendCenterTimeID(int32_t,double)), this, SLOT(gotCenterTimeID(int32_t,double))); - connect(this, SIGNAL(sendCenterTimeID(int32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(flowViewWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), this, SLOT(gotCenterTimeID(int32_t,double))); + connect(this, SIGNAL(sendCenterTimeID(uint32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); } if (graphingWindow) { - connect(graphingWindow, SIGNAL(sendCenterTimeID(int32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); - connect(flowViewWindow, SIGNAL(sendCenterTimeID(int32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(graphingWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), flowViewWindow, SLOT(gotCenterTimeID(int32_t,double))); + connect(flowViewWindow, SIGNAL(sendCenterTimeID(uint32_t,double)), graphingWindow, SLOT(gotCenterTimeID(int32_t,double))); } flowViewWindow->show(); diff --git a/mainwindow.h b/mainwindow.h index eec38a8..68b8cec 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -32,6 +32,7 @@ #include "motorcontrollerconfigwindow.h" #include "signalviewerwindow.h" #include "re/temporalgraphwindow.h" +#include "re/dbccomparatorwindow.h" class CANConnection; class ConnectionWindow; @@ -63,6 +64,8 @@ private slots: void showGraphingWindow(); void showFrameDataAnalysis(); void clearFrames(); + void expandAllRows(); + void collapseAllRows(); void showPlaybackWindow(); void showFlowViewWindow(); void showFrameSenderWindow(); @@ -83,6 +86,7 @@ private slots: void showBisectWindow(); void showSignalViewer(); void showTemporalGraphWindow(); + void showDBCComparisonWindow(); void exitApp(); void handleSaveDecoded(); void connectionStatusUpdated(int conns); @@ -115,7 +119,7 @@ signals: void framesUpdated(int numFrames); //something has updated the frame list (send at gui update frequency) void frameUpdateRapid(int numFrames); void settingsUpdated(); - void sendCenterTimeID(int32_t ID, double timestamp); + void sendCenterTimeID(uint32_t ID, double timestamp); private: Ui::MainWindow *ui; @@ -163,6 +167,7 @@ private: BisectWindow* bisectWindow; SignalViewerWindow *signalViewerWindow; TemporalGraphWindow *temporalGraphWindow; + DBCComparatorWindow *dbcComparatorWindow; //various private storage QLabel lbStatusConnected; diff --git a/motorcontrollerconfigwindow.cpp b/motorcontrollerconfigwindow.cpp index eafc31a..15b8d0d 100644 --- a/motorcontrollerconfigwindow.cpp +++ b/motorcontrollerconfigwindow.cpp @@ -4,6 +4,17 @@ #include "mainwindow.h" #include +/* + * Nothing to see here, these are not the droids you're looking for. Go away + * + * + * + * You didn't go away, did you... This is a screen that allows for setting EEPROM configuration for a + * custom motor controller project I was working on. It's hidden by default. You could re-enable it and play around + * with it if you're bored. It might be a good basis for how to set a list of parameters on a device. But, it could be broken + * these days too. It is not maintained any longer as the project it was meant for is abandoned. YMMV. +*/ + MotorControllerConfigWindow::MotorControllerConfigWindow(const QVector *frames, QWidget *parent) : QDialog(parent), ui(new Ui::MotorControllerConfigWindow) @@ -40,9 +51,8 @@ MotorControllerConfigWindow::~MotorControllerConfigWindow() void MotorControllerConfigWindow::updatedFrames(int numFrames) { CANFrame thisFrame; - int id; - int param; - QTableWidgetItem *item; + uint32_t id; + QTableWidgetItem *item = nullptr; if (numFrames == -1) //all frames deleted { @@ -57,18 +67,18 @@ void MotorControllerConfigWindow::updatedFrames(int numFrames) for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { thisFrame = modelFrames->at(i); - id = thisFrame.ID; + id = thisFrame.frameId(); if (id == 0xC2) //response to a query we made { - if (thisFrame.data[2] == 0) + if ((char)thisFrame.payload()[2] == 0) { - int paramID = thisFrame.data[0] + (thisFrame.data[1] * 256); + uint32_t paramID = static_cast(thisFrame.payload()[0] + (thisFrame.payload()[1] * 256)); for (int i = 0; i < params.length(); i++) { if (params[i].paramID == paramID) { - params[i].value = thisFrame.data[4] + (thisFrame.data[5] * 256); + params[i].value = static_cast(thisFrame.payload()[4] + (thisFrame.payload()[5] * 256)); if (params[i].paramType == ASCII) item = new QTableWidgetItem(); //QString::fromUtf8((char *)params[i].value, 2)); if (params[i].paramType == HEX) item = new QTableWidgetItem(Utility::formatHexNum(params[i].value)); if (params[i].paramType == DEC) @@ -177,18 +187,19 @@ void MotorControllerConfigWindow::timerTick() { qDebug() << "Request: " << QString::number(transmitStep); - outFrame.ID = 0xC1; - outFrame.len = 8; + outFrame.setFrameId(0xC1); + QByteArray bytes(8, 0); outFrame.bus = 0; - outFrame.extended = false; - outFrame.data[0] = params[transmitStep].paramID & 0xFF; - outFrame.data[1] = (params[transmitStep].paramID >> 8) & 0xFF; - outFrame.data[2] = 0; //0 = read, 1 = write - outFrame.data[3] = 0; //reserved - outFrame.data[4] = 0; //value goes in bytes 4,5 when writing - outFrame.data[5] = 0; - outFrame.data[6] = 0; //reserved - outFrame.data[7] = 0; //reserved + outFrame.setExtendedFrameFormat(false); + bytes[0] = params[transmitStep].paramID & 0xFF; + bytes[1] = (params[transmitStep].paramID >> 8) & 0xFF; + bytes[2] = 0; //0 = read, 1 = write + bytes[3] = 0; //reserved + bytes[4] = 0; //value goes in bytes 4,5 when writing + bytes[5] = 0; + bytes[6] = 0; //reserved + bytes[7] = 0; //reserved + outFrame.setPayload(bytes); CANConManager::getInstance()->sendFrame(outFrame); @@ -213,18 +224,18 @@ void MotorControllerConfigWindow::timerTick() if (thisValue != params[transmitStep].value) { - outFrame.ID = 0xC1; - outFrame.len = 8; + outFrame.setFrameId(0xC1); + QByteArray bytes(8, 0); outFrame.bus = 0; - outFrame.extended = false; - outFrame.data[0] = params[transmitStep].paramID & 0xFF; - outFrame.data[1] = (params[transmitStep].paramID >> 8) & 0xFF; - outFrame.data[2] = 1; //0 = read, 1 = write - outFrame.data[3] = 0; //reserved - outFrame.data[4] = params[transmitStep].value & 0xFF; - outFrame.data[5] = (params[transmitStep].value >> 8) & 0xFF; - outFrame.data[6] = 0; //reserved - outFrame.data[7] = 0; //reserved + outFrame.setExtendedFrameFormat(false); + bytes[0] = params[transmitStep].paramID & 0xFF; + bytes[1] = (params[transmitStep].paramID >> 8) & 0xFF; + bytes[2] = 1; //0 = read, 1 = write + bytes[3] = 0; //reserved + bytes[4] = params[transmitStep].value & 0xFF; + bytes[5] = (params[transmitStep].value >> 8) & 0xFF; + bytes[6] = 0; //reserved + bytes[7] = 0; //reserved CANConManager::getInstance()->sendFrame(outFrame); } diff --git a/mqtt/LICENSE b/mqtt/LICENSE new file mode 100644 index 0000000..56bef4e --- /dev/null +++ b/mqtt/LICENSE @@ -0,0 +1,2 @@ +This project is dual licensed under the Eclipse Public License 1.0 and the +Eclipse Distribution License 1.0 as described in the epl-v10 and edl-v10 files. diff --git a/mqtt/README.md b/mqtt/README.md new file mode 100644 index 0000000..ba0068b --- /dev/null +++ b/mqtt/README.md @@ -0,0 +1,139 @@ +QMQTT +===== + +mqtt client for Qt + +**Please compile the library with Qt >= 5.3 version. On Windows you need to specify `CONFIG += NO_UNIT_TESTS`, since gtest is not supported.** + +SSL is enabled by default, if the version of OpenSSL < 1.0.2, SSL may not be supported. + +Disable the SSL in CMakeLists.txt (cmake): + + option( ${PROJECT_NAME}_SSL "Enable SSL support for MQTT" OFF ) + +Disable the SSL with src/mqtt/qmqtt.pro (qmake): + + CONFIG+=QMQTT_NO_SSL + +To add websocket support, compile the library with Qt >= 5.7, and specify 'CONFIG += QMQTT_WEBSOCKETS'. +This also works when compiling qmqtt for WebAssembly. + +Usage +===== + +In your QMake project, add: + + QT += qmqtt + +Connect using TCP: + + #include "qmqtt.h" + + QMQTT::Client *client = new QMQTT::Client(QHostAddress::LocalHost, 1883); + client->setClientId("clientId"); + client->setUsername("user"); + client->setPassword("password"); + client->connectToHost(); + +Connect using SSL: + + QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration(); + // Add custom SSL options here (for example extra certificates) + QMQTT::Client *client = new QMQTT::Client("example.com", 8883, sslConfig); + client->setClientId("clientId"); + client->setUsername("user"); + client->setPassword("password"); + // Optionally, set ssl errors you want to ignore. Be careful, because this may weaken security. + // See QSslSocket::ignoreSslErrors(const QList &) for more information. + client->ignoreSslErrors() + client->connectToHost(); + // Here's another option to suppress SSL errors (again, be careful) + QObject::connect(client, &QMQTT::Client::sslErrors, [&](const QList &errors) { + // Investigate the errors here, if you find no serious problems, call ignoreSslErrors() + // to continue connecting. + client->ignoreSslErrors(); + }); + +Connect using WebSockets: + + QMQTT::Client *client = new QMQTT::Client("ws://www.example.com/mqtt", "", QWebSocketProtocol::VersionLatest); + client->setClientId("clientId"); + client->setUsername("user"); + client->setPassword("password"); + client->connectToHost(); + +Slots +===== + + void setHost(const QHostAddress& host); + void setPort(const quint16 port); + void setClientId(const QString& clientId); + void setUsername(const QString& username); + void setPassword(const QString& password); + void setKeepAlive(const int keepAlive); + void setCleanSession(const bool cleansess); + void setAutoReconnect(const bool value); + void setAutoReconnectInterval(const int autoReconnectInterval); + void setWillTopic(const QString& willTopic); + void setWillQos(const quint8 willQos); + void setWillRetain(const bool willRetain); + void setWillMessage(const QString& willMessage); + + void connectToHost(); + void disconnectFromHost(); + + quint16 subscribe(const QString& topic, const quint8 qos); + void unsubscribe(const QString& topic); + + quint16 publish(const Message& message); + +Signals +======= + + void connected(); + void disconnected(); + void error(const QMQTT::ClientError error); + + void subscribed(const QString& topic, const quint8 qos); + void unsubscribed(const QString& topic); + void published(const quint16 msgid, const quint8 qos); + void pingresp(); + void received(const QMQTT::Message& message); + + +License +======= + +New BSD License + + +Contributors +============= + +[@Kampfgnom](https://github.com/Kampfgnom) + +[@rafaeldelucena](https://github.com/rafaeldelucena) + +[@Vortex375](https://github.com/Vortex375) + +[@mwallnoefer](https://github.com/mwallnoefer) + +[@KonstantinRitt](https://github.com/KonstantinRitt) + +[@cncap](https://github.com/cncap) + +[@Psy-Kai](https://github.com/Psy-Kai) + +[@ejvr](https://github.com/ejvr) + +[@keytee](https://github.com/keytee) + + +Authors +======= + +[@emqplus](https://github.com/emqplus) Feng Lee + +[@wguynes](https://github.com/wguynes) William Guynes + +[@wuming123057](https://github.com/wuming123057) Xuan diff --git a/mqtt/edl-v10 b/mqtt/edl-v10 new file mode 100644 index 0000000..d36ee54 --- /dev/null +++ b/mqtt/edl-v10 @@ -0,0 +1,30 @@ +Eclipse Distribution License - v 1.0 + +Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + Neither the name of the Eclipse Foundation, Inc. nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/mqtt/epl-v10 b/mqtt/epl-v10 new file mode 100644 index 0000000..4ec0f61 --- /dev/null +++ b/mqtt/epl-v10 @@ -0,0 +1,220 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC +LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM +CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + +1. DEFINITIONS + +"Contribution" means: + a) in the case of the initial Contributor, the initial code and + documentation distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + + i) changes to the Program, and + ii) additions to the Program; + +where such changes and/or additions to the Program originate from and are +distributed by that particular Contributor. A Contribution 'originates' from a +Contributor if it was added to the Program by such Contributor itself or anyone +acting on such Contributor's behalf. Contributions do not include additions to +the Program which: (i) are separate modules of software distributed in +conjunction with the Program under their own license agreement, and (ii) are +not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents " mean patent claims licensable by a Contributor which are +necessarily infringed by the use or sale of its Contribution alone or when +combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, +including all Contributors. + + +2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license to + reproduce, prepare derivative works of, publicly display, publicly + perform, distribute and sublicense the Contribution of such Contributor, + if any, and such derivative works, in source code and object code form. + + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under + Licensed Patents to make, use, sell, offer to sell, import and otherwise + transfer the Contribution of such Contributor, if any, in source code and + object code form. This patent license shall apply to the combination of the + Contribution and the Program if, at the time the Contribution is added by the + Contributor, such addition of the Contribution causes such combination to be + covered by the Licensed Patents. The patent license shall not apply to any + other combinations which include the Contribution. No hardware per se is + licensed hereunder. + + c) Recipient understands that although each Contributor grants the licenses + to its Contributions set forth herein, no assurances are provided by any + Contributor that the Program does not infringe the patent or other + intellectual property rights of any other entity. Each Contributor disclaims + any liability to Recipient for claims brought by any other entity based on + infringement of intellectual property rights or otherwise. As a condition to + exercising the rights and licenses granted hereunder, each Recipient hereby + assumes sole responsibility to secure any other intellectual property rights + needed, if any. For example, if a third party patent license is required to + allow Recipient to distribute the Program, it is Recipient's responsibility + to acquire that license before distributing the Program. + + d) Each Contributor represents that to its knowledge it has sufficient + copyright rights in its Contribution, if any, to grant the copyright license + set forth in this Agreement. + + +3. REQUIREMENTS + + A Contributor may choose to distribute the Program in object code form under + its own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + + b) its license agreement: + + i) effectively disclaims on behalf of all Contributors all warranties and + conditions, express and implied, including warranties or conditions of + title and non-infringement, and implied warranties or conditions of + merchantability and fitness for a particular purpose; + + ii) effectively excludes on behalf of all Contributors all liability for + damages, including direct, indirect, special, incidental and consequential + damages, such as lost profits; + + iii) states that any provisions which differ from this Agreement are offered + by that Contributor alone and not by any other party; and + + iv) states that source code for the Program is available from such + Contributor, and informs licensees how to obtain it in a reasonable manner + on or through a medium customarily used for software exchange. + + When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + + b) a copy of this Agreement must be included with each copy of the Program. + + Contributors may not remove or alter any copyright notices contained within + the Program. + + Each Contributor must identify itself as the originator of its Contribution, + if any, in a manner that reasonably allows subsequent Recipients to identify + the originator of the Contribution. + + +4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities with + respect to end users, business partners and the like. While this license is + intended to facilitate the commercial use of the Program, the Contributor who + includes the Program in a commercial product offering should do so in a + manner which does not create potential liability for other Contributors. + Therefore, if a Contributor includes the Program in a commercial product + offering, such Contributor ("Commercial Contributor") hereby agrees to defend + and indemnify every other Contributor ("Indemnified Contributor") against any + losses, damages and costs (collectively "Losses") arising from claims, + lawsuits and other legal actions brought by a third party against the + Indemnified Contributor to the extent caused by the acts or omissions of such + Commercial Contributor in connection with its distribution of the Program in + a commercial product offering. The obligations in this section do not apply + to any claims or Losses relating to any actual or alleged intellectual + property infringement. In order to qualify, an Indemnified Contributor must: + a) promptly notify the Commercial Contributor in writing of such claim, and + b) allow the Commercial Contributor to control, and cooperate with the + Commercial Contributor in, the defense and any related settlement + negotiations. The Indemnified Contributor may participate in any such claim + at its own expense. + + For example, a Contributor might include the Program in a commercial product + offering, Product X. That Contributor is then a Commercial Contributor. If + that Commercial Contributor then makes performance claims, or offers + warranties related to Product X, those performance claims and warranties are + such Commercial Contributor's responsibility alone. Under this section, the + Commercial Contributor would have to defend claims against the other + Contributors related to those performance claims and warranties, and if a + court requires any other Contributor to pay any damages as a result, the + Commercial Contributor must pay those damages. + + +5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON + AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER + EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR + CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A + PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the + appropriateness of using and distributing the Program and assumes all risks + associated with its exercise of rights under this Agreement , including but + not limited to the risks and costs of program errors, compliance with + applicable laws, damage to or loss of data, programs or equipment, and + unavailability or interruption of operations. + + +6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY + CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION + LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE + EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY + OF SUCH DAMAGES. + + +7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of the + remainder of the terms of this Agreement, and without further action by the + parties hereto, such provision shall be reformed to the minimum extent + necessary to make such provision valid and enforceable. + + If Recipient institutes patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Program itself + (excluding combinations of the Program with other software or hardware) + infringes such Recipient's patent(s), then such Recipient's rights granted + under Section 2(b) shall terminate as of the date such litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it fails to + comply with any of the material terms or conditions of this Agreement and + does not cure such failure in a reasonable period of time after becoming + aware of such noncompliance. If all Recipient's rights under this Agreement + terminate, Recipient agrees to cease use and distribution of the Program as + soon as reasonably practicable. However, Recipient's obligations under this + Agreement and any licenses granted by Recipient relating to the Program shall + continue and survive. + + Everyone is permitted to copy and distribute copies of this Agreement, but in + order to avoid inconsistency the Agreement is copyrighted and may only be + modified in the following manner. The Agreement Steward reserves the right to + publish new versions (including revisions) of this Agreement from time to + time. No one other than the Agreement Steward has the right to modify this + Agreement. The Eclipse Foundation is the initial Agreement Steward. The + Eclipse Foundation may assign the responsibility to serve as the Agreement + Steward to a suitable separate entity. Each new version of the Agreement will + be given a distinguishing version number. The Program (including + Contributions) may always be distributed subject to the version of the + Agreement under which it was received. In addition, after a new version of + the Agreement is published, Contributor may elect to distribute the Program + (including its Contributions) under the new version. Except as expressly + stated in Sections 2(a) and 2(b) above, Recipient receives no rights or + licenses to the intellectual property of any Contributor under this + Agreement, whether expressly, by implication, estoppel or otherwise. All + rights in the Program not expressly granted under this Agreement are + reserved. + + This Agreement is governed by the laws of the State of New York and the + intellectual property laws of the United States of America. No party to this + Agreement will bring a legal action under this Agreement more than one year + after the cause of action arose. Each party waives its rights to a jury trial + in any resulting litigation. \ No newline at end of file diff --git a/mqtt/qmqtt.h b/mqtt/qmqtt.h new file mode 100644 index 0000000..63f5470 --- /dev/null +++ b/mqtt/qmqtt.h @@ -0,0 +1,38 @@ +/* + * qmqtt.h - qmqtt library heaer + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_H +#define QMQTT_H + +#include "qmqtt_message.h" +#include "qmqtt_client.h" + +#endif // QMQTT_H diff --git a/mqtt/qmqtt.pri b/mqtt/qmqtt.pri new file mode 100644 index 0000000..c5790bf --- /dev/null +++ b/mqtt/qmqtt.pri @@ -0,0 +1,48 @@ +INCLUDEPATH += $$PWD + +PUBLIC_HEADERS += \ + $$PWD/qmqtt_client.h \ + $$PWD/qmqtt_frame.h \ + $$PWD/qmqtt_message.h \ + $$PWD/qmqtt_routesubscription.h \ + $$PWD/qmqtt_routedmessage.h \ + $$PWD/qmqtt_router.h \ + $$PWD/qmqtt_networkinterface.h \ + $$PWD/qmqtt_socketinterface.h \ + $$PWD/qmqtt_timerinterface.h + +PRIVATE_HEADERS += \ + $$PWD/qmqtt_client_p.h \ + $$PWD/qmqtt_message_p.h \ + $$PWD/qmqtt_network_p.h \ + $$PWD/qmqtt_socket_p.h \ + $$PWD/qmqtt_timer_p.h + +SOURCES += \ + $$PWD/qmqtt_client_p.cpp \ + $$PWD/qmqtt_client.cpp \ + $$PWD/qmqtt_frame.cpp \ + $$PWD/qmqtt_message.cpp \ + $$PWD/qmqtt_network.cpp \ + $$PWD/qmqtt_routesubscription.cpp \ + $$PWD/qmqtt_router.cpp \ + $$PWD/qmqtt_socket.cpp \ + $$PWD/qmqtt_timer.cpp + +QMQTT_WEBSOCKETS { + PRIVATE_HEADERS += \ + $$PWD/qmqtt_websocket_p.h \ + $$PWD/qmqtt_websocketiodevice_p.h + + SOURCES += \ + $$PWD/qmqtt_websocket.cpp \ + $$PWD/qmqtt_websocketiodevice.cpp +} + +!contains(CONFIG, QMQTT_NO_SSL) { + PRIVATE_HEADERS += \ + $$PWD/qmqtt_ssl_socket_p.h + + SOURCES += \ + $$PWD/qmqtt_ssl_socket.cpp +} diff --git a/mqtt/qmqtt.pro b/mqtt/qmqtt.pro new file mode 100644 index 0000000..4862266 --- /dev/null +++ b/mqtt/qmqtt.pro @@ -0,0 +1,17 @@ +TARGET = QtQmqtt +QT = core network +qtHaveModule(websockets): QMQTT_WEBSOCKETS: QT += websockets + +DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII + +# CONFIG += QMQTT_NO_SSL + +HEADERS += \ + $$PWD/qmqtt_global.h \ + $$PWD/qmqtt.h + +include(qmqtt.pri) + +HEADERS += $$PUBLIC_HEADERS $$PRIVATE_HEADERS + +load(qt_module) diff --git a/mqtt/qmqtt.qbs b/mqtt/qmqtt.qbs new file mode 100644 index 0000000..b3d0f62 --- /dev/null +++ b/mqtt/qmqtt.qbs @@ -0,0 +1,134 @@ +import qbs +import qbs.TextFile +import qbs.FileInfo + +Product { + name: "qmqtt" + type: [libraryType] + property bool webSocketSupport: false + property string libraryType: "dynamiclibrary" + targetName: "qmqtt" + version: "1.0.0" + + cpp.defines: [ + "QT_BUILD_QMQTT_LIB", + "QT_NO_CAST_TO_ASCII", + "QT_NO_CAST_FROM_ASCII", + ] + + cpp.includePaths: sourceDirectory + + files: [ + "*.cpp" + ] + + Group { + name: "Public Headers" + fileTags: [ + "hpp", + "public_headers" + ] + files: [ + "*.h" + ] + excludeFiles: privateHeaders.files + } + + Group { + id: privateHeaders + name: "Private Headers" + fileTags: [ + "hpp", + "private_headers", + ] + files: [ + "*_p.h" + ] + } + + Group { + fileTagsFilter: libraryType + qbs.install: true + qbs.installDir: "lib" + } + + Group { + fileTagsFilter: "public_headers" + qbs.install: true + qbs.installDir: FileInfo.joinPaths("include", product.name) + } + + Group { + fileTagsFilter: "private_headers" + qbs.install: true + qbs.installDir: FileInfo.joinPaths("include", product.name, version, product.name) + } + + Group { + fileTagsFilter: "Exporter.qbs.module" + qbs.installDir: FileInfo.joinPaths("qbs", "modules", product.name, "private") + qbs.install: true + } + + Group { + fileTagsFilter: "Exporter.pkgconfig.pc" + qbs.installDir: FileInfo.joinPaths("lib" ,"pkgconfig") + qbs.install: true + } + + Depends { + name: "cpp" + } + + Depends { + name: "Qt" + property var baseModules: ["core", "network"] + + Properties { + condition: webSocketSupport + submodules: baseModules.concat(["websockets"]) + } + Properties { + condition: !webSocketSupport + submodules: baseModules + } + } + + Depends { + name: "Exporter.qbs" + } + Depends { + name: "Exporter.pkgconfig" + } + + Export { + Depends { + name: "cpp" + } + + Depends { + name: "Qt" + property var baseModules: ["core", "network"] + Properties { + condition: product.webSocketSupport + submodules: baseModules.concat(["websockets"]) + } + Properties { + condition: !product.webSocketSupport + submodules: baseModules + } + } + + cpp.includePaths: [ + product.sourceDirectory, + FileInfo.joinPaths(qbs.installRoot, qbs.installPrefix, "include"), + ] + prefixMapping: [ + { + prefix: product.sourceDirectory, + replacement: FileInfo.joinPaths(qbs.installRoot, qbs.installPrefix, "include", + product.name) + } + ] + } +} diff --git a/mqtt/qmqtt_client.cpp b/mqtt/qmqtt_client.cpp new file mode 100644 index 0000000..78542e4 --- /dev/null +++ b/mqtt/qmqtt_client.cpp @@ -0,0 +1,412 @@ +/* + * qmqtt_client.cpp - qmqtt client + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_client.h" +#include "qmqtt_client_p.h" + +QMQTT::Client::Client(const QHostAddress& host, + const quint16 port, + QObject* parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); + d->init(host, port); +} + +#ifndef QT_NO_SSL +QMQTT::Client::Client(const QString &hostName, + const quint16 port, + const QSslConfiguration &config, + const bool ignoreSelfSigned, QObject *parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); + d->init(hostName, port, config, ignoreSelfSigned); +} +#endif // QT_NO_SSL + +QMQTT::Client::Client(const QString &hostName, + const quint16 port, + const bool ssl, + const bool ignoreSelfSigned, + QObject* parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); + d->init(hostName, port, ssl, ignoreSelfSigned); +} + +#ifdef QT_WEBSOCKETS_LIB +QMQTT::Client::Client(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + bool ignoreSelfSigned, + QObject* parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); +#ifndef QT_NO_SSL + d->init(url, origin, version, NULL, ignoreSelfSigned); +#else + Q_UNUSED(ignoreSelfSigned) + d->init(url, origin, version); +#endif // QT_NO_SSL +} + +#ifndef QT_NO_SSL +QMQTT::Client::Client(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration& sslConfig, + const bool ignoreSelfSigned, + QObject* parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); + d->init(url, origin, version, &sslConfig, ignoreSelfSigned); +} +#endif // QT_NO_SSL +#endif // QT_WEBSOCKETS_LIB + +QMQTT::Client::Client(NetworkInterface* network, + const QHostAddress& host, + const quint16 port, + QObject* parent) + : QObject(parent) + , d_ptr(new ClientPrivate(this)) +{ + Q_D(Client); + d->init(host, port, network); +} + +QMQTT::Client::~Client() +{ +} + +QHostAddress QMQTT::Client::host() const +{ + Q_D(const Client); + return d->host(); +} + +void QMQTT::Client::setHost(const QHostAddress& host) +{ + Q_D(Client); + d->setHost(host); +} + +QString QMQTT::Client::hostName() const +{ + Q_D(const Client); + return d->hostName(); +} + +void QMQTT::Client::setHostName(const QString &hostName) +{ + Q_D(Client); + d->setHostName(hostName); +} + +quint16 QMQTT::Client::port() const +{ + Q_D(const Client); + return d->port(); +} + +void QMQTT::Client::setPort(const quint16 port) +{ + Q_D(Client); + d->setPort(port); +} + +QString QMQTT::Client::clientId() const +{ + Q_D(const Client); + return d->clientId(); +} + +void QMQTT::Client::setClientId(const QString& clientId) +{ + Q_D(Client); + d->setClientId(clientId); +} + +QString QMQTT::Client::username() const +{ + Q_D(const Client); + return d->username(); +} + +void QMQTT::Client::setUsername(const QString& username) +{ + Q_D(Client); + d->setUsername(username); +} + +QMQTT::MQTTVersion QMQTT::Client::version() const +{ + Q_D(const Client); + return d->version(); +} + +void QMQTT::Client::setVersion(const QMQTT::MQTTVersion version) +{ + Q_D(Client); + d->setVersion(version); +} + +QByteArray QMQTT::Client::password() const +{ + Q_D(const Client); + return d->password(); +} + +void QMQTT::Client::setPassword(const QByteArray &password) +{ + Q_D(Client); + d->setPassword(password); +} + +quint16 QMQTT::Client::keepAlive() const +{ + Q_D(const Client); + return d->keepAlive(); +} + +void QMQTT::Client::setKeepAlive(const quint16 keepAlive) +{ + Q_D(Client); + d->setKeepAlive(keepAlive); +} + +bool QMQTT::Client::cleanSession() const +{ + Q_D(const Client); + return d->cleanSession(); +} + +void QMQTT::Client::setCleanSession(const bool cleanSession) +{ + Q_D(Client); + d->setCleanSession(cleanSession); +} + +bool QMQTT::Client::autoReconnect() const +{ + Q_D(const Client); + return d->autoReconnect(); +} + +void QMQTT::Client::setAutoReconnect(const bool value) +{ + Q_D(Client); + d->setAutoReconnect(value); +} + +int QMQTT::Client::autoReconnectInterval() const +{ + Q_D(const Client); + return d->autoReconnectInterval(); +} + +void QMQTT::Client::setAutoReconnectInterval(const int autoReconnectInterval) +{ + Q_D(Client); + d->setAutoReconnectInterval(autoReconnectInterval); +} + +QString QMQTT::Client::willTopic() const +{ + Q_D(const Client); + return d->willTopic(); +} + +void QMQTT::Client::setWillTopic(const QString& willTopic) +{ + Q_D(Client); + d->setWillTopic(willTopic); +} + +quint8 QMQTT::Client::willQos() const +{ + Q_D(const Client); + return d->willQos(); +} + +void QMQTT::Client::setWillQos(const quint8 willQos) +{ + Q_D(Client); + d->setWillQos(willQos); +} + +bool QMQTT::Client::willRetain() const +{ + Q_D(const Client); + return d->willRetain(); +} + +void QMQTT::Client::setWillRetain(const bool willRetain) +{ + Q_D(Client); + d->setWillRetain(willRetain); +} + +QByteArray QMQTT::Client::willMessage() const +{ + Q_D(const Client); + return d->willMessage(); +} + +void QMQTT::Client::setWillMessage(const QByteArray &willMessage) +{ + Q_D(Client); + d->setWillMessage(willMessage); +} + +QMQTT::ConnectionState QMQTT::Client::connectionState() const +{ + Q_D(const Client); + return d->connectionState(); +} + +bool QMQTT::Client::isConnectedToHost() const +{ + Q_D(const Client); + return d->isConnectedToHost(); +} + +#ifndef QT_NO_SSL +QSslConfiguration QMQTT::Client::sslConfiguration() const +{ + Q_D(const Client); + return d->sslConfiguration(); +} + +void QMQTT::Client::setSslConfiguration(const QSslConfiguration& config) +{ + Q_D(Client); + d->setSslConfiguration(config); +} +#endif // QT_NO_SSL + +void QMQTT::Client::connectToHost() +{ + Q_D(Client); + d->connectToHost(); +} + +void QMQTT::Client::onNetworkConnected() +{ + Q_D(Client); + d->onNetworkConnected(); +} + +quint16 QMQTT::Client::publish(const Message& message) +{ + Q_D(Client); + return d->publish(message); +} + +void QMQTT::Client::subscribe(const QString& topic, const quint8 qos) +{ + Q_D(Client); + d->subscribe(topic, qos); +} + +void QMQTT::Client::unsubscribe(const QString& topic) +{ + Q_D(Client); + d->unsubscribe(topic); +} + +void QMQTT::Client::onTimerPingReq() +{ + Q_D(Client); + d->onTimerPingReq(); +} + +void QMQTT::Client::onPingTimeout() +{ + Q_D(Client); + d->onPingTimeout(); +} + +void QMQTT::Client::disconnectFromHost() +{ + Q_D(Client); + d->disconnectFromHost(); +} + +void QMQTT::Client::onNetworkReceived(const QMQTT::Frame& frame) +{ + Q_D(Client); + d->onNetworkReceived(frame); +} + +void QMQTT::Client::onNetworkDisconnected() +{ + Q_D(Client); + d->onNetworkDisconnected(); +} + +void QMQTT::Client::onNetworkError(QAbstractSocket::SocketError error) +{ + Q_D(Client); + d->onNetworkError(error); +} + +#ifndef QT_NO_SSL +void QMQTT::Client::onSslErrors(const QList& errors) +{ + Q_D(Client); + d->onSslErrors(errors); +} +#endif // QT_NO_SSL + +#ifndef QT_NO_SSL +void QMQTT::Client::ignoreSslErrors() +{ + Q_D(Client); + d->ignoreSslErrors(); +} + +void QMQTT::Client::ignoreSslErrors(const QList& errors) +{ + Q_D(Client); + d->ignoreSslErrors(errors); +} +#endif // QT_NO_SSL diff --git a/mqtt/qmqtt_client.h b/mqtt/qmqtt_client.h new file mode 100644 index 0000000..da89f01 --- /dev/null +++ b/mqtt/qmqtt_client.h @@ -0,0 +1,276 @@ +/* + * qmqtt_client.h - qmqtt client header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_CLIENT_H +#define QMQTT_CLIENT_H + +#include "qmqtt_global.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifdef QT_WEBSOCKETS_LIB +#include +#endif // QT_WEBSOCKETS_LIB + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +namespace QMQTT { + +static const quint8 LIBRARY_VERSION_MAJOR = 0; +static const quint8 LIBRARY_VERSION_MINOR = 3; +static const quint8 LIBRARY_VERSION_REVISION = 1; +//static const char* LIBRARY_VERSION = "0.3.1"; + +enum MQTTVersion +{ + V3_1_0 = 3, + V3_1_1 = 4 +}; + +enum ConnectionState +{ + STATE_INIT = 0, + STATE_CONNECTING, + STATE_CONNECTED, + STATE_DISCONNECTED +}; + +enum ClientError +{ + UnknownError = 0, + SocketConnectionRefusedError, + SocketRemoteHostClosedError, + SocketHostNotFoundError, + SocketAccessError, + SocketResourceError, + SocketTimeoutError, + SocketDatagramTooLargeError, + SocketNetworkError, + SocketAddressInUseError, + SocketAddressNotAvailableError, + SocketUnsupportedSocketOperationError, + SocketUnfinishedSocketOperationError, + SocketProxyAuthenticationRequiredError, + SocketSslHandshakeFailedError, + SocketProxyConnectionRefusedError, + SocketProxyConnectionClosedError, + SocketProxyConnectionTimeoutError, + SocketProxyNotFoundError, + SocketProxyProtocolError, + SocketOperationError, + SocketSslInternalError, + SocketSslInvalidUserDataError, + SocketTemporaryError, + MqttUnacceptableProtocolVersionError=1<<16, + MqttIdentifierRejectedError, + MqttServerUnavailableError, + MqttBadUserNameOrPasswordError, + MqttNotAuthorizedError, + MqttNoPingResponse +}; + +class ClientPrivate; +class Message; +class Frame; +class NetworkInterface; + +class Q_MQTT_EXPORT Client : public QObject +{ + Q_OBJECT + Q_PROPERTY(quint16 _port READ port WRITE setPort) + Q_PROPERTY(QHostAddress _host READ host WRITE setHost) + Q_PROPERTY(QString _hostName READ hostName WRITE setHostName) + Q_PROPERTY(QString _clientId READ clientId WRITE setClientId) + Q_PROPERTY(QString _username READ username WRITE setUsername) + Q_PROPERTY(QByteArray _password READ password WRITE setPassword) + Q_PROPERTY(quint16 _keepAlive READ keepAlive WRITE setKeepAlive) + Q_PROPERTY(MQTTVersion _version READ version WRITE setVersion) + Q_PROPERTY(bool _autoReconnect READ autoReconnect WRITE setAutoReconnect) + Q_PROPERTY(int _autoReconnectInterval READ autoReconnectInterval WRITE setAutoReconnectInterval) + Q_PROPERTY(bool _cleanSession READ cleanSession WRITE setCleanSession) + Q_PROPERTY(QString _willTopic READ willTopic WRITE setWillTopic) + Q_PROPERTY(quint8 _willQos READ willQos WRITE setWillQos) + Q_PROPERTY(bool _willRetain READ willRetain WRITE setWillRetain) + Q_PROPERTY(QByteArray _willMessage READ willMessage WRITE setWillMessage) + Q_PROPERTY(QString _connectionState READ connectionState) +#ifndef QT_NO_SSL + Q_PROPERTY(QSslConfiguration _sslConfiguration READ sslConfiguration WRITE setSslConfiguration) +#endif // QT_NO_SSL + +public: + Client(const QHostAddress& host = QHostAddress::LocalHost, + const quint16 port = 1883, + QObject* parent = NULL); + +#ifndef QT_NO_SSL + Client(const QString& hostName, + const quint16 port, + const QSslConfiguration& config, + const bool ignoreSelfSigned=false, + QObject* parent = NULL); +#endif // QT_NO_SSL + + // This function is provided for backward compatibility with older versions of QMQTT. + // If the ssl parameter is true, this function will load a private key ('cert.key') and a local + // certificate ('cert.crt') from the current working directory. It will also set PeerVerifyMode + // to None. This may not be the safest way to set up an SSL connection. + Client(const QString& hostName, + const quint16 port, + const bool ssl, + const bool ignoreSelfSigned, + QObject* parent = NULL); + +#ifdef QT_WEBSOCKETS_LIB + // Create a connection over websockets + Client(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + bool ignoreSelfSigned = false, + QObject* parent = NULL); + +#ifndef QT_NO_SSL + Client(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration& config, + const bool ignoreSelfSigned = false, + QObject* parent = NULL); +#endif // QT_NO_SSL +#endif // QT_WEBSOCKETS_LIB + + // for testing purposes only + Client(NetworkInterface* network, + const QHostAddress& host = QHostAddress::LocalHost, + const quint16 port = 1883, + QObject* parent = NULL); + + virtual ~Client(); + + QHostAddress host() const; + QString hostName() const; + quint16 port() const; + QString clientId() const; + QString username() const; + QByteArray password() const; + QMQTT::MQTTVersion version() const; + quint16 keepAlive() const; + bool cleanSession() const; + bool autoReconnect() const; + int autoReconnectInterval() const; + ConnectionState connectionState() const; + QString willTopic() const; + quint8 willQos() const; + bool willRetain() const; + QByteArray willMessage() const; + + bool isConnectedToHost() const; +#ifndef QT_NO_SSL + QSslConfiguration sslConfiguration() const; + void setSslConfiguration(const QSslConfiguration& config); +#endif // QT_NO_SSL + +public slots: + void setHost(const QHostAddress& host); + void setHostName(const QString& hostName); + void setPort(const quint16 port); + void setClientId(const QString& clientId); + void setUsername(const QString& username); + void setPassword(const QByteArray& password); + void setVersion(const MQTTVersion version); + void setKeepAlive(const quint16 keepAlive); + void setCleanSession(const bool cleanSession); + void setAutoReconnect(const bool value); + void setAutoReconnectInterval(const int autoReconnectInterval); + void setWillTopic(const QString& willTopic); + void setWillQos(const quint8 willQos); + void setWillRetain(const bool willRetain); + void setWillMessage(const QByteArray& willMessage); + + void connectToHost(); + void disconnectFromHost(); + + void subscribe(const QString& topic, const quint8 qos = 0); + void unsubscribe(const QString& topic); + + quint16 publish(const QMQTT::Message& message); + +#ifndef QT_NO_SSL + void ignoreSslErrors(); + void ignoreSslErrors(const QList& errors); +#endif // QT_NO_SSL + +signals: + void connected(); + void disconnected(); + void error(const QMQTT::ClientError error); + + void subscribed(const QString& topic, const quint8 qos = 0); + void unsubscribed(const QString& topic); + void published(const QMQTT::Message& message, quint16 msgid = 0); + void received(const QMQTT::Message& message); + void pingresp(); +#ifndef QT_NO_SSL + void sslErrors(const QList& errors); +#endif // QT_NO_SSL + +protected slots: + void onNetworkConnected(); + void onNetworkDisconnected(); + void onNetworkReceived(const QMQTT::Frame& frame); + void onTimerPingReq(); + void onPingTimeout(); + void onNetworkError(QAbstractSocket::SocketError error); +#ifndef QT_NO_SSL + void onSslErrors(const QList& errors); +#endif // QT_NO_SSL + +protected: + QScopedPointer d_ptr; + +private: + Q_DISABLE_COPY(Client) + Q_DECLARE_PRIVATE(Client) +}; + +} // namespace QMQTT + +Q_DECLARE_METATYPE(QMQTT::ClientError) + +#endif // QMQTT_CLIENT_H diff --git a/mqtt/qmqtt_client_p.cpp b/mqtt/qmqtt_client_p.cpp new file mode 100644 index 0000000..5f53297 --- /dev/null +++ b/mqtt/qmqtt_client_p.cpp @@ -0,0 +1,811 @@ +/* + * qmqtt_client_p.cpp - qmqtt client private + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_client_p.h" +#include "qmqtt_network_p.h" +#include "qmqtt_frame.h" +#include "qmqtt_message.h" + +#include +#include +#ifndef QT_NO_SSL +#include +#include +#include +#endif // QT_NO_SSL + +Q_LOGGING_CATEGORY(client, "qmqtt.client") + +static const quint8 QOS0 = 0x00; +static const quint8 QOS1 = 0x01; +static const quint8 QOS2 = 0x02; + +QMQTT::ClientPrivate::ClientPrivate(Client* qq_ptr) + : _host(QHostAddress::LocalHost) + , _port(1883) + , _gmid(1) + , _version(MQTTVersion::V3_1_0) + , _clientId(QUuid::createUuid().toString()) + , _cleanSession(false) + , _connectionState(STATE_INIT) + , _willQos(0) + , _willRetain(false) + , q_ptr(qq_ptr) +{ + setKeepAlive(300); +} + +QMQTT::ClientPrivate::~ClientPrivate() +{ +} + +void QMQTT::ClientPrivate::init(const QHostAddress& host, const quint16 port, NetworkInterface* network) +{ + Q_Q(Client); + _host = host; + _port = port; + if(network == NULL) + { + init(new Network(q)); + } + else + { + init(network); + } +} + +#ifndef QT_NO_SSL +void QMQTT::ClientPrivate::init(const QString& hostName, const quint16 port, + const QSslConfiguration &config, const bool ignoreSelfSigned) +{ + Q_Q(Client); + _hostName = hostName; + _port = port; + _ignoreSelfSigned = ignoreSelfSigned; + init(new Network(config, q)); + QObject::connect(_network.data(), &QMQTT::Network::sslErrors, q, &QMQTT::Client::onSslErrors); +} +#endif // QT_NO_SSL + +void QMQTT::ClientPrivate::init(const QString& hostName, const quint16 port, const bool ssl, + const bool ignoreSelfSigned) +{ + Q_Q(Client); + _hostName = hostName; + _port = port; + if (ssl) + { +#ifndef QT_NO_SSL + QSslConfiguration sslConf = QSslConfiguration::defaultConfiguration(); + QList certs = QSslCertificate::fromPath(QStringLiteral("./cert.crt")); + if (!certs.isEmpty()) + sslConf.setLocalCertificate(certs.first()); + QFile file(QStringLiteral("./cert.key")); + if (file.open(QIODevice::ReadOnly)) { + sslConf.setPrivateKey(QSslKey(file.readAll(), QSsl::Rsa)); + } + sslConf.setPeerVerifyMode(QSslSocket::VerifyNone); + init(hostName, port, sslConf, ignoreSelfSigned); +#else + Q_UNUSED(ignoreSelfSigned) + qCritical() << "SSL not supported in this QT build"; +#endif // QT_NO_SSL + } + else + { + init(new Network(q)); + } +} + +#ifdef QT_WEBSOCKETS_LIB +#ifndef QT_NO_SSL +void QMQTT::ClientPrivate::init(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + bool ignoreSelfSigned) +{ + Q_Q(Client); + _hostName = url; + _ignoreSelfSigned = ignoreSelfSigned; + init(new Network(origin, version, sslConfig, q)); +} +#endif // QT_NO_SSL + +void QMQTT::ClientPrivate::init(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version) +{ + Q_Q(Client); + _hostName = url; + init(new Network(origin, version, q)); +} +#endif // QT_WEBSOCKETS_LIB + +void QMQTT::ClientPrivate::init(NetworkInterface* network) +{ + Q_Q(Client); + + _network.reset(network); + _timer.setSingleShot(true); + _pingResponseTimer.setSingleShot(true); + + QObject::connect(&_timer, &QTimer::timeout, q, &Client::onTimerPingReq); + QObject::connect(&_pingResponseTimer, &QTimer::timeout, q, &Client::onPingTimeout); + QObject::connect(_network.data(), &Network::connected, + q, &Client::onNetworkConnected); + QObject::connect(_network.data(), &Network::disconnected, + q, &Client::onNetworkDisconnected); + QObject::connect(_network.data(), &Network::received, + q, &Client::onNetworkReceived); + QObject::connect(_network.data(), &Network::error, + q, &Client::onNetworkError); +} + +void QMQTT::ClientPrivate::connectToHost() +{ + _connectionState = ConnectionState::STATE_CONNECTING; + if (_hostName.isEmpty()) + { + _network->connectToHost(_host, _port); + } + else + { + _network->connectToHost(_hostName, _port); + } +} + +void QMQTT::ClientPrivate::onNetworkConnected() +{ + sendConnect(); +} + +void QMQTT::ClientPrivate::sendConnect() +{ + quint8 header = CONNECT; + quint8 flags = 0; + + //header + Frame frame(header); + + //flags + flags = FLAG_CLEANSESS(flags, _cleanSession ? 1 : 0 ); + flags = FLAG_WILL(flags, willTopic().isEmpty() ? 0 : 1); + if (!willTopic().isEmpty()) + { + flags = FLAG_WILLQOS(flags, willQos()); + flags = FLAG_WILLRETAIN(flags, willRetain() ? 1 : 0); + } + if (!username().isEmpty()) + { + flags = FLAG_USERNAME(flags, 1); + flags = FLAG_PASSWD(flags, !password().isEmpty() ? 1 : 0); + } + + //payload + if(_version == V3_1_1) + { + frame.writeString(QStringLiteral(PROTOCOL_MAGIC_3_1_1)); + } + else + { + frame.writeString(QStringLiteral(PROTOCOL_MAGIC_3_1_0)); + } + frame.writeChar(_version); + frame.writeChar(flags); + frame.writeInt(keepAlive()); + frame.writeString(_clientId); + if(!willTopic().isEmpty()) + { + frame.writeString(willTopic()); + // According to the specs (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718031) + // the will message gets always sent together with the topic, also when it is empty which is perfectly valid. + frame.writeByteArray(_willMessage); + } + if (!_username.isEmpty()) + { + frame.writeString(_username); + if (!_password.isEmpty()) + { + frame.writeByteArray(_password); + } + } + sendFrame(frame); +} + +quint16 QMQTT::ClientPrivate::sendPublish(const Message &message) +{ + quint16 msgid = message.id(); + + quint8 header = PUBLISH; + header = SETRETAIN(header, message.retain() ? 1 : 0); + header = SETQOS(header, message.qos()); + header = SETDUP(header, message.dup() ? 1 : 0); + Frame frame(header); + frame.writeString(message.topic()); + if(message.qos() > QOS0) { + if (msgid == 0) + msgid = nextmid(); + frame.writeInt(msgid); + } + if(!message.payload().isEmpty()) { + frame.writeRawData(message.payload()); + } + sendFrame(frame); + return msgid; +} + +void QMQTT::ClientPrivate::sendPuback(const quint8 type, const quint16 mid) +{ + Frame frame(type); + frame.writeInt(mid); + sendFrame(frame); +} + +quint16 QMQTT::ClientPrivate::sendSubscribe(const QString & topic, const quint8 qos) +{ + quint16 mid = nextmid(); + Frame frame(SETQOS(SUBSCRIBE, QOS1)); + frame.writeInt(mid); + frame.writeString(topic); + frame.writeChar(qos); + sendFrame(frame); + return mid; +} + +quint16 QMQTT::ClientPrivate::sendUnsubscribe(const QString &topic) +{ + quint16 mid = nextmid(); + Frame frame(SETQOS(UNSUBSCRIBE, QOS1)); + frame.writeInt(mid); + frame.writeString(topic); + sendFrame(frame); + return mid; +} + +void QMQTT::ClientPrivate::onTimerPingReq() +{ + if (!isConnectedToHost()) + return; + Frame frame(PINGREQ); + sendFrame(frame); + _pingResponseTimer.start(); +} + +void QMQTT::ClientPrivate::onPingTimeout() +{ + Q_Q(Client); + emit q->error(MqttNoPingResponse); + disconnectFromHost(); +} + +void QMQTT::ClientPrivate::disconnectFromHost() +{ + _connectionState = ConnectionState::STATE_DISCONNECTED; + sendDisconnect(); + _network->disconnectFromHost(); +} + +void QMQTT::ClientPrivate::sendDisconnect() +{ + Frame frame(DISCONNECT); + sendFrame(frame); +} + +void QMQTT::ClientPrivate::sendFrame(const Frame &frame) +{ + _network->sendFrame(frame); + _timer.start(); +} + +void QMQTT::ClientPrivate::stopKeepAlive() +{ + _timer.stop(); + _pingResponseTimer.stop(); +} + +quint16 QMQTT::ClientPrivate::nextmid() +{ + return _gmid++; +} + +quint16 QMQTT::ClientPrivate::publish(const Message& message) +{ + Q_Q(Client); + quint16 msgid = sendPublish(message); + + // Emit published only at QOS0 + if (message.qos() == QOS0) + emit q->published(message, msgid); + else + _midToMessage[msgid] = message; + + return msgid; +} + +void QMQTT::ClientPrivate::puback(const quint8 type, const quint16 msgid) +{ + sendPuback(type, msgid); +} + +void QMQTT::ClientPrivate::subscribe(const QString& topic, const quint8 qos) +{ + quint16 msgid = sendSubscribe(topic, qos); + _midToTopic[msgid] = topic; +} + +void QMQTT::ClientPrivate::unsubscribe(const QString& topic) +{ + quint16 msgid = sendUnsubscribe(topic); + _midToTopic[msgid] = topic; +} + +void QMQTT::ClientPrivate::onNetworkDisconnected() +{ + Q_Q(Client); + + stopKeepAlive(); + _midToTopic.clear(); + _midToMessage.clear(); + emit q->disconnected(); +} + +void QMQTT::ClientPrivate::onNetworkReceived(const QMQTT::Frame& frm) +{ + QMQTT::Frame frame(frm); + quint8 qos = 0; + bool retain, dup; + QString topic; + quint16 mid = 0; + quint8 header = frame.header(); + quint8 type = GETTYPE(header); + + switch(type) + { + case CONNACK: + frame.readChar(); + handleConnack(frame.readChar()); + break; + case PUBLISH: + qos = GETQOS(header); + retain = GETRETAIN(header); + dup = GETDUP(header); + topic = frame.readString(); + if( qos > QOS0) { + mid = frame.readInt(); + } + handlePublish(Message(mid, topic, frame.data(), qos, retain, dup)); + break; + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + mid = frame.readInt(); + handlePuback(type, mid); + break; + case SUBACK: + mid = frame.readInt(); + topic = _midToTopic.take(mid); + qos = frame.readChar(); + handleSuback(topic, qos); + break; + case UNSUBACK: + mid = frame.readInt(); + topic = _midToTopic.take(mid); + handleUnsuback(topic); + break; + case PINGRESP: + handlePingresp(); + break; + default: + break; + } +} + +void QMQTT::ClientPrivate::handleConnack(const quint8 ack) +{ + Q_Q(Client); + + switch (ack) + { + case 0: + _connectionState = ConnectionState::STATE_CONNECTED; + emit q->connected(); + break; + case 1: + emit q->error(MqttUnacceptableProtocolVersionError); + break; + case 2: + emit q->error(MqttIdentifierRejectedError); + break; + case 3: + emit q->error(MqttServerUnavailableError); + break; + case 4: + emit q->error(MqttBadUserNameOrPasswordError); + break; + case 5: + emit q->error(MqttNotAuthorizedError); + break; + default: + emit q->error(UnknownError); + break; + } +} + +void QMQTT::ClientPrivate::handlePublish(const Message& message) +{ + Q_Q(Client); + + if(message.qos() == QOS1) + { + sendPuback(PUBACK, message.id()); + } + else if(message.qos() == QOS2) + { + sendPuback(PUBREC, message.id()); + } + emit q->received(message); +} + +void QMQTT::ClientPrivate::handlePuback(const quint8 type, const quint16 msgid) +{ + Q_Q(Client); + + switch (type) + { + case PUBREC: + sendPuback(SETQOS(PUBREL, QOS1), msgid); + break; + case PUBREL: + sendPuback(PUBCOMP, msgid); + break; + case PUBACK: + case PUBCOMP: + // Emit published on PUBACK at QOS1 and on PUBCOMP at QOS2 + emit q->published(_midToMessage.take(msgid), msgid); + break; + } +} + +void QMQTT::ClientPrivate::handlePingresp() +{ + // Stop the ping response timer to prevent disconnection. It will be restarted when the next + // ping request has been sent. + _pingResponseTimer.stop(); + Q_Q(Client); + emit q->pingresp(); +} + +void QMQTT::ClientPrivate::handleSuback(const QString &topic, const quint8 qos) +{ + Q_Q(Client); + emit q->subscribed(topic, qos); +} + +void QMQTT::ClientPrivate::handleUnsuback(const QString &topic) { + Q_Q(Client); + emit q->unsubscribed(topic); +} + +bool QMQTT::ClientPrivate::autoReconnect() const +{ + return _network->autoReconnect(); +} + +void QMQTT::ClientPrivate::setAutoReconnect(const bool autoReconnect) +{ + _network->setAutoReconnect(autoReconnect); +} + +int QMQTT::ClientPrivate::autoReconnectInterval() const +{ + return _network->autoReconnectInterval(); +} + +void QMQTT::ClientPrivate::setAutoReconnectInterval(const int autoReconnectInterval) +{ + _network->setAutoReconnectInterval(autoReconnectInterval); +} + +bool QMQTT::ClientPrivate::isConnectedToHost() const +{ + return _network->isConnectedToHost(); +} + +QMQTT::ConnectionState QMQTT::ClientPrivate::connectionState() const +{ + return _connectionState; +} + +void QMQTT::ClientPrivate::setCleanSession(const bool cleanSession) +{ + _cleanSession = cleanSession; +} + +bool QMQTT::ClientPrivate::cleanSession() const +{ + return _cleanSession; +} + +void QMQTT::ClientPrivate::setKeepAlive(const quint16 keepAlive) +{ + // _timer will be started when a message is sent. + _timer.setInterval(keepAlive*1000); + // The MQTT specification does not mention a timeout value in this case, so we use 10% of the + // keep alive interval. + _pingResponseTimer.setInterval(qBound(keepAlive * 100, 10000, keepAlive * 1000)); +} + +quint16 QMQTT::ClientPrivate::keepAlive() const +{ + return _timer.interval() / 1000; +} + +void QMQTT::ClientPrivate::setPassword(const QByteArray& password) +{ + _password = password; +} + +QByteArray QMQTT::ClientPrivate::password() const +{ + return _password; +} + +void QMQTT::ClientPrivate::setUsername(const QString& username) +{ + _username = username; +} + +QString QMQTT::ClientPrivate::username() const +{ + return _username; +} + +void QMQTT::ClientPrivate::setVersion(const MQTTVersion version) +{ + _version = version; +} + +QMQTT::MQTTVersion QMQTT::ClientPrivate::version() const +{ + return _version; +} + +void QMQTT::ClientPrivate::setClientId(const QString& clientId) +{ + if(clientId.isEmpty()) + { + _clientId = QUuid::createUuid().toString(); + } + else + { + _clientId = clientId; + } +} + +QString QMQTT::ClientPrivate::clientId() const +{ + return _clientId; +} + +void QMQTT::ClientPrivate::setPort(const quint16 port) +{ + _port = port; +} + +quint16 QMQTT::ClientPrivate::port() const +{ + return _port; +} + +void QMQTT::ClientPrivate::setHost(const QHostAddress& host) +{ + _host = host; +} + +QHostAddress QMQTT::ClientPrivate::host() const +{ + return _host; +} + +void QMQTT::ClientPrivate::setHostName(const QString& hostName) +{ + _hostName = hostName; +} + +QString QMQTT::ClientPrivate::hostName() const +{ + return _hostName; +} + +QString QMQTT::ClientPrivate::willTopic() const +{ + return _willTopic; +} + +void QMQTT::ClientPrivate::setWillTopic(const QString& willTopic) +{ + _willTopic = willTopic; +} + +quint8 QMQTT::ClientPrivate::willQos() const +{ + return _willQos; +} + +void QMQTT::ClientPrivate::setWillQos(const quint8 willQos) +{ + _willQos = willQos; +} + +bool QMQTT::ClientPrivate::willRetain() const +{ + return _willRetain; +} + +void QMQTT::ClientPrivate::setWillRetain(const bool willRetain) +{ + _willRetain = willRetain; +} + +QByteArray QMQTT::ClientPrivate::willMessage() const +{ + return _willMessage; +} + +void QMQTT::ClientPrivate::setWillMessage(const QByteArray& willMessage) +{ + _willMessage = willMessage; +} + +void QMQTT::ClientPrivate::onNetworkError(QAbstractSocket::SocketError socketError) +{ + Q_Q(Client); + + switch (socketError) + { + case QAbstractSocket::ConnectionRefusedError: + emit q->error(SocketConnectionRefusedError); + break; + case QAbstractSocket::RemoteHostClosedError: + emit q->error(SocketRemoteHostClosedError); + break; + case QAbstractSocket::HostNotFoundError: + emit q->error(SocketHostNotFoundError); + break; + case QAbstractSocket::SocketAccessError: + emit q->error(SocketAccessError); + break; + case QAbstractSocket::SocketResourceError: + emit q->error(SocketResourceError); + break; + case QAbstractSocket::SocketTimeoutError: + emit q->error(SocketTimeoutError); + break; + case QAbstractSocket::DatagramTooLargeError: + emit q->error(SocketDatagramTooLargeError); + break; + case QAbstractSocket::NetworkError: + emit q->error(SocketNetworkError); + break; + case QAbstractSocket::AddressInUseError: + emit q->error(SocketAddressInUseError); + break; + case QAbstractSocket::SocketAddressNotAvailableError: + emit q->error(SocketAddressNotAvailableError); + break; + case QAbstractSocket::UnsupportedSocketOperationError: + emit q->error(SocketUnsupportedSocketOperationError); + break; + case QAbstractSocket::UnfinishedSocketOperationError: + emit q->error(SocketUnfinishedSocketOperationError); + break; + case QAbstractSocket::ProxyAuthenticationRequiredError: + emit q->error(SocketProxyAuthenticationRequiredError); + break; + case QAbstractSocket::SslHandshakeFailedError: + emit q->error(SocketSslHandshakeFailedError); + break; + case QAbstractSocket::ProxyConnectionRefusedError: + emit q->error(SocketProxyConnectionRefusedError); + break; + case QAbstractSocket::ProxyConnectionClosedError: + emit q->error(SocketProxyConnectionClosedError); + break; + case QAbstractSocket::ProxyConnectionTimeoutError: + emit q->error(SocketProxyConnectionTimeoutError); + break; + case QAbstractSocket::ProxyNotFoundError: + emit q->error(SocketProxyNotFoundError); + break; + case QAbstractSocket::ProxyProtocolError: + emit q->error(SocketProxyProtocolError); + break; + case QAbstractSocket::OperationError: + emit q->error(SocketOperationError); + break; + case QAbstractSocket::SslInternalError: + emit q->error(SocketSslInternalError); + break; + case QAbstractSocket::SslInvalidUserDataError: + emit q->error(SocketSslInvalidUserDataError); + break; + case QAbstractSocket::TemporaryError: + emit q->error(SocketTemporaryError); + break; + default: + emit q->error(UnknownError); + break; + } +} + +#ifndef QT_NO_SSL +void QMQTT::ClientPrivate::ignoreSslErrors() +{ + _network->ignoreSslErrors(); +} + +void QMQTT::ClientPrivate::ignoreSslErrors(const QList& errors) +{ + _network->ignoreSslErrors(errors); +} + +QSslConfiguration QMQTT::ClientPrivate::sslConfiguration() const +{ + return _network->sslConfiguration(); +} + +void QMQTT::ClientPrivate::setSslConfiguration(const QSslConfiguration& config) +{ + _network->setSslConfiguration(config); +} + +void QMQTT::ClientPrivate::onSslErrors(const QList& errors) +{ + Q_Q(Client); + + emit q->sslErrors(errors); + + if (!_ignoreSelfSigned) + return; + foreach (QSslError error, errors) + { + if (error.error() != QSslError::SelfSignedCertificate && + error.error() != QSslError::SelfSignedCertificateInChain) + { + return; + } + } + ignoreSslErrors(); +} +#endif // QT_NO_SSL diff --git a/mqtt/qmqtt_client_p.h b/mqtt/qmqtt_client_p.h new file mode 100644 index 0000000..03ec994 --- /dev/null +++ b/mqtt/qmqtt_client_p.h @@ -0,0 +1,183 @@ +/* + * qmqtt_client_p.h - qmqtt client private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_CLIENT_P_H +#define QMQTT_CLIENT_P_H + +#include "qmqtt_client.h" + +#include +#include +#include +#include +#include +#include + +#ifdef QT_WEBSOCKETS_LIB +#include +#endif // QT_WEBSOCKETS_LIB + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +namespace QMQTT { + +class NetworkInterface; + +class ClientPrivate +{ +public: + ClientPrivate(Client* qq_ptr); + ~ClientPrivate(); + + void init(const QHostAddress& host, const quint16 port, NetworkInterface* network = NULL); +#ifndef QT_NO_SSL + void init(const QString& hostName, const quint16 port, const QSslConfiguration& config, + const bool ignoreSelfSigned=false); +#endif // QT_NO_SSL + void init(const QString& hostName, const quint16 port, const bool ssl, const bool ignoreSelfSigned); +#ifdef QT_WEBSOCKETS_LIB +#ifndef QT_NO_SSL + void init(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + bool ignoreSelfSigned); +#endif // QT_NO_SSL + void init(const QString& url, + const QString& origin, + QWebSocketProtocol::Version version); +#endif // QT_WEBSOCKETS_LIB + void init(NetworkInterface* network); + + QHostAddress _host; + QString _hostName; + quint16 _port; +#ifdef QT_WEBSOCKETS_LIB + QWebSocketProtocol::Version _webSocketVersion; +#endif // QT_WEBSOCKETS_LIB +#ifndef QT_NO_SSL + bool _ignoreSelfSigned; +#endif // QT_NO_SSL + quint16 _gmid; + MQTTVersion _version; + QString _clientId; + QString _username; + QByteArray _password; + bool _cleanSession; + ConnectionState _connectionState; + QScopedPointer _network; + QTimer _timer; + QTimer _pingResponseTimer; + QString _willTopic; + quint8 _willQos; + bool _willRetain; + QByteArray _willMessage; + QHash _midToTopic; + QHash _midToMessage; + + Client* const q_ptr; + + quint16 nextmid(); + void connectToHost(); + void sendConnect(); + void onTimerPingReq(); + void onPingTimeout(); + quint16 sendUnsubscribe(const QString &topic); + quint16 sendSubscribe(const QString &topic, const quint8 qos); + quint16 sendPublish(const Message &message); + void sendPuback(const quint8 type, const quint16 mid); + void sendDisconnect(); + void sendFrame(const Frame &frame); + void disconnectFromHost(); + void stopKeepAlive(); + void onNetworkConnected(); + void onNetworkDisconnected(); + quint16 publish(const Message& message); + void puback(const quint8 type, const quint16 msgid); + void subscribe(const QString& topic, const quint8 qos); + void unsubscribe(const QString& topic); + void onNetworkReceived(const QMQTT::Frame& frame); + void handleConnack(const quint8 ack); + void handlePublish(const Message& message); + void handlePuback(const quint8 type, const quint16 msgid); + void handleSuback(const QString& topic, const quint8 qos); + void handleUnsuback(const QString& topic); + void handlePingresp(); + bool autoReconnect() const; + void setAutoReconnect(const bool autoReconnect); + int autoReconnectInterval() const; + void setAutoReconnectInterval(const int autoReconnectInterval); + bool isConnectedToHost() const; + QMQTT::ConnectionState connectionState() const; + void setCleanSession(const bool cleanSession); + bool cleanSession() const; + void setKeepAlive(const quint16 keepAlive); + quint16 keepAlive() const; + void setPassword(const QByteArray& password); + QByteArray password() const; + void setUsername(const QString& username); + QString username() const; + void setVersion(const MQTTVersion); + MQTTVersion version() const; + void setClientId(const QString& clientId); + QString clientId() const; + void setPort(const quint16 port); + quint16 port() const; + void setHost(const QHostAddress& host); + QHostAddress host() const; + void setHostName(const QString& hostName); + QString hostName() const; + void setWillTopic(const QString& willTopic); + void setWillQos(const quint8 willQos); + void setWillRetain(const bool willRetain); + void setWillMessage(const QByteArray& willMessage); + QString willTopic() const; + quint8 willQos() const; + bool willRetain() const; + QByteArray willMessage() const; + void onNetworkError(QAbstractSocket::SocketError error); +#ifndef QT_NO_SSL + void ignoreSslErrors(); + void ignoreSslErrors(const QList& errors); + QSslConfiguration sslConfiguration() const; + void setSslConfiguration(const QSslConfiguration& config); + void onSslErrors(const QList& errors); +#endif // QT_NO_SSL + + Q_DECLARE_PUBLIC(Client) +}; + +} // namespace QMQTT + +#endif // QMQTT_CLIENT_P_H diff --git a/mqtt/qmqtt_frame.cpp b/mqtt/qmqtt_frame.cpp new file mode 100644 index 0000000..7f7e152 --- /dev/null +++ b/mqtt/qmqtt_frame.cpp @@ -0,0 +1,209 @@ +/* + * qmqtt_frame.cpp - qmqtt frame + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_frame.h" + +#include +#include + +namespace QMQTT { + +Q_LOGGING_CATEGORY(frame, "qmqtt.frame") + +Frame::Frame() + : _header(0) + , _data(QByteArray()) +{ +} + +Frame::Frame(const quint8 header) + : _header(header) + , _data(QByteArray()) +{ +} + +Frame::Frame(const quint8 header, const QByteArray &data) + : _header(header) + , _data(data) +{ +} + +Frame::Frame(const Frame& other) +{ + _header = other._header; + _data = other._data; +} + +Frame& Frame::operator=(const Frame& other) +{ + _header = other._header; + _data = other._data; + return *this; +} + +bool Frame::operator==(const Frame& other) const +{ + return _header == other._header + && _data == other._data; +} + + +Frame::~Frame() +{ +} + +quint8 Frame::header() const +{ + return _header; +} + +QByteArray Frame::data() const +{ + return _data; +} + +quint8 Frame::readChar() +{ + char c = _data.at(0); + _data.remove(0, 1); + return c; +} + +quint16 Frame::readInt() +{ + quint8 msb = static_cast(_data.at(0)); + quint8 lsb = static_cast(_data.at(1)); + _data.remove(0, 2); + return (msb << 8) | lsb; +} + +QByteArray Frame::readByteArray() +{ + quint16 len = readInt(); + QByteArray data = _data.left(len); + _data.remove(0, len); + return data; +} + +QString Frame::readString() +{ + quint16 len = readInt(); + QString s = QString::fromUtf8(_data.left(len)); + _data.remove(0, len); + return s; +} + +void Frame::writeInt(const quint16 i) +{ + _data.append(MSB(i)); + _data.append(LSB(i)); +} + +void Frame::writeByteArray(const QByteArray &data) +{ + if (data.size() > (int)USHRT_MAX) + { + qCritical("qmqtt: Binary data size bigger than %u bytes, truncate it!", USHRT_MAX); + writeInt(USHRT_MAX); + _data.append(data.left(USHRT_MAX)); + return; + } + + writeInt(data.size()); + _data.append(data); +} + +void Frame::writeString(const QString &string) +{ + QByteArray data = string.toUtf8(); + if (data.size() > (int)USHRT_MAX) + { + qCritical("qmqtt: String size bigger than %u bytes, truncate it!", USHRT_MAX); + data.resize(USHRT_MAX); + } + writeInt(data.size()); + _data.append(data); +} + +void Frame::writeChar(const quint8 c) +{ + _data.append(c); +} + +void Frame::writeRawData(const QByteArray &data) +{ + _data.append(data); +} + +void Frame::write(QDataStream &stream) const +{ + QByteArray lenbuf; + + if (!encodeLength(lenbuf, _data.size())) + { + qCritical("qmqtt: Control packet bigger than 256 MB, dropped!"); + return; + } + + stream << (quint8)_header; + if(_data.size() == 0) { + stream << (quint8)0; + return; + } + if (stream.writeRawData(lenbuf.data(), lenbuf.size()) != lenbuf.size()) + { + qCritical("qmqtt: Control packet write error!"); + return; + } + if (stream.writeRawData(_data.data(), _data.size()) != _data.size()) + { + qCritical("qmqtt: Control packet write error!"); + } +} + +bool Frame::encodeLength(QByteArray &lenbuf, int length) const +{ + lenbuf.clear(); + quint8 d; + do { + d = length % 128; + length /= 128; + if (length > 0) { + d |= 0x80; + } + lenbuf.append(d); + } while (length > 0); + + return lenbuf.size() <= 4; +} + +} // namespace QMQTT diff --git a/mqtt/qmqtt_frame.h b/mqtt/qmqtt_frame.h new file mode 100644 index 0000000..0005b82 --- /dev/null +++ b/mqtt/qmqtt_frame.h @@ -0,0 +1,137 @@ +/* + * qmqtt_frame.h - qmqtt frame heaer + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_FRAME_H +#define QMQTT_FRAME_H + +#include "qmqtt_global.h" + +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QDataStream) + +#define PROTOCOL_MAGIC_3_1_0 "MQIsdp" +#define PROTOCOL_MAGIC_3_1_1 "MQTT" + +#define RANDOM_CLIENT_PREFIX "QMQTT-" + +#define CONNECT 0x10 +#define CONNACK 0x20 +#define PUBLISH 0x30 +#define PUBACK 0x40 +#define PUBREC 0x50 +#define PUBREL 0x60 +#define PUBCOMP 0x70 +#define SUBSCRIBE 0x80 +#define SUBACK 0x90 +#define UNSUBSCRIBE 0xA0 +#define UNSUBACK 0xB0 +#define PINGREQ 0xC0 +#define PINGRESP 0xD0 +#define DISCONNECT 0xE0 + +#define LSB(A) quint8(A & 0x00FF) +#define MSB(A) quint8((A & 0xFF00) >> 8) + +/* +|-------------------------------------- +| 7 6 5 4 | 3 | 2 1 | 0 | +| Type | DUP flag | QoS | RETAIN | +|-------------------------------------- +*/ +#define GETTYPE(HDR) (HDR & 0xF0) +#define SETQOS(HDR, Q) (HDR | ((Q) << 1)) +#define GETQOS(HDR) ((HDR & 0x06) >> 1) +#define SETDUP(HDR, D) (HDR | ((D) << 3)) +#define GETDUP(HDR) ((HDR & 0x08) >> 3) +#define SETRETAIN(HDR, R) (HDR | (R)) +#define GETRETAIN(HDR) (HDR & 0x01) + +/* +|---------------------------------------------------------------------------------- +| 7 | 6 | 5 | 4 3 | 2 | 1 | 0 | +| username | password | willretain | willqos | willflag | cleansession | reserved | +|---------------------------------------------------------------------------------- +*/ +#define FLAG_CLEANSESS(F, C) (F | ((C) << 1)) +#define FLAG_WILL(F, W) (F | ((W) << 2)) +#define FLAG_WILLQOS(F, Q) (F | ((Q) << 3)) +#define FLAG_WILLRETAIN(F, R) (F | ((R) << 5)) +#define FLAG_PASSWD(F, P) (F | ((P) << 6)) +#define FLAG_USERNAME(F, U) (F | ((U) << 7)) + +namespace QMQTT { + +class Q_MQTT_EXPORT Frame +{ +public: + explicit Frame(); + explicit Frame(const quint8 header); + explicit Frame(const quint8 header, const QByteArray &data); + virtual ~Frame(); + + Frame(const Frame& other); + Frame& operator=(const Frame& other); + + bool operator==(const Frame& other) const; + inline bool operator!=(const Frame& other) const + { return !operator==(other); } + + quint8 header() const; + QByteArray data() const; + + quint16 readInt(); + quint8 readChar(); + QByteArray readByteArray(); + QString readString(); + + void writeInt(const quint16 i); + void writeChar(const quint8 c); + void writeByteArray(const QByteArray &data); + void writeString(const QString &string); + void writeRawData(const QByteArray &data); + + //TODO: FIXME LATER + void write(QDataStream &stream) const; + bool encodeLength(QByteArray &lenbuf, int length) const; + +private: + quint8 _header; + QByteArray _data; +}; + +} // namespace QMQTT + +Q_DECLARE_METATYPE(QMQTT::Frame) + +#endif // QMQTT_FRAME_H diff --git a/mqtt/qmqtt_global.h b/mqtt/qmqtt_global.h new file mode 100644 index 0000000..07e8447 --- /dev/null +++ b/mqtt/qmqtt_global.h @@ -0,0 +1,48 @@ +/* + * qmqtt_global.h - qmqtt libray global + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_GLOBAL_H +#define QMQTT_GLOBAL_H + +#include + +//#ifndef QT_STATIC +//# if defined(QT_BUILD_QMQTT_LIB) +//# define Q_MQTT_EXPORT Q_DECL_EXPORT +//# else +//# define Q_MQTT_EXPORT Q_DECL_IMPORT +//# endif +//#else +#define Q_MQTT_EXPORT +//#endif + +#endif // QMQTT_GLOBAL_H + diff --git a/mqtt/qmqtt_message.cpp b/mqtt/qmqtt_message.cpp new file mode 100644 index 0000000..7beec31 --- /dev/null +++ b/mqtt/qmqtt_message.cpp @@ -0,0 +1,136 @@ +/* + * qmqtt_message.cpp - qmqtt message + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_message.h" +#include "qmqtt_message_p.h" + +namespace QMQTT { + +Message::Message() + : d(new MessagePrivate) +{ +} + +Message::Message(const quint16 id, const QString &topic, const QByteArray &payload, + const quint8 qos, const bool retain, const bool dup) + : d(new MessagePrivate(id, topic, payload, qos, retain, dup)) +{ +} + +Message::Message(const Message &other) + : d(other.d) +{ +} + +Message::~Message() +{ +} + +Message &Message::operator=(const Message &other) +{ + d = other.d; + return *this; +} + +bool Message::operator==(const Message &other) const +{ + if (d == other.d) + return true; + return d->id == other.d->id + && d->qos == other.d->qos + && d->retain == other.d->retain + && d->dup == other.d->dup + && d->topic == other.d->topic + && d->payload == other.d->payload; +} + +quint16 Message::id() const +{ + return d->id; +} + +void Message::setId(const quint16 id) +{ + d->id = id; +} + +quint8 Message::qos() const +{ + return d->qos; +} + +void Message::setQos(const quint8 qos) +{ + d->qos = qos; +} + +bool Message::retain() const +{ + return d->retain; +} + +void Message::setRetain(const bool retain) +{ + d->retain = retain; +} + +bool Message::dup() const +{ + return d->dup; +} + +void Message::setDup(const bool dup) +{ + d->dup = dup; +} + +QString Message::topic() const +{ + return d->topic; +} + +void Message::setTopic(const QString &topic) +{ + d->topic = topic; +} + +QByteArray Message::payload() const +{ + return d->payload; +} + +void Message::setPayload(const QByteArray &payload) +{ + d->payload = payload; +} + +} // namespace QMQTT diff --git a/mqtt/qmqtt_message.h b/mqtt/qmqtt_message.h new file mode 100644 index 0000000..3dbaa02 --- /dev/null +++ b/mqtt/qmqtt_message.h @@ -0,0 +1,96 @@ +/* + * qmqtt_message.h - qmqtt message header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_MESSAGE_H +#define QMQTT_MESSAGE_H + +#include "qmqtt_global.h" + +#include +#include +#include +#include + +namespace QMQTT { + +class MessagePrivate; + +class Q_MQTT_EXPORT Message +{ +public: + Message(); + explicit Message(const quint16 id, const QString &topic, const QByteArray &payload, + const quint8 qos = 0, const bool retain = false, const bool dup = false); + Message(const Message &other); + ~Message(); + + Message &operator=(const Message &other); +#ifdef Q_COMPILER_RVALUE_REFS + inline Message &operator=(Message &&other) Q_DECL_NOTHROW + { swap(other); return *this; } +#endif + + bool operator==(const Message &other) const; + inline bool operator!=(const Message &other) const + { return !operator==(other); } + + inline void swap(Message &other) Q_DECL_NOTHROW + { qSwap(d, other.d); } + + quint16 id() const; + void setId(const quint16 id); + + quint8 qos() const; + void setQos(const quint8 qos); + + bool retain() const; + void setRetain(const bool retain); + + bool dup() const; + void setDup(const bool dup); + + QString topic() const; + void setTopic(const QString &topic); + + QByteArray payload() const; + void setPayload(const QByteArray &payload); + +private: + QSharedDataPointer d; +}; + +} // namespace QMQTT + +Q_DECLARE_SHARED(QMQTT::Message) + +Q_DECLARE_METATYPE(QMQTT::Message) + +#endif // QMQTT_MESSAGE_H diff --git a/mqtt/qmqtt_message_p.h b/mqtt/qmqtt_message_p.h new file mode 100644 index 0000000..148019c --- /dev/null +++ b/mqtt/qmqtt_message_p.h @@ -0,0 +1,83 @@ +/* + * qmqtt_message.h - qmqtt message private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_MESSAGE_P_H +#define QMQTT_MESSAGE_P_H + +#include +#include +#include + +namespace QMQTT { + +class MessagePrivate : public QSharedData +{ +public: + inline MessagePrivate() + : QSharedData(), + id(0), + qos(0), + retain(false), + dup(false) + {} + + inline MessagePrivate(const MessagePrivate &other) + : QSharedData(other), + id(other.id), + qos(other.qos), + retain(other.retain), + dup(other.dup), + topic(other.topic), + payload(other.payload) + {} + + inline MessagePrivate(quint16 id, const QString &topic, const QByteArray &payload, + quint8 qos, bool retain, bool dup) + : QSharedData(), + id(id), + qos(qos), + retain(retain), + dup(dup), + topic(topic), + payload(payload) + {} + + quint16 id; + quint8 qos : 2; + quint8 retain: 1; + quint8 dup: 1; + QString topic; + QByteArray payload; +}; + +} // namespace QMQTT + +#endif // QMQTT_MESSAGE_P_H diff --git a/mqtt/qmqtt_network.cpp b/mqtt/qmqtt_network.cpp new file mode 100644 index 0000000..b4f55ab --- /dev/null +++ b/mqtt/qmqtt_network.cpp @@ -0,0 +1,295 @@ +/* + * qmqtt_network.cpp - qmqtt network + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_network_p.h" +#include "qmqtt_socket_p.h" +#include "qmqtt_ssl_socket_p.h" +#include "qmqtt_timer_p.h" +#include "qmqtt_websocket_p.h" +#include "qmqtt_frame.h" + +#include + +const quint16 DEFAULT_PORT = 1883; +const quint16 DEFAULT_SSL_PORT = 8883; +const bool DEFAULT_AUTORECONNECT = false; +const int DEFAULT_AUTORECONNECT_INTERVAL_MS = 5000; + +QMQTT::Network::Network(QObject* parent) + : NetworkInterface(parent) + , _port(DEFAULT_PORT) + , _autoReconnect(DEFAULT_AUTORECONNECT) + , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS) + , _socket(new QMQTT::Socket) + , _autoReconnectTimer(new QMQTT::Timer) + , _readState(Header) +{ + initialize(); +} + +#ifndef QT_NO_SSL +QMQTT::Network::Network(const QSslConfiguration& config, QObject *parent) + : NetworkInterface(parent) + , _port(DEFAULT_SSL_PORT) + , _autoReconnect(DEFAULT_AUTORECONNECT) + , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS) + , _socket(new QMQTT::SslSocket(config)) + , _autoReconnectTimer(new QMQTT::Timer) + , _readState(Header) +{ + initialize(); + connect(_socket, &QMQTT::SslSocket::sslErrors, this, &QMQTT::Network::sslErrors); +} +#endif // QT_NO_SSL + +#ifdef QT_WEBSOCKETS_LIB +#ifndef QT_NO_SSL +QMQTT::Network::Network(const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + QObject* parent) + : NetworkInterface(parent) + , _port(DEFAULT_SSL_PORT) + , _autoReconnect(DEFAULT_AUTORECONNECT) + , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS) + , _socket(new QMQTT::WebSocket(origin, version, sslConfig)) + , _autoReconnectTimer(new QMQTT::Timer) + , _readState(Header) +{ + initialize(); +} +#endif // QT_NO_SSL + +QMQTT::Network::Network(const QString& origin, + QWebSocketProtocol::Version version, + QObject* parent) + : NetworkInterface(parent) + , _port(DEFAULT_PORT) + , _autoReconnect(DEFAULT_AUTORECONNECT) + , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS) + , _socket(new QMQTT::WebSocket(origin, version)) + , _autoReconnectTimer(new QMQTT::Timer) + , _readState(Header) +{ + initialize(); +} +#endif // QT_WEBSOCKETS_LIB + +QMQTT::Network::Network(SocketInterface* socketInterface, TimerInterface* timerInterface, + QObject* parent) + : NetworkInterface(parent) + , _port(DEFAULT_PORT) + , _autoReconnect(DEFAULT_AUTORECONNECT) + , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS) + , _socket(socketInterface) + , _autoReconnectTimer(timerInterface) + , _readState(Header) +{ + initialize(); +} + +void QMQTT::Network::initialize() +{ + _socket->setParent(this); + _autoReconnectTimer->setParent(this); + _autoReconnectTimer->setSingleShot(true); + _autoReconnectTimer->setInterval(_autoReconnectInterval); + + QObject::connect(_socket, &SocketInterface::connected, this, &Network::connected); + QObject::connect(_socket, &SocketInterface::disconnected, this, &Network::onDisconnected); + QObject::connect(_socket->ioDevice(), &QIODevice::readyRead, this, &Network::onSocketReadReady); + QObject::connect( + _autoReconnectTimer, &TimerInterface::timeout, + this, static_cast(&Network::connectToHost)); + QObject::connect(_socket, + static_cast(&SocketInterface::error), + this, &Network::onSocketError); +} + +QMQTT::Network::~Network() +{ +} + +bool QMQTT::Network::isConnectedToHost() const +{ + return _socket->state() == QAbstractSocket::ConnectedState; +} + +void QMQTT::Network::connectToHost(const QHostAddress& host, const quint16 port) +{ + // Reset the hostname, because if it is not empty connectToHost() will use it instead of _host. + _hostName.clear(); + _host = host; + _port = port; + connectToHost(); +} + +void QMQTT::Network::connectToHost(const QString& hostName, const quint16 port) +{ + _hostName = hostName; + _port = port; + connectToHost(); +} + +void QMQTT::Network::connectToHost() +{ + _readState = Header; + if (_hostName.isEmpty()) + { + _socket->connectToHost(_host, _port); + } + else + { + _socket->connectToHost(_hostName, _port); + } +} + +void QMQTT::Network::onSocketError(QAbstractSocket::SocketError socketError) +{ + emit error(socketError); + if(_autoReconnect) + { + _autoReconnectTimer->start(); + } +} + +void QMQTT::Network::sendFrame(const Frame& frame) +{ + if(_socket->state() == QAbstractSocket::ConnectedState) + { + QDataStream out(_socket->ioDevice()); + frame.write(out); + } +} + +void QMQTT::Network::disconnectFromHost() +{ + _socket->disconnectFromHost(); +} + +QAbstractSocket::SocketState QMQTT::Network::state() const +{ + return _socket->state(); +} + +bool QMQTT::Network::autoReconnect() const +{ + return _autoReconnect; +} + +void QMQTT::Network::setAutoReconnect(const bool autoReconnect) +{ + _autoReconnect = autoReconnect; +} + +int QMQTT::Network::autoReconnectInterval() const +{ + return _autoReconnectInterval; +} + +void QMQTT::Network::setAutoReconnectInterval(const int autoReconnectInterval) +{ + _autoReconnectInterval = autoReconnectInterval; + _autoReconnectTimer->setInterval(_autoReconnectInterval); +} + +void QMQTT::Network::onSocketReadReady() +{ + QIODevice *ioDevice = _socket->ioDevice(); + // Only read the available (cached) bytes, so the read will never block. + QByteArray data = ioDevice->read(ioDevice->bytesAvailable()); + foreach(char byte, data) { + switch (_readState) { + case Header: + _header = static_cast(byte); + _readState = Length; + _length = 0; + _shift = 0; + _data.resize(0); // keep allocated buffer + break; + case Length: + _length |= (byte & 0x7F) << _shift; + _shift += 7; + if ((byte & 0x80) != 0) + break; + if (_length == 0) { + _readState = Header; + Frame frame(_header, _data); + emit received(frame); + break; + } + _readState = PayLoad; + _data.reserve(_length); + break; + case PayLoad: + _data.append(byte); + --_length; + if (_length > 0) + break; + _readState = Header; + Frame frame(_header, _data); + emit received(frame); + break; + } + } +} + +void QMQTT::Network::onDisconnected() +{ + emit disconnected(); + if(_autoReconnect) + { + _autoReconnectTimer->start(); + } +} + +#ifndef QT_NO_SSL +void QMQTT::Network::ignoreSslErrors(const QList& errors) +{ + _socket->ignoreSslErrors(errors); +} + +void QMQTT::Network::ignoreSslErrors() +{ + _socket->ignoreSslErrors(); +} + +QSslConfiguration QMQTT::Network::sslConfiguration() const +{ + return _socket->sslConfiguration(); +} + +void QMQTT::Network::setSslConfiguration(const QSslConfiguration& config) +{ + _socket->setSslConfiguration(config); +} +#endif // QT_NO_SSL diff --git a/mqtt/qmqtt_network_p.h b/mqtt/qmqtt_network_p.h new file mode 100644 index 0000000..8dc77fc --- /dev/null +++ b/mqtt/qmqtt_network_p.h @@ -0,0 +1,139 @@ +/* + * qmqtt_network_p.h - qmqtt network private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_NETWORK_P_H +#define QMQTT_NETWORK_P_H + +#include "qmqtt_networkinterface.h" + +#include +#include +#include +#include + +#ifdef QT_WEBSOCKETS_LIB +#include +#endif // QT_WEBSOCKETS_LIB + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +namespace QMQTT { + +class SocketInterface; +class TimerInterface; +class Frame; + +class Network : public NetworkInterface +{ + Q_OBJECT + +public: + Network(QObject* parent = NULL); +#ifndef QT_NO_SSL + Network(const QSslConfiguration& config, QObject* parent = NULL); +#endif // QT_NO_SSL +#ifdef QT_WEBSOCKETS_LIB +#ifndef QT_NO_SSL + Network(const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + QObject* parent = NULL); +#endif // QT_NO_SSL + Network(const QString& origin, + QWebSocketProtocol::Version version, + QObject* parent = NULL); +#endif // QT_WEBSOCKETS_LIB + Network(SocketInterface* socketInterface, TimerInterface* timerInterface, + QObject* parent = NULL); + ~Network(); + + void sendFrame(const Frame &frame); + bool isConnectedToHost() const; + bool autoReconnect() const; + void setAutoReconnect(const bool autoReconnect); + QAbstractSocket::SocketState state() const; + int autoReconnectInterval() const; + void setAutoReconnectInterval(const int autoReconnectInterval); +#ifndef QT_NO_SSL + void ignoreSslErrors(const QList& errors); + QSslConfiguration sslConfiguration() const; + void setSslConfiguration(const QSslConfiguration& config); +#endif // QT_NO_SSL + +public slots: + void connectToHost(const QHostAddress& host, const quint16 port); + void connectToHost(const QString& hostName, const quint16 port); + void disconnectFromHost(); +#ifndef QT_NO_SSL + void ignoreSslErrors(); +#endif // QT_NO_SSL + +protected slots: + void onSocketError(QAbstractSocket::SocketError socketError); + +protected: + void initialize(); + + quint16 _port; + QHostAddress _host; + QString _hostName; + bool _autoReconnect; + int _autoReconnectInterval; + SocketInterface* _socket; + TimerInterface* _autoReconnectTimer; + + enum ReadState { + Header, + Length, + PayLoad + }; + + ReadState _readState; + quint8 _header; + int _length; + int _shift; + QByteArray _data; + +protected slots: + void onSocketReadReady(); + void onDisconnected(); + void connectToHost(); + +private: + Q_DISABLE_COPY(Network) +}; + +} // namespace QMQTT + +#endif // QMQTT_NETWORK_P_H diff --git a/mqtt/qmqtt_networkinterface.h b/mqtt/qmqtt_networkinterface.h new file mode 100644 index 0000000..c2d927d --- /dev/null +++ b/mqtt/qmqtt_networkinterface.h @@ -0,0 +1,92 @@ +/* + * qmqtt_networkinterface.h - qmqtt network interface header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_NETWORK_INTERFACE_H +#define QMQTT_NETWORK_INTERFACE_H + +#include "qmqtt_global.h" + +#include +#include +#include +#include +#include + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +namespace QMQTT { + +class Frame; + +class Q_MQTT_EXPORT NetworkInterface : public QObject +{ + Q_OBJECT +public: + explicit NetworkInterface(QObject* parent = NULL) : QObject(parent) {} + virtual ~NetworkInterface() {} + + virtual void sendFrame(const Frame& frame) = 0; + virtual bool isConnectedToHost() const = 0; + virtual bool autoReconnect() const = 0; + virtual void setAutoReconnect(const bool autoReconnect) = 0; + virtual int autoReconnectInterval() const = 0; + virtual void setAutoReconnectInterval(const int autoReconnectInterval) = 0; + virtual QAbstractSocket::SocketState state() const = 0; +#ifndef QT_NO_SSL + virtual void ignoreSslErrors(const QList& errors) = 0; + virtual QSslConfiguration sslConfiguration() const = 0; + virtual void setSslConfiguration(const QSslConfiguration& config) = 0; +#endif // QT_NO_SSL + +public slots: + virtual void connectToHost(const QHostAddress& host, const quint16 port) = 0; + virtual void connectToHost(const QString& hostName, const quint16 port) = 0; + virtual void disconnectFromHost() = 0; +#ifndef QT_NO_SSL + virtual void ignoreSslErrors() = 0; +#endif // QT_NO_SSL + +signals: + void connected(); + void disconnected(); + void received(const QMQTT::Frame& frame); + void error(QAbstractSocket::SocketError error); +#ifndef QT_NO_SSL + void sslErrors(const QList& errors); +#endif // QT_NO_SSL +}; + +} // namespace QMQTT + +#endif // QMQTT_NETWORK_INTERFACE_H diff --git a/mqtt/qmqtt_routedmessage.h b/mqtt/qmqtt_routedmessage.h new file mode 100644 index 0000000..54af227 --- /dev/null +++ b/mqtt/qmqtt_routedmessage.h @@ -0,0 +1,71 @@ +/* + * qmqtt_router.h - qmqtt router + * + * Copyright (c) 2013 Ery Lee + * Router added by Niklas Wulf + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_ROUTEDMESSAGE_H +#define QMQTT_ROUTEDMESSAGE_H + +#include "qmqtt_message.h" + +#include +#include +#include + +namespace QMQTT { + +class RouteSubscription; + +class Q_MQTT_EXPORT RoutedMessage +{ +public: + inline RoutedMessage() + {} + inline RoutedMessage(const Message &message) + : _message(message) + {} + + inline const Message &message() const + { return _message; } + inline QHash parameters() const + { return _parameters; } + +private: + friend class RouteSubscription; + + Message _message; + QHash _parameters; +}; + +} // namespace QMQTT + +Q_DECLARE_METATYPE(QMQTT::RoutedMessage) + +#endif // QMQTT_ROUTEDMESSAGE_H diff --git a/mqtt/qmqtt_router.cpp b/mqtt/qmqtt_router.cpp new file mode 100644 index 0000000..f8fe309 --- /dev/null +++ b/mqtt/qmqtt_router.cpp @@ -0,0 +1,67 @@ +/* + * qmqtt_router.cpp - qmqtt router + * + * Copyright (c) 2013 Ery Lee + * Router added by Niklas Wulf + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_router.h" +#include "qmqtt_client.h" +#include "qmqtt_routesubscription.h" + +#include + +namespace QMQTT { + +Q_LOGGING_CATEGORY(router, "qmqtt.router") + +Router::Router(Client *parent) : QObject(parent), _client(parent) +{ +} + +RouteSubscription *Router::subscribe(const QString &route) +{ + RouteSubscription *subscription = new RouteSubscription(this); + subscription->setRoute(route); + connect(_client, &Client::connected, subscription, [this, subscription]() { + _client->subscribe(subscription->_topic, 0); + }); + if (_client->isConnectedToHost()) + _client->subscribe(subscription->_topic, 0); + connect(_client, &Client::received, subscription, &RouteSubscription::routeMessage); + return subscription; +} + +Client *Router::client() const +{ + return _client; +} + +} // namespace QMQTT + diff --git a/mqtt/qmqtt_router.h b/mqtt/qmqtt_router.h new file mode 100644 index 0000000..84988b0 --- /dev/null +++ b/mqtt/qmqtt_router.h @@ -0,0 +1,60 @@ +/* + * qmqtt_router.h - qmqtt router + * + * Copyright (c) 2013 Ery Lee + * Router added by Niklas Wulf + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_ROUTER_H +#define QMQTT_ROUTER_H + +#include "qmqtt_global.h" + +#include + +namespace QMQTT { + +class Client; +class RouteSubscription; + +class Q_MQTT_EXPORT Router : public QObject +{ + Q_OBJECT +public: + explicit Router(Client *parent = 0); + + RouteSubscription *subscribe(const QString &route); + Client *client() const; + +private: + Client *_client; +}; + +} // namespace QMQTT + +#endif // QMQTT_ROUTER_H diff --git a/mqtt/qmqtt_routesubscription.cpp b/mqtt/qmqtt_routesubscription.cpp new file mode 100644 index 0000000..81c4f93 --- /dev/null +++ b/mqtt/qmqtt_routesubscription.cpp @@ -0,0 +1,117 @@ +/* + * qmqtt_router.cpp - qmqtt router + * + * Copyright (c) 2013 Ery Lee + * Router added by Niklas Wulf + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_routesubscription.h" +#include "qmqtt_router.h" +#include "qmqtt_client.h" +#include "qmqtt_routedmessage.h" + +#include +#include +#include +#include +#include + +namespace QMQTT { + +Q_LOGGING_CATEGORY(routerSubscription, "qmqtt.routersubscription") + +RouteSubscription::RouteSubscription(Router *parent) + : QObject(parent), + _client(parent->client()) +{ + Q_ASSERT(!_client.isNull()); +} + +RouteSubscription::~RouteSubscription() +{ + if (Q_LIKELY(!_client.isNull() && _client->isConnectedToHost())) + _client->unsubscribe(_topic); +} + +QString RouteSubscription::route() const +{ + return _topic; +} + +void RouteSubscription::setRoute(const QString &route) +{ + QRegularExpression parameterNamesRegExp(QStringLiteral("\\:([a-zA-Z0-9]+)")); // note how names must not contain dashes or underscores + + // Remove paramter names to get the actual topic "route" + QString topic = route; + topic.remove(parameterNamesRegExp); + + // Remove the MQTT wildcards to get a regular expression, which matches the parameters + QString parameterRegExp = route; + parameterRegExp + .remove(QLatin1Char('+')) + .replace(parameterNamesRegExp, QStringLiteral("([a-zA-Z0-9_-]+)")) // note how parameter values may contain dashes or underscores + .remove(QLatin1Char('#')) + .replace(QLatin1String("$"), QLatin1String("\\$")); + + // Extract the parameter names + QRegularExpressionMatchIterator it = parameterNamesRegExp.globalMatch(route); + QStringList names; + while(it.hasNext()) { + QRegularExpressionMatch match = it.next(); + QString parameterName = match.captured(1); + names << parameterName; + } + + _topic = topic; + _parameterNames = names; + _regularExpression = QRegularExpression(parameterRegExp); +} + +void RouteSubscription::routeMessage(const Message &message) +{ + QString topic = message.topic(); + QRegularExpressionMatch match = _regularExpression.match(topic); + if(!match.hasMatch()) { + return; + } + + RoutedMessage routedMessage(message); + + for(int i = 0, c = _parameterNames.size(); i < c; ++i) { + QString name = _parameterNames.at(i); + QString value = match.captured(i + 1); + + routedMessage._parameters.insert(name, value); + } + + emit received(routedMessage); +} + +} // namespace QMQTT diff --git a/mqtt/qmqtt_routesubscription.h b/mqtt/qmqtt_routesubscription.h new file mode 100644 index 0000000..bd0608f --- /dev/null +++ b/mqtt/qmqtt_routesubscription.h @@ -0,0 +1,79 @@ +/* + * qmqtt_router.h - qmqtt router + * + * Copyright (c) 2013 Ery Lee + * Router added by Niklas Wulf + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_ROUTESUBSCRIPTION_H +#define QMQTT_ROUTESUBSCRIPTION_H + +#include "qmqtt_global.h" + +#include +#include +#include +#include +#include + +namespace QMQTT { + +class Client; +class Message; +class RoutedMessage; +class Router; + +class Q_MQTT_EXPORT RouteSubscription : public QObject +{ + Q_OBJECT +public: + ~RouteSubscription(); + + QString route() const; + +signals: + void received(const RoutedMessage &message); + +private slots: + void routeMessage(const Message &message); + +private: + friend class Router; + + explicit RouteSubscription(Router *parent = 0); + void setRoute(const QString &route); + + QPointer _client; + QString _topic; + QRegularExpression _regularExpression; + QStringList _parameterNames; +}; + +} // namespace QMQTT + +#endif // QMQTT_ROUTESUBSCRIPTION_H diff --git a/mqtt/qmqtt_socket.cpp b/mqtt/qmqtt_socket.cpp new file mode 100644 index 0000000..f0628f0 --- /dev/null +++ b/mqtt/qmqtt_socket.cpp @@ -0,0 +1,81 @@ +/* + * qmqtt_socket.cpp - qmqtt socket + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_socket_p.h" + +#include + +QMQTT::Socket::Socket(QObject* parent) + : SocketInterface(parent) + , _socket(new QTcpSocket(this)) +{ + connect(_socket.data(), &QTcpSocket::connected, this, &SocketInterface::connected); + connect(_socket.data(), &QTcpSocket::disconnected, this, &SocketInterface::disconnected); + connect(_socket.data(), + static_cast(&QTcpSocket::error), + this, + static_cast(&SocketInterface::error)); +} + +QMQTT::Socket::~Socket() +{ +} + +QIODevice *QMQTT::Socket::ioDevice() +{ + return _socket.data(); +} + +void QMQTT::Socket::connectToHost(const QHostAddress& address, quint16 port) +{ + _socket->connectToHost(address, port); +} + +void QMQTT::Socket::connectToHost(const QString& hostName, quint16 port) +{ + _socket->connectToHost(hostName, port); +} + +void QMQTT::Socket::disconnectFromHost() +{ + _socket->disconnectFromHost(); +} + +QAbstractSocket::SocketState QMQTT::Socket::state() const +{ + return _socket->state(); +} + +QAbstractSocket::SocketError QMQTT::Socket::error() const +{ + return _socket->error(); +} diff --git a/mqtt/qmqtt_socket_p.h b/mqtt/qmqtt_socket_p.h new file mode 100644 index 0000000..248a42d --- /dev/null +++ b/mqtt/qmqtt_socket_p.h @@ -0,0 +1,69 @@ +/* + * qmqtt_socket_p.h - qmqtt socket private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_SOCKET_P_H +#define QMQTT_SOCKET_P_H + +#include "qmqtt_socketinterface.h" + +#include +#include +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QIODevice) +QT_FORWARD_DECLARE_CLASS(QTcpSocket) + +namespace QMQTT +{ + +class Socket : public SocketInterface +{ + Q_OBJECT +public: + explicit Socket(QObject* parent = NULL); + virtual ~Socket(); + + virtual QIODevice *ioDevice(); + void connectToHost(const QHostAddress& address, quint16 port); + void connectToHost(const QString& hostName, quint16 port); + void disconnectFromHost(); + QAbstractSocket::SocketState state() const; + QAbstractSocket::SocketError error() const; + +protected: + QScopedPointer _socket; +}; + +} + +#endif // QMQTT_SOCKET_P_H diff --git a/mqtt/qmqtt_socketinterface.h b/mqtt/qmqtt_socketinterface.h new file mode 100644 index 0000000..97965b1 --- /dev/null +++ b/mqtt/qmqtt_socketinterface.h @@ -0,0 +1,84 @@ +/* + * qmqtt_socketinterface.h - qmqtt socket interface header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_SOCKET_INTERFACE_H +#define QMQTT_SOCKET_INTERFACE_H + +#include "qmqtt_global.h" + +#include +#include +#include +#include +#include + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +QT_FORWARD_DECLARE_CLASS(QIODevice) + +namespace QMQTT +{ + +class Q_MQTT_EXPORT SocketInterface : public QObject +{ + Q_OBJECT +public: + explicit SocketInterface(QObject* parent = NULL) : QObject(parent) {} + virtual ~SocketInterface() {} + + virtual QIODevice* ioDevice() = 0; + virtual void connectToHost(const QHostAddress& address, quint16 port) = 0; + virtual void connectToHost(const QString& hostName, quint16 port) = 0; + virtual void disconnectFromHost() = 0; + virtual QAbstractSocket::SocketState state() const = 0; + virtual QAbstractSocket::SocketError error() const = 0; +#ifndef QT_NO_SSL + virtual void ignoreSslErrors(const QList& errors) { Q_UNUSED(errors); } + virtual void ignoreSslErrors() {} + virtual QSslConfiguration sslConfiguration() const { return QSslConfiguration(); } + virtual void setSslConfiguration(const QSslConfiguration& config) { Q_UNUSED(config); } +#endif // QT_NO_SSL + +signals: + void connected(); + void disconnected(); + void error(QAbstractSocket::SocketError socketError); +#ifndef QT_NO_SSL + void sslErrors(const QList& errors); +#endif // QT_NO_SSL +}; + +} + +#endif // QMQTT_SOCKET_INTERFACE_H diff --git a/mqtt/qmqtt_ssl_socket.cpp b/mqtt/qmqtt_ssl_socket.cpp new file mode 100644 index 0000000..2d3a808 --- /dev/null +++ b/mqtt/qmqtt_ssl_socket.cpp @@ -0,0 +1,112 @@ +/* + * qmqtt_ssl_socket.cpp - qmqtt SSL socket + * + * Copyright (c) 2013 Ery Lee + * Copyright (c) 2016 Matthias Dieter Wallnöfer + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_ssl_socket_p.h" + +#ifndef QT_NO_SSL + +#include +#include + +QMQTT::SslSocket::SslSocket(const QSslConfiguration& config, QObject* parent) + : SocketInterface(parent) + , _socket(new QSslSocket(this)) +{ + _socket->setSslConfiguration(config); + connect(_socket.data(), &QSslSocket::encrypted, this, &SocketInterface::connected); + connect(_socket.data(), &QSslSocket::disconnected, this, &SocketInterface::disconnected); + connect(_socket.data(), + static_cast(&QSslSocket::error), + this, + static_cast(&SocketInterface::error)); + connect(_socket.data(), + static_cast&)>(&QSslSocket::sslErrors), + this, + &SslSocket::sslErrors); +} + +QMQTT::SslSocket::~SslSocket() +{ +} + +QIODevice *QMQTT::SslSocket::ioDevice() +{ + return _socket.data(); +} + +void QMQTT::SslSocket::connectToHost(const QHostAddress& address, quint16 port) +{ + _socket->connectToHostEncrypted(address.toString(), port); +} + +void QMQTT::SslSocket::connectToHost(const QString& hostName, quint16 port) +{ + _socket->connectToHostEncrypted(hostName, port); +} + +void QMQTT::SslSocket::disconnectFromHost() +{ + _socket->disconnectFromHost(); +} + +QAbstractSocket::SocketState QMQTT::SslSocket::state() const +{ + return _socket->state(); +} + +QAbstractSocket::SocketError QMQTT::SslSocket::error() const +{ + return _socket->error(); +} + +void QMQTT::SslSocket::ignoreSslErrors(const QList& errors) +{ + _socket->ignoreSslErrors(errors); +} + +void QMQTT::SslSocket::ignoreSslErrors() +{ + _socket->ignoreSslErrors(); +} + +QSslConfiguration QMQTT::SslSocket::sslConfiguration() const +{ + return _socket->sslConfiguration(); +} + +void QMQTT::SslSocket::setSslConfiguration(const QSslConfiguration& config) +{ + _socket->setSslConfiguration(config); +} + +#endif // QT_NO_SSL diff --git a/mqtt/qmqtt_ssl_socket_p.h b/mqtt/qmqtt_ssl_socket_p.h new file mode 100644 index 0000000..46ddc33 --- /dev/null +++ b/mqtt/qmqtt_ssl_socket_p.h @@ -0,0 +1,79 @@ +/* + * qmqtt_ssl_socket_p.h - qmqtt SSL socket private header + * + * Copyright (c) 2013 Ery Lee + * Copyright (c) 2016 Matthias Dieter Wallnöfer + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_SSL_SOCKET_P_H +#define QMQTT_SSL_SOCKET_P_H + +#ifndef QT_NO_SSL + +#include "qmqtt_socketinterface.h" + +#include +#include +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QSslSocket) +QT_FORWARD_DECLARE_CLASS(QSslError) +#include + +namespace QMQTT +{ + +class SslSocket : public SocketInterface +{ + Q_OBJECT +public: + explicit SslSocket(const QSslConfiguration& config, QObject* parent = NULL); + virtual ~SslSocket(); + + virtual QIODevice *ioDevice(); + void connectToHost(const QHostAddress& address, quint16 port); + void connectToHost(const QString& hostName, quint16 port); + void disconnectFromHost(); + QAbstractSocket::SocketState state() const; + QAbstractSocket::SocketError error() const; + void ignoreSslErrors(const QList& errors); + void ignoreSslErrors(); + QSslConfiguration sslConfiguration() const; + void setSslConfiguration(const QSslConfiguration& config); + +protected: + QScopedPointer _socket; +}; + +} + +#endif // QT_NO_SSL + +#endif // QMQTT_SSL_SOCKET_P_H diff --git a/mqtt/qmqtt_timer.cpp b/mqtt/qmqtt_timer.cpp new file mode 100644 index 0000000..a971d83 --- /dev/null +++ b/mqtt/qmqtt_timer.cpp @@ -0,0 +1,73 @@ +/* + * qmqtt_timer.cpp - qmqtt timer + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "qmqtt_timer_p.h" + +QMQTT::Timer::Timer(QObject* parent) + : TimerInterface(parent) +{ + connect(&_timer, &QTimer::timeout, this, &TimerInterface::timeout); +} + +QMQTT::Timer::~Timer() +{ +} + +bool QMQTT::Timer::isSingleShot() const +{ + return _timer.isSingleShot(); +} + +void QMQTT::Timer::setSingleShot(bool singleShot) +{ + _timer.setSingleShot(singleShot); +} + +int QMQTT::Timer::interval() const +{ + return _timer.interval(); +} + +void QMQTT::Timer::setInterval(int msec) +{ + _timer.setInterval(msec); +} + +void QMQTT::Timer::start() +{ + _timer.start(); +} + +void QMQTT::Timer::stop() +{ + _timer.stop(); +} diff --git a/mqtt/qmqtt_timer_p.h b/mqtt/qmqtt_timer_p.h new file mode 100644 index 0000000..093a141 --- /dev/null +++ b/mqtt/qmqtt_timer_p.h @@ -0,0 +1,62 @@ +/* + * qmqtt_timer_p.h - qmqtt timer private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_TIMER_P_H +#define QMQTT_TIMER_P_H + +#include "qmqtt_timerinterface.h" + +#include +#include + +namespace QMQTT { + +class Timer : public TimerInterface +{ + Q_OBJECT +public: + explicit Timer(QObject *parent = 0); + virtual ~Timer(); + + bool isSingleShot() const; + void setSingleShot(bool singleShot); + int interval() const; + void setInterval(int msec); + void start(); + void stop(); + +protected: + QTimer _timer; +}; + +} + +#endif // QMQTT_TIMER_P_H diff --git a/mqtt/qmqtt_timerinterface.h b/mqtt/qmqtt_timerinterface.h new file mode 100644 index 0000000..4f2cfcb --- /dev/null +++ b/mqtt/qmqtt_timerinterface.h @@ -0,0 +1,62 @@ +/* + * qmqtt_timerinterface.h - qmqtt timer interface header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_TIMER_INTERFACE_H +#define QMQTT_TIMER_INTERFACE_H + +#include "qmqtt_global.h" + +#include + +namespace QMQTT { + +class Q_MQTT_EXPORT TimerInterface : public QObject +{ + Q_OBJECT +public: + explicit TimerInterface(QObject* parent = NULL) : QObject(parent) {} + virtual ~TimerInterface() {} + + virtual bool isSingleShot() const = 0; + virtual void setSingleShot(bool singleShot) = 0; + virtual int interval() const = 0; + virtual void setInterval(int msec) = 0; + virtual void start() = 0; + virtual void stop() = 0; + +signals: + void timeout(); +}; + +} + +#endif // QMQTT_TIMER_INTERFACE_H + diff --git a/mqtt/qmqtt_websocket.cpp b/mqtt/qmqtt_websocket.cpp new file mode 100644 index 0000000..c824786 --- /dev/null +++ b/mqtt/qmqtt_websocket.cpp @@ -0,0 +1,103 @@ +#ifdef QT_WEBSOCKETS_LIB + +#include "qmqtt_websocket_p.h" + +#include +#include +#include + +#ifndef QT_NO_SSL +QMQTT::WebSocket::WebSocket(const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + QObject* parent) + : SocketInterface(parent) + , _socket(new QWebSocket(origin, version, this)) + , _ioDevice(new WebSocketIODevice(_socket, this)) +{ + initialize(); + if (sslConfig != NULL) + _socket->setSslConfiguration(*sslConfig); + connect(_socket, &QWebSocket::sslErrors, this, &WebSocket::sslErrors); +} +#endif // QT_NO_SSL + +QMQTT::WebSocket::WebSocket(const QString& origin, + QWebSocketProtocol::Version version, + QObject* parent) + : SocketInterface(parent) + , _socket(new QWebSocket(origin, version, this)) + , _ioDevice(new WebSocketIODevice(_socket, this)) +{ + initialize(); +} + +void QMQTT::WebSocket::initialize() +{ + connect(_socket, &QWebSocket::connected, this, &WebSocket::connected); + connect(_socket, &QWebSocket::disconnected, this, &WebSocket::disconnected); + connect(_socket, + static_cast(&QWebSocket::error), + this, + static_cast(&SocketInterface::error)); +} + +QMQTT::WebSocket::~WebSocket() +{ +} + +void QMQTT::WebSocket::connectToHost(const QHostAddress& address, quint16 port) +{ + Q_UNUSED(address) + Q_UNUSED(port) + qFatal("No supported"); +} + +void QMQTT::WebSocket::connectToHost(const QString& hostName, quint16 port) +{ + Q_UNUSED(port) + QUrl url(hostName); + QNetworkRequest request(url); + request.setRawHeader("Sec-WebSocket-Protocol", "mqtt"); + _ioDevice->connectToHost(request); +} + +void QMQTT::WebSocket::disconnectFromHost() +{ + _socket->close(); +} + +QAbstractSocket::SocketState QMQTT::WebSocket::state() const +{ + return _socket->state(); +} + +QAbstractSocket::SocketError QMQTT::WebSocket::error() const +{ + return _socket->error(); +} + +#ifndef QT_NO_SSL +void QMQTT::WebSocket::ignoreSslErrors(const QList& errors) +{ + _socket->ignoreSslErrors(errors); +} + +void QMQTT::WebSocket::ignoreSslErrors() +{ + _socket->ignoreSslErrors(); +} + +QSslConfiguration QMQTT::WebSocket::sslConfiguration() const +{ + return _socket->sslConfiguration(); +} + +void QMQTT::WebSocket::setSslConfiguration(const QSslConfiguration& config) +{ + _socket->setSslConfiguration(config); +} + +#endif // QT_NO_SSL + +#endif // QT_WEBSOCKETS_LIB diff --git a/mqtt/qmqtt_websocket_p.h b/mqtt/qmqtt_websocket_p.h new file mode 100644 index 0000000..6d159fa --- /dev/null +++ b/mqtt/qmqtt_websocket_p.h @@ -0,0 +1,102 @@ +/* + * qmqtt_websocket_p.h - qmqtt socket private header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef QMQTT_WEBSOCKET_H +#define QMQTT_WEBSOCKET_H + +#ifdef QT_WEBSOCKETS_LIB + +#include +#include + +#include +#include +#include +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QIODevice) + +#ifndef QT_NO_SSL +#include +QT_FORWARD_DECLARE_CLASS(QSslError) +#endif // QT_NO_SSL + +namespace QMQTT +{ + +class WebSocket : public SocketInterface +{ + Q_OBJECT +public: +#ifndef QT_NO_SSL + WebSocket(const QString& origin, + QWebSocketProtocol::Version version, + const QSslConfiguration* sslConfig, + QObject* parent = NULL); +#endif // QT_NO_SSL + + WebSocket(const QString& origin, + QWebSocketProtocol::Version version, + QObject* parent = NULL); + + virtual ~WebSocket(); + + QIODevice *ioDevice() + { + return _ioDevice; + } + + void connectToHost(const QHostAddress& address, quint16 port); + void connectToHost(const QString& hostName, quint16 port); + void disconnectFromHost(); + QAbstractSocket::SocketState state() const; + QAbstractSocket::SocketError error() const; +#ifndef QT_NO_SSL + void ignoreSslErrors(const QList& errors); + void ignoreSslErrors(); + QSslConfiguration sslConfiguration() const; + void setSslConfiguration(const QSslConfiguration& config); +#endif // QT_NO_SSL + +private: + void initialize(); + + QWebSocket *_socket; + WebSocketIODevice *_ioDevice; +}; + +} + +#endif // QT_WEBSOCKETS_LIB + +#endif // QMQTT_WEBSOCKET_H diff --git a/mqtt/qmqtt_websocketiodevice.cpp b/mqtt/qmqtt_websocketiodevice.cpp new file mode 100644 index 0000000..478d3c3 --- /dev/null +++ b/mqtt/qmqtt_websocketiodevice.cpp @@ -0,0 +1,48 @@ +#ifdef QT_WEBSOCKETS_LIB + +#include "qmqtt_websocketiodevice_p.h" + +#include + +QMQTT::WebSocketIODevice::WebSocketIODevice(QWebSocket *socket, QObject *parent) + : QIODevice(parent) + , _webSocket(socket) +{ + connect(_webSocket, &QWebSocket::bytesWritten, this, &WebSocketIODevice::bytesWritten); + connect(_webSocket, &QWebSocket::binaryMessageReceived, + this, &WebSocketIODevice::binaryMessageReceived); +} + +bool QMQTT::WebSocketIODevice::connectToHost(const QNetworkRequest &request) +{ + _webSocket->open(request); + return QIODevice::open(QIODevice::ReadWrite); +} + +qint64 QMQTT::WebSocketIODevice::bytesAvailable() const +{ + return _buffer.count(); +} + +void QMQTT::WebSocketIODevice::binaryMessageReceived(const QByteArray &frame) +{ + _buffer.append(frame); + emit readyRead(); +} + +qint64 QMQTT::WebSocketIODevice::readData(char *data, qint64 maxSize) +{ + int size = qMin(static_cast(maxSize), _buffer.count()); + for (int i=0; i(maxSize)); + return _webSocket->sendBinaryMessage(d); +} + +#endif // QT_WEBSOCKETS_LIB diff --git a/mqtt/qmqtt_websocketiodevice_p.h b/mqtt/qmqtt_websocketiodevice_p.h new file mode 100644 index 0000000..e936220 --- /dev/null +++ b/mqtt/qmqtt_websocketiodevice_p.h @@ -0,0 +1,86 @@ +/* + * qmqtt_socketinterface.h - qmqtt socket interface header + * + * Copyright (c) 2013 Ery Lee + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of mqttc nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef QMQTT_WEBSOCKETIODEVICE_H +#define QMQTT_WEBSOCKETIODEVICE_H + +#ifdef QT_WEBSOCKETS_LIB + +#include +#include +#include +#include + +QT_FORWARD_DECLARE_CLASS(QWebSocket) +QT_FORWARD_DECLARE_CLASS(QNetworkRequest) +QT_FORWARD_DECLARE_CLASS(QSslError) + +namespace QMQTT +{ + +class WebSocketIODevice : public QIODevice +{ + Q_OBJECT +public: + explicit WebSocketIODevice(QWebSocket *socket, QObject *parent = NULL); + + bool connectToHost(const QNetworkRequest &request); + + virtual qint64 bytesAvailable() const; + +signals: + void connected(); + + void disconnected(); + + void error(QAbstractSocket::SocketError error); + + void sslErrors(const QList &errors); + +protected: + virtual qint64 readData(char *data, qint64 maxSize); + + virtual qint64 writeData(const char *data, qint64 maxSize); + +private slots: + void binaryMessageReceived(const QByteArray &frame); + +private: + QByteArray _buffer; + QWebSocket *_webSocket; +}; + +} + +#endif // QT_WEBSOCKETS_LIB + +#endif // QMQTT_WEBSOCKETIODEVICE_H diff --git a/qt-installer-windows.qs b/qt-installer-windows.qs index 92908f7..7e1a79b 100644 --- a/qt-installer-windows.qs +++ b/qt-installer-windows.qs @@ -14,8 +14,8 @@ // Unfortunately it is not possible to disable deps like qt.tools.qtcreator var INSTALL_COMPONENTS = [ installer.environmentVariable("PLATFORM") == "x64" ? - "qt.qt5.5123.win64_msvc2017_64" : - "qt.qt5.5123.win32_msvc2017", + "qt.qt5.5141.win64_msvc2017_64" : + "qt.qt5.5141.win32_msvc2017", ]; function Controller() { @@ -28,15 +28,6 @@ function Controller() { }); } -Controller.prototype.DynamicTelemetryPluginFormCallback = function() { - gui.currentPageWidget().TelemetryPluginForm.statisticGroupBox.disableStatisticRadioButton.setChecked(true); - gui.clickButton(buttons.NextButton); - - //for(var key in widget.TelemetryPluginForm.statisticGroupBox){ - // console.log(key); - //} -} - Controller.prototype.WelcomePageCallback = function() { console.log("Step: " + gui.currentPageWidget()); // At least for 3.0.4 immediately clicking Next fails, so wait a bit. @@ -61,16 +52,6 @@ Controller.prototype.TargetDirectoryPageCallback = function() { gui.clickButton(buttons.NextButton); }; -Controller.prototype.ComponentSelectionPageCallback = function() { - console.log("Step: " + gui.currentPageWidget()); - var page = gui.currentPageWidget(); - page.deselectAll(); - for (var i = 0; i < INSTALL_COMPONENTS.length; i++) { - page.selectComponent(INSTALL_COMPONENTS[i]); - } - gui.clickButton(buttons.NextButton); -}; - Controller.prototype.LicenseAgreementPageCallback = function() { console.log("Step: " + gui.currentPageWidget()); gui.currentPageWidget().AcceptLicenseRadioButton.setChecked(true); @@ -98,4 +79,22 @@ Controller.prototype.FinishedPageCallback = function() { gui.clickButton(buttons.FinishButton); }; +Controller.prototype.DynamicTelemetryPluginFormCallback = function() { + var widget = gui.currentPageWidget(); + widget.TelemetryPluginForm.statisticGroupBox.disableStatisticRadioButton.checked = true; + gui.clickButton(buttons.NextButton); +} + +Controller.prototype.ComponentSelectionPageCallback = function() { + var page = gui.pageWidgetByObjectName("ComponentSelectionPage"); + + var archiveCheckBox = gui.findChild(page, "Archive"); + var latestCheckBox = gui.findChild(page, "Latest releases"); + var fetchButton = gui.findChild(page, "FetchCategoryButton"); + + archiveCheckBox.click(); + latestCheckBox.click(); + fetchButton.click(); +} + // vim: set ft=javascript: diff --git a/re/dbccomparatorwindow.cpp b/re/dbccomparatorwindow.cpp new file mode 100644 index 0000000..57d4c1e --- /dev/null +++ b/re/dbccomparatorwindow.cpp @@ -0,0 +1,400 @@ +#include "dbccomparatorwindow.h" +#include "ui_dbccomparatorwindow.h" +#include "helpwindow.h" +#include +#include +#include + +DBCComparatorWindow::DBCComparatorWindow(QWidget *parent) : + QDialog(parent), + ui(new Ui::DBCComparatorWindow) +{ + ui->setupUi(this); + setWindowFlags(Qt::Window); + + connect(ui->btnDBCFile1, SIGNAL(clicked(bool)), this, SLOT(loadFirstFile())); + connect(ui->btnDBCFile2, SIGNAL(clicked(bool)), this, SLOT(loadSecondFile())); + connect(ui->btnSaveDetails, SIGNAL(clicked(bool)), this, SLOT(saveDetails())); + + ui->lblFirstFile->setText(""); + ui->lblSecondFile->setText(""); + + firstDBC = nullptr; + secondDBC = nullptr; + + installEventFilter(this); +} + +DBCComparatorWindow::~DBCComparatorWindow() +{ + removeEventFilter(this); + delete ui; +} + +void DBCComparatorWindow::showEvent(QShowEvent *) +{ + readSettings(); +} + +void DBCComparatorWindow::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event) + writeSettings(); +} + +bool DBCComparatorWindow::eventFilter(QObject *obj, QEvent *event) +{ + if (event->type() == QEvent::KeyRelease) { + QKeyEvent *keyEvent = static_cast(event); + switch (keyEvent->key()) + { + case Qt::Key_F1: + HelpWindow::getRef()->showHelp("filecomparison.html"); + break; + } + return true; + } else { + // standard event processing + return QObject::eventFilter(obj, event); + } + return false; +} + +void DBCComparatorWindow::readSettings() +{ + QSettings settings; + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + resize(settings.value("DBCComparator/WindowSize", QSize(720, 631)).toSize()); + move(settings.value("DBCComparator/WindowPos", QPoint(50, 50)).toPoint()); + } +} + +void DBCComparatorWindow::writeSettings() +{ + QSettings settings; + + if (settings.value("Main/SaveRestorePositions", false).toBool()) + { + settings.setValue("DBCComparator/WindowSize", size()); + settings.setValue("DBCComparator/WindowPos", pos()); + } +} + +QString DBCComparatorWindow::loadDBC(DBCFile **file) +{ + QString filename; + QFileDialog dialog; + QSettings settings; + + QStringList filters; + filters.append(QString(tr("DBC Files (*.dbc *.DBC)"))); + + dialog.setDirectory(settings.value("FileIO/LoadSaveDirectory", dialog.directory().path()).toString()); + dialog.setFileMode(QFileDialog::ExistingFile); + dialog.setNameFilters(filters); + dialog.setViewMode(QFileDialog::Detail); + + if (dialog.exec() == QDialog::Accepted) + { + filename = dialog.selectedFiles()[0]; + + QProgressDialog progress(qApp->activeWindow()); + progress.setWindowModality(Qt::WindowModal); + progress.setLabelText("Loading file..."); + progress.setCancelButton(nullptr); + progress.setRange(0,0); + progress.setMinimumDuration(0); + progress.show(); + + qApp->processEvents(); + + if (dialog.selectedNameFilter() == filters[0]) + { + if (file[0]) delete file[0]; + file[0] = new DBCFile; + file[0]->loadFile(filename); + qDebug() << "Loaded the DBC file into first slot"; + } + + progress.cancel(); + return filename; + } + return QString(); +} + +void DBCComparatorWindow::loadFirstFile() +{ + QString filename; + filename = loadDBC(&firstDBC); + ui->lblFirstFile->setText(filename); + if (firstDBC && secondDBC) calculateDetails(); +} + +void DBCComparatorWindow::loadSecondFile() +{ + QString filename; + filename = loadDBC(&secondDBC); + ui->lblSecondFile->setText(filename); + if (firstDBC && secondDBC) calculateDetails(); +} + +void DBCComparatorWindow::calculateDetails() +{ + QProgressDialog progress(this); + progress.setWindowModality(Qt::WindowModal); + progress.setLabelText("Calculating differences"); + progress.setCancelButton(nullptr); + progress.setRange(0,0); + progress.setMinimumDuration(0); + progress.show(); + + qApp->processEvents(); + + firstDBC->sort(); + secondDBC->sort(); + + + ui->treeDetails->clear(); + + //Find nodes missing in one of the DBC files + + QTreeWidgetItem *nodeDiffRoot = new QTreeWidgetItem(); + nodeDiffRoot->setText(0, "Node Differences"); + QTreeWidgetItem *nodesMissingDBCFirst = new QTreeWidgetItem(); + nodesMissingDBCFirst->setText(0, "Nodes not found in first DBC"); + QTreeWidgetItem *nodesMissingDBCSecond = new QTreeWidgetItem(); + nodesMissingDBCSecond->setText(0, "Nodes not found in second DBC"); + nodeDiffRoot->addChild(nodesMissingDBCFirst); + nodeDiffRoot->addChild(nodesMissingDBCSecond); + ui->treeDetails->addTopLevelItem(nodeDiffRoot); + + for (int i = 0; i < firstDBC->dbc_nodes.count(); i++) + { + QString nodeName = firstDBC->dbc_nodes[i].name; + DBC_NODE *node = secondDBC->findNodeByName(nodeName); + if (!node) + { + QTreeWidgetItem *missingNodeItem = new QTreeWidgetItem(); + missingNodeItem->setText(0, nodeName); + nodesMissingDBCSecond->addChild(missingNodeItem); + } + } + + for (int i = 0; i < secondDBC->dbc_nodes.count(); i++) + { + QString nodeName = secondDBC->dbc_nodes[i].name; + DBC_NODE *node = firstDBC->findNodeByName(nodeName); + if (!node) + { + QTreeWidgetItem *missingNodeItem = new QTreeWidgetItem(); + missingNodeItem->setText(0, nodeName); + nodesMissingDBCFirst->addChild(missingNodeItem); + } + } + + + + //Find messages that are missing in one of the DBC files + //If a message exists in both then check for missing signals + + QTreeWidgetItem *msgDiffRoot = new QTreeWidgetItem(); + msgDiffRoot->setText(0, "Message Differences"); + QTreeWidgetItem *msgMissingDBCFirst = new QTreeWidgetItem(); + msgMissingDBCFirst->setText(0, "Messages not found in first DBC"); + QTreeWidgetItem *msgMissingDBCSecond = new QTreeWidgetItem(); + msgMissingDBCSecond->setText(0, "Messages not found in second DBC"); + QTreeWidgetItem *msgSignalsDiff = new QTreeWidgetItem(); + msgSignalsDiff->setText(0, "Messages with missing signals"); + QTreeWidgetItem *sigDiffOne = new QTreeWidgetItem(); + sigDiffOne->setText(0, "Missing from first DBC"); + QTreeWidgetItem *sigDiffTwo = new QTreeWidgetItem(); + sigDiffTwo->setText(0, "Missing from second DBC"); + QTreeWidgetItem *sigModifiedRoot = new QTreeWidgetItem(); + sigModifiedRoot->setText(0, "Modified Signals"); + msgSignalsDiff->addChild(sigDiffOne); + msgSignalsDiff->addChild(sigDiffTwo); + + msgDiffRoot->addChild(msgMissingDBCFirst); + msgDiffRoot->addChild(msgMissingDBCSecond); + msgDiffRoot->addChild(msgSignalsDiff); + msgDiffRoot->addChild(sigModifiedRoot); + + ui->treeDetails->addTopLevelItem(msgDiffRoot); + + QTreeWidgetItem *msgItem; + QTreeWidgetItem *sigTemp; + + for (int i = 0; i < firstDBC->messageHandler->getCount(); i++) + { + DBC_MESSAGE *thisMsg = firstDBC->messageHandler->findMsgByIdx(i); + QString msgName = thisMsg->name; + DBC_MESSAGE *otherMsg = secondDBC->messageHandler->findMsgByName(msgName); + if (!otherMsg) + { + QTreeWidgetItem *missingMsgItem = new QTreeWidgetItem(); + missingMsgItem->setText(0, msgName+ " (" + Utility::formatCANID(thisMsg->ID) + ")"); + msgMissingDBCSecond->addChild(missingMsgItem); + } + else //both have Msg. Check sigs for missing + { + bool thisMsgHasMissing = false; + bool thisMsgHasMods = false; + + for (int i = 0; i < thisMsg->sigHandler->getCount(); i++) + { + DBC_SIGNAL *thisSig = thisMsg->sigHandler->findSignalByIdx(i); + QString sigName = thisSig->name; + DBC_SIGNAL *otherSig = otherMsg->sigHandler->findSignalByName(sigName); + if (!otherSig) + { + QTreeWidgetItem *missingSigItem = new QTreeWidgetItem(); + missingSigItem->setText(0, sigName); + if (!thisMsgHasMissing) + { + thisMsgHasMissing = true; + msgItem = new QTreeWidgetItem(); + msgItem->setText(0, msgName + " (" + Utility::formatCANID(thisMsg->ID) + ")"); + sigDiffTwo->addChild(msgItem); + } + msgItem->addChild(missingSigItem); + } + else //signal exists on both sides. See if it as changed position or length + { + bool didChange = false; + QTreeWidgetItem *sigItem = new QTreeWidgetItem(); + sigItem->setText(0, sigName); + if (thisSig->startBit != otherSig->startBit) + { + didChange = true; + QTreeWidgetItem *sigStartBit = new QTreeWidgetItem(); + sigStartBit->setText(0, "Start Bit First DBC: " + QString::number(thisSig->startBit) + " Second: " + QString::number(otherSig->startBit)); + sigItem->addChild(sigStartBit); + } + if (thisSig->signalSize != otherSig->signalSize) + { + didChange = true; + QTreeWidgetItem *sigSize = new QTreeWidgetItem(); + sigSize->setText(0, "Size First DBC: " + QString::number(thisSig->signalSize) + " Second: " + QString::number(otherSig->signalSize)); + sigItem->addChild(sigSize); + } + if (thisSig->bias != otherSig->bias) + { + didChange = true; + QTreeWidgetItem *sigBias = new QTreeWidgetItem(); + sigBias->setText(0, "Bias First DBC: " + QString::number(thisSig->bias) + " Second: " + QString::number(otherSig->bias)); + sigItem->addChild(sigBias); + } + if (thisSig->factor != otherSig->factor) + { + didChange = true; + QTreeWidgetItem *sigFactor = new QTreeWidgetItem(); + sigFactor->setText(0, "Factor First DBC: " + QString::number(thisSig->factor) + " Second: " + QString::number(otherSig->factor)); + sigItem->addChild(sigFactor); + } + if (didChange) + { + if (!thisMsgHasMods) + { + thisMsgHasMods = true; + sigTemp = new QTreeWidgetItem(); + sigTemp->setText(0, msgName + " (" + Utility::formatCANID(thisMsg->ID) + ")"); + sigModifiedRoot->addChild(sigTemp); + } + sigTemp->addChild(sigItem); + } + } + } + thisMsgHasMissing = false; + for (int i = 0; i < otherMsg->sigHandler->getCount(); i++) + { + DBC_SIGNAL *thisSig = otherMsg->sigHandler->findSignalByIdx(i); + QString sigName = thisSig->name; + DBC_SIGNAL *otherSig = thisMsg->sigHandler->findSignalByName(sigName); + if (!otherSig) + { + QTreeWidgetItem *missingSigItem = new QTreeWidgetItem(); + missingSigItem->setText(0, sigName); + if (!thisMsgHasMissing) + { + thisMsgHasMissing = true; + msgItem = new QTreeWidgetItem(); + msgItem->setText(0, msgName + " (" + Utility::formatCANID(thisMsg->ID) + ")"); + sigDiffOne->addChild(msgItem); + } + msgItem->addChild(missingSigItem); + } + } + } + } + + for (int i = 0; i < secondDBC->messageHandler->getCount(); i++) + { + DBC_MESSAGE *origMsg = secondDBC->messageHandler->findMsgByIdx(i); + QString msgName = origMsg->name; + DBC_MESSAGE *msg = firstDBC->messageHandler->findMsgByName(msgName); + if (!msg) + { + QTreeWidgetItem *missingMsgItem = new QTreeWidgetItem(); + missingMsgItem->setText(0, msgName + " (" + Utility::formatCANID(origMsg->ID) + ")"); + msgMissingDBCFirst->addChild(missingMsgItem); + } + } + + QSettings settings; + if (settings.value("InfoCompare/AutoExpand", false).toBool()) + { + ui->treeDetails->expandAll(); + } + + progress.cancel(); + + qApp->processEvents(); +} + +void DBCComparatorWindow::saveDetails() +{ + QString filename; + QFileDialog dialog(this); + QSettings settings; + + QStringList filters; + filters.append(QString(tr("Text File (*.txt)"))); + + dialog.setFileMode(QFileDialog::AnyFile); + dialog.setNameFilters(filters); + dialog.setViewMode(QFileDialog::Detail); + dialog.setAcceptMode(QFileDialog::AcceptSave); + dialog.setDirectory(settings.value("FileComparator/LoadSaveDirectory", dialog.directory().path()).toString()); + + if (dialog.exec() == QDialog::Accepted) + { + filename = dialog.selectedFiles()[0]; + settings.setValue("FileComparator/LoadSaveDirectory", dialog.directory().path()); + if (!filename.contains('.')) filename += ".txt"; + QFile *outFile = new QFile(filename); + + if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTreeWidget *tree = ui->treeDetails; + + + QTreeWidgetItemIterator it(tree); + while (*it) { + QTreeWidgetItem *item = *it; + QString itemText = item->text(0); + while (item->parent()) + { + outFile->write(" "); + item = item->parent(); + } + outFile->write(itemText.toUtf8() + "\n"); + ++it; + } + + outFile->close(); + + } +} + diff --git a/re/dbccomparatorwindow.h b/re/dbccomparatorwindow.h new file mode 100644 index 0000000..b05f155 --- /dev/null +++ b/re/dbccomparatorwindow.h @@ -0,0 +1,45 @@ +#ifndef DBCCOMPARATORWINDOW_H +#define DBCCOMPARATORWINDOW_H + +#include +#include +#include +#include "framefileio.h" +#include "dbc/dbc_classes.h" +#include "dbc/dbchandler.h" +#include "utility.h" + +namespace Ui { +class DBCComparatorWindow; +} + +class DBCComparatorWindow : public QDialog +{ + Q_OBJECT + +public: + explicit DBCComparatorWindow(QWidget *parent = 0); + ~DBCComparatorWindow(); + +private slots: + void loadFirstFile(); + void loadSecondFile(); + void saveDetails(); + +private: + Ui::DBCComparatorWindow *ui; + DBCFile *firstDBC; + DBCFile *secondDBC; + QString firstDBCFilename; + QString secondDBCFilename; + + void calculateDetails(); + void showEvent(QShowEvent *); + void closeEvent(QCloseEvent *event); + bool eventFilter(QObject *obj, QEvent *event); + QString loadDBC(DBCFile **file); + void readSettings(); + void writeSettings(); +}; + +#endif //DBCCOMPARATORWINDOW_H diff --git a/re/discretestatewindow.cpp b/re/discretestatewindow.cpp index ddf5f1d..a4a0ba3 100644 --- a/re/discretestatewindow.cpp +++ b/re/discretestatewindow.cpp @@ -140,10 +140,10 @@ void DiscreteStateWindow::updatedFrames(int numFrames) { thisFrame = modelFrames->at(i); - if (!idFilters.contains(thisFrame.ID)) + if (!idFilters.contains(thisFrame.frameId())) { - idFilters.insert(thisFrame.ID, true); - QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(thisFrame.ID, thisFrame.extended), ui->listID); + idFilters.insert(thisFrame.frameId(), true); + QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(thisFrame.frameId(), thisFrame.hasExtendedFrameFormat()), ui->listID); listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag listItem->setCheckState(Qt::Checked); //default all filters to be set active } @@ -164,11 +164,11 @@ void DiscreteStateWindow::refreshFilterList() for (int i = 0; i < modelFrames->length(); i++) { CANFrame thisFrame = modelFrames->at(i); - id = thisFrame.ID; + id = thisFrame.frameId(); if (!idFilters.contains(id)) { idFilters.insert(id, true); - QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(id, thisFrame.extended), ui->listID); + QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(id, thisFrame.hasExtendedFrameFormat()), ui->listID); listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag listItem->setCheckState(Qt::Checked); //default all filters to be set active } @@ -359,7 +359,7 @@ void DiscreteStateWindow::calculateResults() frameCache.clear(); for (int i = 0; i < modelFrames->count(); i++) { - if (modelFrames->at(i).ID == (unsigned int)it.key()) frameCache.append(modelFrames->at(i)); + if (modelFrames->at(i).frameId() == (unsigned int)it.key()) frameCache.append(modelFrames->at(i)); } for (int bits = maxBits; bits >= minBits; bits--) { diff --git a/re/filecomparatorwindow.cpp b/re/filecomparatorwindow.cpp index 3efcfea..a159146 100644 --- a/re/filecomparatorwindow.cpp +++ b/re/filecomparatorwindow.cpp @@ -36,7 +36,7 @@ void FileComparatorWindow::showEvent(QShowEvent *) void FileComparatorWindow::closeEvent(QCloseEvent *event) { - Q_UNUSED(event); + Q_UNUSED(event) writeSettings(); } @@ -118,18 +118,20 @@ void FileComparatorWindow::clearReference() void FileComparatorWindow::calculateDetails() { - QMap interestedIDs; - QMap referenceIDs; + QMap interestedIDs; + QMap referenceIDs; QTreeWidgetItem *interestedOnlyBase, *referenceOnlyBase = nullptr, *sharedBase, *bitmapBaseInterested, *bitmapBaseReference = nullptr; QTreeWidgetItem *valuesBase, *detail, *sharedItem, *valuesInterested, *valuesReference = nullptr; uint64_t tmp; + const unsigned char *data; + int dataLen; bool uniqueInterested = ui->ckUniqueToInterested->isChecked(); QProgressDialog progress(this); progress.setWindowModality(Qt::WindowModal); progress.setLabelText("Calculating differences"); - progress.setCancelButton(0); + progress.setCancelButton(nullptr); progress.setRange(0,0); progress.setMinimumDuration(0); progress.show(); @@ -152,22 +154,25 @@ void FileComparatorWindow::calculateDetails() for (int x = 0; x < interestedFrames.count(); x++) { CANFrame frame = interestedFrames.at(x); - if (interestedIDs.contains(frame.ID)) //if we saw this ID before then add to the QList in there + data = reinterpret_cast(frame.payload().constData()); + dataLen = frame.payload().count(); + + if (interestedIDs.contains(frame.frameId())) //if we saw this ID before then add to the QList in there { - for (unsigned int y = 0; y < frame.len; y++) + for (int y = 0; y < dataLen; y++) { - interestedIDs[frame.ID].values[y][frame.data[y]]++; - tmp = frame.data[y]; + interestedIDs[frame.frameId()].values[y][data[y]]++; + tmp = data[y]; tmp = tmp << (8 * y); - interestedIDs[frame.ID].bitmap |= tmp; - //qDebug() << "bitmap: " << QString::number(interestedIDs[frame.ID].bitmap, 16); + interestedIDs[frame.frameId()].bitmap |= tmp; + //qDebug() << "bitmap: " << QString::number(interestedIDs[frame.frameId()].bitmap, 16); } } else //never seen this ID before so add one { FrameData *newData = new FrameData(); - newData->ID = frame.ID; - newData->dataLen = frame.len; + newData->ID = frame.frameId(); + newData->dataLen = dataLen; //it would be possible to implement a constructor for FrameData //that sets the bitmap and values to zero. That would be cleaner and better. newData->bitmap = 0; @@ -179,15 +184,15 @@ void FileComparatorWindow::calculateDetails() } } //memset(newData->values, 0, 256 * 8); - for (unsigned int y = 0; y < frame.len; y++) + for (int y = 0; y < dataLen; y++) { - newData->values[y][frame.data[y]] = 1; - tmp = frame.data[y]; + newData->values[y][data[y]] = 1; + tmp = data[y]; tmp = tmp << (8 * y); newData->bitmap |= tmp; //qDebug() << "bitmap: " << QString::number(newData->bitmap, 16); } - interestedIDs.insert(frame.ID, *newData); + interestedIDs.insert(frame.frameId(), *newData); } } @@ -196,22 +201,25 @@ void FileComparatorWindow::calculateDetails() for (int x = 0; x < referenceFrames.count(); x++) { CANFrame frame = referenceFrames.at(x); - if (referenceIDs.contains(frame.ID)) //if we saw this ID before then add to the QList in there + data = reinterpret_cast(frame.payload().constData()); + dataLen = frame.payload().count(); + + if (referenceIDs.contains(frame.frameId())) //if we saw this ID before then add to the QList in there { - for (unsigned int y = 0; y < frame.len; y++) + for (int y = 0; y < dataLen; y++) { - referenceIDs[frame.ID].values[y][frame.data[y]]++; - tmp = frame.data[y]; + referenceIDs[frame.frameId()].values[y][data[y]]++; + tmp = data[y]; tmp = tmp << (8 * y); - referenceIDs[frame.ID].bitmap |= tmp; - //qDebug() << "bitmap: " << QString::number(referenceIDs[frame.ID].bitmap, 16); + referenceIDs[frame.frameId()].bitmap |= tmp; + //qDebug() << "bitmap: " << QString::number(referenceIDs[frame.frameId()].bitmap, 16); } } else //never seen this ID before so add one { FrameData *newData = new FrameData(); - newData->ID = frame.ID; - newData->dataLen = frame.len; + newData->ID = frame.frameId(); + newData->dataLen = dataLen; newData->bitmap = 0; for (int x = 0; x < 8; x++) { @@ -221,15 +229,15 @@ void FileComparatorWindow::calculateDetails() } } //memset(newData->values, 0, 256 * 8); - for (unsigned int y = 0; y < frame.len; y++) + for (int y = 0; y < dataLen; y++) { - newData->values[y][frame.data[y]] = 1; - tmp = frame.data[y]; + newData->values[y][data[y]] = 1; + tmp = data[y]; tmp = tmp << (8 * y); newData->bitmap |= tmp; //qDebug() << "bitmap: " << QString::number(newData->bitmap, 16); } - referenceIDs.insert(frame.ID, *newData); + referenceIDs.insert(frame.frameId(), *newData); } } @@ -238,7 +246,7 @@ void FileComparatorWindow::calculateDetails() //now we iterate through the IDs within both files and see which are unique to one file and which //are shared bool interestedHadUnique = false; - QMap::iterator i; + QMap::iterator i; int framesCounter = 0; for (i = interestedIDs.begin(); i != interestedIDs.end(); ++i) { @@ -249,7 +257,7 @@ void FileComparatorWindow::calculateDetails() qApp->processEvents(); } - int keyone = i.key(); + uint32_t keyone = i.key(); if (!referenceIDs.contains(keyone)) { valuesBase = new QTreeWidgetItem(); @@ -316,7 +324,7 @@ void FileComparatorWindow::calculateDetails() for (int j = 0; j < 256; j++) { detail = new QTreeWidgetItem(); - detail->setText(0, Utility::formatHexNum(j)); + detail->setText(0, Utility::formatHexNum(static_cast(j))); if ((interested.values[i][j] > 0) && (reference.values[i][j] == 0) ) { valuesInterested->addChild(detail); @@ -336,10 +344,10 @@ void FileComparatorWindow::calculateDetails() if (!uniqueInterested) { - QMap::iterator itwo; + QMap::iterator itwo; for (itwo = referenceIDs.begin(); itwo != referenceIDs.end(); ++itwo) { - int keytwo = itwo.key(); + unsigned int keytwo = itwo.key(); if (!interestedIDs.contains(keytwo)) { valuesBase = new QTreeWidgetItem(); diff --git a/re/filecomparatorwindow.h b/re/filecomparatorwindow.h index d348255..61cef8c 100644 --- a/re/filecomparatorwindow.h +++ b/re/filecomparatorwindow.h @@ -14,7 +14,7 @@ class FileComparatorWindow; struct FrameData { - int ID; + uint32_t ID; int dataLen; uint64_t bitmap; int values[8][256]; //first index is the data byte, second is # of times we saw that value diff --git a/re/flowviewwindow.cpp b/re/flowviewwindow.cpp index c3ec0c0..31e4010 100644 --- a/re/flowviewwindow.cpp +++ b/re/flowviewwindow.cpp @@ -250,14 +250,14 @@ void FlowViewWindow::plottableDoubleClick(QCPAbstractPlottable* plottable, QMous int id = 0; //apply transforms to get the X axis value where we double clicked double coord = plottable->keyAxis()->pixelToCoord(event->localPos().x()); - if (frameCache.count() > 0) id = frameCache[0].ID; + if (frameCache.count() > 0) id = frameCache[0].frameId(); if (secondsMode) emit sendCenterTimeID(id, coord); else emit sendCenterTimeID(id, coord / 1000000.0); } void FlowViewWindow::gotCenterTimeID(int32_t ID, double timestamp) { - uint64_t t_stamp; + int64_t t_stamp; t_stamp = timestamp * 1000000l; @@ -278,7 +278,7 @@ void FlowViewWindow::gotCenterTimeID(int32_t ID, double timestamp) int bestIdx = -1; for (int i = 0; i < frameCache.count(); i++) { - if (frameCache[i].timestamp > t_stamp) + if (frameCache[i].timeStamp().microSeconds() > t_stamp) { bestIdx = i - 1; break; @@ -293,7 +293,7 @@ void FlowViewWindow::gotCenterTimeID(int32_t ID, double timestamp) memcpy(refBytes, currBytes, 8); } - memcpy(currBytes, frameCache.at(currentPosition).data, 8); + memcpy(currBytes, frameCache.at(currentPosition).payload().data(), 8); updateDataView(); } @@ -397,8 +397,10 @@ void FlowViewWindow::updatedFrames(int numFrames) { QVectornewX[8]; QVectornewY[8]; + const unsigned char *data; + int dataLen = 0; - CANFrame thisFrame; + const CANFrame *thisFrame; if (numFrames == -1) //all frames deleted. Kill the display { ui->listFrameID->clear(); @@ -428,40 +430,42 @@ void FlowViewWindow::updatedFrames(int numFrames) { if (numFrames > modelFrames->count()) return; unsigned int refID; - if (frameCache.count() > 0) refID = frameCache[0].ID; + if (frameCache.count() > 0) refID = frameCache[0].frameId(); else refID = 0; bool needRefresh = false; for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { - thisFrame = modelFrames->at(i); + thisFrame = &modelFrames->at(i); + data = reinterpret_cast(thisFrame->payload().constData()); + dataLen = thisFrame->payload().length(); - if (!foundID.contains(thisFrame.ID)) + if (!foundID.contains(thisFrame->frameId())) { - foundID.append(thisFrame.ID); - FilterUtility::createFilterItem(thisFrame.ID, ui->listFrameID); + foundID.append(thisFrame->frameId()); + FilterUtility::createFilterItem(thisFrame->frameId(), ui->listFrameID); } - if (thisFrame.ID == refID) + if (thisFrame->frameId() == refID) { - frameCache.append(thisFrame); + frameCache.append(*thisFrame); - for (int k = 0; k < 8; k++) + for (int k = 0; k < dataLen; k++) { if (ui->cbTimeGraph->isChecked()) { if (secondsMode){ - newX[k].append((double)(thisFrame.timestamp) / 1000000.0); + newX[k].append((double)(thisFrame->timeStamp().microSeconds()) / 1000000.0); } else { - newX[k].append(thisFrame.timestamp); + newX[k].append(thisFrame->timeStamp().microSeconds()); } } else { newX[k].append(x[k].count()); } - newY[k].append(thisFrame.data[k]); + newY[k].append(data[k]); needRefresh = true; } } @@ -469,20 +473,20 @@ void FlowViewWindow::updatedFrames(int numFrames) if (ui->cbLiveMode->checkState() == Qt::Checked) { currentPosition = frameCache.count() - 1; - memcpy(currBytes, frameCache.at(currentPosition).data, 8); + memcpy(currBytes, frameCache.at(currentPosition).payload(), 8); memcpy(refBytes, currBytes, 8); } if (needRefresh) { - for (int k = 0; k < 8; k++) + for (int k = 0; k < dataLen; k++) { if (graphRef[k] && graphRef[k]->data()) graphRef[k]->addData(newX[k], newY[k]); } ui->graphView->replot(); updateDataView(); - if (ui->cbSync->checkState() == Qt::Checked) emit sendCenterTimeID(frameCache[currentPosition].ID, frameCache[currentPosition].timestamp / 1000000.0); + if (ui->cbSync->checkState() == Qt::Checked) emit sendCenterTimeID(frameCache[currentPosition].frameId(), frameCache[currentPosition].timeStamp().microSeconds() / 1000000.0); } } updateFrameLabel(); @@ -497,7 +501,9 @@ void FlowViewWindow::removeAllGraphs() void FlowViewWindow::createGraph(int byteNum) { int tempVal; - float minval=1000000, maxval = -100000; + double minval = 1000000.0, maxval = -100000.0; + const unsigned char *data; + const CANFrame *frame; qDebug() << "Create Graph " << byteNum; @@ -512,16 +518,19 @@ void FlowViewWindow::createGraph(int byteNum) for (int j = 0; j < numEntries; j++) { - tempVal = frameCache[j].data[byteNum]; + frame = &frameCache[j]; + data = reinterpret_cast(frame->payload().constData()); + + tempVal = data[byteNum]; if (graphByTime) { if (secondsMode){ - x[byteNum][j] = (double)(frameCache[j].timestamp) / 1000000.0; + x[byteNum][j] = frame->timeStamp().microSeconds() / 1000000.0; } else { - x[byteNum][j] = frameCache[j].timestamp; + x[byteNum][j] = frame->timeStamp().microSeconds(); } } else @@ -551,7 +560,7 @@ void FlowViewWindow::refreshIDList() for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - id = thisFrame.ID; + id = thisFrame.frameId(); if (!foundID.contains(id)) { foundID.append(id); @@ -581,9 +590,9 @@ void FlowViewWindow::changeID(QString newID) for (int x = 0; x < modelFrames->count(); x++) { CANFrame thisFrame = modelFrames->at(x); - if (thisFrame.ID == id) + if (thisFrame.frameId() == id) { - for (int j = thisFrame.len; j < 8; j++) thisFrame.data[j] = 0; + thisFrame.payload().clear(); frameCache.append(thisFrame); } } @@ -600,7 +609,7 @@ void FlowViewWindow::changeID(QString newID) updateGraphLocation(); - memcpy(currBytes, frameCache.at(currentPosition).data, 8); + memcpy(currBytes, frameCache.at(currentPosition).payload().constData(), 8); memcpy(refBytes, currBytes, 8); updateDataView(); @@ -635,7 +644,8 @@ void FlowViewWindow::btnStopClick() playbackActive = false; currentPosition = 0; - memcpy(currBytes, frameCache.at(currentPosition).data, 8); + + memcpy(currBytes, frameCache.at(currentPosition).payload().constData(), 8); memcpy(refBytes, currBytes, 8); updateFrameLabel(); @@ -695,23 +705,23 @@ void FlowViewWindow::timerTriggered() void FlowViewWindow::updateDataView() { - ui->txtCurr1->setText(Utility::formatNumber(currBytes[0])); - ui->txtCurr2->setText(Utility::formatNumber(currBytes[1])); - ui->txtCurr3->setText(Utility::formatNumber(currBytes[2])); - ui->txtCurr4->setText(Utility::formatNumber(currBytes[3])); - ui->txtCurr5->setText(Utility::formatNumber(currBytes[4])); - ui->txtCurr6->setText(Utility::formatNumber(currBytes[5])); - ui->txtCurr7->setText(Utility::formatNumber(currBytes[6])); - ui->txtCurr8->setText(Utility::formatNumber(currBytes[7])); + ui->txtCurr1->setText(Utility::formatNumber((unsigned char)currBytes[0])); + ui->txtCurr2->setText(Utility::formatNumber((unsigned char)currBytes[1])); + ui->txtCurr3->setText(Utility::formatNumber((unsigned char)currBytes[2])); + ui->txtCurr4->setText(Utility::formatNumber((unsigned char)currBytes[3])); + ui->txtCurr5->setText(Utility::formatNumber((unsigned char)currBytes[4])); + ui->txtCurr6->setText(Utility::formatNumber((unsigned char)currBytes[5])); + ui->txtCurr7->setText(Utility::formatNumber((unsigned char)currBytes[6])); + ui->txtCurr8->setText(Utility::formatNumber((unsigned char)currBytes[7])); - ui->txtRef1->setText(Utility::formatNumber(refBytes[0])); - ui->txtRef2->setText(Utility::formatNumber(refBytes[1])); - ui->txtRef3->setText(Utility::formatNumber(refBytes[2])); - ui->txtRef4->setText(Utility::formatNumber(refBytes[3])); - ui->txtRef5->setText(Utility::formatNumber(refBytes[4])); - ui->txtRef6->setText(Utility::formatNumber(refBytes[5])); - ui->txtRef7->setText(Utility::formatNumber(refBytes[6])); - ui->txtRef8->setText(Utility::formatNumber(refBytes[7])); + ui->txtRef1->setText(Utility::formatNumber((unsigned char)refBytes[0])); + ui->txtRef2->setText(Utility::formatNumber((unsigned char)refBytes[1])); + ui->txtRef3->setText(Utility::formatNumber((unsigned char)refBytes[2])); + ui->txtRef4->setText(Utility::formatNumber((unsigned char)refBytes[3])); + ui->txtRef5->setText(Utility::formatNumber((unsigned char)refBytes[4])); + ui->txtRef6->setText(Utility::formatNumber((unsigned char)refBytes[5])); + ui->txtRef7->setText(Utility::formatNumber((unsigned char)refBytes[6])); + ui->txtRef8->setText(Utility::formatNumber((unsigned char)refBytes[7])); ui->flowView->setReference(refBytes, false); ui->flowView->updateData(currBytes, true); @@ -757,7 +767,8 @@ void FlowViewWindow::updatePosition(bool forward) uint8_t cngByte; for (int i = 0; i < 8; i++) { - cngByte = currBytes[i] ^ frameCache.at(currentPosition).data[i]; + unsigned char thisByte = static_cast(frameCache.at(currentPosition).payload().data()[i]); + cngByte = currBytes[i] ^ thisByte; changedBits |= (uint64_t)cngByte << (8ull * i); } @@ -771,9 +782,9 @@ void FlowViewWindow::updatePosition(bool forward) playbackTimer->stop(); } - memcpy(currBytes, frameCache.at(currentPosition).data, 8); + memcpy(currBytes, frameCache.at(currentPosition).payload().constData(), 8); - if (ui->cbSync->checkState() == Qt::Checked) emit sendCenterTimeID(frameCache[currentPosition].ID, frameCache[currentPosition].timestamp / 1000000.0); + if (ui->cbSync->checkState() == Qt::Checked) emit sendCenterTimeID(frameCache[currentPosition].frameId(), frameCache[currentPosition].timeStamp().microSeconds() / 1000000.0); } void FlowViewWindow::updateGraphLocation() @@ -787,9 +798,9 @@ void FlowViewWindow::updateGraphLocation() { if (secondsMode) { - ui->graphView->xAxis->setRange(frameCache[start].timestamp / 1000000.0, frameCache[end].timestamp / 1000000.0); + ui->graphView->xAxis->setRange(frameCache[start].timeStamp().microSeconds() / 1000000.0, frameCache[end].timeStamp().microSeconds() / 1000000.0); /* - ui->graphView->xAxis->setTickStep((frameCache[end].timestamp - frameCache[start].timestamp)/ 3000000.0); + ui->graphView->xAxis->setTickStep((frameCache[end].timeStamp().microSeconds() - frameCache[start].timeStamp().microSeconds())/ 3000000.0); ui->graphView->xAxis->setSubTickCount(0); ui->graphView->xAxis->setNumberFormat("f"); ui->graphView->xAxis->setNumberPrecision(6); @@ -797,9 +808,9 @@ void FlowViewWindow::updateGraphLocation() } else { - ui->graphView->xAxis->setRange(frameCache[start].timestamp, frameCache[end].timestamp); + ui->graphView->xAxis->setRange(frameCache[start].timeStamp().microSeconds(), frameCache[end].timeStamp().microSeconds()); /* - ui->graphView->xAxis->setTickStep((frameCache[end].timestamp - frameCache[start].timestamp)/ 3.0); + ui->graphView->xAxis->setTickStep((frameCache[end].timeStamp().microSeconds() - frameCache[start].timeStamp().microSeconds())/ 3.0); ui->graphView->xAxis->setSubTickCount(0); ui->graphView->xAxis->setNumberFormat("f"); ui->graphView->xAxis->setNumberPrecision(0); */ diff --git a/re/flowviewwindow.h b/re/flowviewwindow.h index fa07799..258c614 100644 --- a/re/flowviewwindow.h +++ b/re/flowviewwindow.h @@ -40,11 +40,11 @@ private slots: void gotCellClick(int x, int y); signals: - void sendCenterTimeID(int32_t ID, double timestamp); + void sendCenterTimeID(uint32_t ID, double timestamp); private: Ui::FlowViewWindow *ui; - QList foundID; + QList foundID; QList frameCache; const QVector *modelFrames; unsigned char refBytes[8]; diff --git a/re/frameinfowindow.cpp b/re/frameinfowindow.cpp index 894e6f8..03ab8e6 100644 --- a/re/frameinfowindow.cpp +++ b/re/frameinfowindow.cpp @@ -39,6 +39,12 @@ FrameInfoWindow::FrameInfoWindow(const QVector *frames, QWidget *paren ui->graphHistogram->xAxis->setRange(0, 63); ui->graphHistogram->yAxis->setRange(0, 100); + QSharedPointer graphHistoLogTicker(new QCPAxisTickerLog); + ui->graphHistogram->yAxis->setTicker(graphHistoLogTicker); + ui->graphHistogram->yAxis2->setTicker(graphHistoLogTicker); + ui->graphHistogram->yAxis->setNumberFormat("eb"); // e = exponential, b = beautiful decimal powers + ui->graphHistogram->yAxis->setNumberPrecision(0); //log ticker always picks powers of 10 so no need or use for precision + ui->graphHistogram->axisRect()->setupFullAxesBox(); ui->graphHistogram->xAxis->setLabel("Bits"); @@ -63,6 +69,12 @@ FrameInfoWindow::FrameInfoWindow(const QVector *frames, QWidget *paren ui->timeHistogram->xAxis->setRange(0, numIntervalHistBars); ui->timeHistogram->yAxis->setRange(0, 100); + QSharedPointer logTicker(new QCPAxisTickerLog); + ui->timeHistogram->yAxis->setTicker(logTicker); + ui->timeHistogram->yAxis2->setTicker(logTicker); + ui->timeHistogram->yAxis->setScaleType(QCPAxis::stLogarithmic); + ui->timeHistogram->yAxis->setNumberFormat("eb"); // e = exponential, b = beautiful decimal powers + ui->timeHistogram->yAxis->setNumberPrecision(0); //log ticker always picks powers of 10 so no need or use for precision ui->timeHistogram->axisRect()->setupFullAxesBox(); ui->timeHistogram->xAxis->setLabel("Interval (ms)"); @@ -138,7 +150,7 @@ FrameInfoWindow::~FrameInfoWindow() void FrameInfoWindow::closeEvent(QCloseEvent *event) { - Q_UNUSED(event); + Q_UNUSED(event) writeSettings(); } @@ -211,14 +223,14 @@ void FrameInfoWindow::updatedFrames(int numFrames) for (int x = modelFrames->count() - numFrames; x < modelFrames->count(); x++) { CANFrame thisFrame = modelFrames->at(x); - int32_t id = static_cast(thisFrame.ID); + int32_t id = static_cast(thisFrame.frameId()); if (!foundID.contains(id)) { foundID.append(id); FilterUtility::createFilterItem(id, ui->listFrameID); } - if (currID == modelFrames->at(x).ID) + if (currID == modelFrames->at(x).frameId()) { thisID = true; break; @@ -244,10 +256,10 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) { int targettedID; int minLen, maxLen, thisLen; - uint64_t avgInterval; - uint64_t minInterval; - uint64_t maxInterval; - uint64_t thisInterval; + int64_t avgInterval; + int64_t minInterval; + int64_t maxInterval; + int64_t thisInterval; int minData[8]; int maxData[8]; int dataHistogram[256][8]; @@ -260,10 +272,10 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) uint8_t referenceBits[8]; QTreeWidgetItem *baseNode, *dataBase, *histBase, *tempItem; - targettedID = static_cast(Utility::ParseStringToNum(newID)); - if (modelFrames->count() == 0) return; + targettedID = static_cast(Utility::ParseStringToNum(newID)); + qDebug() << "Started update details window with id " << targettedID; avgInterval = 0; @@ -275,9 +287,12 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - if (thisFrame.ID == static_cast(targettedID)) frameCache.append(thisFrame); + if (thisFrame.frameId() == static_cast(targettedID)) frameCache.append(thisFrame); } + const unsigned char *data = reinterpret_cast(frameCache.at(0).payload().constData()); + int dataLen = frameCache.at(0).payload().length(); + ui->treeDetails->clear(); if (frameCache.count() == 0) return; @@ -285,7 +300,7 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) baseNode = new QTreeWidgetItem(); baseNode->setText(0, QString("ID: ") + newID ); - if (frameCache[0].extended) //if these frames seem to be extended then try for J1939 decoding + if (frameCache[0].hasExtendedFrameFormat()) //if these frames seem to be extended then try for J1939 decoding { // ------- J1939 decoding ---------- J1939ID jid; @@ -336,13 +351,13 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr(" Priority bits: ") + Utility::formatNumber( FilterUtility::getGMLanPriorityBits(targettedID))); + tempItem->setText(0, tr(" Priority bits: ") + Utility::formatNumber( (uint64_t)FilterUtility::getGMLanPriorityBits(targettedID))); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr(" Arbitration Id: ") + Utility::formatNumber( FilterUtility::getGMLanArbitrationId(targettedID))); + tempItem->setText(0, tr(" Arbitration Id: ") + Utility::formatNumber( (uint64_t)FilterUtility::getGMLanArbitrationId(targettedID))); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr(" Sender Id: ") + Utility::formatNumber( FilterUtility::getGMLanSenderId(targettedID))); + tempItem->setText(0, tr(" Sender Id: ") + Utility::formatNumber( (uint64_t)FilterUtility::getGMLanSenderId(targettedID))); baseNode->addChild(tempItem); } @@ -364,33 +379,39 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) } for (int j = 0; j < 64; j++) bitfieldHistogram[j] = 0; - for (int c = 0; c < 8; c++) + data = reinterpret_cast(frameCache.at(0).payload().constData()); + dataLen = frameCache.at(0).payload().length(); + + for (int c = 0; c < dataLen; c++) { changedBits[c] = 0; - referenceBits[c] = frameCache.at(0).data[c]; + referenceBits[c] = data[c]; //qDebug() << referenceBits[c]; } - std::vector sortedIntervals; - uint64_t intervalSum = 0; + std::vector sortedIntervals; + int64_t intervalSum = 0; //then find all data points for (int j = 0; j < frameCache.count(); j++) { + data = reinterpret_cast(frameCache.at(j).payload().constData()); + dataLen = frameCache.at(j).payload().length(); + byteGraphX.append(j); - for (uint32_t bytcnt = 0; bytcnt < frameCache[j].len; bytcnt++) + for (int bytcnt = 0; bytcnt < dataLen; bytcnt++) { - byteGraphY[bytcnt].append(frameCache[j].data[bytcnt]); + byteGraphY[bytcnt].append(data[bytcnt]); } if (j != 0) { //TODO - we try the interval whichever way doesn't go negative. But, we should probably sort the frame list before //starting so that the intervals are all correct. - if (frameCache[j].timestamp > frameCache[j-1].timestamp) - thisInterval = (frameCache[j].timestamp - frameCache[j-1].timestamp); + if (frameCache[j].timeStamp().microSeconds() > frameCache[j-1].timeStamp().microSeconds()) + thisInterval = (frameCache[j].timeStamp().microSeconds() - frameCache[j-1].timeStamp().microSeconds()); else - thisInterval = (frameCache[j-1].timestamp - frameCache[j].timestamp); + thisInterval = (frameCache[j-1].timeStamp().microSeconds() - frameCache[j].timeStamp().microSeconds()); sortedIntervals.push_back(thisInterval); intervalSum += thisInterval; @@ -398,12 +419,12 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) if (thisInterval < minInterval) minInterval = thisInterval; avgInterval += thisInterval; } - thisLen = frameCache.at(j).len; + thisLen = dataLen; if (thisLen > maxLen) maxLen = thisLen; if (thisLen < minLen) minLen = thisLen; for (int c = 0; c < thisLen; c++) { - unsigned char dat = frameCache.at(j).data[c]; + unsigned char dat = data[c]; if (minData[c] > dat) minData[c] = dat; if (maxData[c] < dat) maxData[c] = dat; dataHistogram[dat][c]++; //add one to count for this @@ -420,7 +441,7 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) } std::sort(sortedIntervals.begin(), sortedIntervals.end()); - uint64_t intervalStdDiv = 0, intervalPctl5 = 0, intervalPctl95 = 0, intervalMean = 0, intervalVariance = 0; + int64_t intervalStdDiv = 0, intervalPctl5 = 0, intervalPctl95 = 0, intervalMean = 0, intervalVariance = 0; int maxTimeCounter = -1; if (sortedIntervals.size() > 0) @@ -432,17 +453,17 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) } intervalVariance /= sortedIntervals.size(); - intervalStdDiv = sqrt(intervalVariance); + intervalStdDiv = static_cast(sqrt(intervalVariance)); - intervalPctl5 = sortedIntervals[floor(0.05 * sortedIntervals.size())]; - intervalPctl95 = sortedIntervals[floor(0.95 * sortedIntervals.size())]; + intervalPctl5 = sortedIntervals[static_cast(floor(0.05 * sortedIntervals.size()))]; + intervalPctl95 = sortedIntervals[static_cast(floor(0.95 * sortedIntervals.size()))]; - uint64_t step = ceil((maxInterval - minInterval) / numIntervalHistBars); + uint64_t step = static_cast(ceil((maxInterval - minInterval) / numIntervalHistBars)); qDebug() << "Step: " << step << " minInt: " << minInterval << " maxInt: " << maxInterval; - int index = 0; + unsigned int index = 0; int counter = 0; for(int l = 0; l <= numIntervalHistBars; l++) { - uint64_t currentMax = maxInterval - ((numIntervalHistBars - l) * step); // avoid missing the biggest value due to rounding errors + int64_t currentMax = maxInterval - ((numIntervalHistBars - l) * step); // avoid missing the biggest value due to rounding errors qDebug() << "CurrentMax: " << currentMax; while(index < sortedIntervals.size()) { if(sortedIntervals[index] <= currentMax) { @@ -474,22 +495,22 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Average inter-frame interval: ") + QString::number(avgInterval / 1000.0f) + "ms"); + tempItem->setText(0, tr("Average inter-frame interval: ") + QString::number(avgInterval / 1000.0) + "ms"); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Minimum inter-frame interval: ") + QString::number(minInterval / 1000.0f) + "ms"); + tempItem->setText(0, tr("Minimum inter-frame interval: ") + QString::number(minInterval / 1000.0) + "ms"); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Maximum inter-frame interval: ") + QString::number(maxInterval / 1000.0f) + "ms"); + tempItem->setText(0, tr("Maximum inter-frame interval: ") + QString::number(maxInterval / 1000.0) + "ms"); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Inter-frame interval variation: ") + QString::number((maxInterval - minInterval) / 1000.0f) + "ms"); + tempItem->setText(0, tr("Inter-frame interval variation: ") + QString::number((maxInterval - minInterval) / 1000.0) + "ms"); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Interval standard deviation: ") + QString::number(intervalStdDiv / 1000.0f) + "ms"); + tempItem->setText(0, tr("Interval standard deviation: ") + QString::number(intervalStdDiv / 1000.0) + "ms"); baseNode->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Minimum range to fit 90% of inter-frame intervals: ") + QString::number((intervalPctl95 - intervalPctl5) / 1000.0f) + "ms"); + tempItem->setText(0, tr("Minimum range to fit 90% of inter-frame intervals: ") + QString::number((intervalPctl95 - intervalPctl5) / 1000.0) + "ms"); baseNode->addChild(tempItem); for (int c = 0; c < maxLen; c++) { @@ -506,7 +527,7 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) dataBase->addChild(tempItem); tempItem = new QTreeWidgetItem(); - tempItem->setText(0, tr("Range: ") + Utility::formatNumber(minData[c]) + tr(" to ") + Utility::formatNumber(maxData[c])); + tempItem->setText(0, tr("Range: ") + Utility::formatNumber((unsigned int)minData[c]) + tr(" to ") + Utility::formatNumber((unsigned int)maxData[c])); dataBase->addChild(tempItem); histBase->setText(0, tr("Histogram")); dataBase->addChild(histBase); @@ -516,7 +537,7 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) if (dataHistogram[d][c] > 0) { tempItem = new QTreeWidgetItem(); - tempItem->setText(0, QString::number(d) + "/0x" + QString::number(d, 16) +" (" + Utility::formatByteAsBinary(d) +") -> " + QString::number(dataHistogram[d][c])); + tempItem->setText(0, QString::number(d) + "/0x" + QString::number(d, 16) +" (" + Utility::formatByteAsBinary(static_cast(d)) +") -> " + QString::number(dataHistogram[d][c])); histBase->addChild(tempItem); } } @@ -548,7 +569,8 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) graphBrush.setStyle(Qt::SolidPattern); ui->graphHistogram->graph()->setPen(Qt::NoPen); ui->graphHistogram->graph()->setBrush(graphBrush); - ui->graphHistogram->yAxis->setRange(0, maxY * 1.02); + ui->graphHistogram->yAxis->setRange(0.8, maxY * 1.2); + ui->graphHistogram->yAxis->setScaleType(QCPAxis::stLogarithmic); ui->graphHistogram->axisRect()->setupFullAxesBox(); ui->graphHistogram->replot(); @@ -566,12 +588,6 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) ui->timeHistogram->addGraph(); ui->timeHistogram->graph()->setData(timeGraphX, timeGraphY); ui->timeHistogram->graph()->setLineStyle(QCPGraph::lsStepLeft); //connect points with lines - ui->timeHistogram->yAxis->setScaleType(QCPAxis::stLogarithmic); - QSharedPointer logTicker(new QCPAxisTickerLog); - ui->timeHistogram->yAxis->setTicker(logTicker); - ui->timeHistogram->yAxis2->setTicker(logTicker); - ui->timeHistogram->yAxis->setNumberFormat("eb"); // e = exponential, b = beautiful decimal powers - ui->timeHistogram->yAxis->setNumberPrecision(0); //log ticker always picks powers of 10 so no need or use for precision //QBrush graphBrush; graphBrush.setColor(Qt::red); graphBrush.setStyle(Qt::SolidPattern); @@ -600,7 +616,7 @@ void FrameInfoWindow::refreshIDList() for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - id = (int)thisFrame.ID; + id = (int)thisFrame.frameId(); if (!foundID.contains(id)) { foundID.append(id); diff --git a/re/fuzzingwindow.cpp b/re/fuzzingwindow.cpp index 43c60c7..f510f7a 100644 --- a/re/fuzzingwindow.cpp +++ b/re/fuzzingwindow.cpp @@ -2,6 +2,7 @@ #include "ui_fuzzingwindow.h" #include "utility.h" #include +#include #include "mainwindow.h" #include "helpwindow.h" #include "connections/canconmanager.h" @@ -26,6 +27,15 @@ FuzzingWindow::FuzzingWindow(const QVector *frames, QWidget *parent) : connect(ui->listID, &QListWidget::itemChanged, this, &FuzzingWindow::idListChanged); connect(ui->spinBytes, SIGNAL(valueChanged(int)), this, SLOT(changedNumDataBytes(int))); connect(ui->bitfield, SIGNAL(gridClicked(int,int)), this, SLOT(bitfieldClicked(int,int))); + connect(ui->txtByte0, &QLineEdit::returnPressed, this, [=](){changedDataByteText(0, ui->txtByte0->text());}); + connect(ui->txtByte1, &QLineEdit::returnPressed, this, [=](){changedDataByteText(1, ui->txtByte1->text());}); + connect(ui->txtByte2, &QLineEdit::returnPressed, this, [=](){changedDataByteText(2, ui->txtByte2->text());}); + connect(ui->txtByte3, &QLineEdit::returnPressed, this, [=](){changedDataByteText(3, ui->txtByte3->text());}); + connect(ui->txtByte4, &QLineEdit::returnPressed, this, [=](){changedDataByteText(4, ui->txtByte4->text());}); + connect(ui->txtByte5, &QLineEdit::returnPressed, this, [=](){changedDataByteText(5, ui->txtByte5->text());}); + connect(ui->txtByte6, &QLineEdit::returnPressed, this, [=](){changedDataByteText(6, ui->txtByte6->text());}); + connect(ui->txtByte7, &QLineEdit::returnPressed, this, [=](){changedDataByteText(7, ui->txtByte7->text());}); + connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int))); @@ -94,7 +104,7 @@ void FuzzingWindow::updatedFrames(int numFrames) if (numFrames > modelFrames->count()) return; for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { - id = modelFrames->at(i).ID; + id = modelFrames->at(i).frameId(); if (!foundIDs.contains(id)) { foundIDs.append(id); @@ -110,9 +120,32 @@ void FuzzingWindow::changePlaybackSpeed(int newSpeed) fuzzTimer->setInterval(newSpeed); } +void FuzzingWindow::changedDataByteText(int which, QString valu) +{ + int startBit = which * 8; + int byt = valu.toInt(nullptr, 16); + + for (int i = 0; i < 8; i++) + { + bitGrid[startBit + i] = (byt & (1 << i)) ? 2 : 0; + } + + redrawGrid(); +} + void FuzzingWindow::changedNumDataBytes(int newVal) { qDebug() << "new num bytes: " << newVal; + + ui->txtByte0->setEnabled((newVal > 0) ? true : false); + ui->txtByte1->setEnabled((newVal > 1) ? true : false); + ui->txtByte2->setEnabled((newVal > 2) ? true : false); + ui->txtByte3->setEnabled((newVal > 3) ? true : false); + ui->txtByte4->setEnabled((newVal > 4) ? true : false); + ui->txtByte5->setEnabled((newVal > 5) ? true : false); + ui->txtByte6->setEnabled((newVal > 6) ? true : false); + ui->txtByte7->setEnabled((newVal > 7) ? true : false); + int byt; for (int i = 0; i < 64; i++) { @@ -132,18 +165,31 @@ void FuzzingWindow::changedNumDataBytes(int newVal) void FuzzingWindow::timerTriggered() { + static uint64_t lastByteUpdate = 0; CANFrame thisFrame; - thisFrame.remote = false; sendingBuffer.clear(); + //Every 250ms update the text fields to show our progress and what's going on. + if (QDateTime::currentMSecsSinceEpoch() - lastByteUpdate > 250) + { + ui->txtByte0->setText(QString::number(currentBytes[0], 16)); + ui->txtByte1->setText(QString::number(currentBytes[1], 16)); + ui->txtByte2->setText(QString::number(currentBytes[2], 16)); + ui->txtByte3->setText(QString::number(currentBytes[3], 16)); + ui->txtByte4->setText(QString::number(currentBytes[4], 16)); + ui->txtByte5->setText(QString::number(currentBytes[5], 16)); + ui->txtByte6->setText(QString::number(currentBytes[6], 16)); + ui->txtByte7->setText(QString::number(currentBytes[7], 16)); + } int buses = ui->cbBuses->currentIndex(); for (int count = 0; count < ui->spinBurst->value(); count++) { - thisFrame.ID = currentID; - for (int i = 0; i < 8; i++) thisFrame.data[i] = currentBytes[i]; - if (currentID > 0x7FF) thisFrame.extended = true; - else thisFrame.extended = false; - thisFrame.bus = 0; //hard coded for now. TODO: do not hard code - thisFrame.len = ui->spinBytes->value(); + thisFrame.setFrameId(currentID); + QByteArray bytes(ui->spinBytes->value(), 0); + for (int i = 0; i < bytes.length(); i++) bytes[i] = currentBytes[i]; + thisFrame.setPayload(bytes); + if (currentID > 0x7FF) thisFrame.setExtendedFrameFormat(true); + else thisFrame.setExtendedFrameFormat(false); + thisFrame.bus = 0; //hard coded for now. TODO: do not hard code if (buses < (ui->cbBuses->count() - 1)) { @@ -205,12 +251,12 @@ void FuzzingWindow::calcNextID() if (rangeIDSelect) { int range = endID - startID; - if (range != 0) currentID = startID + qrand() % range; + if (range != 0) currentID = startID + QRandomGenerator::global()->bounded(range); else currentID = startID; } else //IDs by filter so pick a random selected ID from the filter list { - currentIdx = qrand() % selectedIDs.length(); + currentIdx = QRandomGenerator::global()->bounded(selectedIDs.length()); currentID = selectedIDs[currentIdx]; } } @@ -232,7 +278,7 @@ void FuzzingWindow::calcNextBitPattern() thisBit = bitGrid[byt * 8 + bit]; if (thisBit == 1) { - if ((qrand() % 2) == 1) currentBytes[byt] |= (1 << bit); + if ((QRandomGenerator::global()->bounded(2)) == 1) currentBytes[byt] |= (1 << bit); } if (thisBit == 2) currentBytes[byt] |= (1 << bit); } @@ -346,12 +392,12 @@ void FuzzingWindow::toggleFuzzing() if (rangeIDSelect) { int range = endID - startID; - if (range != 0) currentID = startID + qrand() % range; + if (range != 0) currentID = startID + QRandomGenerator::global()->bounded(range); else currentID = startID; } else //IDs by filter so pick a random selected ID from the filter list { - currentIdx = qrand() % selectedIDs.length(); + currentIdx = QRandomGenerator::global()->bounded(selectedIDs.length()); currentID = selectedIDs[currentIdx]; } } @@ -371,7 +417,7 @@ void FuzzingWindow::refreshIDList() for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - id = thisFrame.ID; + id = thisFrame.frameId(); if (!foundIDs.contains(id)) { foundIDs.append(id); diff --git a/re/fuzzingwindow.h b/re/fuzzingwindow.h index d920bc3..23a7ece 100644 --- a/re/fuzzingwindow.h +++ b/re/fuzzingwindow.h @@ -65,6 +65,7 @@ private: void calcNextBitPattern(); void redrawGrid(); bool eventFilter(QObject *obj, QEvent *event); + void changedDataByteText(int which, QString valu); }; #endif // FUZZINGWINDOW_H diff --git a/re/graphingwindow.cpp b/re/graphingwindow.cpp index d33d439..8849183 100644 --- a/re/graphingwindow.cpp +++ b/re/graphingwindow.cpp @@ -186,7 +186,7 @@ void GraphingWindow::updatedFrames(int numFrames) for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { thisFrame = modelFrames->at(i); - if (graphParams[j].ID == thisFrame.ID) + if (graphParams[j].ID == thisFrame.frameId()) { appendToGraph(graphParams[j], thisFrame, x, y); appendedToGraph = true; @@ -1075,15 +1075,15 @@ void GraphingWindow::appendToGraph(GraphParams ¶ms, CANFrame &frame, QVector { params.strideSoFar = 0; int64_t tempVal; //64 bit temp value. - tempVal = Utility::processIntegerSignal(frame.data, params.startBit, params.numBits, params.intelFormat, params.isSigned); //& params.mask; + tempVal = Utility::processIntegerSignal(frame.payload(), params.startBit, params.numBits, params.intelFormat, params.isSigned); //& params.mask; double xVal, yVal; if (secondsMode) { - xVal = ((double)(frame.timestamp) / 1000000.0 - params.xbias); + xVal = ((double)(frame.timeStamp().microSeconds()) / 1000000.0 - params.xbias); } else { - xVal = (frame.timestamp - params.xbias); + xVal = (frame.timeStamp().microSeconds() - params.xbias); } yVal = (tempVal * params.scale) + params.bias; params.x.append(xVal); @@ -1113,7 +1113,7 @@ void GraphingWindow::createGraph(GraphParams ¶ms, bool createGraphParam) for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - if (thisFrame.ID == params.ID && thisFrame.remote == false) frameCache.append(thisFrame); + if (thisFrame.frameId() == params.ID && thisFrame.frameType() == QCanBusFrame::DataFrame) frameCache.append(thisFrame); } //to fix weirdness where a graph that has no data won't be able to be edited, selected, or deleted properly @@ -1122,12 +1122,10 @@ void GraphingWindow::createGraph(GraphParams ¶ms, bool createGraphParam) if (frameCache.count() == 0) { CANFrame dummy; - dummy.ID = params.ID; + dummy.setFrameId(params.ID); dummy.bus = 0; - dummy.len = 8; - dummy.remote = false; - dummy.timestamp = 0; - for (int i = 0; i < 8; i++) dummy.data[i] = 0; + dummy.setPayload(QByteArray(8, 0)); + dummy.setFrameType(QCanBusFrame::DataFrame); frameCache.append(dummy); } @@ -1147,15 +1145,15 @@ void GraphingWindow::createGraph(GraphParams ¶ms, bool createGraphParam) for (int j = 0; j < numEntries; j++) { int k = j * params.stride; - tempVal = Utility::processIntegerSignal(frameCache[k].data, sBit, bits, intelFormat, isSigned); //& params.mask; + tempVal = Utility::processIntegerSignal(frameCache[k].payload(), sBit, bits, intelFormat, isSigned); //& params.mask; //qDebug() << tempVal; if (secondsMode) { - params.x[j] = (frameCache[k].timestamp) / 1000000.0; + params.x[j] = (frameCache[k].timeStamp().microSeconds()) / 1000000.0; } else { - params.x[j] = frameCache[k].timestamp; + params.x[j] = frameCache[k].timeStamp().microSeconds(); } params.y[j] = (tempVal * params.scale) + params.bias; if (params.y[j] < yminval) yminval = params.y[j]; diff --git a/re/graphingwindow.h b/re/graphingwindow.h index 0d4781e..20d35c1 100644 --- a/re/graphingwindow.h +++ b/re/graphingwindow.h @@ -71,7 +71,7 @@ private slots: void zoomOut(); signals: - void sendCenterTimeID(int32_t ID, double timestamp); + void sendCenterTimeID(uint32_t ID, double timestamp); private: Ui::GraphingWindow *ui; diff --git a/re/isotp_interpreterwindow.cpp b/re/isotp_interpreterwindow.cpp index 3aeb8fc..9d5e440 100644 --- a/re/isotp_interpreterwindow.cpp +++ b/re/isotp_interpreterwindow.cpp @@ -2,6 +2,7 @@ #include "ui_isotp_interpreterwindow.h" #include "mainwindow.h" #include "helpwindow.h" +#include "filterutility.h" ISOTP_InterpreterWindow::ISOTP_InterpreterWindow(const QVector *frames, QWidget *parent) : QDialog(parent), @@ -73,6 +74,7 @@ void ISOTP_InterpreterWindow::showEvent(QShowEvent* event) qApp->processEvents(); decoder->updatedFrames(-2); + //decoder->rapidFrames(nullptr, *modelFrames); progress.cancel(); @@ -81,7 +83,7 @@ void ISOTP_InterpreterWindow::showEvent(QShowEvent* event) void ISOTP_InterpreterWindow::closeEvent(QCloseEvent *event) { - Q_UNUSED(event); + Q_UNUSED(event) removeEventFilter(this); writeSettings(); } @@ -129,14 +131,14 @@ void ISOTP_InterpreterWindow::writeSettings() void ISOTP_InterpreterWindow::interpretCapturedFrames() { clearList(); - decoder->rapidFrames(nullptr, *modelFrames); + decoder->updatedFrames(-2); } void ISOTP_InterpreterWindow::listFilterItemChanged(QListWidgetItem *item) { if (item) { - int id = item->text().toInt(nullptr, 16); + int id = FilterUtility::getIdAsInt(item); bool state = item->checkState(); //qDebug() << id << "*" << state; idFilters[id] = state; @@ -194,7 +196,7 @@ void ISOTP_InterpreterWindow::updatedFrames(int numFrames) void ISOTP_InterpreterWindow::headerClicked(int logicalIndex) { ui->tableIsoFrames->setSortingEnabled(false); - ui->tableIsoFrames->sortByColumn(logicalIndex); + ui->tableIsoFrames->sortByColumn(logicalIndex, Qt::SortOrder::AscendingOrder); } void ISOTP_InterpreterWindow::showDetailView() @@ -208,17 +210,21 @@ void ISOTP_InterpreterWindow::showDetailView() msg = &messages[rowNum]; - if (msg->len != msg->data.length()) + const unsigned char *data = reinterpret_cast(msg->payload().constData()); + int dataLen = msg->payload().length(); + + if (msg->reportedLength != dataLen) { buildString.append("Message didn't have the correct number of bytes.\rExpected " - + QString::number(msg->len) + " got " - + QString::number(msg->data.length()) + "\r\r"); + + QString::number(msg->reportedLength) + " got " + + QString::number(dataLen) + "\r\r"); } buildString.append(tr("Raw Payload: ")); - for (int i = 0; i < messages[rowNum].data.count(); i++) + + for (int i = 0; i < dataLen; i++) { - buildString.append(Utility::formatNumber(messages[rowNum].data[i])); + buildString.append(Utility::formatNumber(data[i])); buildString.append(" "); } buildString.append("\r\r"); @@ -236,22 +242,6 @@ void ISOTP_InterpreterWindow::newUDSMessage(UDS_MESSAGE msg) buildText = ui->txtFrameDetails->toPlainText(); - /* - buildText.append("UDS Message:\n"); - if (msg.isErrorReply) - { - buildText.append("Error reply for service " + udsDecoder->getServiceShortDesc(msg.service)); - buildText.append("\nError Desc: " + udsDecoder->getNegativeResponseShort(msg.subFunc)); - } - else - { - if (msg.service < 0x3F || (msg.service > 0x7F && msg.service < 0xAF)) - buildText.append("Request for service " + udsDecoder->getServiceShortDesc(msg.service) + " Sub Func: " + QString::number(msg.subFunc)); - else - buildText.append("Response on service " + udsDecoder->getServiceShortDesc(msg.service - 0x40) + " Sub Func: " + QString::number(msg.subFunc)); - }*/ - - //Much more detailed analysis than the code above. You'll like it. buildText.append(udsDecoder->getDetailedMessageAnalysis(msg)); ui->txtFrameDetails->setPlainText(buildText); @@ -262,17 +252,18 @@ void ISOTP_InterpreterWindow::newISOMessage(ISOTP_MESSAGE msg) int rowNum; QString tempString; - if ((msg.len != msg.data.count()) && !ui->cbShowIncomplete->isChecked()) return; + const unsigned char *data = reinterpret_cast(msg.payload().constData()); + int dataLen = msg.payload().length(); - if (idFilters.find(msg.ID) == idFilters.end()) + if ((msg.reportedLength != dataLen) && !ui->cbShowIncomplete->isChecked()) return; + + if (idFilters.find(msg.frameId()) == idFilters.end()) { - idFilters.insert(msg.ID, true); + idFilters.insert(msg.frameId(), true); - QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(msg.ID, msg.extended), ui->listFilter); - listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag - listItem->setCheckState(Qt::Checked); + FilterUtility::createCheckableFilterItem(msg.frameId(), true, ui->listFilter); } - if (!idFilters[msg.ID]) return; + if (!idFilters[msg.frameId()]) return; messages.append(msg); rowNum = ui->tableIsoFrames->rowCount(); @@ -280,22 +271,19 @@ void ISOTP_InterpreterWindow::newISOMessage(ISOTP_MESSAGE msg) ui->tableIsoFrames->insertRow(rowNum); QTableWidgetItem *item = new QTableWidgetItem; - item->setData(Qt::EditRole, Utility::formatTimestamp(msg.timestamp)); + item->setData(Qt::EditRole, Utility::formatTimestamp(msg.timeStamp().microSeconds())); //ui->tableIsoFrames->setItem(rowNum, 0, (double)msg.timestamp, Utility::formatTimestamp(msg.timestamp))); ui->tableIsoFrames->setItem(rowNum, 0, item); - ui->tableIsoFrames->setItem(rowNum, 1, new QTableWidgetItem(QString::number(msg.ID, 16))); + ui->tableIsoFrames->setItem(rowNum, 1, new QTableWidgetItem(QString::number(msg.frameId(), 16))); ui->tableIsoFrames->setItem(rowNum, 2, new QTableWidgetItem(QString::number(msg.bus))); if (msg.isReceived) ui->tableIsoFrames->setItem(rowNum, 3, new QTableWidgetItem("Rx")); else ui->tableIsoFrames->setItem(rowNum, 3, new QTableWidgetItem("Tx")); - ui->tableIsoFrames->setItem(rowNum, 4, new QTableWidgetItem(QString::number(msg.len))); + ui->tableIsoFrames->setItem(rowNum, 4, new QTableWidgetItem(QString::number(msg.payload().length()))); - for (int i = 0; i < msg.data.count(); i++) + for (int i = 0; i < dataLen; i++) { - tempString.append(Utility::formatNumber(msg.data[i])); + tempString.append(Utility::formatNumber(data[i])); tempString.append(" "); } ui->tableIsoFrames->setItem(rowNum, 5, new QTableWidgetItem(tempString)); - } - - diff --git a/re/newgraphdialog.cpp b/re/newgraphdialog.cpp index 541458c..f9917c7 100644 --- a/re/newgraphdialog.cpp +++ b/re/newgraphdialog.cpp @@ -1,6 +1,7 @@ #include "newgraphdialog.h" #include "ui_newgraphdialog.h" #include +#include #include "utility.h" #include "helpwindow.h" @@ -15,13 +16,9 @@ NewGraphDialog::NewGraphDialog(DBCHandler *handler, QWidget *parent) : connect(ui->colorSwatch, SIGNAL(clicked(bool)), this, SLOT(colorSwatchClick())); connect(ui->btnAddGraph, SIGNAL(clicked(bool)), this, SLOT(addButtonClicked())); - // Seed the random generator with current time - QTime time = QTime::currentTime(); - qsrand((uint)time.msec()); - QPalette p = ui->colorSwatch->palette(); //using 160 instead of 255 so that colors are always at least a little dark - p.setColor(QPalette::Button, QColor(qrand() % 160,qrand() % 160,qrand() % 160)); + p.setColor(QPalette::Button, QColor(QRandomGenerator::global()->bounded(160),QRandomGenerator::global()->bounded(160), QRandomGenerator::global()->bounded(160))); ui->colorSwatch->setPalette(p); connect(ui->cbMessages, SIGNAL(currentIndexChanged(int)), this, SLOT(loadSignals(int))); diff --git a/re/rangestatewindow.cpp b/re/rangestatewindow.cpp index e51f264..498ff20 100644 --- a/re/rangestatewindow.cpp +++ b/re/rangestatewindow.cpp @@ -3,6 +3,7 @@ #include "mainwindow.h" #include "utility.h" #include "helpwindow.h" +#include "filterutility.h" RangeStateWindow::RangeStateWindow(const QVector *frames, QWidget *parent) : QDialog(parent), @@ -68,7 +69,7 @@ RangeStateWindow::RangeStateWindow(const QVector *frames, QWidget *par [=](QListWidgetItem *item) { bool isChecked = false; - int id = Utility::ParseStringToNum(item->text()); + int id = FilterUtility::getIdAsInt(item); if (item->checkState() == Qt::Checked) isChecked = true; idFilters[id] = isChecked; }); @@ -158,12 +159,10 @@ void RangeStateWindow::updatedFrames(int numFrames) for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) { thisFrame = modelFrames->at(i); - if (!idFilters.contains(thisFrame.ID)) + if (!idFilters.contains(thisFrame.frameId())) { - idFilters.insert(thisFrame.ID, true); - QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(thisFrame.ID, thisFrame.extended), ui->listFilter); - listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag - listItem->setCheckState(Qt::Checked); //default all filters to be set active + idFilters.insert(thisFrame.frameId(), true); + FilterUtility::createCheckableFilterItem(thisFrame.frameId(), true, ui->listFilter); } } } @@ -178,15 +177,11 @@ void RangeStateWindow::refreshFilterList() for (int i = 0; i < modelFrames->length(); i++) { - id = modelFrames->at(i).ID; + id = modelFrames->at(i).frameId(); if (!idFilters.contains(id)) { idFilters.insert(id, true); - QListWidgetItem* listItem; - if (id < 0x800) listItem = new QListWidgetItem(Utility::formatCANID(id, false), ui->listFilter); - else listItem = new QListWidgetItem(Utility::formatCANID(id, true), ui->listFilter); - listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag - listItem->setCheckState(Qt::Checked); //default all filters to be set active + FilterUtility::createCheckableFilterItem(id, true, ui->listFilter); } } @@ -223,7 +218,7 @@ void RangeStateWindow::recalcButton() id = iter.key(); for (int j = 0; j < modelFrames->count(); j++) { - if (modelFrames->at(j).ID == id) frameCache.append(modelFrames->at(j)); + if (modelFrames->at(j).frameId() == id) frameCache.append(modelFrames->at(j)); } //now we've got a list with all the same ID. Time to send it off for processing signalsFactory(); @@ -247,7 +242,7 @@ void RangeStateWindow::signalsFactory() int granularity = ui->spinGranularity->value(); int sigType = ui->cbSignalMode->currentIndex() + 1; int signedType = ui->cbSignedMode->currentIndex() + 1; - int maxBits = frameCache.at(0).len * 8; + int maxBits = frameCache.at(0).payload().length() * 8; int sens = ui->slideSensitivity->value(); for (int sigSize = maxSig; sigSize >= minSig; sigSize -= granularity) @@ -297,7 +292,7 @@ bool RangeStateWindow::processSignal(int startBit, int bitLength, int sensitivit for (i = 0; i < numFrames; i++) { - valu = Utility::processIntegerSignal(frameCache.at(i).data, startBit, bitLength, !bigEndian, isSigned); + valu = Utility::processIntegerSignal(frameCache.at(i).payload(), startBit, bitLength, !bigEndian, isSigned); if (valu < lowestValue) lowestValue = valu; if (valu > highestValue) highestValue = valu; } @@ -316,7 +311,7 @@ bool RangeStateWindow::processSignal(int startBit, int bitLength, int sensitivit return false; //doesn't range enough. for (i = 0; i < numFrames; i++) - scaledVals.append((int)((Utility::processIntegerSignal(frameCache.at(i).data, startBit, bitLength, !bigEndian, isSigned) - lowestValue))); + scaledVals.append((int)((Utility::processIntegerSignal(frameCache.at(i).payload(), startBit, bitLength, !bigEndian, isSigned) - lowestValue))); for (i = 1; i < numFrames; i++) { @@ -365,9 +360,9 @@ bool RangeStateWindow::processSignal(int startBit, int bitLength, int sensitivit { //createGraph(scaledVals); QString temp; - temp = "ID: " + QString::number(frameCache.at(0).ID, 16) + " startBit: " + QString::number(startBit) + " len: " + QString::number(bitLength); + temp = "ID: " + QString::number(frameCache.at(0).frameId(), 16) + " startBit: " + QString::number(startBit) + " len: " + QString::number(bitLength); int64_t foundSig; - foundSig = frameCache.at(0).ID; + foundSig = frameCache.at(0).frameId(); foundSig += (int64_t)startBit << 32; foundSig += (int64_t)bitLength << 40; @@ -474,12 +469,12 @@ void RangeStateWindow::clickedSignalList(int idx) for (int j = 0; j < modelFrames->count(); j++) { - if (modelFrames->at(j).ID == id) frameCache.append(modelFrames->at(j)); + if (modelFrames->at(j).frameId() == id) frameCache.append(modelFrames->at(j)); } int numFrames = frameCache.count(); QVector values; values.reserve(numFrames); - for (int i = 0; i < numFrames; i++) values.append((int)((Utility::processIntegerSignal(frameCache.at(i).data, startBit, bitLength, !isBigEndian, isSigned)))); + for (int i = 0; i < numFrames; i++) values.append((int)((Utility::processIntegerSignal(frameCache.at(i).payload(), startBit, bitLength, !isBigEndian, isSigned)))); createGraph(values); } diff --git a/re/sniffer/SnifferDelegate.cpp b/re/sniffer/SnifferDelegate.cpp index bd594a0..34cdd5e 100644 --- a/re/sniffer/SnifferDelegate.cpp +++ b/re/sniffer/SnifferDelegate.cpp @@ -116,7 +116,7 @@ void SnifferDelegate::paint(QPainter *painter, const QStyleOptionViewItem &optio painter->setOpacity(1.0); painter->setPen(QApplication::palette().color(QPalette::Text)); painter->setFont(mainFont); - painter->drawText(QRect(viewport.left(), viewport.top() + xSector + yOffset, xSpan, mainFontInfo->pixelSize()), Qt::AlignCenter, Utility::formatNumber(val)); + painter->drawText(QRect(viewport.left(), viewport.top() + xSector + yOffset, xSpan, mainFontInfo->pixelSize()), Qt::AlignCenter, Utility::formatNumber((unsigned char)val)); } QSize SnifferDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const diff --git a/re/sniffer/snifferitem.cpp b/re/sniffer/snifferitem.cpp index b86462b..5ab1a50 100644 --- a/re/sniffer/snifferitem.cpp +++ b/re/sniffer/snifferitem.cpp @@ -4,20 +4,25 @@ SnifferItem::SnifferItem(const CANFrame& pFrame, quint32 seq): - mID(pFrame.ID) + mID(pFrame.frameId()) { - for (int i = 0; i < 8; i++) { - mNotch[i] =0; + const unsigned char *data = reinterpret_cast(pFrame.payload().constData()); + int dataLen = pFrame.payload().length(); + + for (int i = 0; i < dataLen; i++) { + mNotch[i] = 0; mMarker.data[i] = 0; mMarker.dataTimestamp[i] = 0; - mCurrent.data[i] = pFrame.data[i]; + if (i < dataLen) mCurrent.data[i] = data[i]; + else mCurrent.data[i] = 0; mCurrent.dataTimestamp[i] = seq; } mLastMarker = mMarker; - mCurrent.len = pFrame.len; + mCurrent.len = dataLen; + /* that's dirty */ update(pFrame, seq, false); - update(pFrame, seq, false); + update(pFrame, seq, false); //anyone know why we're doing this twice?! } @@ -112,21 +117,24 @@ void SnifferItem::update(const CANFrame& pFrame, quint32 timeSeq, bool mute) mLastTime = mCurrentTime; mCurrSeqVal = timeSeq; + const unsigned char *data = reinterpret_cast(pFrame.payload().constData()); + int dataLen = pFrame.payload().length(); + /* copy new value */ - for (int i = 0; i < 8; i++) + for (int i = 0; i < dataLen; i++) { - maskedData = pFrame.data[i]; + maskedData = data[i]; if (mute) maskedData &= ~mNotch[i]; maskedCurr = mCurrent.data[i]; if (mute) maskedCurr &= ~mNotch[i]; if (maskedCurr != maskedData) { - mCurrent.data[i] = pFrame.data[i]; + mCurrent.data[i] = data[i]; mCurrent.dataTimestamp[i] = timeSeq; } } - mCurrent.len = pFrame.len; - mCurrentTime = pFrame.timestamp; + mCurrent.len = dataLen; + mCurrentTime = pFrame.timeStamp().microSeconds(); /* update marker */ //We "OR" our stored marker with the changed bits. diff --git a/re/sniffer/sniffermodel.cpp b/re/sniffer/sniffermodel.cpp index 2fb0b77..d700d9c 100644 --- a/re/sniffer/sniffermodel.cpp +++ b/re/sniffer/sniffermodel.cpp @@ -70,7 +70,7 @@ QVariant SnifferModel::data(const QModelIndex &index, int role) const int data = item->getData(col-tc::DATA_0); if(data >= 0) { - return QString("%1").arg(data, 2, 16, QLatin1Char('0')).toUpper(); + return QString("%1").arg((uint8_t)data, 2, 16, QLatin1Char('0')).toUpper(); } } break; @@ -300,20 +300,20 @@ void SnifferModel::update(CANConnection*, QVector& pFrames) { foreach(const CANFrame& frame, pFrames) { - if(!mMap.contains(frame.ID)) + if(!mMap.contains(frame.frameId())) { - int index = std::distance(mMap.begin(), mMap.lowerBound(frame.ID)); + int index = std::distance(mMap.begin(), mMap.lowerBound(frame.frameId())); /* add the frame */ beginInsertRows(QModelIndex(), index, index); - mMap[frame.ID] = new SnifferItem(frame, mTimeSequence); - mMap[frame.ID]->update(frame, mTimeSequence, mMuteNotched); + mMap[frame.frameId()] = new SnifferItem(frame, mTimeSequence); + mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched); endInsertRows(); - emit idChange(frame.ID, true); + emit idChange(frame.frameId(), true); } else //updateData - mMap[frame.ID]->update(frame, mTimeSequence, mMuteNotched); + mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched); } } diff --git a/re/temporalgraphwindow.cpp b/re/temporalgraphwindow.cpp index afd4d42..2b3ff4c 100644 --- a/re/temporalgraphwindow.cpp +++ b/re/temporalgraphwindow.cpp @@ -196,13 +196,13 @@ void TemporalGraphWindow::generateGraph() x.reserve(frameCount); y.reserve(frameCount); - xminval = xmaxval = modelFrames->at(0).timestamp / 1000000.0; - yminval = ymaxval = modelFrames->at(0).ID; + xminval = xmaxval = modelFrames->at(0).timeStamp().microSeconds() / 1000000.0; + yminval = ymaxval = modelFrames->at(0).frameId(); for (int i = 0; i < frameCount; i++) { - x.append(modelFrames->at(i).timestamp / 1000000.0); - y.append(modelFrames->at(i).ID); + x.append(modelFrames->at(i).timeStamp().microSeconds() / 1000000.0); + y.append(modelFrames->at(i).frameId()); if (x[i] > xmaxval) xmaxval = x[i]; if (x[i] < xminval) xminval = x[i]; if (y[i] > ymaxval) ymaxval = y[i]; @@ -246,8 +246,8 @@ void TemporalGraphWindow::generateGraph() for (int i = 0; i < frameCount; i++) { - int x = static_cast(((modelFrames->at(i).timestamp / 1000000.0) - xminval) * 4.0); - int y = static_cast(modelFrames->at(i).ID - yminval) / 30; + int x = static_cast(((modelFrames->at(i).timeStamp().microSeconds() / 1000000.0) - xminval) * 4.0); + int y = static_cast(modelFrames->at(i).frameId() - yminval) / 30; double val = colorMap->data()->cell(x, y); double inc; inc = 1 / (val + 1); //logarithmic decay diff --git a/re/udsscanwindow.cpp b/re/udsscanwindow.cpp index 081cfa7..cf060d8 100644 --- a/re/udsscanwindow.cpp +++ b/re/udsscanwindow.cpp @@ -237,8 +237,8 @@ void UDSScanWindow::scanUDS() for (id = startID; id <= endID; id++) { - test.ID = id; - test.data.clear(); + test.setFrameId( id ); + test.payload().clear(); if (ui->ckTester->isChecked()) { @@ -354,17 +354,19 @@ void UDSScanWindow::gotUDSReply(UDS_MESSAGE msg) int offset = ui->spinReplyOffset->value(); UDS_MESSAGE sentFrame; bool gotReply = false; + const unsigned char *data = reinterpret_cast(msg.payload().constData()); + int dataLen = msg.payload().length(); int numSending = sendingFrames.length(); if (numSending == 0) return; if (currIdx >= numSending) return; sentFrame = sendingFrames[currIdx]; - id = msg.ID; + id = msg.frameId(); - qDebug() << "UDS message ID " << QString::number(msg.ID,16) << " service: " << QString::number(msg.service, 16) << " subfunc: " << QString::number(msg.subFunc, 16); + qDebug() << "UDS message ID " << QString::number(msg.frameId(),16) << " service: " << QString::number(msg.service, 16) << " subfunc: " << QString::number(msg.subFunc, 16); - if ((id == (uint32_t)(sentFrame.ID + offset)) || ui->cbAllowAdaptiveOffset->isChecked()) + if ((id == (uint32_t)(sentFrame.frameId() + offset)) || ui->cbAllowAdaptiveOffset->isChecked()) { serviceShortName = udsHandler->getServiceShortDesc(sentFrame.service); if (serviceShortName.length() < 3) serviceShortName = QString::number(sentFrame.service, 16); @@ -374,10 +376,10 @@ void UDSScanWindow::gotUDSReply(UDS_MESSAGE msg) QTreeWidgetItem *nodePositive = new QTreeWidgetItem(); QString reply = "POSITIVE "; - for (int i = 0; i < msg.data.length(); i++) + for (int i = 0; i < dataLen; i++) { reply.append(" "); - reply.append(Utility::formatHexNum(msg.data[i])); + reply.append(Utility::formatHexNum(data[i])); } nodePositive->setText(0, reply); nodePositive->setForeground(0, QBrush(Qt::darkGreen)); @@ -387,12 +389,12 @@ void UDSScanWindow::gotUDSReply(UDS_MESSAGE msg) } else if ( msg.isErrorReply && (msg.service == sendingFrames[currIdx].service) ) { - if (msg.data.length()) + if (dataLen) { setupNodes(id); QTreeWidgetItem *nodeNegative = new QTreeWidgetItem(); qDebug() << ui->spinNumBytes->value(); - nodeNegative->setText(0, "NEGATIVE - " + udsHandler->getNegativeResponseShort(msg.data[0])); + nodeNegative->setText(0, "NEGATIVE - " + udsHandler->getNegativeResponseShort(data[0])); nodeNegative->setForeground(0, QBrush(Qt::darkRed)); nodeSubFunc->addChild(nodeNegative); nodeSubFunc->setForeground(0, QBrush(Qt::darkRed)); @@ -413,10 +415,10 @@ void UDSScanWindow::setupNodes(uint32_t replyID) if (serviceShortName.length() < 3) serviceShortName = QString::number(sendingFrames[currIdx].service, 16); QTreeWidgetItem *replyNode = nullptr; - if (!nodeID || nodeID->text(0) != Utility::formatHexNum(sendingFrames[currIdx].ID)) + if (!nodeID || nodeID->text(0) != Utility::formatHexNum(sendingFrames[currIdx].frameId())) { nodeID = new QTreeWidgetItem(); - nodeID->setText(0, Utility::formatHexNum(sendingFrames[currIdx].ID)); + nodeID->setText(0, Utility::formatHexNum(sendingFrames[currIdx].frameId())); ui->treeResults->addTopLevelItem(nodeID); nodeService = nullptr; } @@ -486,6 +488,9 @@ void UDSScanWindow::sendNextMsg() else { waitTimer->stop(); + udsHandler->setReception(false); + udsHandler->setProcessAllIDs(false); + udsHandler->setFlowCtrl(false); ui->btnScan->setText("Start Scan"); currentlyRunning = false; } diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 83c64d9..e877944 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -230,23 +230,21 @@ void CANScriptHelper::clearFilters() void CANScriptHelper::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSValue data) { CANFrame frame; - frame.extended = false; - frame.remote = false; - frame.ID = static_cast(id.toInt()); - frame.len = length.toUInt(); - if (frame.len > 8) frame.len = 8; + frame.setExtendedFrameFormat(false); + frame.setFrameId(static_cast(id.toInt())); + QByteArray bytes(length.toUInt(), 0); if (!data.isArray()) qDebug() << "data isn't an array"; - for (unsigned int i = 0; i < frame.len; i++) + for (int i = 0; i < bytes.length(); i++) { - frame.data[i] = (uint8_t)data.property(i).toInt(); + bytes[i] = (uint8_t)data.property(i).toInt(); } - + frame.setPayload(bytes); frame.bus = (uint32_t)bus.toInt(); //if (frame.bus > 1) frame.bus = 1; - if (frame.ID > 0x7FF) frame.extended = true; + if (frame.frameId() > 0x7FF) frame.setExtendedFrameFormat(true); qDebug() << "sending frame from script"; CANConManager::getInstance()->sendFrame(frame); @@ -256,15 +254,19 @@ void CANScriptHelper::gotTargettedFrame(const CANFrame &frame) { if (!gotFrameFunction.isCallable()) return; //nothing to do if we can't even call the function //qDebug() << "Got frame in script interface"; + + const unsigned char *data = reinterpret_cast(frame.payload().constData()); + int dataLen = frame.payload().length(); + for (int i = 0; i < filters.length(); i++) { - if (filters[i].checkFilter(frame.ID, frame.bus)) + if (filters[i].checkFilter(frame.frameId(), frame.bus)) { QJSValueList args; - args << frame.bus << frame.ID << frame.len; - QJSValue dataBytes = scriptEngine->newArray(frame.len); + args << frame.bus << frame.frameId() << frame.payload().length(); + QJSValue dataBytes = scriptEngine->newArray(dataLen); - for (unsigned int j = 0; j < frame.len; j++) dataBytes.setProperty(j, QJSValue(frame.data[j])); + for (int j = 0; j < dataLen; j++) dataBytes.setProperty(j, QJSValue(data[j])); args.append(dataBytes); gotFrameFunction.call(args); return; //as soon as one filter matches we jump out @@ -301,26 +303,30 @@ void ISOTPScriptHelper::setFilter(QJSValue id, QJSValue mask, QJSValue bus) handler->addFilter(busVal, idVal, maskVal); } -void ISOTPScriptHelper::sendISOTP(QJSValue bus, QJSValue id, QJSValue length, QJSValue data) +void ISOTPScriptHelper::sendISOTP(QJSValue bus, QJSValue id, QJSValue length, QJSValue dataBytes) { ISOTP_MESSAGE msg; - msg.extended = false; - msg.ID = id.toInt(); - msg.len = length.toUInt(); + QByteArray dataArray; + msg.setExtendedFrameFormat(false); + msg.setFrameId(id.toUInt()); + dataArray.resize(length.toInt()); - if (!data.isArray()) qDebug() << "data isn't an array"; + int dataLen = msg.payload().length(); - for (int i = 0; i < msg.len; i++) + if (!dataBytes.isArray()) qDebug() << "data isn't an array"; + + for (int i = 0; i < dataLen; i++) { - msg.data[i] = static_cast(data.property(i).toInt()); + dataArray[i] = static_cast(dataBytes.property(i).toInt()); } + msg.setPayload(dataArray); msg.bus = bus.toInt(); - if (msg.ID > 0x7FF) msg.extended = true; + if (msg.frameId() > 0x7FF) msg.setExtendedFrameFormat(true); qDebug() << "sending isotp message from script"; - handler->sendISOTPFrame(msg.bus, msg.ID, msg.data); + handler->sendISOTPFrame(msg.bus, msg.frameId(), msg.payload()); } void ISOTPScriptHelper::setRxCallback(QJSValue cb) @@ -335,10 +341,10 @@ void ISOTPScriptHelper::newISOMessage(ISOTP_MESSAGE msg) //qDebug() << "Got frame in script interface"; QJSValueList args; - args << msg.bus << msg.ID << msg.len; - QJSValue dataBytes = scriptEngine->newArray(static_cast(msg.len)); + args << msg.bus << msg.frameId() << msg.payload().length(); + QJSValue dataBytes = scriptEngine->newArray(static_cast(msg.payload().length())); - for (int j = 0; j < msg.len; j++) dataBytes.setProperty(static_cast(j), QJSValue(msg.data[j])); + for (int j = 0; j < msg.payload().length(); j++) dataBytes.setProperty(static_cast(j), QJSValue((unsigned char)msg.payload()[j])); args.append(dataBytes); gotFrameFunction.call(args); } @@ -375,25 +381,25 @@ void UDSScriptHelper::setFilter(QJSValue id, QJSValue mask, QJSValue bus) void UDSScriptHelper::sendUDS(QJSValue bus, QJSValue id, QJSValue service, QJSValue sublen, QJSValue subFunc, QJSValue length, QJSValue data) { UDS_MESSAGE msg; - msg.extended = false; - msg.ID = id.toUInt(); - msg.len = length.toUInt(); + QByteArray dataArray; + msg.setExtendedFrameFormat(false); + msg.setFrameId( id.toUInt() ); + dataArray.resize(length.toUInt()); msg.service = service.toUInt(); msg.subFuncLen = sublen.toUInt(); msg.subFunc = subFunc.toUInt(); if (!data.isArray()) qDebug() << "data isn't an array"; - msg.data.reserve(msg.len); - - for (int i = 0; i < msg.len; i++) + for (int i = 0; i < msg.payload().length(); i++) { - msg.data.append(static_cast(data.property(static_cast(i)).toInt())); + dataArray[i] = (static_cast(data.property(static_cast(i)).toInt())); } + msg.setPayload(dataArray); msg.bus = bus.toInt(); - if (msg.ID > 0x7FF) msg.extended = true; + if (msg.frameId() > 0x7FF) msg.setExtendedFrameFormat( true ); qDebug() << "sending UDS message from script"; @@ -408,15 +414,15 @@ void UDSScriptHelper::setRxCallback(QJSValue cb) void UDSScriptHelper::newUDSMessage(UDS_MESSAGE msg) { //qDebug() << "udsScriptHelper got a UDS message"; - qDebug() << "UDS script helper. Msg data len: " << msg.len; + qDebug() << "UDS script helper. Msg data len: " << msg.payload().length(); if (!gotFrameFunction.isCallable()) return; //nothing to do if we can't even call the function qDebug() << "Got frame in script interface"; QJSValueList args; - args << msg.bus << msg.ID << msg.service << msg.subFunc << msg.len; - QJSValue dataBytes = scriptEngine->newArray(static_cast(msg.len)); + args << msg.bus << msg.frameId() << msg.service << msg.subFunc << msg.payload().length(); + QJSValue dataBytes = scriptEngine->newArray(static_cast(msg.payload().length())); - for (int j = 0; j < msg.data.length(); j++) dataBytes.setProperty(static_cast(j), QJSValue(msg.data[j])); + for (int j = 0; j < msg.payload().length(); j++) dataBytes.setProperty(static_cast(j), QJSValue((unsigned char)msg.payload()[j])); args.append(dataBytes); gotFrameFunction.call(args); } diff --git a/scriptingwindow.cpp b/scriptingwindow.cpp index fef3ca7..46ffa2b 100644 --- a/scriptingwindow.cpp +++ b/scriptingwindow.cpp @@ -18,7 +18,6 @@ ScriptingWindow::ScriptingWindow(const QVector *frames, QWidget *paren editor = new JSEdit(); editor->setFrameShape(JSEdit::NoFrame); editor->setWordWrapMode(QTextOption::NoWrap); - editor->setTabStopWidth(4); editor->setEnabled(false); editor->setFont(QFont("Monospace", 12)); editor->show(); diff --git a/signalviewerwindow.cpp b/signalviewerwindow.cpp index a093bee..c401b49 100644 --- a/signalviewerwindow.cpp +++ b/signalviewerwindow.cpp @@ -71,7 +71,7 @@ void SignalViewerWindow::processFrame(CANFrame &frame) { sig = signalList.at(i); if (!sig) return; - if (sig->parentMessage->ID == frame.ID) + if (sig->parentMessage->ID == frame.frameId()) { if (sig->processAsText(frame, sigString, false)) //if true we could interpret the signal so update it in the list { diff --git a/simplecrypt.cpp b/simplecrypt.cpp new file mode 100644 index 0000000..79a16ba --- /dev/null +++ b/simplecrypt.cpp @@ -0,0 +1,252 @@ +/* +Copyright (c) 2011, Andre Somers +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Rathenau Instituut, Andre Somers nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR #######; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "simplecrypt.h" +#include +#include +#include +#include +#include +#include + +SimpleCrypt::SimpleCrypt(): + m_key(0), + m_compressionMode(CompressionAuto), + m_protectionMode(ProtectionChecksum), + m_lastError(ErrorNoError) +{ + qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF)); +} + +SimpleCrypt::SimpleCrypt(quint64 key): + m_key(key), + m_compressionMode(CompressionAuto), + m_protectionMode(ProtectionChecksum), + m_lastError(ErrorNoError) +{ + qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF)); + splitKey(); +} + +void SimpleCrypt::setKey(quint64 key) +{ + m_key = key; + splitKey(); +} + +void SimpleCrypt::splitKey() +{ + m_keyParts.clear(); + m_keyParts.resize(8); + for (int i=0;i<8;i++) { + quint64 part = m_key; + for (int j=i; j>0; j--) + part = part >> 8; + part = part & 0xff; + m_keyParts[i] = static_cast(part); + } +} + +QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext) +{ + QByteArray plaintextArray = plaintext.toUtf8(); + return encryptToByteArray(plaintextArray); +} + +QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext) +{ + if (m_keyParts.isEmpty()) { + qWarning() << "No key set."; + m_lastError = ErrorNoKeySet; + return QByteArray(); + } + + + QByteArray ba = plaintext; + + CryptoFlags flags = CryptoFlagNone; + if (m_compressionMode == CompressionAlways) { + ba = qCompress(ba, 9); //maximum compression + flags |= CryptoFlagCompression; + } else if (m_compressionMode == CompressionAuto) { + QByteArray compressed = qCompress(ba, 9); + if (compressed.count() < ba.count()) { + ba = compressed; + flags |= CryptoFlagCompression; + } + } + + QByteArray integrityProtection; + if (m_protectionMode == ProtectionChecksum) { + flags |= CryptoFlagChecksum; + QDataStream s(&integrityProtection, QIODevice::WriteOnly); + s << qChecksum(ba.constData(), ba.length()); + } else if (m_protectionMode == ProtectionHash) { + flags |= CryptoFlagHash; + QCryptographicHash hash(QCryptographicHash::Sha1); + hash.addData(ba); + + integrityProtection += hash.result(); + } + + //prepend a random char to the string + char randomChar = char(qrand() & 0xFF); + ba = randomChar + integrityProtection + ba; + + int pos(0); + char lastChar(0); + + int cnt = ba.count(); + + while (pos < cnt) { + ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar; + lastChar = ba.at(pos); + ++pos; + } + + QByteArray resultArray; + resultArray.append(char(0x03)); //version for future updates to algorithm + resultArray.append(char(flags)); //encryption flags + resultArray.append(ba); + + m_lastError = ErrorNoError; + return resultArray; +} + +QString SimpleCrypt::encryptToString(const QString& plaintext) +{ + QByteArray plaintextArray = plaintext.toUtf8(); + QByteArray cypher = encryptToByteArray(plaintextArray); + QString cypherString = QString::fromLatin1(cypher.toBase64()); + return cypherString; +} + +QString SimpleCrypt::encryptToString(QByteArray plaintext) +{ + QByteArray cypher = encryptToByteArray(plaintext); + QString cypherString = QString::fromLatin1(cypher.toBase64()); + return cypherString; +} + +QString SimpleCrypt::decryptToString(const QString &cyphertext) +{ + QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1()); + QByteArray plaintextArray = decryptToByteArray(cyphertextArray); + QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size()); + + return plaintext; +} + +QString SimpleCrypt::decryptToString(QByteArray cypher) +{ + QByteArray ba = decryptToByteArray(cypher); + QString plaintext = QString::fromUtf8(ba, ba.size()); + + return plaintext; +} + +QByteArray SimpleCrypt::decryptToByteArray(const QString& cyphertext) +{ + QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1()); + QByteArray ba = decryptToByteArray(cyphertextArray); + + return ba; +} + +QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher) +{ + if (m_keyParts.isEmpty()) { + qWarning() << "No key set."; + m_lastError = ErrorNoKeySet; + return QByteArray(); + } + + QByteArray ba = cypher; + + if( cypher.count() < 3 ) + return QByteArray(); + + char version = ba.at(0); + + if (version !=3) { //we only work with version 3 + m_lastError = ErrorUnknownVersion; + qWarning() << "Invalid version or not a cyphertext."; + return QByteArray(); + } + + CryptoFlags flags = CryptoFlags(ba.at(1)); + + ba = ba.mid(2); + int pos(0); + int cnt(ba.count()); + char lastChar = 0; + + while (pos < cnt) { + char currentChar = ba[pos]; + ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8); + lastChar = currentChar; + ++pos; + } + + ba = ba.mid(1); //chop off the random number at the start + + bool integrityOk(true); + if (flags.testFlag(CryptoFlagChecksum)) { + if (ba.length() < 2) { + m_lastError = ErrorIntegrityFailed; + return QByteArray(); + } + quint16 storedChecksum; + { + QDataStream s(&ba, QIODevice::ReadOnly); + s >> storedChecksum; + } + ba = ba.mid(2); + quint16 checksum = qChecksum(ba.constData(), ba.length()); + integrityOk = (checksum == storedChecksum); + } else if (flags.testFlag(CryptoFlagHash)) { + if (ba.length() < 20) { + m_lastError = ErrorIntegrityFailed; + return QByteArray(); + } + QByteArray storedHash = ba.left(20); + ba = ba.mid(20); + QCryptographicHash hash(QCryptographicHash::Sha1); + hash.addData(ba); + integrityOk = (hash.result() == storedHash); + } + + if (!integrityOk) { + m_lastError = ErrorIntegrityFailed; + return QByteArray(); + } + + if (flags.testFlag(CryptoFlagCompression)) + ba = qUncompress(ba); + + m_lastError = ErrorNoError; + return ba; +} diff --git a/simplecrypt.h b/simplecrypt.h new file mode 100644 index 0000000..e275639 --- /dev/null +++ b/simplecrypt.h @@ -0,0 +1,225 @@ +/* +Copyright (c) 2011, Andre Somers +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Rathenau Instituut, Andre Somers nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR #######; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef SIMPLECRYPT_H +#define SIMPLECRYPT_H +#include +#include +#include + +/** + @short Simple encryption and decryption of strings and byte arrays + + This class provides a simple implementation of encryption and decryption + of strings and byte arrays. + + @warning The encryption provided by this class is NOT strong encryption. It may + help to shield things from curious eyes, but it will NOT stand up to someone + determined to break the encryption. Don't say you were not warned. + + The class uses a 64 bit key. Simply create an instance of the class, set the key, + and use the encryptToString() method to calculate an encrypted version of the input string. + To decrypt that string again, use an instance of SimpleCrypt initialized with + the same key, and call the decryptToString() method with the encrypted string. If the key + matches, the decrypted version of the string will be returned again. + + If you do not provide a key, or if something else is wrong, the encryption and + decryption function will return an empty string or will return a string containing nonsense. + lastError() will return a value indicating if the method was succesful, and if not, why not. + + SimpleCrypt is prepared for the case that the encryption and decryption + algorithm is changed in a later version, by prepending a version identifier to the cypertext. + */ +class SimpleCrypt +{ +public: + /** + CompressionMode describes if compression will be applied to the data to be + encrypted. + */ + enum CompressionMode { + CompressionAuto, /*!< Only apply compression if that results in a shorter plaintext. */ + CompressionAlways, /*!< Always apply compression. Note that for short inputs, a compression may result in longer data */ + CompressionNever /*!< Never apply compression. */ + }; + /** + IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data + or wrong decryption keys. + + Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This + increases the length of the resulting cypertext, but makes it possible to check if the plaintext + appears to be valid after decryption. + */ + enum IntegrityProtectionMode { + ProtectionNone, /*!< The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance. */ + ProtectionChecksum,/*!< A simple checksum is used to verify that the data is in order. If not, an empty string is returned. */ + ProtectionHash /*!< A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check */ + }; + /** + Error describes the type of error that occured. + */ + enum Error { + ErrorNoError, /*!< No error occurred. */ + ErrorNoKeySet, /*!< No key was set. You can not encrypt or decrypt without a valid key. */ + ErrorUnknownVersion, /*!< The version of this data is unknown, or the data is otherwise not valid. */ + ErrorIntegrityFailed, /*!< The integrity check of the data failed. Perhaps the wrong key was used. */ + }; + + /** + Constructor. + + Constructs a SimpleCrypt instance without a valid key set on it. + */ + SimpleCrypt(); + /** + Constructor. + + Constructs a SimpleCrypt instance and initializes it with the given @arg key. + */ + explicit SimpleCrypt(quint64 key); + + /** + (Re-) initializes the key with the given @arg key. + */ + void setKey(quint64 key); + /** + Returns true if SimpleCrypt has been initialized with a key. + */ + bool hasKey() const {return !m_keyParts.isEmpty();} + + /** + Sets the compression mode to use when encrypting data. The default mode is Auto. + + Note that decryption is not influenced by this mode, as the decryption recognizes + what mode was used when encrypting. + */ + void setCompressionMode(CompressionMode mode) {m_compressionMode = mode;} + /** + Returns the CompressionMode that is currently in use. + */ + CompressionMode compressionMode() const {return m_compressionMode;} + + /** + Sets the integrity mode to use when encrypting data. The default mode is Checksum. + + Note that decryption is not influenced by this mode, as the decryption recognizes + what mode was used when encrypting. + */ + void setIntegrityProtectionMode(IntegrityProtectionMode mode) {m_protectionMode = mode;} + /** + Returns the IntegrityProtectionMode that is currently in use. + */ + IntegrityProtectionMode integrityProtectionMode() const {return m_protectionMode;} + + /** + Returns the last error that occurred. + */ + Error lastError() const {return m_lastError;} + + /** + Encrypts the @arg plaintext string with the key the class was initialized with, and returns + a cyphertext the result. The result is a base64 encoded version of the binary array that is the + actual result of the string, so it can be stored easily in a text format. + */ + QString encryptToString(const QString& plaintext) ; + /** + Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns + a cyphertext the result. The result is a base64 encoded version of the binary array that is the + actual result of the encryption, so it can be stored easily in a text format. + */ + QString encryptToString(QByteArray plaintext) ; + /** + Encrypts the @arg plaintext string with the key the class was initialized with, and returns + a binary cyphertext in a QByteArray the result. + + This method returns a byte array, that is useable for storing a binary format. If you need + a string you can store in a text file, use encryptToString() instead. + */ + QByteArray encryptToByteArray(const QString& plaintext) ; + /** + Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns + a binary cyphertext in a QByteArray the result. + + This method returns a byte array, that is useable for storing a binary format. If you need + a string you can store in a text file, use encryptToString() instead. + */ + QByteArray encryptToByteArray(QByteArray plaintext) ; + + /** + Decrypts a cyphertext string encrypted with this class with the set key back to the + plain text version. + + If an error occured, such as non-matching keys between encryption and decryption, + an empty string or a string containing nonsense may be returned. + */ + QString decryptToString(const QString& cyphertext) ; + /** + Decrypts a cyphertext string encrypted with this class with the set key back to the + plain text version. + + If an error occured, such as non-matching keys between encryption and decryption, + an empty string or a string containing nonsense may be returned. + */ + QByteArray decryptToByteArray(const QString& cyphertext) ; + /** + Decrypts a cyphertext binary encrypted with this class with the set key back to the + plain text version. + + If an error occured, such as non-matching keys between encryption and decryption, + an empty string or a string containing nonsense may be returned. + */ + QString decryptToString(QByteArray cypher) ; + /** + Decrypts a cyphertext binary encrypted with this class with the set key back to the + plain text version. + + If an error occured, such as non-matching keys between encryption and decryption, + an empty string or a string containing nonsense may be returned. + */ + QByteArray decryptToByteArray(QByteArray cypher) ; + + //enum to describe options that have been used for the encryption. Currently only one, but + //that only leaves room for future extensions like adding a cryptographic hash... + enum CryptoFlag{CryptoFlagNone = 0, + CryptoFlagCompression = 0x01, + CryptoFlagChecksum = 0x02, + CryptoFlagHash = 0x04 + }; + Q_DECLARE_FLAGS(CryptoFlags, CryptoFlag); +private: + + void splitKey(); + + quint64 m_key; + QVector m_keyParts; + CompressionMode m_compressionMode; + IntegrityProtectionMode m_protectionMode; + Error m_lastError; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(SimpleCrypt::CryptoFlags) + +#endif // SimpleCrypt_H diff --git a/ui/dbccomparatorwindow.ui b/ui/dbccomparatorwindow.ui new file mode 100644 index 0000000..6f736d6 --- /dev/null +++ b/ui/dbccomparatorwindow.ui @@ -0,0 +1,131 @@ + + + DBCComparatorWindow + + + + 0 + 0 + 720 + 631 + + + + DBC Comparator + + + + + + + + + + + 16 + + + + Side 1 + + + Qt::AlignCenter + + + + + + + TextLabel + + + + + + + Load New File + + + + + + + + + Qt::Vertical + + + + + + + + + + 16 + + + + Side 2 + + + Qt::AlignCenter + + + + + + + TextLabel + + + + + + + + + Load A File + + + + + + + + + + + + + Qt::Horizontal + + + + + + + + 1 + + + + + + + + Save Details to File + + + + + + + btnDBCFile1 + btnDBCFile2 + treeDetails + btnSaveDetails + + + + diff --git a/ui/dbcmaineditor.ui b/ui/dbcmaineditor.ui index dedb4a2..dfc98ce 100644 --- a/ui/dbcmaineditor.ui +++ b/ui/dbcmaineditor.ui @@ -13,37 +13,177 @@ DBC Editing Window - + - + - + - Nodes + New Node + + + + :/icons/images/node_new.png:/icons/images/node_new.png + + + Qt::ToolButtonTextUnderIcon - + + + false + + + New Message + + + + :/icons/images/message_new.png:/icons/images/message_new.png + + + Qt::ToolButtonTextUnderIcon + + + + + + + false + + + New Signal + + + + :/icons/images/signal_new.png:/icons/images/signal_new.png + + + Qt::ToolButtonTextUnderIcon + + + + + + + false + + + Delete + + + + :/icons/images/skull.png:/icons/images/skull.png + + + Qt::ToolButtonTextUnderIcon + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + false + + + QAbstractItemView::NoDragDrop + + + Qt::IgnoreAction + + + QAbstractItemView::SingleSelection + + + 28 + + + true + + + false + + + + 1 + + + - - - Messages - - + + + + + Find: + + + + + + + + + + Search + + + + - + + + + + Search Results: 0 of 0 + + + + + + + Next + + + + + + + Previous + + + + - + + + diff --git a/ui/dbcmessageeditor.ui b/ui/dbcmessageeditor.ui new file mode 100644 index 0000000..7ce6554 --- /dev/null +++ b/ui/dbcmessageeditor.ui @@ -0,0 +1,120 @@ + + + DBCMessageEditor + + + + 0 + 0 + 311 + 371 + + + + Message Editor + + + + + + + + Frame ID: + + + + + + + + + + + + + Message Name: + + + + + + + + + + Frame Length: + + + + + + + Text Color: + + + + + + + Background Color: + + + + + + + Comments: + + + + + + + + + + Sending Node: + + + + + + + true + + + + + + + Set + + + + + + + Set + + + + + + + + + Sample Colored Output: + + + Qt::AlignCenter + + + + + + + + + + + diff --git a/ui/dbcnodeeditor.ui b/ui/dbcnodeeditor.ui new file mode 100644 index 0000000..f56bd35 --- /dev/null +++ b/ui/dbcnodeeditor.ui @@ -0,0 +1,45 @@ + + + DBCNodeEditor + + + + 0 + 0 + 311 + 88 + + + + Node Editor + + + + + + + + Node Name: + + + + + + + + + + Comments: + + + + + + + + + + + + + diff --git a/ui/dbcsignaleditor.ui b/ui/dbcsignaleditor.ui index d2ea6aa..4a1d45c 100644 --- a/ui/dbcsignaleditor.ui +++ b/ui/dbcsignaleditor.ui @@ -6,7 +6,7 @@ 0 0 - 1239 + 967 644 @@ -15,10 +15,7 @@ - - - - + @@ -210,7 +207,7 @@ - Value Table For Selected Signal: + Value Table: @@ -228,7 +225,6 @@ - signalsList txtName rbNotMulti rbMultiplexed diff --git a/ui/fuzzingwindow.ui b/ui/fuzzingwindow.ui index cef5ff5..ba6e22f 100644 --- a/ui/fuzzingwindow.ui +++ b/ui/fuzzingwindow.ui @@ -13,7 +13,7 @@ Fuzzing Window - + @@ -248,6 +248,151 @@ + + + + Byte Values (Always in hexadecimal) + + + Qt::AlignCenter + + + + + + + + + + 75 + true + + + + 0 + + + Qt::PlainText + + + + + + + + + + + 75 + true + + + + 1 + + + + + + + + + + + 75 + true + + + + 2 + + + + + + + + + + + 75 + true + + + + 3 + + + + + + + + + + + 75 + true + + + + 4 + + + + + + + + + + + 75 + true + + + + 5 + + + + + + + + + + + 75 + true + + + + 6 + + + + + + + + + + + 75 + true + + + + 7 + + + + + + + + diff --git a/ui/mainsettingsdialog.ui b/ui/mainsettingsdialog.ui index cce67e8..678280e 100644 --- a/ui/mainsettingsdialog.ui +++ b/ui/mainsettingsdialog.ui @@ -7,7 +7,7 @@ 0 0 965 - 591 + 668 @@ -287,10 +287,10 @@ - false + true - Remote Connection: + MQTT Remote CAN Settings: @@ -300,6 +300,9 @@ + + + @@ -307,16 +310,30 @@ - - - - - + + - Auto start remote hosting + User Name: + + + + + + + + + + Password + + + + + + + QLineEdit::Password @@ -371,7 +388,6 @@ cbInfoAutoExpand lineRemoteHost lineRemotePort - cbAutoStartRemote diff --git a/ui/mainwindow.ui b/ui/mainwindow.ui index 1bda8d1..c50a4ae 100644 --- a/ui/mainwindow.ui +++ b/ui/mainwindow.ui @@ -191,6 +191,23 @@ + + + + true + + + Overwrite Mode + + + + + + + Qt::Horizontal + + + @@ -199,12 +216,23 @@ - - - true - + - Overwrite Mode + Expand All Rows + + + + + + + Collapse All Rows + + + + + + + Qt::Horizontal @@ -265,7 +293,7 @@ 0 0 800 - 22 + 23 @@ -276,6 +304,7 @@ + @@ -503,6 +532,11 @@ Temporal Graph + + + DBC Comparison + + diff --git a/ui/newconnectiondialog.ui b/ui/newconnectiondialog.ui index de55127..26eeb74 100644 --- a/ui/newconnectiondialog.ui +++ b/ui/newconnectiondialog.ui @@ -6,8 +6,8 @@ 0 0 - 356 - 282 + 359 + 291 @@ -33,7 +33,7 @@ - + false @@ -46,7 +46,14 @@ - Network connection + Network Connection + + + + + + + MQTT Connection diff --git a/utility.h b/utility.h index e9f8b65..ab2d44d 100644 --- a/utility.h +++ b/utility.h @@ -179,18 +179,23 @@ public: return (value1 * (1.0 - samplePoint)) + (value2 * samplePoint); } - static int64_t processIntegerSignal(const uint8_t *data, int startBit, int sigSize, bool littleEndian, bool isSigned) + static int64_t processIntegerSignal(const QByteArray data, int startBit, int sigSize, bool littleEndian, bool isSigned) { int64_t result = 0; int bit; + int maxBytes = (startBit + sigSize) / 8; + if (data.size() < maxBytes) return 0; + if (littleEndian) { bit = startBit; for (int bitpos = 0; bitpos < sigSize; bitpos++) { if (bit < 64) { + int bytePos = bit / 8; + if (bytePos >= data.count()) return 0; //error! if (data[bit / 8] & (1 << (bit % 8))) result += (1ULL << bitpos); } @@ -203,6 +208,8 @@ public: for (int bitpos = 0; bitpos < sigSize; bitpos++) { if (bit < 64) { + int bytePos = bit / 8; + if (bytePos >= data.count()) return 0; //error! if (data[bit / 8] & (1 << (bit % 8))) result += (1ULL << (sigSize - bitpos - 1)); }