From e7ded7737a00ac3a5b5668d1d3a321d77b8936eb Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sat, 19 Mar 2016 21:40:21 -0400 Subject: [PATCH 01/86] Preliminary pass at converting connection system to use a more generic approach and support more devices and multiple devices at the same time. --- SavvyCAN.pro | 10 +- canconnection.cpp | 128 +++++++++++++++++++ canconnection.h | 74 +++++++++++ canconnectioncontainer.cpp | 15 +++ canconnectioncontainer.h | 21 ++++ canconnectionmodel.cpp | 130 +++++++++++++++++++ canconnectionmodel.h | 33 +++++ connectionwindow.cpp | 166 +++++++++++++----------- connectionwindow.h | 26 ++-- connectionwindow.ui | 252 ++++++++++++++++++++++++------------- firmwareuploaderwindow.cpp | 6 +- mainwindow.cpp | 67 ++-------- mainwindow.h | 6 - serialworker.cpp | 59 +++++---- serialworker.h | 33 ++--- 15 files changed, 739 insertions(+), 287 deletions(-) create mode 100644 canconnection.cpp create mode 100644 canconnection.h create mode 100644 canconnectioncontainer.cpp create mode 100644 canconnectioncontainer.h create mode 100644 canconnectionmodel.cpp create mode 100644 canconnectionmodel.h diff --git a/SavvyCAN.pro b/SavvyCAN.pro index acc556d..fba0533 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -48,7 +48,10 @@ SOURCES += main.cpp\ udsscanwindow.cpp \ can_structs.cpp \ isotp_interpreterwindow.cpp \ - isotp_decoder.cpp + isotp_decoder.cpp \ + canconnectionmodel.cpp \ + canconnection.cpp \ + canconnectioncontainer.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -83,7 +86,10 @@ HEADERS += mainwindow.h \ fuzzingwindow.h \ udsscanwindow.h \ isotp_interpreterwindow.h \ - isotp_decoder.h + isotp_decoder.h \ + canconnectionmodel.h \ + canconnection.h \ + canconnectioncontainer.h FORMS += mainwindow.ui \ graphingwindow.ui \ diff --git a/canconnection.cpp b/canconnection.cpp new file mode 100644 index 0000000..c26c507 --- /dev/null +++ b/canconnection.cpp @@ -0,0 +1,128 @@ +#include "canconnection.h" + +CAN_Bus::CAN_Bus() +{ + speed = 250000; + listenOnly = false; + singleWire = false; + active = false; + connection = NULL; + busNum = 0; +} + +void CAN_Bus::setSpeed(int newSpeed) +{ + speed = newSpeed; +} + +void CAN_Bus::setListenOnly(bool mode) +{ + listenOnly = mode; +} + +void CAN_Bus::setSingleWire(bool mode) +{ + singleWire = mode; +} + +void CAN_Bus::setEnabled(bool mode) +{ + active = mode; +} + +void CAN_Bus::setConnection(CANConnection *conn) +{ + connection = conn; +} + +void CAN_Bus::setBusNum(int num) +{ + busNum = num; +} + +int CAN_Bus::getSpeed() +{ + return speed; +} + +int CAN_Bus::getBusNum() +{ + return busNum; +} + +bool CAN_Bus::isListenOnly() +{ + return listenOnly; +} + +bool CAN_Bus::isSingleWire() +{ + return singleWire; +} + +bool CAN_Bus::isActive() +{ + return active; +} + +CANConnection* CAN_Bus::getConnection() +{ + return connection; +} + +CANConnection::CANConnection(CANFrameModel *pModel, int base) +{ + model = pModel; + numBuses = getNumBuses(); + busBase = base; +} + +int CANConnection::getNumBuses() +{ + return 1; +} + +int CANConnection::getBusBase() +{ + return busBase; +} + +QString CANConnection::getConnTypeName() +{ + return QString("Generic"); +} + +QString CANConnection::getConnPortName() +{ + return portName; +} + +void CANConnection::run() +{ + +} + +void CANConnection::sendFrame(const CANFrame * frame) +{ + +} + +void CANConnection::sendFrameBatch(const QList *frames) +{ + +} + +void CANConnection::updatePortName(QString portName) +{ + this->portName = portName; +} + +void CANConnection::stopFrameCapture(int bus) +{ + +} + +void CANConnection::startFrameCapture(int bus) +{ + +} diff --git a/canconnection.h b/canconnection.h new file mode 100644 index 0000000..258378c --- /dev/null +++ b/canconnection.h @@ -0,0 +1,74 @@ +#ifndef CANCONNECTION_H +#define CANCONNECTION_H + +#include +#include +#include "can_structs.h" +#include "canframemodel.h" + +class CANConnection; + +class CAN_Bus +{ +public: + CAN_Bus(); + int busNum; + int speed; + bool listenOnly; + bool singleWire; + bool active; //is this bus turned on? + CANConnection *connection; + + void setSpeed(int); // new speed + void setListenOnly(bool); //bool for whether to only listen + void setSingleWire(bool); //bool for whether to use single wire mode + void setEnabled(bool); //whether this bus should be enabled or not. + void setConnection(CANConnection *); + void setBusNum(int); + int getSpeed(); + int getBusNum(); + bool isListenOnly(); + bool isSingleWire(); + bool isActive(); + CANConnection *getConnection(); +}; + +class CANConnection : public QObject +{ + Q_OBJECT + +public: + CANConnection(CANFrameModel *, int); + virtual int getNumBuses(); + int getBusBase(); + QString getConnTypeName(); + QString getConnPortName(); + +signals: + void error(const QString &); + void frameUpdateRapid(int); + void frameUpdate(int); + void connectionSuccess(); + void connectionFailure(); + void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte (listen only, single wire, etc) + +public slots: + virtual void run(); + virtual void sendFrame(const CANFrame *); + virtual void sendFrameBatch(const QList *); + virtual void updatePortName(QString); //string version of the port to connect to. This base doesnt know a thing about this value + virtual void stopFrameCapture(int); //pass bus number + virtual void startFrameCapture(int); //pass bus number. Only if stopped. Defaults to started anyway + //virtual void updateBusSettings(int); //bus number that was updated. + +protected: + bool quit; + int numBuses; + int busBase; //first bus this class is supposed to handle + QString portName; //for easy access later on + QString connType; //what kind of connection this is (socketcan, kvaser, etc) + bool isConnected; //is the whole device connected? (Is the code connected to the device itself) + CANFrameModel *model; +}; + +#endif // CANCONNECTION_H diff --git a/canconnectioncontainer.cpp b/canconnectioncontainer.cpp new file mode 100644 index 0000000..15d9baa --- /dev/null +++ b/canconnectioncontainer.cpp @@ -0,0 +1,15 @@ +#include "canconnectioncontainer.h" + +CANConnectionContainer::CANConnectionContainer(CANConnection *conn) +{ + thread = new QThread(); + connection = conn; + connection->moveToThread(thread); +} + +CANConnectionContainer::~CANConnectionContainer() +{ + //have to stop the actual execution first before deleting + delete thread; + delete connection; +} diff --git a/canconnectioncontainer.h b/canconnectioncontainer.h new file mode 100644 index 0000000..eb90066 --- /dev/null +++ b/canconnectioncontainer.h @@ -0,0 +1,21 @@ +#ifndef CANCONNECTIONCONTAINER_H +#define CANCONNECTIONCONTAINER_H + +#include "canconnection.h" +#include + +class CANConnectionContainer +{ +public: + CANConnectionContainer(CANConnection *conn); + ~CANConnectionContainer(); + + CANConnection* getRef(); + + +private: + CANConnection *connection; + QThread *thread; +}; + +#endif // CANCONNECTIONCONTAINER_H diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp new file mode 100644 index 0000000..02063b6 --- /dev/null +++ b/canconnectionmodel.cpp @@ -0,0 +1,130 @@ +#include "canconnectionmodel.h" + +CANConnectionModel::CANConnectionModel(QObject *parent) + : QAbstractTableModel(parent) +{ +} + +QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role != Qt::DisplayRole) + return QVariant(); + + if (orientation == Qt::Horizontal) + { + switch (section) + { + case 0: + return QString(tr("Bus")); + break; + case 1: + return QString(tr("Type")); + break; + case 2: + return QString(tr("Port")); + break; + case 3: + return QString(tr("Speed")); + break; + case 4: + return QString(tr("Listen Only")); + break; + case 5: + return QString(tr("Single Wire")); + break; + case 6: + return QString(tr("Active")); + break; + } + } + + else + return QString::number(section + 1); + + return QVariant(); +} + +int CANConnectionModel::rowCount(const QModelIndex &parent) const +{ + return buses.count(); +} + +int CANConnectionModel::columnCount(const QModelIndex &parent) const +{ + return 7; +} + +QVariant CANConnectionModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (index.row() >= (buses.count())) + return QVariant(); + + if (role == Qt::DisplayRole) { + CAN_Bus bus = buses[index.row()]; + CANConnection *conn = bus.connection; + switch (index.column()) + { + case 0: //bus + return QString::number(bus.busNum); + break; + case 1: //type + if (conn) conn->getConnTypeName(); + break; + case 2: //port + if (conn) conn->getConnPortName(); + break; + case 3: //speed + return QString::number(bus.speed); + break; + case 4: //Listen Only + if (bus.listenOnly) return QString("True"); + else return QString("False"); + break; + case 5: //Single Wire + if (bus.singleWire) return QString("True"); + else return QString("False"); + break; + case 6: //Active + if (bus.active) return QString("True"); + else return QString("False"); + break; + default: + return QVariant(); + } + } + else + return QVariant(); +} + +void CANConnectionModel::addConnection(CANConnection *conn) +{ + CAN_Bus bus; + beginResetModel(); + CANConnectionContainer *cont = new CANConnectionContainer(conn); + connections.append(cont); + + int numBuses = conn->getNumBuses(); + for (int i = 0; i < numBuses; i++) + { + bus.busNum = conn->getBusBase() + i; + buses.append(bus); + } + + endResetModel(); +} + +CAN_Bus* CANConnectionModel::findBusByNum(int bus) +{ + for (int i = 0; i < buses.count(); i++) + { + if (buses[i].busNum == bus) + { + return &buses[i]; + } + } + return NULL; +} + diff --git a/canconnectionmodel.h b/canconnectionmodel.h new file mode 100644 index 0000000..8042719 --- /dev/null +++ b/canconnectionmodel.h @@ -0,0 +1,33 @@ +#ifndef CANCONNECTIONMODEL_H +#define CANCONNECTIONMODEL_H + +#include "canconnection.h" +#include "canconnectioncontainer.h" + +#include + +class CANConnectionModel : public QAbstractTableModel +{ + Q_OBJECT + +public: + explicit CANConnectionModel(QObject *parent = 0); + + // Header: + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + + void addConnection(CANConnection *conn); + +private: + QList connections; + QList buses; + + CAN_Bus *findBusByNum(int bus); +}; + +#endif // CANCONNECTIONMODEL_H diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 8a8ea45..7b5ffe9 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -2,7 +2,7 @@ #include "ui_connectionwindow.h" #include -ConnectionWindow::ConnectionWindow(QWidget *parent) : +ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : QDialog(parent), ui(new Ui::ConnectionWindow) { @@ -10,34 +10,34 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : settings = new QSettings(); + connModel = new CANConnectionModel(); + ui->tableConnections->setModel(connModel); + + canModel = cModel; + + ui->tableConnections->setColumnWidth(0, 50); + ui->tableConnections->setColumnWidth(1, 110); + ui->tableConnections->setColumnWidth(2, 110); + ui->tableConnections->setColumnWidth(3, 150); + ui->tableConnections->setColumnWidth(4, 75); + ui->tableConnections->setColumnWidth(5, 75); + ui->tableConnections->setColumnWidth(6, 75); + int temp = settings->value("Main/DefaultConnectionType", 0).toInt(); - if (temp == 0) currentConnType = ConnectionType::GVRET_SERIAL; - if (temp == 1) currentConnType = ConnectionType::KVASER; - if (temp == 2) currentConnType = ConnectionType::SOCKETCAN; + //currentPortName = settings->value("Main/DefaultConnectionPort", "").toString(); - currentPortName = settings->value("Main/DefaultConnectionPort", "").toString(); - - currentSpeed1 = -1; - currentSpeed2 = -1; + //currentSpeed1 = -1; ui->ckSingleWire->setChecked(settings->value("Main/SingleWireMode", false).toBool()); - ui->cbSpeed0->addItem(tr("")); - ui->cbSpeed0->addItem(tr("Disabled")); - ui->cbSpeed0->addItem(tr("125000")); - ui->cbSpeed0->addItem(tr("250000")); - ui->cbSpeed0->addItem(tr("500000")); - ui->cbSpeed0->addItem(tr("1000000")); - ui->cbSpeed0->addItem(tr("33333")); - - ui->cbSpeed1->addItem(tr("")); - ui->cbSpeed1->addItem(tr("Disabled")); - ui->cbSpeed1->addItem(tr("125000")); - ui->cbSpeed1->addItem(tr("250000")); - ui->cbSpeed1->addItem(tr("500000")); - ui->cbSpeed1->addItem(tr("1000000")); - ui->cbSpeed1->addItem(tr("33333")); + ui->cbSpeed->addItem(tr("")); + ui->cbSpeed->addItem(tr("Disabled")); + ui->cbSpeed->addItem(tr("125000")); + ui->cbSpeed->addItem(tr("250000")); + ui->cbSpeed->addItem(tr("500000")); + ui->cbSpeed->addItem(tr("1000000")); + ui->cbSpeed->addItem(tr("33333")); #ifdef Q_OS_LINUX ui->rbSocketCAN->setEnabled(true); @@ -47,10 +47,12 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : ui->rbKvaser->setEnabled(true); #endif - connect(ui->btnOK, SIGNAL(clicked(bool)), this, SLOT(handleOKButton())); - connect(ui->rbGVRET, SIGNAL(toggled(bool)), this, SLOT(handleConnTypeChanged())); - connect(ui->rbKvaser, SIGNAL(toggled(bool)), this, SLOT(handleConnTypeChanged())); - connect(ui->rbSocketCAN, SIGNAL(toggled(bool)), this, SLOT(handleConnTypeChanged())); + connect(ui->btnOK, &QAbstractButton::clicked, this, &ConnectionWindow::handleOKButton); + connect(ui->rbGVRET, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->rbKvaser, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->rbSocketCAN, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); + connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); } ConnectionWindow::~ConnectionWindow() @@ -78,6 +80,28 @@ void ConnectionWindow::handleOKButton() QString conn; int connType = 0; + if (ui->tableConnections->selectionModel()->currentIndex().row() >= 0) + { + + } + else //new connection + { + if (ui->rbGVRET->isChecked()) + { + SerialWorker *serial = new SerialWorker(canModel, 0); + connModel->addConnection(serial); + } + else if (ui->rbKvaser->isChecked()) + { + + } + else if (ui->rbSocketCAN->isChecked()) + { + + } + } + +/* if (ui->rbGVRET->isChecked()) { conn = "GVRET"; @@ -100,16 +124,29 @@ void ConnectionWindow::handleOKButton() } currentPortName = getPortName(); - currentSpeed1 = getSpeed0(); - currentSpeed2 = getSpeed1(); + currentSpeed1 = getSpeed(); settings->setValue("Main/DefaultConnectionPort", currentPortName); settings->setValue("Main/DefaultConnectionType", connType); settings->setValue("Main/SingleWireMode", ui->ckSingleWire->isChecked()); - emit updateConnectionSettings(conn, getPortName(), getSpeed0(), getSpeed1()); + emit updateConnectionSettings(conn, getPortName(), getSpeed()); this->close(); +*/ +} + +void ConnectionWindow::handleConnSelectionChanged() +{ + int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); + if (selIdx == 0) + { + ui->btnOK->setText(tr("Create New Connection")); + } + else + { + ui->btnOK->setText(tr("Update Connection Settings")); + } } void ConnectionWindow::getSerialPorts() @@ -120,7 +157,7 @@ void ConnectionWindow::getSerialPorts() for (int i = 0; i < ports.count(); i++) { ui->cbPort->addItem(ports[i].portName()); - if (currentPortName == ports[i].portName()) ui->cbPort->setCurrentIndex(i); + //if (currentPortName == ports[i].portName()) ui->cbPort->setCurrentIndex(i); } } @@ -147,47 +184,33 @@ void ConnectionWindow::getSocketcanPorts() } } -void ConnectionWindow::setSpeeds(int speed0, int speed1) +void ConnectionWindow::setSpeed(int speed0) { bool found = false; - qDebug() << speed0 << "X" << speed1; + qDebug() << speed0; - for (int i = 0; i < ui->cbSpeed0->count(); i++) + for (int i = 0; i < ui->cbSpeed->count(); i++) { - if (ui->cbSpeed0->itemText(i).toInt() == speed0) + if (ui->cbSpeed->itemText(i).toInt() == speed0) { - ui->cbSpeed0->setCurrentIndex(i); + ui->cbSpeed->setCurrentIndex(i); found = true; } } if (!found) { - ui->cbSpeed0->addItem(QString::number(speed0)); - ui->cbSpeed0->setCurrentIndex(ui->cbSpeed0->count() - 1); + ui->cbSpeed->addItem(QString::number(speed0)); + ui->cbSpeed->setCurrentIndex(ui->cbSpeed->count() - 1); } - found = false; - for (int i = 0; i < ui->cbSpeed1->count(); i++) - { - if (ui->cbSpeed1->itemText(i).toInt() == speed1) - { - ui->cbSpeed1->setCurrentIndex(i); - found = true; - } - } - if (!found) - { - ui->cbSpeed1->addItem(QString::number(speed1)); - ui->cbSpeed1->setCurrentIndex(ui->cbSpeed1->count() - 1); - } } //-1 means leave it at whatever it booted up to. 0 means disable. Otherwise the actual rate we want. -int ConnectionWindow::getSpeed0() +int ConnectionWindow::getSpeed() { - switch (ui->cbSpeed0->currentIndex()) + switch (ui->cbSpeed->currentIndex()) { case -1: return -1; @@ -199,26 +222,7 @@ int ConnectionWindow::getSpeed0() return 0; break; default: - return (ui->cbSpeed0->currentText().toInt()); - break; - } -} - -int ConnectionWindow::getSpeed1() -{ - switch (ui->cbSpeed1->currentIndex()) - { - case -1: - return -1; - break; - case 0: - return -1; - break; - case 1: - return 0; - break; - default: - return (ui->cbSpeed1->currentText().toInt()); + return (ui->cbSpeed->currentText().toInt()); break; } } @@ -235,13 +239,23 @@ ConnectionType::ConnectionType ConnectionWindow::getConnectionType() if (ui->rbSocketCAN->isChecked()) return ConnectionType::SOCKETCAN; } -void ConnectionWindow::setCAN1SWMode(bool mode) +void ConnectionWindow::setSWMode(bool mode) { ui->ckSingleWire->setChecked(mode); } -bool ConnectionWindow::getCAN1SWMode() +bool ConnectionWindow::getSWMode() { if (ui->ckSingleWire->checkState() == Qt::Checked) return true; return false; } + +void ConnectionWindow::handleRemoveConn() +{ + +} + +void ConnectionWindow::handleRevert() +{ + +} diff --git a/connectionwindow.h b/connectionwindow.h index e098f67..66b92da 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -1,10 +1,14 @@ #ifndef CONNECTIONWINDOW_H #define CONNECTIONWINDOW_H +#include "canconnectionmodel.h" + #include #include #include #include +#include "canconnection.h" +#include "serialworker.h" namespace Ui { class ConnectionWindow; @@ -25,34 +29,36 @@ class ConnectionWindow : public QDialog Q_OBJECT public: - explicit ConnectionWindow(QWidget *parent = 0); + explicit ConnectionWindow(CANFrameModel *canModel, QWidget *parent = 0); ~ConnectionWindow(); void showEvent(QShowEvent *); - int getSpeed0(); - int getSpeed1(); + int getSpeed(); QString getPortName(); //name of port to connect to ConnectionType::ConnectionType getConnectionType(); - bool getCAN1SWMode(); + bool getSWMode(); signals: - void updateConnectionSettings(QString connectionType, QString port, int speed0, int speed1); + void updateConnectionSettings(QString connectionType, QString port, int speed); public slots: - void setSpeeds(int speed0, int speed1); - void setCAN1SWMode(bool mode); + void setSpeed(int speed0); + void setSWMode(bool mode); private slots: void handleOKButton(); void handleConnTypeChanged(); + void handleConnSelectionChanged(); + void handleRemoveConn(); + void handleRevert(); + private: Ui::ConnectionWindow *ui; QList ports; QSettings *settings; + CANConnectionModel *connModel; + CANFrameModel *canModel; - ConnectionType::ConnectionType currentConnType; - QString currentPortName; - int currentSpeed1, currentSpeed2; void getSerialPorts(); void getKvaserPorts(); diff --git a/connectionwindow.ui b/connectionwindow.ui index dc48369..b62f1b3 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -6,109 +6,191 @@ 0 0 - 335 - 235 + 952 + 433 Connection Settings - + - - - Connection Type - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - GVRET Serial - - - true - - - - - - - false - - - Kvaser - - - - - - - false - - - SocketCAN - - - - - - - - - - - 0 - 0 - - - - Port: - - - - - - - - - - + + + - CAN0 Speed + Connections: - - - - CAN1 Speed + + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows - - + + + + + + Activate Selected Connection + + + + + + + Remove Selected Connection + + + + - - + + + + + + Activate All Connections + + + + + + + Deactivate All Connections + + + + - - - Set CAN1 to Single Wire Mode - - - - - - - Update Settings - - + + + + + Connection Type + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + GVRET Serial + + + true + + + + + + + false + + + Kvaser + + + + + + + false + + + SocketCAN + + + + + + + + + + + 0 + 0 + + + + Port: + + + + + + + + + + Single Wire Mode + + + + + + + Listen Only Mode + + + + + + + + + CAN Speed + + + + + + + + + + + + + + Create New Connection + + + + + + + Revert + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index b9be616..f881ff5 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -80,7 +80,7 @@ void FirmwareUploaderWindow::gotTargettedFrame(int frameLoc) if ((frame.data[6] == ((token >> 16) & 0xFF)) && (frame.data[7] == ((token >> 24) & 0xFF))) { qDebug() << "starting firmware process"; - MainWindow::getReference()->setTargettedID(baseAddress + 0x20); + //MainWindow::getReference()->setTargettedID(baseAddress + 0x20); transferInProgress = true; sendFirmwareChunk(); } @@ -163,7 +163,7 @@ void FirmwareUploaderWindow::handleStartStopTransfer() bus = ui->spinBus->value(); baseAddress = Utility::ParseStringToNum(ui->txtBaseAddr->text()); qDebug() << "Base address: " + QString::number(baseAddress); - MainWindow::getReference()->setTargettedID(baseAddress + 0x10); + //MainWindow::getReference()->setTargettedID(baseAddress + 0x10); CANFrame *output = new CANFrame; output->extended = false; output->len = 8; @@ -181,7 +181,7 @@ void FirmwareUploaderWindow::handleStartStopTransfer() else //stop anything in process { ui->btnStartStop->setText("Start Upload"); - MainWindow::getReference()->setTargettedID(-1); + //MainWindow::getReference()->setTargettedID(-1); } } diff --git a/mainwindow.cpp b/mainwindow.cpp index 5426539..be2d26f 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -64,6 +64,7 @@ MainWindow::MainWindow(QWidget *parent) : //enabling the below line kills performance in every way imaginable. Left here as a warning. Do not do this. //ui->canFramesView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + /* worker = new SerialWorker(model); worker->moveToThread(&serialWorkerThread); connect(&serialWorkerThread, &QThread::finished, worker, &QObject::deleteLater); @@ -81,6 +82,7 @@ MainWindow::MainWindow(QWidget *parent) : connect(this, &MainWindow::settingsUpdated, worker, &SerialWorker::readSettings); serialWorkerThread.start(); serialWorkerThread.setPriority(QThread::HighPriority); + */ graphingWindow = NULL; frameInfoWindow = NULL; @@ -176,7 +178,7 @@ MainWindow::MainWindow(QWidget *parent) : model->clearFrames(); //Automatically create the connection window so it can be updated even if we never opened it. - connectionWindow = new ConnectionWindow(); + connectionWindow = new ConnectionWindow(model); connect(connectionWindow, SIGNAL(updateConnectionSettings(QString,QString,int,int)), this, SLOT(updateConnectionSettings(QString,QString,int,int))); } @@ -384,45 +386,7 @@ void MainWindow::updateConnectionSettings(QString connectionType, QString port, canSpeed1 = speed1; if (isConnected) { - emit updateBaudRates(speed0, speed1); - } -} - -void MainWindow::connButtonPress() -{ - if (!isConnected) - { - if (connType == "GVRET") - { - QList ports; - ports = QSerialPortInfo::availablePorts(); - - for (int i = 0; i < ports.count(); i++) - { - if (ports[i].portName() == portName) - { - portInfo = ports[i]; - //need to create some way to send single wire mode to serial port code - emit sendSerialPort(&portInfo); - lbStatusConnected.setText(tr("Attempting to connect to port ") + portName); - } - } - } - else if (connType == "KVASER") - { - - } - else if (connType == "SOCKETCAN") - { - - } - } - else - { - emit closeSerialPort(); - isConnected = false; - lbStatusConnected.setText(tr("Not Connected")); - ui->actionConnect->setText(tr("Connect")); + //emit updateBaudRates(speed0, speed1); } } @@ -576,16 +540,6 @@ void MainWindow::normalizeTiming() emit framesUpdated(-2); //claim an all new set of frames because every frame was updated. } -void MainWindow::changeBaudRates() -{ - int Speed1 = 0, Speed2 = 0; - - //Speed1 = ui->cbSpeed1->currentText().toInt(); - //Speed2 = ui->cbSpeed2->currentText().toInt(); - - emit updateBaudRates(Speed1, Speed2); -} - void MainWindow::handleLoadFile() { QString filename; @@ -785,7 +739,7 @@ void MainWindow::connectionSucceeded(int baud0, int baud1) ui->cbSpeed2->setCurrentIndex(ui->cbSpeed2->count() - 1); } */ - if (connectionWindow) connectionWindow->setSpeeds(baud0, baud1); + if (connectionWindow) connectionWindow->setSpeed(baud0); //ui->btnConnect->setEnabled(false); ui->actionConnect->setText(tr("Disconnect")); isConnected = true; @@ -843,16 +797,11 @@ void MainWindow::gotDeviceInfo(int build, int swCAN) if (connectionWindow) { - if (swCAN == 1) connectionWindow->setCAN1SWMode(true); - else connectionWindow->setCAN1SWMode(false); + if (swCAN == 1) connectionWindow->setSWMode(true); + else connectionWindow->setSWMode(false); } } -void MainWindow::setTargettedID(int id) -{ - worker->targetFrameID(id); -} - void MainWindow::showSettingsDialog() { if (!settingsDialog) @@ -1039,7 +988,7 @@ void MainWindow::showConnectionSettingsWindow() { if (!connectionWindow) { - connectionWindow = new ConnectionWindow(); + connectionWindow = new ConnectionWindow(model); connect(connectionWindow, SIGNAL(updateConnectionSettings(QString,QString,int,int)), this, SLOT(updateConnectionSettings(QString,QString,int,int))); } connectionWindow->show(); diff --git a/mainwindow.h b/mainwindow.h index fc8115f..278c688 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -39,7 +39,6 @@ public: explicit MainWindow(QWidget *parent = 0); static QString loadedFileName; static MainWindow *getReference(); - void setTargettedID(int); ~MainWindow(); private slots: @@ -48,7 +47,6 @@ private slots: void handleSaveFilteredFile(); void handleSaveFilters(); void handleLoadFilters(); - void connButtonPress(); void showGraphingWindow(); void showFrameDataAnalysis(); void clearFrames(); @@ -69,7 +67,6 @@ private slots: void showISOInterpreterWindow(); void exitApp(); void handleSaveDecoded(); - void changeBaudRates(); void connectionFailed(); void gotDeviceInfo(int, int); void connectionSucceeded(int, int); @@ -92,9 +89,6 @@ public slots: void updateConnectionSettings(QString connectionType, QString port, int speed0, int speed1); signals: - void sendSerialPort(QSerialPortInfo *port); - void closeSerialPort(); - void updateBaudRates(int, int); void sendCANFrame(const CANFrame *, int); void stopFrameCapturing(); void startFrameCapturing(); diff --git a/serialworker.cpp b/serialworker.cpp index 61a0b5f..95b9322 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -5,19 +5,16 @@ #include #include -SerialWorker::SerialWorker(CANFrameModel *model, QObject *parent) : QObject(parent) +SerialWorker::SerialWorker(CANFrameModel *model, int base) : CANConnection(model, base) { serial = NULL; rx_state = IDLE; rx_step = 0; buildFrame = new CANFrame; - canModel = model; ticker = NULL; framesRapid = 0; - capturing = true; gotValidated = true; isAutoRestart = false; - targetID = -1; txTimestampBasis = QDateTime::currentMSecsSinceEpoch(); @@ -121,8 +118,8 @@ void SerialWorker::setSerialPort(QSerialPortInfo *port) continuousTimeSync = true; serial->write(output); - if (doValidation) connected = false; - else connected = true; + if (doValidation) isConnected = false; + else isConnected = true; connect(serial, SIGNAL(readyRead()), this, SLOT(readSerialData())); if (doValidation) QTimer::singleShot(1000, this, SLOT(connectionTimeout())); } @@ -130,7 +127,7 @@ void SerialWorker::setSerialPort(QSerialPortInfo *port) void SerialWorker::connectionTimeout() { //one second after trying to connect are we actually connected? - if (!connected) //no? + if (!isConnected) //no? { //then emit the the failure signal and see if anyone cares qDebug() << "Failed to connect to GVRET at that com port"; @@ -157,7 +154,7 @@ void SerialWorker::readSerialData() } } -void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0) +void SerialWorker::sendFrame(const CANFrame *frame) { QByteArray buffer; int c; @@ -169,12 +166,12 @@ void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0) //qDebug() << "Sending out frame with id " << frame->ID; //show our sent frames in the list too. This happens even if we're not connected. - canModel->addFrame(tempFrame, false); + model->addFrame(tempFrame, false); framesRapid++; if (serial == NULL) return; if (!serial->isOpen()) return; - if (!connected) return; + if (!isConnected) return; ID = frame->ID; if (frame->extended) ID |= 1 << 31; @@ -185,7 +182,7 @@ void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0) buffer[3] = (unsigned char)(ID >> 8); buffer[4] = (unsigned char)(ID >> 16); buffer[5] = (unsigned char)(ID >> 24); - buffer[6] = (unsigned char)(bus & 1); + buffer[6] = (unsigned char)((frame->bus - this->getBusBase()) & 1); buffer[7] = (unsigned char)frame->len; for (c = 0; c < frame->len; c++) { @@ -203,7 +200,7 @@ void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0) void SerialWorker::sendFrameBatch(const QList *frames) { sendBulkMutex.lock(); - for (int i = 0; i < frames->length(); i++) sendFrame(&frames->at(i), frames->at(i).bus); + for (int i = 0; i < frames->length(); i++) sendFrame(&frames->at(i)); sendBulkMutex.unlock(); } @@ -321,15 +318,14 @@ void SerialWorker::procRXChar(unsigned char c) rx_state = IDLE; rx_step = 0; //qDebug() << "emit from serial handler to main form id: " << buildFrame->ID; - if (capturing) - { + //if (capturing) + //{ buildFrame->isReceived = true; - canModel->addFrame(*buildFrame, false); + model->addFrame(*buildFrame, false); //take the time the frame came in and try to resync the time base. if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame->timestamp / 1000); - framesRapid++; - if (buildFrame->ID == targetID) emit gotTargettedFrame(canModel->rowCount() - 1); - } + framesRapid++; + //} } break; } @@ -414,8 +410,8 @@ void SerialWorker::procRXChar(unsigned char c) qDebug() << "Baud 1 = " << can1Baud; if (!can1Enabled) can1Baud = 0; if (!can0Enabled) can0Baud = 0; - connected = true; - emit connectionSuccess(can0Baud, can1Baud); + isConnected = true; + emit connectionSuccess(); break; } rx_step++; @@ -462,7 +458,7 @@ void SerialWorker::handleTick() { //qDebug() << "Tick!"; - if (connected) + if (isConnected) { if (!gotValidated && doValidation) { @@ -517,6 +513,7 @@ void SerialWorker::closeSerialPort() serial = NULL; } +/* void SerialWorker::stopFrameCapture() { qDebug() << "Stopping frame capture"; @@ -528,8 +525,24 @@ void SerialWorker::startFrameCapture() qDebug() << "Starting up frame capture"; capturing = true; } +*/ -void SerialWorker::targetFrameID(int target) +void SerialWorker::updatePortName(QString portName) { - targetID = target; + QList ports; + + CANConnection::updatePortName(portName); + + ports = QSerialPortInfo::availablePorts(); + + for (int i = 0; i < ports.count(); i++) + { + if (portName == ports[i].portName()) + { + setSerialPort(&ports[i]); + return; + } + } } + + diff --git a/serialworker.h b/serialworker.h index 1658c04..df54810 100644 --- a/serialworker.h +++ b/serialworker.h @@ -8,6 +8,7 @@ #include #include "can_structs.h" #include "canframemodel.h" +#include "canconnection.h" namespace SERIALSTATE { @@ -29,23 +30,14 @@ enum STATE //keep this enum synchronized with the Arduino firmware project } using namespace SERIALSTATE; -class SerialWorker : public QObject +class SerialWorker : public CANConnection { Q_OBJECT public: - SerialWorker(CANFrameModel *model, QObject *parent = 0); + SerialWorker(CANFrameModel *, int); ~SerialWorker(); void readSettings(); - void targetFrameID(int); - -signals: //we emit signals - void error(const QString &); - void frameUpdateRapid(int); //sent *much* more rapidly than the above signal - one param for # of frames - void connectionSuccess(int, int); - void connectionFailure(); - void deviceInfo(int, int); - void gotTargettedFrame(int); private slots: //we receive things in slots void readSerialData(); @@ -54,31 +46,26 @@ private slots: //we receive things in slots void handleReconnect(); public slots: - void run(); + void run() override; void setSerialPort(QSerialPortInfo*); void closeSerialPort(); - void sendFrame(const CANFrame *, int); - void sendFrameBatch(const QList *); + void sendFrame(const CANFrame *) override; + void sendFrameBatch(const QList *) override; void updateBaudRates(int, int); - void stopFrameCapture(); - void startFrameCapture(); //only need to call this if previously stopped. Otherwise it's the default + //void stopFrameCapture(int) override; + //void startFrameCapture(int) override; + void updatePortName(QString) override; //string version of the port to connect to. This base doesnt know a thing about this value -private: - QString portName; - bool quit; - bool connected; - bool capturing; +private: bool doValidation; bool gotValidated; bool isAutoRestart; bool continuousTimeSync; QSerialPort *serial; QSerialPortInfo *currentPort; - CANFrameModel *canModel; QTimer *ticker; QMutex sendBulkMutex; int framesRapid; - int targetID; STATE rx_state; int rx_step; CANFrame *buildFrame; From 0bd3a3b95ba452b0bc048d4b7ea0675a421447fd Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sat, 26 Mar 2016 20:17:10 -0400 Subject: [PATCH 02/86] Additional implementation of new connection system. The GVRET code can now connect and run its thread. --- canconnection.cpp | 5 +++++ canconnection.h | 9 +++++++-- canconnectioncontainer.cpp | 15 ++++++++++++++- canconnectioncontainer.h | 6 ++++-- canconnectionmodel.cpp | 35 +++++++++++++++++++++++++---------- canconnectionmodel.h | 5 +++++ connectionwindow.cpp | 38 +++++++++++++++++++++++++++++++++++++- connectionwindow.h | 5 ++++- connectionwindow.ui | 2 +- mainwindow.cpp | 1 - mainwindow.h | 2 ++ mainwindow.ui | 3 +-- serialworker.cpp | 18 ++++++++++++++++++ serialworker.h | 3 +++ 14 files changed, 126 insertions(+), 21 deletions(-) diff --git a/canconnection.cpp b/canconnection.cpp index c26c507..fb9ac11 100644 --- a/canconnection.cpp +++ b/canconnection.cpp @@ -126,3 +126,8 @@ void CANConnection::startFrameCapture(int bus) { } + +void CANConnection::updateBusSettings(CAN_Bus *bus) +{ + +} diff --git a/canconnection.h b/canconnection.h index 258378c..57be38b 100644 --- a/canconnection.h +++ b/canconnection.h @@ -33,6 +33,11 @@ public: CANConnection *getConnection(); }; + +//Gentle reminder, CANConnection objects run in their own thread (each one, different thread) +//so, for the love of God, do not try to access them directly. +//Use the signal/slots system to do indirect calls. +//Please and thank you. class CANConnection : public QObject { Q_OBJECT @@ -41,7 +46,7 @@ public: CANConnection(CANFrameModel *, int); virtual int getNumBuses(); int getBusBase(); - QString getConnTypeName(); + virtual QString getConnTypeName(); QString getConnPortName(); signals: @@ -59,7 +64,7 @@ public slots: virtual void updatePortName(QString); //string version of the port to connect to. This base doesnt know a thing about this value virtual void stopFrameCapture(int); //pass bus number virtual void startFrameCapture(int); //pass bus number. Only if stopped. Defaults to started anyway - //virtual void updateBusSettings(int); //bus number that was updated. + virtual void updateBusSettings(CAN_Bus *bus); //reference to the bus that changed. protected: bool quit; diff --git a/canconnectioncontainer.cpp b/canconnectioncontainer.cpp index 15d9baa..63a5069 100644 --- a/canconnectioncontainer.cpp +++ b/canconnectioncontainer.cpp @@ -1,10 +1,18 @@ +#include "canconnection.h" #include "canconnectioncontainer.h" CANConnectionContainer::CANConnectionContainer(CANConnection *conn) { thread = new QThread(); connection = conn; - connection->moveToThread(thread); + connection->moveToThread(thread); + + connect(thread, &QThread::finished, conn, &QObject::deleteLater); + connect(thread, &QThread::started, conn, &CANConnection::run); //setup timers within the proper thread + connect(conn, &CANConnection::frameUpdateRapid, MainWindow::getReference(), &MainWindow::gotFrames, Qt::QueuedConnection); + connect(MainWindow::getReference(), &MainWindow::sendCANFrame, conn, &CANConnection::sendFrame, Qt::QueuedConnection); + thread->start(); + thread->setPriority(QThread::HighPriority); } CANConnectionContainer::~CANConnectionContainer() @@ -13,3 +21,8 @@ CANConnectionContainer::~CANConnectionContainer() delete thread; delete connection; } + +CANConnection* CANConnectionContainer::getRef() +{ + return connection; +} diff --git a/canconnectioncontainer.h b/canconnectioncontainer.h index eb90066..9ff2b22 100644 --- a/canconnectioncontainer.h +++ b/canconnectioncontainer.h @@ -2,17 +2,19 @@ #define CANCONNECTIONCONTAINER_H #include "canconnection.h" +#include #include +#include "mainwindow.h" -class CANConnectionContainer +class CANConnectionContainer : public QObject { + Q_OBJECT public: CANConnectionContainer(CANConnection *conn); ~CANConnectionContainer(); CANConnection* getRef(); - private: CANConnection *connection; QThread *thread; diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 02063b6..089bba0 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -1,3 +1,5 @@ +#include "canconnection.h" +#include "canconnectioncontainer.h" #include "canconnectionmodel.h" CANConnectionModel::CANConnectionModel(QObject *parent) @@ -71,10 +73,12 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const return QString::number(bus.busNum); break; case 1: //type - if (conn) conn->getConnTypeName(); + if (conn) return conn->getConnTypeName(); + else qDebug() << "Tried to show connection type but connection was NULL"; break; case 2: //port - if (conn) conn->getConnPortName(); + if (conn) return conn->getConnPortName(); + else qDebug() << "Tried to show connection port but connection was NULL"; break; case 3: //speed return QString::number(bus.speed); @@ -102,20 +106,31 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const void CANConnectionModel::addConnection(CANConnection *conn) { CAN_Bus bus; - beginResetModel(); CANConnectionContainer *cont = new CANConnectionContainer(conn); connections.append(cont); +} - int numBuses = conn->getNumBuses(); - for (int i = 0; i < numBuses; i++) - { - bus.busNum = conn->getBusBase() + i; - buses.append(bus); - } - +void CANConnectionModel::addBus(CAN_Bus &bus) +{ + beginResetModel(); + buses.append(bus); endResetModel(); } +CAN_Bus* CANConnectionModel::getBus(int bus) +{ + if (bus < 0) return NULL; + if (bus >= buses.count()) return NULL; + return &buses[bus]; +} + +CANConnection* CANConnectionModel::getConnection(int conn) +{ + if (conn < 0) return NULL; + if (conn >= connections.count()) return NULL; + return connections[conn]->getRef(); +} + CAN_Bus* CANConnectionModel::findBusByNum(int bus) { for (int i = 0; i < buses.count(); i++) diff --git a/canconnectionmodel.h b/canconnectionmodel.h index 8042719..f6a183b 100644 --- a/canconnectionmodel.h +++ b/canconnectionmodel.h @@ -6,6 +6,8 @@ #include +class CANConnectionContainer; + class CANConnectionModel : public QAbstractTableModel { Q_OBJECT @@ -22,6 +24,9 @@ public: QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; void addConnection(CANConnection *conn); + void addBus(CAN_Bus &bus); + CAN_Bus* getBus(int bus); + CANConnection* getConnection(int conn); private: QList connections; diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 7b5ffe9..be52a32 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -88,8 +88,44 @@ void ConnectionWindow::handleOKButton() { if (ui->rbGVRET->isChecked()) { - SerialWorker *serial = new SerialWorker(canModel, 0); + SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); connModel->addConnection(serial); + + qDebug() << "Setup initial connection object"; + + CAN_Bus bus; + bus.active = true; + bus.busNum = serial->getBusBase(); + bus.connection = serial; + bus.listenOnly = ui->ckListenOnly->isChecked(); + bus.singleWire = ui->ckSingleWire->isChecked(); + + if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed + else if (ui->cbSpeed->currentIndex() == 1) + { + bus.speed = 0; + bus.active = false; + } + else bus.speed = ui->cbSpeed->currentText().toInt(); + connModel->addBus(bus); + + int numBuses = serial->getNumBuses(); + for (int i = 1; i < numBuses; i++) + { + bus.active = false; + bus.listenOnly = false; + bus.singleWire = false; + bus.speed = 250000; + bus.busNum = serial->getBusBase() + i; + bus.connection = serial; + connModel->addBus(bus); + qDebug() << "Added bus " << bus.busNum; + } + + //call through signal/slot interface without using connect + QMetaObject::invokeMethod(serial, "updatePortName", + Qt::QueuedConnection, + Q_ARG(QString, ui->cbPort->currentText())); } else if (ui->rbKvaser->isChecked()) { diff --git a/connectionwindow.h b/connectionwindow.h index 66b92da..afa75e3 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -10,6 +10,8 @@ #include "canconnection.h" #include "serialworker.h" +class CANConnectionModel; + namespace Ui { class ConnectionWindow; } @@ -38,7 +40,8 @@ public: bool getSWMode(); signals: - void updateConnectionSettings(QString connectionType, QString port, int speed); + void updateBusSettings(CAN_Bus *bus); + void updatePortName(QString port); public slots: void setSpeed(int speed0); diff --git a/connectionwindow.ui b/connectionwindow.ui index b62f1b3..6dbd5fe 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -6,7 +6,7 @@ 0 0 - 952 + 1009 433 diff --git a/mainwindow.cpp b/mainwindow.cpp index be2d26f..5ab24af 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -109,7 +109,6 @@ MainWindow::MainWindow(QWidget *parent) : model->setDBCHandler(dbcHandler); connect(ui->actionSetup, SIGNAL(triggered(bool)), SLOT(showConnectionSettingsWindow())); - connect(ui->actionConnect, SIGNAL(triggered(bool)), this, SLOT(connButtonPress())); connect(ui->actionOpen_Log_File, &QAction::triggered, this, &MainWindow::handleLoadFile); connect(ui->actionGraph_Dta, &QAction::triggered, this, &MainWindow::showGraphingWindow); connect(ui->actionFrame_Data_Analysis, &QAction::triggered, this, &MainWindow::showFrameDataAnalysis); diff --git a/mainwindow.h b/mainwindow.h index 278c688..03bb1cd 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -27,6 +27,8 @@ #include "udsscanwindow.h" #include "isotp_interpreterwindow.h" +class ConnectionWindow; + namespace Ui { class MainWindow; } diff --git a/mainwindow.ui b/mainwindow.ui index fafd407..327ac92 100644 --- a/mainwindow.ui +++ b/mainwindow.ui @@ -245,7 +245,6 @@ Connection - @@ -350,7 +349,7 @@ - Set Port + Open Connection WIndow diff --git a/serialworker.cpp b/serialworker.cpp index 95b9322..811dea7 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -7,6 +7,7 @@ SerialWorker::SerialWorker(CANFrameModel *model, int base) : CANConnection(model, base) { + qDebug() << "Serial Worker constructor"; serial = NULL; rx_state = IDLE; rx_step = 0; @@ -39,6 +40,7 @@ SerialWorker::~SerialWorker() void SerialWorker::run() { + qDebug() << "Serial worker thread starting"; ticker = new QTimer; connect(ticker, SIGNAL(timeout()), this, SLOT(handleTick())); @@ -545,4 +547,20 @@ void SerialWorker::updatePortName(QString portName) } } +int SerialWorker::getNumBuses() +{ + return 2; +} +QString SerialWorker::getConnTypeName() +{ + return QString("GVRET"); +} + +void SerialWorker::updateBusSettings(CAN_Bus *bus) +{ + int busNum = bus->busNum - busBase; + if (busNum < 0) return; + if (busNum >= numBuses) return; + qDebug() << "About to update bus " << busNum << " on GVRET"; +} diff --git a/serialworker.h b/serialworker.h index df54810..a83a637 100644 --- a/serialworker.h +++ b/serialworker.h @@ -38,6 +38,8 @@ public: SerialWorker(CANFrameModel *, int); ~SerialWorker(); void readSettings(); + int getNumBuses(); + QString getConnTypeName() override; private slots: //we receive things in slots void readSerialData(); @@ -55,6 +57,7 @@ public slots: //void stopFrameCapture(int) override; //void startFrameCapture(int) override; void updatePortName(QString) override; //string version of the port to connect to. This base doesnt know a thing about this value + void updateBusSettings(CAN_Bus *bus) override; private: bool doValidation; From 87c201aa44456c8388686163c9f607cac147894b Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sat, 26 Mar 2016 22:01:34 -0400 Subject: [PATCH 03/86] Added ability for connections to update the connection view details based on hardware status. --- canconnection.h | 8 +++++++- canconnectionmodel.cpp | 6 ++++++ canconnectionmodel.h | 1 + connectionwindow.cpp | 41 ++++++++++++++--------------------------- connectionwindow.h | 2 +- serialworker.cpp | 3 ++- 6 files changed, 31 insertions(+), 30 deletions(-) diff --git a/canconnection.h b/canconnection.h index 57be38b..598d967 100644 --- a/canconnection.h +++ b/canconnection.h @@ -55,7 +55,13 @@ signals: void frameUpdate(int); void connectionSuccess(); void connectionFailure(); - void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte (listen only, single wire, etc) + void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte + + //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) + //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only + //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really + //being passed. Just set for things that really are being updated. + void busStatus(int, int, int); public slots: virtual void run(); diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 089bba0..8510f8d 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -7,6 +7,12 @@ CANConnectionModel::CANConnectionModel(QObject *parent) { } +void CANConnectionModel::refreshView() +{ + beginResetModel(); + endResetModel(); +} + QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) diff --git a/canconnectionmodel.h b/canconnectionmodel.h index f6a183b..1e0410e 100644 --- a/canconnectionmodel.h +++ b/canconnectionmodel.h @@ -27,6 +27,7 @@ public: void addBus(CAN_Bus &bus); CAN_Bus* getBus(int bus); CANConnection* getConnection(int conn); + void refreshView(); private: QList connections; diff --git a/connectionwindow.cpp b/connectionwindow.cpp index be52a32..ea5dea5 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -89,6 +89,7 @@ void ConnectionWindow::handleOKButton() if (ui->rbGVRET->isChecked()) { SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); + connect(serial, SIGNAL(busStatus(int,int,int)), this, SLOT(receiveBusStatus(int,int,int))); connModel->addConnection(serial); qDebug() << "Setup initial connection object"; @@ -136,40 +137,26 @@ void ConnectionWindow::handleOKButton() } } +} -/* - if (ui->rbGVRET->isChecked()) +void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) +{ + qDebug() << "bus " << bus << " speed " << speed << " status " << status; + CAN_Bus *busRef = connModel->getBus(bus); + if (status & 40) busRef->setSpeed(speed); + if (status & 8) //update enabled status { - conn = "GVRET"; - connType = 0; - currentConnType = ConnectionType::GVRET_SERIAL; + busRef->setEnabled((status & 1)?true:false); } - - if (ui->rbKvaser->isChecked()) + if (status & 0x10) //update single wire status { - conn = "KVASER"; - connType = 1; - currentConnType = ConnectionType::KVASER; + busRef->setSingleWire((status & 2)?true:false); } - - if (ui->rbSocketCAN->isChecked()) + if (status & 0x20) //update listen only status { - conn = "SOCKETCAN"; - connType = 2; - currentConnType = ConnectionType::SOCKETCAN; + busRef->setListenOnly((status & 4)?true:false); } - - currentPortName = getPortName(); - currentSpeed1 = getSpeed(); - - settings->setValue("Main/DefaultConnectionPort", currentPortName); - settings->setValue("Main/DefaultConnectionType", connType); - settings->setValue("Main/SingleWireMode", ui->ckSingleWire->isChecked()); - - emit updateConnectionSettings(conn, getPortName(), getSpeed()); - - this->close(); -*/ + connModel->refreshView(); } void ConnectionWindow::handleConnSelectionChanged() diff --git a/connectionwindow.h b/connectionwindow.h index afa75e3..399c838 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -53,7 +53,7 @@ private slots: void handleConnSelectionChanged(); void handleRemoveConn(); void handleRevert(); - + void receiveBusStatus(int bus, int speed, int status); private: Ui::ConnectionWindow *ui; diff --git a/serialworker.cpp b/serialworker.cpp index 811dea7..a55f9d5 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -81,7 +81,6 @@ void SerialWorker::setSerialPort(QSerialPortInfo *port) serial = new QSerialPort(*port); qDebug() << "Serial port name is " << port->portName(); - //serial->setBaudRate(10000000); //more speed! probably does nothing for USB serial serial->setDataBits(serial->Data8); serial->setFlowControl(serial->HardwareControl); //this is important though if (!serial->open(QIODevice::ReadWrite)) @@ -414,6 +413,8 @@ void SerialWorker::procRXChar(unsigned char c) if (!can0Enabled) can0Baud = 0; isConnected = true; emit connectionSuccess(); + emit busStatus(busBase, can0Baud, can0Enabled?0x49:0x48); //say that we're updating baud rate and set enabled status + emit busStatus(busBase + 1, can1Baud, can1Enabled?0x49:0x48); break; } rx_step++; From a3cd14e495c69002157446e76b24a914112b9797 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sun, 27 Mar 2016 22:37:02 -0400 Subject: [PATCH 04/86] Additional implementation of the new connection scheme. It is now possible to send frames to CANConnection objects indirectly based on registered bus number. This further abstracts the interface. Things are reasonably stable now for frame reception. Initial work has been done to support frame transmission as well. This is currently less stable but mostly working. --- connectionwindow.cpp | 77 ++++++++++++++++++++++++++++++++++++-- connectionwindow.h | 3 ++ connectionwindow.ui | 7 ++++ firmwareuploaderwindow.cpp | 9 +++-- firmwareuploaderwindow.h | 2 +- frameplaybackwindow.cpp | 8 +--- frameplaybackwindow.h | 5 +-- framesenderwindow.cpp | 4 +- framesenderwindow.h | 2 +- fuzzingwindow.h | 2 +- mainwindow.cpp | 41 ++++++++++---------- mainwindow.h | 5 --- scriptcontainer.cpp | 2 +- scriptcontainer.h | 2 +- scriptingwindow.h | 2 +- serialworker.cpp | 3 ++ udsscanwindow.cpp | 2 +- udsscanwindow.h | 2 +- 18 files changed, 128 insertions(+), 50 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index ddf526f..3cff915 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -10,6 +10,10 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : settings = new QSettings(); + qRegisterMetaType("CAN_Bus *"); + qRegisterMetaType("const CANFrame *"); + qRegisterMetaType *>("const QList *"); + connModel = new CANConnectionModel(); ui->tableConnections->setModel(connModel); @@ -53,6 +57,7 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : connect(ui->rbSocketCAN, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); + connect(ui->btnNewConn, &QPushButton::clicked, this, &ConnectionWindow::handleNewConn); } ConnectionWindow::~ConnectionWindow() @@ -68,6 +73,13 @@ void ConnectionWindow::showEvent(QShowEvent* event) handleConnTypeChanged(); } +void ConnectionWindow::handleNewConn() +{ + ui->tableConnections->selectionModel()->clearSelection(); + ui->tableConnections->selectionModel()->clearCurrentIndex(); + handleConnSelectionChanged(); +} + void ConnectionWindow::handleConnTypeChanged() { if (ui->rbGVRET->isChecked()) getSerialPorts(); @@ -79,10 +91,29 @@ void ConnectionWindow::handleOKButton() { QString conn; int connType = 0; + int whichRow = ui->tableConnections->selectionModel()->currentIndex().row(); + qDebug() << whichRow; - if (ui->tableConnections->selectionModel()->currentIndex().row() >= 0) + if (whichRow > -1) { - + //load settings from GUI into appropriate CAN_Bus entry and then send it off to the appropriate + //CANConnection object + CAN_Bus *bus = connModel->getBus(whichRow); + bus->setListenOnly(ui->ckListenOnly->isChecked()); + bus->setSingleWire(ui->ckSingleWire->isChecked()); + if (ui->cbSpeed->currentIndex() == 1) + { + bus->speed = 0; + bus->setEnabled(false); + } + else if (ui->cbSpeed->currentIndex() > 1) + { + bus->setSpeed(ui->cbSpeed->currentText().toInt()); + } + //call through signal/slot interface without using connect + QMetaObject::invokeMethod(bus->connection, "updateBusSettings", + Qt::QueuedConnection, + Q_ARG(CAN_Bus *, bus)); } else //new connection { @@ -162,13 +193,34 @@ void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) void ConnectionWindow::handleConnSelectionChanged() { int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); - if (selIdx == 0) + qDebug() << selIdx; + if (selIdx == -1) { ui->btnOK->setText(tr("Create New Connection")); + ui->cbPort->setEnabled(true); + ui->rbGVRET->setEnabled(true); + ui->rbKvaser->setEnabled(true); + ui->rbSocketCAN->setEnabled(true); + ui->cbPort->setCurrentIndex(0); + ui->ckListenOnly->setChecked(false); + ui->ckSingleWire->setChecked(false); } else { ui->btnOK->setText(tr("Update Connection Settings")); + ui->cbPort->setEnabled(false); + ui->rbGVRET->setEnabled(false); + ui->rbKvaser->setEnabled(false); + ui->rbSocketCAN->setEnabled(false); + CAN_Bus *bus = connModel->getBus(selIdx); + if (bus->connection->getConnTypeName() == "GVRET") ui->rbGVRET->setChecked(true); + if (bus->connection->getConnTypeName() == "KVASER") ui->rbKvaser->setChecked(true); + if (bus->connection->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); + ui->ckListenOnly->setChecked(bus->isListenOnly()); + ui->ckSingleWire->setChecked(bus->isSingleWire()); + int speed = bus->getSpeed(); + setSpeed(speed); + connModel->refreshView(); } } @@ -284,3 +336,22 @@ void ConnectionWindow::handleRevert() { } + +void ConnectionWindow::sendFrame(const CANFrame *frame) +{ + CAN_Bus *bus = connModel->getBus(frame->bus); + if (bus == NULL) return; + QMetaObject::invokeMethod(bus->connection, "sendFrame", + Qt::QueuedConnection, + Q_ARG(const CANFrame *, frame)); +} + +void ConnectionWindow::sendFrameBatch(const QList *frames) +{ + if (frames->count() == 0) return; + CAN_Bus *bus = connModel->getBus(frames->at(0).bus); + if (bus == NULL) return; + QMetaObject::invokeMethod(bus->connection, "sendFrameBatch", + Qt::QueuedConnection, + Q_ARG(const QList *, frames)); +} diff --git a/connectionwindow.h b/connectionwindow.h index 399c838..b3efdd5 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -46,6 +46,8 @@ signals: public slots: void setSpeed(int speed0); void setSWMode(bool mode); + void sendFrame(const CANFrame *); + void sendFrameBatch(const QList *); private slots: void handleOKButton(); @@ -53,6 +55,7 @@ private slots: void handleConnSelectionChanged(); void handleRemoveConn(); void handleRevert(); + void handleNewConn(); void receiveBusStatus(int bus, int speed, int status); private: diff --git a/connectionwindow.ui b/connectionwindow.ui index 6dbd5fe..db0cd9a 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -33,6 +33,13 @@ + + + + New Connection + + + diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index f881ff5..bbf9860 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -125,6 +125,7 @@ void FirmwareUploaderWindow::sendFirmwareChunk() int xorByte = 0; output->extended = false; output->len = 7; + output->bus = bus; output->ID = baseAddress + 0x16; output->data[0] = currentSendingPosition & 0xFF; output->data[1] = (currentSendingPosition >> 8) & 0xFF; @@ -134,7 +135,7 @@ void FirmwareUploaderWindow::sendFirmwareChunk() output->data[5] = firmwareData[firmwareLocation++]; for (int i = 0; i < 6; i++) xorByte = xorByte ^ output->data[i]; output->data[6] = xorByte; - sendCANFrame(output, bus); + sendCANFrame(output); timer->start(); } @@ -142,13 +143,14 @@ void FirmwareUploaderWindow::sendFirmwareEnding() { CANFrame *output = new CANFrame; output->extended = false; + output->bus = bus; output->len = 4; output->ID = baseAddress + 0x30; output->data[0] = 0xC0; output->data[1] = 0xDE; output->data[2] = 0xFA; output->data[3] = 0xDE; - sendCANFrame(output, bus); + sendCANFrame(output); } void FirmwareUploaderWindow::handleStartStopTransfer() @@ -167,6 +169,7 @@ void FirmwareUploaderWindow::handleStartStopTransfer() CANFrame *output = new CANFrame; output->extended = false; output->len = 8; + output->bus = bus; output->ID = baseAddress; output->data[0] = 0xDE; output->data[1] = 0xAD; @@ -176,7 +179,7 @@ void FirmwareUploaderWindow::handleStartStopTransfer() output->data[5] = (token >> 8) & 0xFF; output->data[6] = (token >> 16) & 0xFF; output->data[7] = (token >> 24) & 0xFF; - sendCANFrame(output, bus); + sendCANFrame(output); } else //stop anything in process { diff --git a/firmwareuploaderwindow.h b/firmwareuploaderwindow.h index 5371c19..619a3b7 100644 --- a/firmwareuploaderwindow.h +++ b/firmwareuploaderwindow.h @@ -20,7 +20,7 @@ public: ~FirmwareUploaderWindow(); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); public slots: void gotTargettedFrame(int frameLoc); diff --git a/frameplaybackwindow.cpp b/frameplaybackwindow.cpp index 765f482..0754675 100644 --- a/frameplaybackwindow.cpp +++ b/frameplaybackwindow.cpp @@ -18,7 +18,7 @@ * */ -FramePlaybackWindow::FramePlaybackWindow(const QVector *frames, SerialWorker *worker, QWidget *parent) : +FramePlaybackWindow::FramePlaybackWindow(const QVector *frames, QWidget *parent) : QDialog(parent), ui(new Ui::FramePlaybackWindow) { @@ -33,7 +33,6 @@ FramePlaybackWindow::FramePlaybackWindow(const QVector *frames, Serial readSettings(); modelFrames = frames; - serialWorker = worker; playbackTimer = new QTimer(); @@ -70,9 +69,6 @@ FramePlaybackWindow::FramePlaybackWindow(const QVector *frames, Serial playbackTimer->setInterval(ui->spinPlaySpeed->value()); //set the timer to the default value of the control - connect(this, SIGNAL(sendCANFrame(const CANFrame*,int)), worker, SLOT(sendFrame(const CANFrame*,int)), Qt::QueuedConnection); - connect(this, SIGNAL(sendFrameBatch(const QList*)), worker, SLOT(sendFrameBatch(const QList*)), Qt::QueuedConnection); - QStringList headers; headers << "Source" << "Loops"; ui->tblSequence->setColumnCount(2); @@ -85,8 +81,6 @@ FramePlaybackWindow::~FramePlaybackWindow() { delete ui; - disconnect(serialWorker); - playbackTimer->stop(); delete playbackTimer; } diff --git a/frameplaybackwindow.h b/frameplaybackwindow.h index 07296dd..2c82753 100644 --- a/frameplaybackwindow.h +++ b/frameplaybackwindow.h @@ -27,7 +27,7 @@ class FramePlaybackWindow : public QDialog Q_OBJECT public: - explicit FramePlaybackWindow(const QVector *frames, SerialWorker *worker, QWidget *parent = 0); + explicit FramePlaybackWindow(const QVector *frames, QWidget *parent = 0); ~FramePlaybackWindow(); private slots: @@ -54,7 +54,7 @@ private slots: void loadFilters(); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); void sendFrameBatch(const QList *); private: @@ -65,7 +65,6 @@ private: const QVector *modelFrames; int currentPosition; QTimer *playbackTimer; - SerialWorker *serialWorker; bool playbackActive; bool playbackForward; int whichBusSend; diff --git a/framesenderwindow.cpp b/framesenderwindow.cpp index 91dd13c..e5b722c 100644 --- a/framesenderwindow.cpp +++ b/framesenderwindow.cpp @@ -151,7 +151,7 @@ void FrameSenderWindow::processIncomingFrame(CANFrame *frame) sendingData[sd].count++; doModifiers(sd); updateGridRow(sd); - sendCANFrame(&sendingData[sd], sendingData[sd].bus); + sendCANFrame(&sendingData[sd]); } else //delayed sending frame { @@ -354,7 +354,7 @@ void FrameSenderWindow::handleTick() doModifiers(i); updateGridRow(i); qDebug() << "About to try to send a frame"; - emit sendCANFrame(&sendingData[i], sendingData[i].bus); + emit sendCANFrame(&sendingData[i]); if (trigger->ID > 0) trigger->readyCount = false; //reset flag if this is a timed ID trigger } } diff --git a/framesenderwindow.h b/framesenderwindow.h index e80d585..5560e9e 100644 --- a/framesenderwindow.h +++ b/framesenderwindow.h @@ -31,7 +31,7 @@ private slots: void updatedFrames(int); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); private: Ui::FrameSenderWindow *ui; diff --git a/fuzzingwindow.h b/fuzzingwindow.h index 4521602..724d84c 100644 --- a/fuzzingwindow.h +++ b/fuzzingwindow.h @@ -29,7 +29,7 @@ public: ~FuzzingWindow(); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); void sendFrameBatch(const QList *); private slots: diff --git a/mainwindow.cpp b/mainwindow.cpp index 96377c8..4f6cd5f 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -184,8 +184,8 @@ MainWindow::MainWindow(QWidget *parent) : MainWindow::~MainWindow() { - serialWorkerThread.quit(); - serialWorkerThread.wait(); + //serialWorkerThread.quit(); + //serialWorkerThread.wait(); //delete worker; if (graphingWindow) @@ -339,16 +339,16 @@ void MainWindow::readSettings() ui->cbAutoScroll->setChecked(true); } + /* int cType = settings.value("Main/DefaultConnectionType", 0).toInt(); if (cType == 0) connType = "GVRET"; if (cType == 1) connType = "KVASER"; if (cType == 2) connType = "SOCKETCAN"; portName = settings.value("Main/DefaultConnectionPort", "").toString(); - canSpeed0 = -1; - canSpeed1 = -1; + */ - qDebug() << connType; - qDebug() << portName; + //qDebug() << connType; + //qDebug() << portName; //"Main/SingleWireMode" @@ -379,11 +379,11 @@ void MainWindow::writeSettings() void MainWindow::updateConnectionSettings(QString connectionType, QString port, int speed0, int speed1) { - connType = connectionType; - portName = port; + //connType = connectionType; + //portName = port; - canSpeed0 = speed0; - canSpeed1 = speed1; + //canSpeed0 = speed0; + //canSpeed1 = speed1; if (isConnected) { //emit updateBaudRates(speed0, speed1); @@ -863,7 +863,7 @@ void MainWindow::showFrameSenderWindow() else frameSenderWindow = new FrameSenderWindow(model->getFilteredListReference()); - connect(frameSenderWindow, &FrameSenderWindow::sendCANFrame, worker, &SerialWorker::sendFrame); + connect(frameSenderWindow, &FrameSenderWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); } frameSenderWindow->show(); } @@ -873,9 +873,12 @@ void MainWindow::showPlaybackWindow() if (!playbackWindow) { if (!useFiltered) - playbackWindow = new FramePlaybackWindow(model->getListReference(), worker); + playbackWindow = new FramePlaybackWindow(model->getListReference()); else - playbackWindow = new FramePlaybackWindow(model->getFilteredListReference(), worker); + playbackWindow = new FramePlaybackWindow(model->getFilteredListReference()); + + connect(playbackWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*)), Qt::QueuedConnection); + connect(playbackWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*)), Qt::QueuedConnection); } playbackWindow->show(); } @@ -885,8 +888,8 @@ void MainWindow::showFirmwareUploaderWindow() if (!firmwareUploaderWindow) { firmwareUploaderWindow = new FirmwareUploaderWindow(model->getListReference()); - connect(firmwareUploaderWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), worker, SLOT(sendFrame(const CANFrame*,int))); - connect(worker, SIGNAL(gotTargettedFrame(int)), firmwareUploaderWindow, SLOT(gotTargettedFrame(int))); + connect(firmwareUploaderWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); + //connect(worker, SIGNAL(gotTargettedFrame(int)), firmwareUploaderWindow, SLOT(gotTargettedFrame(int))); } firmwareUploaderWindow->show(); } @@ -914,8 +917,8 @@ void MainWindow::showFuzzingWindow() if (!fuzzingWindow) { fuzzingWindow = new FuzzingWindow(model->getListReference()); - connect(fuzzingWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), worker, SLOT(sendFrame(const CANFrame*,int))); - connect(fuzzingWindow, SIGNAL(sendFrameBatch(const QList*)), worker, SLOT(sendFrameBatch(const QList*))); + connect(fuzzingWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); + connect(fuzzingWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*))); } fuzzingWindow->show(); } @@ -925,7 +928,7 @@ void MainWindow::showUDSScanWindow() if (!udsScanWindow) { udsScanWindow = new UDSScanWindow(model->getListReference()); - connect(udsScanWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), worker, SLOT(sendFrame(const CANFrame*,int))); + connect(udsScanWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), connectionWindow, SLOT(sendFrame(const CANFrame*))); } udsScanWindow->show(); } @@ -935,7 +938,7 @@ void MainWindow::showScriptingWindow() if (!scriptingWindow) { scriptingWindow = new ScriptingWindow(model->getListReference()); - connect(scriptingWindow, &ScriptingWindow::sendCANFrame, worker, &SerialWorker::sendFrame); + connect(scriptingWindow, &ScriptingWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); } scriptingWindow->show(); } diff --git a/mainwindow.h b/mainwindow.h index 03bb1cd..cbe0c0d 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -108,8 +108,6 @@ private: //canbus related data CANFrameModel *model; DBCHandler *dbcHandler; - QThread serialWorkerThread; - SerialWorker *worker; QByteArray inputBuffer; QTimer updateTimer; QTime *elapsedTime; @@ -147,9 +145,6 @@ private: QLabel lbStatusDatabase; int normalRowHeight; bool isConnected; - QSerialPortInfo portInfo; - QString connType, portName; - int canSpeed0, canSpeed1; //private methods void saveDecodedTextFile(QString); diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 236b979..9e14e2d 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -111,7 +111,7 @@ void ScriptContainer::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSV if (frame.ID > 0x7FF) frame.extended = true; //qDebug() << "Sending frame from script"; - emit sendCANFrame(&frame, frame.bus); + emit sendCANFrame(&frame); } void ScriptContainer::gotFrame(const CANFrame &frame) diff --git a/scriptcontainer.h b/scriptcontainer.h index b570f12..fd4b33d 100644 --- a/scriptcontainer.h +++ b/scriptcontainer.h @@ -32,7 +32,7 @@ private slots: void tick(); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); private: QJSEngine scriptEngine; diff --git a/scriptingwindow.h b/scriptingwindow.h index d27620b..179e672 100644 --- a/scriptingwindow.h +++ b/scriptingwindow.h @@ -33,7 +33,7 @@ private slots: public slots: signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); private: void closeEvent(QCloseEvent *event); diff --git a/serialworker.cpp b/serialworker.cpp index a55f9d5..b35d672 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -564,4 +564,7 @@ void SerialWorker::updateBusSettings(CAN_Bus *bus) if (busNum < 0) return; if (busNum >= numBuses) return; qDebug() << "About to update bus " << busNum << " on GVRET"; + if (busNum == 0) can0Baud = bus->getSpeed(); + if (busNum == 1) can1Baud = bus->getSpeed(); + updateBaudRates(can0Baud,can1Baud); } diff --git a/udsscanwindow.cpp b/udsscanwindow.cpp index 7398477..a4c4f6c 100644 --- a/udsscanwindow.cpp +++ b/udsscanwindow.cpp @@ -210,7 +210,7 @@ void UDSScanWindow::sendNextMsg() currIdx++; if (currIdx < sendingFrames.count()) { - emit sendCANFrame(&sendingFrames[currIdx], sendingFrames[currIdx].bus); + emit sendCANFrame(&sendingFrames[currIdx]); waitTimer->start(); } else diff --git a/udsscanwindow.h b/udsscanwindow.h index 1066198..c53114b 100644 --- a/udsscanwindow.h +++ b/udsscanwindow.h @@ -18,7 +18,7 @@ public: ~UDSScanWindow(); signals: - void sendCANFrame(const CANFrame *, int); + void sendCANFrame(const CANFrame *); private slots: void updatedFrames(int numFrames); From 0210e963d560d4f4dcb46555de5ac693773b9c5b Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 29 Mar 2016 10:36:53 -0400 Subject: [PATCH 05/86] Changes to utilize new functionality of GVRET - ability to set listen only mode --- config.h | 4 +-- connectionwindow.cpp | 8 ++--- serialworker.cpp | 76 +++++++++++++++++++++++++++++++++++++++----- serialworker.h | 1 + 4 files changed, 75 insertions(+), 14 deletions(-) diff --git a/config.h b/config.h index 08e40d0..92a2526 100644 --- a/config.h +++ b/config.h @@ -1,12 +1,12 @@ #ifndef CONFIG #define CONFIG -#define VERSION 152 +#define VERSION 153 //try to keep this in sync. //SavvyCAN will complain if you connect a GVRET board with a revision //less than this number. -#define CURRENT_GVRET_VER 331 +#define CURRENT_GVRET_VER 334 #endif // CONFIG diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 3cff915..fe757f6 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -92,7 +92,7 @@ void ConnectionWindow::handleOKButton() QString conn; int connType = 0; int whichRow = ui->tableConnections->selectionModel()->currentIndex().row(); - qDebug() << whichRow; + qDebug() << "OK pressed. Row " << whichRow; if (whichRow > -1) { @@ -193,7 +193,7 @@ void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) void ConnectionWindow::handleConnSelectionChanged() { int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); - qDebug() << selIdx; + qDebug() << "Selection: " << selIdx; if (selIdx == -1) { ui->btnOK->setText(tr("Create New Connection")); @@ -220,7 +220,7 @@ void ConnectionWindow::handleConnSelectionChanged() ui->ckSingleWire->setChecked(bus->isSingleWire()); int speed = bus->getSpeed(); setSpeed(speed); - connModel->refreshView(); + //connModel->refreshView(); } } @@ -265,7 +265,7 @@ void ConnectionWindow::setSpeed(int speed0) { bool found = false; - qDebug() << speed0; + qDebug() << "Set Speed " << speed0; for (int i = 0; i < ui->cbSpeed->count(); i++) { diff --git a/serialworker.cpp b/serialworker.cpp index b35d672..31a6734 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -378,7 +378,8 @@ void SerialWorker::procRXChar(unsigned char c) switch (rx_step) { case 0: - can0Enabled = c; + can0Enabled = (c & 0xF); + can0ListenOnly = (c >> 4); break; case 1: can0Baud = c; @@ -393,7 +394,9 @@ void SerialWorker::procRXChar(unsigned char c) can0Baud |= c << 24; break; case 5: - can1Enabled = c; + can1Enabled = (c & 0xF); + can1ListenOnly = (c >> 4); + deviceSingleWireMode = (c >> 6); break; case 6: can1Baud = c; @@ -409,12 +412,27 @@ void SerialWorker::procRXChar(unsigned char c) rx_state = IDLE; qDebug() << "Baud 0 = " << can0Baud; qDebug() << "Baud 1 = " << can1Baud; - if (!can1Enabled) can1Baud = 0; - if (!can0Enabled) can0Baud = 0; + + can0Baud &= 0x80000000; + if (can0Enabled) can0Baud &= 0x40000000; + if (can0ListenOnly) can0Baud &= 0x20000000; + + can1Baud &= 0x80000000; + if (can1Enabled) can1Baud &= 0x40000000; + if (can1ListenOnly) can1Baud &= 0x20000000; + if (deviceSingleWireMode > 0) can1Baud &= 0x10000000; + isConnected = true; emit connectionSuccess(); - emit busStatus(busBase, can0Baud, can0Enabled?0x49:0x48); //say that we're updating baud rate and set enabled status - emit busStatus(busBase + 1, can1Baud, can1Enabled?0x49:0x48); + int can0Status = 0x78; //updating everything we can update + int can1Status = 0x78; + if (can0Enabled) can0Status +=1; + if (can0ListenOnly) can0Status += 4; + if (can1Enabled) can1Status += 1; + if (deviceSingleWireMode > 0) can1Status += 2; + if (can1ListenOnly) can1Status += 4; + emit busStatus(busBase, can0Baud, can0Status); + emit busStatus(busBase + 1, can1Baud, can1Status); break; } rx_step++; @@ -564,7 +582,49 @@ void SerialWorker::updateBusSettings(CAN_Bus *bus) if (busNum < 0) return; if (busNum >= numBuses) return; qDebug() << "About to update bus " << busNum << " on GVRET"; - if (busNum == 0) can0Baud = bus->getSpeed(); - if (busNum == 1) can1Baud = bus->getSpeed(); + if (busNum == 0) + { + can0Baud = bus->getSpeed(); + can0Baud &= 0x80000000; + if (bus->isActive()) + { + can0Baud &= 0x40000000; + can0Enabled = true; + } + else can0Enabled = false; + + if (bus->isListenOnly()) + { + can0Baud &= 0x20000000; + can0ListenOnly = true; + } + else can0ListenOnly = false; + } + if (busNum == 1) + { + can1Baud = bus->getSpeed(); + can1Baud &= 0x80000000; + if (bus->isActive()) + { + can1Baud &= 0x40000000; + can1Enabled = true; + } + else can1Enabled = false; + + if (bus->isListenOnly()) + { + can1Baud &= 0x20000000; + can1ListenOnly = true; + } + else can1ListenOnly = false; + + if (bus->isSingleWire()) + { + can1Baud &= 0x10000000; + deviceSingleWireMode = 1; + } + else deviceSingleWireMode = 0; + } + updateBaudRates(can0Baud,can1Baud); } diff --git a/serialworker.h b/serialworker.h index a83a637..41a8691 100644 --- a/serialworker.h +++ b/serialworker.h @@ -74,6 +74,7 @@ private: CANFrame *buildFrame; int can0Baud, can1Baud; bool can0Enabled, can1Enabled; + bool can0ListenOnly, can1ListenOnly; int deviceBuildNum; int deviceSingleWireMode; uint64_t txTimestampBasis; From ff5c9649a083c798f0b7efc049e0717526efd8f4 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 29 Mar 2016 21:25:07 -0400 Subject: [PATCH 06/86] Bug fixes, moved enable to a checkbox with the rest of the checkboxes. --- canconnection.h | 4 +-- connectionwindow.cpp | 81 +++++++++++++++++++++++++++----------------- connectionwindow.h | 3 ++ connectionwindow.ui | 18 +++++----- serialworker.cpp | 36 ++++++++++---------- 5 files changed, 82 insertions(+), 60 deletions(-) diff --git a/canconnection.h b/canconnection.h index 598d967..2a824cb 100644 --- a/canconnection.h +++ b/canconnection.h @@ -53,8 +53,8 @@ signals: void error(const QString &); void frameUpdateRapid(int); void frameUpdate(int); - void connectionSuccess(); - void connectionFailure(); + void connectionSuccess(CANConnection *); + void connectionFailure(CANConnection *); void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index fe757f6..cb61e1f 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -58,6 +58,8 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); connect(ui->btnNewConn, &QPushButton::clicked, this, &ConnectionWindow::handleNewConn); + connect(ui->btnActivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleEnableAll); + connect(ui->btnDeactivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleDisableAll); } ConnectionWindow::~ConnectionWindow() @@ -80,6 +82,16 @@ void ConnectionWindow::handleNewConn() handleConnSelectionChanged(); } +void ConnectionWindow::handleEnableAll() +{ + +} + +void ConnectionWindow::handleDisableAll() +{ + +} + void ConnectionWindow::handleConnTypeChanged() { if (ui->rbGVRET->isChecked()) getSerialPorts(); @@ -87,6 +99,38 @@ void ConnectionWindow::handleConnTypeChanged() if (ui->rbSocketCAN->isChecked()) getSocketcanPorts(); } +void ConnectionWindow::connectionSuccess(CANConnection *conn) +{ + CAN_Bus bus; + bus.active = true; + bus.busNum = conn->getBusBase(); + bus.connection = conn; + bus.listenOnly = ui->ckListenOnly->isChecked(); + bus.singleWire = ui->ckSingleWire->isChecked(); + + if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed + else if (ui->cbSpeed->currentIndex() == 1) + { + bus.speed = 0; + bus.active = false; + } + else bus.speed = ui->cbSpeed->currentText().toInt(); + connModel->addBus(bus); + + int numBuses = conn->getNumBuses(); + for (int i = 1; i < numBuses; i++) + { + bus.active = false; + bus.listenOnly = false; + bus.singleWire = false; + bus.speed = 250000; + bus.busNum = conn->getBusBase() + i; + bus.connection = conn; + connModel->addBus(bus); + qDebug() << "Added bus " << bus.busNum; + } +} + void ConnectionWindow::handleOKButton() { QString conn; @@ -101,6 +145,7 @@ void ConnectionWindow::handleOKButton() CAN_Bus *bus = connModel->getBus(whichRow); bus->setListenOnly(ui->ckListenOnly->isChecked()); bus->setSingleWire(ui->ckSingleWire->isChecked()); + bus->setEnabled(ui->ckEnabled->isChecked()); if (ui->cbSpeed->currentIndex() == 1) { bus->speed = 0; @@ -109,11 +154,12 @@ void ConnectionWindow::handleOKButton() else if (ui->cbSpeed->currentIndex() > 1) { bus->setSpeed(ui->cbSpeed->currentText().toInt()); - } + } //call through signal/slot interface without using connect QMetaObject::invokeMethod(bus->connection, "updateBusSettings", Qt::QueuedConnection, Q_ARG(CAN_Bus *, bus)); + connModel->refreshView(); } else //new connection { @@ -121,39 +167,11 @@ void ConnectionWindow::handleOKButton() { SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); connect(serial, SIGNAL(busStatus(int,int,int)), this, SLOT(receiveBusStatus(int,int,int))); + connect(serial, SIGNAL(connectionSuccess(CANConnection*)), this, SLOT(connectionSuccess(CANConnection*))); connModel->addConnection(serial); qDebug() << "Setup initial connection object"; - CAN_Bus bus; - bus.active = true; - bus.busNum = serial->getBusBase(); - bus.connection = serial; - bus.listenOnly = ui->ckListenOnly->isChecked(); - bus.singleWire = ui->ckSingleWire->isChecked(); - - if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed - else if (ui->cbSpeed->currentIndex() == 1) - { - bus.speed = 0; - bus.active = false; - } - else bus.speed = ui->cbSpeed->currentText().toInt(); - connModel->addBus(bus); - - int numBuses = serial->getNumBuses(); - for (int i = 1; i < numBuses; i++) - { - bus.active = false; - bus.listenOnly = false; - bus.singleWire = false; - bus.speed = 250000; - bus.busNum = serial->getBusBase() + i; - bus.connection = serial; - connModel->addBus(bus); - qDebug() << "Added bus " << bus.busNum; - } - //call through signal/slot interface without using connect QMetaObject::invokeMethod(serial, "updatePortName", Qt::QueuedConnection, @@ -204,6 +222,7 @@ void ConnectionWindow::handleConnSelectionChanged() ui->cbPort->setCurrentIndex(0); ui->ckListenOnly->setChecked(false); ui->ckSingleWire->setChecked(false); + ui->ckEnabled->setChecked(true); } else { @@ -218,9 +237,9 @@ void ConnectionWindow::handleConnSelectionChanged() if (bus->connection->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); ui->ckListenOnly->setChecked(bus->isListenOnly()); ui->ckSingleWire->setChecked(bus->isSingleWire()); + ui->ckEnabled->setChecked(bus->isActive()); int speed = bus->getSpeed(); setSpeed(speed); - //connModel->refreshView(); } } diff --git a/connectionwindow.h b/connectionwindow.h index b3efdd5..51b6c37 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -56,7 +56,10 @@ private slots: void handleRemoveConn(); void handleRevert(); void handleNewConn(); + void handleEnableAll(); + void handleDisableAll(); void receiveBusStatus(int bus, int speed, int status); + void connectionSuccess(CANConnection *conn); private: Ui::ConnectionWindow *ui; diff --git a/connectionwindow.ui b/connectionwindow.ui index db0cd9a..f157991 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -33,19 +33,12 @@ - - - - New Connection - - - - + - Activate Selected Connection + New Connection @@ -152,6 +145,13 @@ + + + + Enabled + + + diff --git a/serialworker.cpp b/serialworker.cpp index 31a6734..3b2bbf2 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -134,7 +134,7 @@ void SerialWorker::connectionTimeout() qDebug() << "Failed to connect to GVRET at that com port"; //ticker->stop(); closeSerialPort(); //make sure it's properly closed anyway - emit connectionFailure(); + emit connectionFailure(this); } } @@ -413,17 +413,17 @@ void SerialWorker::procRXChar(unsigned char c) qDebug() << "Baud 0 = " << can0Baud; qDebug() << "Baud 1 = " << can1Baud; - can0Baud &= 0x80000000; - if (can0Enabled) can0Baud &= 0x40000000; - if (can0ListenOnly) can0Baud &= 0x20000000; + can0Baud |= 0x80000000; + if (can0Enabled) can0Baud |= 0x40000000; + if (can0ListenOnly) can0Baud |= 0x20000000; - can1Baud &= 0x80000000; - if (can1Enabled) can1Baud &= 0x40000000; - if (can1ListenOnly) can1Baud &= 0x20000000; - if (deviceSingleWireMode > 0) can1Baud &= 0x10000000; + can1Baud |= 0x80000000; + if (can1Enabled) can1Baud |= 0x40000000; + if (can1ListenOnly) can1Baud |= 0x20000000; + if (deviceSingleWireMode > 0) can1Baud |= 0x10000000; isConnected = true; - emit connectionSuccess(); + emit connectionSuccess(this); int can0Status = 0x78; //updating everything we can update int can1Status = 0x78; if (can0Enabled) can0Status +=1; @@ -431,8 +431,8 @@ void SerialWorker::procRXChar(unsigned char c) if (can1Enabled) can1Status += 1; if (deviceSingleWireMode > 0) can1Status += 2; if (can1ListenOnly) can1Status += 4; - emit busStatus(busBase, can0Baud, can0Status); - emit busStatus(busBase + 1, can1Baud, can1Status); + emit busStatus(busBase, can0Baud & 0xFFFFF, can0Status); + emit busStatus(busBase + 1, can1Baud & 0xFFFFF, can1Status); break; } rx_step++; @@ -585,17 +585,17 @@ void SerialWorker::updateBusSettings(CAN_Bus *bus) if (busNum == 0) { can0Baud = bus->getSpeed(); - can0Baud &= 0x80000000; + can0Baud |= 0x80000000; if (bus->isActive()) { - can0Baud &= 0x40000000; + can0Baud |= 0x40000000; can0Enabled = true; } else can0Enabled = false; if (bus->isListenOnly()) { - can0Baud &= 0x20000000; + can0Baud |= 0x20000000; can0ListenOnly = true; } else can0ListenOnly = false; @@ -603,24 +603,24 @@ void SerialWorker::updateBusSettings(CAN_Bus *bus) if (busNum == 1) { can1Baud = bus->getSpeed(); - can1Baud &= 0x80000000; + can1Baud |= 0x80000000; if (bus->isActive()) { - can1Baud &= 0x40000000; + can1Baud |= 0x40000000; can1Enabled = true; } else can1Enabled = false; if (bus->isListenOnly()) { - can1Baud &= 0x20000000; + can1Baud |= 0x20000000; can1ListenOnly = true; } else can1ListenOnly = false; if (bus->isSingleWire()) { - can1Baud &= 0x10000000; + can1Baud |= 0x10000000; deviceSingleWireMode = 1; } else deviceSingleWireMode = 0; From a8c817bcd064941da28e826e193649b98643278a Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 29 Mar 2016 21:47:25 -0400 Subject: [PATCH 07/86] Switch to unsigned integers where appropriate. --- serialworker.cpp | 2 +- serialworker.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/serialworker.cpp b/serialworker.cpp index 3b2bbf2..36c26e7 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -205,7 +205,7 @@ void SerialWorker::sendFrameBatch(const QList *frames) sendBulkMutex.unlock(); } -void SerialWorker::updateBaudRates(int Speed1, int Speed2) +void SerialWorker::updateBaudRates(unsigned int Speed1, unsigned int Speed2) { QByteArray buffer; qDebug() << "Got signal to update bauds. 1: " << Speed1 <<" 2: " << Speed2; diff --git a/serialworker.h b/serialworker.h index 41a8691..9505281 100644 --- a/serialworker.h +++ b/serialworker.h @@ -53,7 +53,7 @@ public slots: void closeSerialPort(); void sendFrame(const CANFrame *) override; void sendFrameBatch(const QList *) override; - void updateBaudRates(int, int); + void updateBaudRates(unsigned int, unsigned int); //void stopFrameCapture(int) override; //void startFrameCapture(int) override; void updatePortName(QString) override; //string version of the port to connect to. This base doesnt know a thing about this value From 8f7dc4a34b4c212e378a66e28ab94185599f6972 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Fri, 6 May 2016 14:48:05 -0400 Subject: [PATCH 08/86] Some additional work on new connection window. --- connectionwindow.cpp | 20 ++++++++++++++++++-- connectionwindow.h | 2 ++ connectionwindow.ui | 18 +++++++++--------- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index fe757f6..134c8ee 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -58,6 +58,9 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); connect(ui->btnNewConn, &QPushButton::clicked, this, &ConnectionWindow::handleNewConn); + connect(ui->btnActivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleEnableAll); + connect(ui->btnDeactivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleDisableAll); + connect(ui->btnRemoveBus, &QPushButton::clicked, this, &ConnectionWindow::handleRemoveConn); } ConnectionWindow::~ConnectionWindow() @@ -101,6 +104,7 @@ void ConnectionWindow::handleOKButton() CAN_Bus *bus = connModel->getBus(whichRow); bus->setListenOnly(ui->ckListenOnly->isChecked()); bus->setSingleWire(ui->ckSingleWire->isChecked()); + bus->setEnabled(ui->ckEnabled->isChecked()); if (ui->cbSpeed->currentIndex() == 1) { bus->speed = 0; @@ -126,7 +130,7 @@ void ConnectionWindow::handleOKButton() qDebug() << "Setup initial connection object"; CAN_Bus bus; - bus.active = true; + bus.active = ui->ckEnabled->isChecked(); bus.busNum = serial->getBusBase(); bus.connection = serial; bus.listenOnly = ui->ckListenOnly->isChecked(); @@ -204,6 +208,7 @@ void ConnectionWindow::handleConnSelectionChanged() ui->cbPort->setCurrentIndex(0); ui->ckListenOnly->setChecked(false); ui->ckSingleWire->setChecked(false); + ui->ckEnabled->setChecked(true); } else { @@ -211,13 +216,14 @@ void ConnectionWindow::handleConnSelectionChanged() ui->cbPort->setEnabled(false); ui->rbGVRET->setEnabled(false); ui->rbKvaser->setEnabled(false); - ui->rbSocketCAN->setEnabled(false); + ui->rbSocketCAN->setEnabled(false); CAN_Bus *bus = connModel->getBus(selIdx); if (bus->connection->getConnTypeName() == "GVRET") ui->rbGVRET->setChecked(true); if (bus->connection->getConnTypeName() == "KVASER") ui->rbKvaser->setChecked(true); if (bus->connection->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); ui->ckListenOnly->setChecked(bus->isListenOnly()); ui->ckSingleWire->setChecked(bus->isSingleWire()); + ui->ckEnabled->setChecked(bus->isActive()); int speed = bus->getSpeed(); setSpeed(speed); //connModel->refreshView(); @@ -337,6 +343,16 @@ void ConnectionWindow::handleRevert() } +void ConnectionWindow::handleEnableAll() +{ + +} + +void ConnectionWindow::handleDisableAll() +{ + +} + void ConnectionWindow::sendFrame(const CANFrame *frame) { CAN_Bus *bus = connModel->getBus(frame->bus); diff --git a/connectionwindow.h b/connectionwindow.h index b3efdd5..b07a002 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -54,6 +54,8 @@ private slots: void handleConnTypeChanged(); void handleConnSelectionChanged(); void handleRemoveConn(); + void handleEnableAll(); + void handleDisableAll(); void handleRevert(); void handleNewConn(); void receiveBusStatus(int bus, int speed, int status); diff --git a/connectionwindow.ui b/connectionwindow.ui index db0cd9a..f157991 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -33,19 +33,12 @@ - - - - New Connection - - - - + - Activate Selected Connection + New Connection @@ -152,6 +145,13 @@ + + + + Enabled + + + From 97db24b69818f10252f42d3e20ab175deecf9c65 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:30:44 +0200 Subject: [PATCH 09/86] initial support for socketcan --- canbus.cpp | 6 ++ canbus.h | 11 +++ socketcanconnection.cpp | 157 ++++++++++++++++++++++++++++++++++++++++ socketcanconnection.h | 44 +++++++++++ 4 files changed, 218 insertions(+) create mode 100644 canbus.cpp create mode 100644 canbus.h create mode 100644 socketcanconnection.cpp create mode 100644 socketcanconnection.h diff --git a/canbus.cpp b/canbus.cpp new file mode 100644 index 0000000..882ca33 --- /dev/null +++ b/canbus.cpp @@ -0,0 +1,6 @@ +#include "canbus.h" + +CAN_Bus::CAN_Bus() +{ + +} diff --git a/canbus.h b/canbus.h new file mode 100644 index 0000000..d27d955 --- /dev/null +++ b/canbus.h @@ -0,0 +1,11 @@ +#ifndef CAN_BUS_H +#define CAN_BUS_H + + +class CAN_Bus +{ +public: + CAN_Bus(); +}; + +#endif // CAN_BUS_H \ No newline at end of file diff --git a/socketcanconnection.cpp b/socketcanconnection.cpp new file mode 100644 index 0000000..c39c7c0 --- /dev/null +++ b/socketcanconnection.cpp @@ -0,0 +1,157 @@ +#include +#include +#include + + +#include "canframemodel.h" +#include "canconnection.h" +#include "socketcanconnection.h" + +/***********************************/ +/**** nested class ****/ +/***********************************/ + + +BUSConfig::BUSConfig():isConfigured(false){} + +void BUSConfig::reset() { + isConfigured = false; +} + +bool BUSConfig::operator==(CANBus& bus) { + return isConfigured && speed == bus.speed && + listenOnly == bus.listenOnly && active == bus.active; +} + +void BUSConfig::operator=(CANBus& bus) { + isConfigured = true; + speed = bus.speed; + listenOnly = bus.listenOnly; + active = bus.active; +} + + + +/***********************************/ +/**** class definition ****/ +/***********************************/ + +SocketCanConnection::SocketCanConnection(CANFrameModel *model, int base) : CANConnection(model, base), mDev_p(NULL) +{ + qDebug() << "SocketCanConnection()"; + qRegisterMetaType("CANFrame"); +} + +SocketCanConnection::~SocketCanConnection() +{ + qDebug() << "~SocketCanConnection()"; + /* stop device */ +} + +void SocketCanConnection::updateBusSettings(CANBus bus) +{ + qDebug()<<"updateBusSettings"; + + if(mConf == bus) return; + + /* disconnect device if we have one connected */ + if(mDev_p) disconnect(); + + /* if bus is not active we are done */ + if(!bus.active) return; + + /* create device */ + mDev_p = QCanBus::instance()->createDevice("socketcan", portName); + if (!mDev_p) { + qDebug() << "can't create device"; + return; + } + + /* connect slots */ + connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCanConnection::errorReceived); + connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); + connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCanConnection::framesWritten); + + /* set configuration */ + /*if (p.useConfigurationEnabled) { + foreach (const SettingsDialog::ConfigurationItem &item, p.configurations) + mDev->setConfigurationParameter(item.first, item.second); + }*/ + + /* connect device */ + if (!mDev_p->connectDevice()) { + disconnect(); + qDebug() << "can't connect device"; + } +} + + +/***********************************/ +/**** private methods ****/ +/***********************************/ + + +/* connect device */ +void SocketCanConnection::disconnect() { + if(mDev_p) { + mDev_p->disconnectDevice(); + delete mDev_p; + mDev_p = Q_NULLPTR; + } +} + + +void SocketCanConnection::errorReceived(QCanBusDevice::CanBusError error) const +{ + switch (error) { + case QCanBusDevice::ReadError: + case QCanBusDevice::WriteError: + case QCanBusDevice::ConnectionError: + case QCanBusDevice::ConfigurationError: + case QCanBusDevice::UnknownError: + qWarning() << mDev_p->errorString(); + default: + break; + } +} + +void SocketCanConnection::framesWritten(qint64 count) +{ + qDebug() << "Number of frames written:" << count; +} + +void SocketCanConnection::framesReceived() +{ + /* sanity checks */ + if(!mDev_p) return; + + /* read frame */ + while(true) + { + const QCanBusFrame recFrame = mDev_p->readFrame(); + /* exit case */ + if(!recFrame.isValid()) return; + + if(!recFrame.payload().isEmpty() && + recFrame.payload().length()<=8) + { + CANFrame frame; + frame.len = recFrame.payload().length(); + frame.bus = 0; + memcpy(frame.data, recFrame.payload().data(), frame.len); + frame.extended = false; + frame.ID = recFrame.frameId(); + frame.isReceived = true; + frame.timestamp = recFrame.timeStamp().microSeconds(); + + /* send frame */ + QMetaObject::invokeMethod(model, "addFrame", + Qt::QueuedConnection, + Q_ARG(CANFrame, frame), + Q_ARG(bool, false)); + } + else { + qDebug() << "invalid frame"; + } + } +} diff --git a/socketcanconnection.h b/socketcanconnection.h new file mode 100644 index 0000000..18f5251 --- /dev/null +++ b/socketcanconnection.h @@ -0,0 +1,44 @@ +#ifndef SOCKETCANCONNECTION_H +#define SOCKETCANCONNECTION_H + +#include +#include + +#include "canframemodel.h" +#include "canconnection.h" + +class BUSConfig { +public: + BUSConfig(); + void reset(); + bool operator ==(CANBus&); + void operator =(CANBus&); + bool isConfigured; + int speed; + bool listenOnly; + bool active; +}; + + +class SocketCanConnection : public CANConnection +{ + Q_OBJECT + +public: + SocketCanConnection(CANFrameModel *, int); + virtual ~SocketCanConnection() override; + +public slots: + virtual void updateBusSettings(CANBus) override; + +private: + void errorReceived(QCanBusDevice::CanBusError error) const; + void framesWritten(qint64 count); + void framesReceived(); + void disconnect(); + + QCanBusDevice* mDev_p; + BUSConfig mConf; +}; + +#endif // SOCKETCANCONNECTION_H From 38d3b348323d5162e66e77a0131e648b9615a0ea Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:31:49 +0200 Subject: [PATCH 10/86] mv canbus to its own file --- canbus.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++- canbus.h | 33 +++++++++++++++++++---- 2 files changed, 104 insertions(+), 6 deletions(-) diff --git a/canbus.cpp b/canbus.cpp index 882ca33..6a8b35b 100644 --- a/canbus.cpp +++ b/canbus.cpp @@ -1,6 +1,81 @@ +#include #include "canbus.h" -CAN_Bus::CAN_Bus() +CANBus::CANBus() { + speed = 250000; + listenOnly = false; + singleWire = false; + active = false; + container = Q_NULLPTR; + busNum = 0; +} +CANBus::CANBus(const CANBus& pBus) : + speed(pBus.speed), + listenOnly(pBus.listenOnly), + singleWire(pBus.singleWire), + active(pBus.active), + container(pBus.container), /* TODO: check if container is really needed */ + busNum(pBus.busNum) {} + + +void CANBus::setSpeed(int newSpeed) +{ + speed = newSpeed; +} + +void CANBus::setListenOnly(bool mode) +{ + listenOnly = mode; +} + +void CANBus::setSingleWire(bool mode) +{ + singleWire = mode; +} + +void CANBus::setEnabled(bool mode) +{ + active = mode; +} + +void CANBus::setContainer(CANConnectionContainer* pContainer) +{ + container = pContainer; +} + +void CANBus::setBusNum(int num) +{ + busNum = num; +} + +int CANBus::getSpeed() +{ + return speed; +} + +int CANBus::getBusNum() +{ + return busNum; +} + +bool CANBus::isListenOnly() +{ + return listenOnly; +} + +bool CANBus::isSingleWire() +{ + return singleWire; +} + +bool CANBus::isActive() +{ + return active; +} + +CANConnectionContainer* CANBus::getContainer() +{ + return container; } diff --git a/canbus.h b/canbus.h index d27d955..a343c92 100644 --- a/canbus.h +++ b/canbus.h @@ -1,11 +1,34 @@ -#ifndef CAN_BUS_H -#define CAN_BUS_H +#ifndef CANBus_H +#define CANBus_H -class CAN_Bus +class CANConnectionContainer; + +class CANBus { public: - CAN_Bus(); + CANBus(); + CANBus(const CANBus&); + virtual ~CANBus(){}; /*TODO: remove connection from CANBus and add CANBus as an element of CANConnection */ + int busNum; + int speed; + bool listenOnly; + bool singleWire; + bool active; //is this bus turned on? + CANConnectionContainer* container; + + void setSpeed(int); // new speed + void setListenOnly(bool); //bool for whether to only listen + void setSingleWire(bool); //bool for whether to use single wire mode + void setEnabled(bool); //whether this bus should be enabled or not. + void setContainer(CANConnectionContainer *); + CANConnectionContainer* getContainer(); + void setBusNum(int); + int getSpeed(); + int getBusNum(); + bool isListenOnly(); + bool isSingleWire(); + bool isActive(); }; -#endif // CAN_BUS_H \ No newline at end of file +#endif // CANBus_H From e9f4dac3a1819a91d9caef05d4d31ed56270eed1 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:32:50 +0200 Subject: [PATCH 11/86] class to struct as the others --- can_structs.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/can_structs.h b/can_structs.h index 0326947..d118dc8 100644 --- a/can_structs.h +++ b/can_structs.h @@ -4,7 +4,7 @@ #include #include -class CANFrame +struct CANFrame { public: int ID; From 9ae3d4f9791401ee758a93bfe08ba93472d45958 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:34:15 +0200 Subject: [PATCH 12/86] removed can_bus and change slot from pointer to object as the object might have been deallocated when the slot is activated --- canconnection.cpp | 70 +---------------------------------------------- canconnection.h | 31 ++------------------- 2 files changed, 4 insertions(+), 97 deletions(-) diff --git a/canconnection.cpp b/canconnection.cpp index fb9ac11..70cf602 100644 --- a/canconnection.cpp +++ b/canconnection.cpp @@ -1,74 +1,6 @@ #include "canconnection.h" -CAN_Bus::CAN_Bus() -{ - speed = 250000; - listenOnly = false; - singleWire = false; - active = false; - connection = NULL; - busNum = 0; -} -void CAN_Bus::setSpeed(int newSpeed) -{ - speed = newSpeed; -} - -void CAN_Bus::setListenOnly(bool mode) -{ - listenOnly = mode; -} - -void CAN_Bus::setSingleWire(bool mode) -{ - singleWire = mode; -} - -void CAN_Bus::setEnabled(bool mode) -{ - active = mode; -} - -void CAN_Bus::setConnection(CANConnection *conn) -{ - connection = conn; -} - -void CAN_Bus::setBusNum(int num) -{ - busNum = num; -} - -int CAN_Bus::getSpeed() -{ - return speed; -} - -int CAN_Bus::getBusNum() -{ - return busNum; -} - -bool CAN_Bus::isListenOnly() -{ - return listenOnly; -} - -bool CAN_Bus::isSingleWire() -{ - return singleWire; -} - -bool CAN_Bus::isActive() -{ - return active; -} - -CANConnection* CAN_Bus::getConnection() -{ - return connection; -} CANConnection::CANConnection(CANFrameModel *pModel, int base) { @@ -127,7 +59,7 @@ void CANConnection::startFrameCapture(int bus) } -void CANConnection::updateBusSettings(CAN_Bus *bus) +void CANConnection::updateBusSettings(CANBus bus) { } diff --git a/canconnection.h b/canconnection.h index 2a824cb..d2aa0cb 100644 --- a/canconnection.h +++ b/canconnection.h @@ -4,35 +4,9 @@ #include #include #include "can_structs.h" +#include "canbus.h" #include "canframemodel.h" -class CANConnection; - -class CAN_Bus -{ -public: - CAN_Bus(); - int busNum; - int speed; - bool listenOnly; - bool singleWire; - bool active; //is this bus turned on? - CANConnection *connection; - - void setSpeed(int); // new speed - void setListenOnly(bool); //bool for whether to only listen - void setSingleWire(bool); //bool for whether to use single wire mode - void setEnabled(bool); //whether this bus should be enabled or not. - void setConnection(CANConnection *); - void setBusNum(int); - int getSpeed(); - int getBusNum(); - bool isListenOnly(); - bool isSingleWire(); - bool isActive(); - CANConnection *getConnection(); -}; - //Gentle reminder, CANConnection objects run in their own thread (each one, different thread) //so, for the love of God, do not try to access them directly. @@ -70,7 +44,8 @@ public slots: virtual void updatePortName(QString); //string version of the port to connect to. This base doesnt know a thing about this value virtual void stopFrameCapture(int); //pass bus number virtual void startFrameCapture(int); //pass bus number. Only if stopped. Defaults to started anyway - virtual void updateBusSettings(CAN_Bus *bus); //reference to the bus that changed. + /* this is not safe to use pointers with QueuedConnection */ + virtual void updateBusSettings(CANBus); //reference to the bus that changed. protected: bool quit; From 39e07dc3a7d0e53f9055aba96f2ecd0f431810d8 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:35:00 +0200 Subject: [PATCH 13/86] fixed thread deletion --- canconnectioncontainer.cpp | 6 +++++- canconnectioncontainer.h | 3 +-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/canconnectioncontainer.cpp b/canconnectioncontainer.cpp index 63a5069..302a3be 100644 --- a/canconnectioncontainer.cpp +++ b/canconnectioncontainer.cpp @@ -1,5 +1,6 @@ #include "canconnection.h" #include "canconnectioncontainer.h" +#include "mainwindow.h" CANConnectionContainer::CANConnectionContainer(CANConnection *conn) { @@ -7,7 +8,6 @@ CANConnectionContainer::CANConnectionContainer(CANConnection *conn) connection = conn; connection->moveToThread(thread); - connect(thread, &QThread::finished, conn, &QObject::deleteLater); connect(thread, &QThread::started, conn, &CANConnection::run); //setup timers within the proper thread connect(conn, &CANConnection::frameUpdateRapid, MainWindow::getReference(), &MainWindow::gotFrames, Qt::QueuedConnection); connect(MainWindow::getReference(), &MainWindow::sendCANFrame, conn, &CANConnection::sendFrame, Qt::QueuedConnection); @@ -18,6 +18,10 @@ CANConnectionContainer::CANConnectionContainer(CANConnection *conn) CANConnectionContainer::~CANConnectionContainer() { //have to stop the actual execution first before deleting + thread->quit(); + if(!thread->wait()) { + qDebug() << "can't stop thread"; + } delete thread; delete connection; } diff --git a/canconnectioncontainer.h b/canconnectioncontainer.h index 9ff2b22..8a4a429 100644 --- a/canconnectioncontainer.h +++ b/canconnectioncontainer.h @@ -1,10 +1,9 @@ #ifndef CANCONNECTIONCONTAINER_H #define CANCONNECTIONCONTAINER_H -#include "canconnection.h" #include #include -#include "mainwindow.h" +#include "canconnection.h" class CANConnectionContainer : public QObject { From 7165b113994267ac66d33ab1ff879721efba6e0e Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:36:26 +0200 Subject: [PATCH 14/86] change slot parameter from pointer to object as the object might have been deallocated when the slot is activated --- canframemodel.cpp | 3 ++- canframemodel.h | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index fe54877..57d542d 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -281,7 +281,8 @@ QVariant CANFrameModel::headerData(int section, Qt::Orientation orientation, return QVariant(); } -void CANFrameModel::addFrame(const CANFrame &frame, bool autoRefresh = false) + +void CANFrameModel::addFrame(CANFrame frame, bool autoRefresh = false) { mutex.lock(); CANFrame tempFrame; diff --git a/canframemodel.h b/canframemodel.h index 7e93007..f53db11 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -23,7 +23,6 @@ public: int columnCount(const QModelIndex &) const; int totalFrameCount(); - void addFrame(const CANFrame &, bool); void sendRefresh(); void sendRefresh(int); void sendBulkRefresh(int); @@ -46,6 +45,9 @@ public: const QVector *getFilteredListReference() const; //Thus saith the Lord, NO. const QMap *getFiltersReference() const; //this neither +public slots: + void addFrame(CANFrame, bool); + signals: void updatedFiltersList(); From 18b1a86a5658ed8082b20719c0ef01f21e3a96c2 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:45:17 +0200 Subject: [PATCH 15/86] under heavy work... --- canconnectionmodel.cpp | 31 ++++----- canconnectionmodel.h | 13 ++-- connectionwindow.cpp | 148 ++++++++++++++++++++++++++++------------- connectionwindow.h | 5 +- connectionwindow.ui | 68 ++++++++++++++++++- mainwindow.cpp | 5 +- 6 files changed, 194 insertions(+), 76 deletions(-) diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 8510f8d..7ec8ca7 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -71,8 +71,8 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const return QVariant(); if (role == Qt::DisplayRole) { - CAN_Bus bus = buses[index.row()]; - CANConnection *conn = bus.connection; + CANBus bus = buses[index.row()]; + CANConnection *conn = bus.getContainer()->getRef(); switch (index.column()) { case 0: //bus @@ -109,35 +109,32 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const return QVariant(); } -void CANConnectionModel::addConnection(CANConnection *conn) -{ - CAN_Bus bus; - CANConnectionContainer *cont = new CANConnectionContainer(conn); - connections.append(cont); -} -void CANConnectionModel::addBus(CAN_Bus &bus) +void CANConnectionModel::addBus(CANBus &bus) { beginResetModel(); buses.append(bus); endResetModel(); } -CAN_Bus* CANConnectionModel::getBus(int bus) +void CANConnectionModel::removeBus(int busIdx) +{ + if (busIdx>=0 && busIdx < buses.count()) { + beginResetModel(); + buses.removeAt(busIdx); + endResetModel(); + } +} + +CANBus* CANConnectionModel::getBus(int bus) { if (bus < 0) return NULL; if (bus >= buses.count()) return NULL; return &buses[bus]; } -CANConnection* CANConnectionModel::getConnection(int conn) -{ - if (conn < 0) return NULL; - if (conn >= connections.count()) return NULL; - return connections[conn]->getRef(); -} -CAN_Bus* CANConnectionModel::findBusByNum(int bus) +CANBus* CANConnectionModel::findBusByNum(int bus) { for (int i = 0; i < buses.count(); i++) { diff --git a/canconnectionmodel.h b/canconnectionmodel.h index 1e0410e..22dacdc 100644 --- a/canconnectionmodel.h +++ b/canconnectionmodel.h @@ -2,6 +2,7 @@ #define CANCONNECTIONMODEL_H #include "canconnection.h" +#include "canbus.h" #include "canconnectioncontainer.h" #include @@ -23,17 +24,19 @@ public: QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - void addConnection(CANConnection *conn); - void addBus(CAN_Bus &bus); - CAN_Bus* getBus(int bus); + void addConnection(CANConnectionContainer *conn); + void removeConnection(CANConnection*); + void addBus(CANBus &bus); + void removeBus(int busIdx); + CANBus* getBus(int bus); CANConnection* getConnection(int conn); void refreshView(); private: QList connections; - QList buses; + QList buses; - CAN_Bus *findBusByNum(int bus); + CANBus *findBusByNum(int bus); }; #endif // CANCONNECTIONMODEL_H diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 1ee5c74..8014093 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -1,6 +1,10 @@ +#include + #include "connectionwindow.h" #include "ui_connectionwindow.h" -#include +#include "socketcanconnection.h" + + ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : QDialog(parent), @@ -10,7 +14,7 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : settings = new QSettings(); - qRegisterMetaType("CAN_Bus *"); + qRegisterMetaType("CANBus"); qRegisterMetaType("const CANFrame *"); qRegisterMetaType *>("const QList *"); @@ -44,7 +48,7 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : ui->cbSpeed->addItem(tr("33333")); #ifdef Q_OS_LINUX - ui->rbSocketCAN->setEnabled(true); + ui->rbSocketCAN->setEnabled(isSocketCanAvailable()); #endif #ifdef Q_OS_WIN @@ -57,6 +61,7 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : connect(ui->rbSocketCAN, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); + connect(connModel, &QAbstractItemModel::modelReset, this, &ConnectionWindow::handleConnSelectionChanged); connect(ui->btnNewConn, &QPushButton::clicked, this, &ConnectionWindow::handleNewConn); connect(ui->btnActivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleEnableAll); connect(ui->btnDeactivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleDisableAll); @@ -102,7 +107,8 @@ void ConnectionWindow::handleConnTypeChanged() void ConnectionWindow::connectionSuccess(CANConnection *conn) { - CAN_Bus bus; +#if 0 + CANBus bus; bus.active = true; bus.busNum = conn->getBusBase(); bus.connection = conn; @@ -130,6 +136,7 @@ void ConnectionWindow::connectionSuccess(CANConnection *conn) connModel->addBus(bus); qDebug() << "Added bus " << bus.busNum; } +#endif } void ConnectionWindow::handleOKButton() @@ -141,9 +148,9 @@ void ConnectionWindow::handleOKButton() if (whichRow > -1) { - //load settings from GUI into appropriate CAN_Bus entry and then send it off to the appropriate + //load settings from GUI into appropriate CANBus entry and then send it off to the appropriate //CANConnection object - CAN_Bus *bus = connModel->getBus(whichRow); + CANBus *bus = connModel->getBus(whichRow); bus->setListenOnly(ui->ckListenOnly->isChecked()); bus->setSingleWire(ui->ckSingleWire->isChecked()); bus->setEnabled(ui->ckEnabled->isChecked()); @@ -157,9 +164,9 @@ void ConnectionWindow::handleOKButton() bus->setSpeed(ui->cbSpeed->currentText().toInt()); } //call through signal/slot interface without using connect - QMetaObject::invokeMethod(bus->connection, "updateBusSettings", + QMetaObject::invokeMethod(bus->getContainer()->getRef(), "updateBusSettings", Qt::QueuedConnection, - Q_ARG(CAN_Bus *, bus)); + Q_ARG(CANBus, *bus)); connModel->refreshView(); } else //new connection @@ -169,14 +176,15 @@ void ConnectionWindow::handleOKButton() SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); connect(serial, SIGNAL(busStatus(int,int,int)), this, SLOT(receiveBusStatus(int,int,int))); connect(serial, SIGNAL(connectionSuccess(CANConnection*)), this, SLOT(connectionSuccess(CANConnection*))); - connModel->addConnection(serial); + CANConnectionContainer* container = new CANConnectionContainer(serial); + qDebug() << "Setup initial connection object"; - CAN_Bus bus; + CANBus bus; bus.active = ui->ckEnabled->isChecked(); bus.busNum = serial->getBusBase(); - bus.connection = serial; + bus.container = container; bus.listenOnly = ui->ckListenOnly->isChecked(); bus.singleWire = ui->ckSingleWire->isChecked(); @@ -187,6 +195,7 @@ void ConnectionWindow::handleOKButton() bus.active = false; } else bus.speed = ui->cbSpeed->currentText().toInt(); + connModel->addBus(bus); int numBuses = serial->getNumBuses(); @@ -197,7 +206,7 @@ void ConnectionWindow::handleOKButton() bus.singleWire = false; bus.speed = 250000; bus.busNum = serial->getBusBase() + i; - bus.connection = serial; + bus.container = container; connModel->addBus(bus); qDebug() << "Added bus " << bus.busNum; } @@ -213,7 +222,42 @@ void ConnectionWindow::handleOKButton() } else if (ui->rbSocketCAN->isChecked()) { + /* TODO: sanity checks here */ + /* text, port, etc, ... */ + /* factorize code with other probes */ + /* create connection */ + SocketCanConnection* conn = new SocketCanConnection(canModel, 0); /* what is base? (second param) */ + + /* set port name */ + conn->updatePortName(ui->lePort->text()); + + /* add connection to a container (this creates the thread) */ + CANConnectionContainer* container = new CANConnectionContainer(conn); + + /* set bus configuration */ + CANBus bus; + bus.active = ui->ckEnabled->isChecked(); + bus.busNum = 0; // not used + bus.container = container; + bus.listenOnly = ui->ckListenOnly->isChecked(); + bus.singleWire = ui->ckSingleWire->isChecked(); + + if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed + else if (ui->cbSpeed->currentIndex() == 1) + { + bus.speed = 0; + bus.active = false; + } + else bus.speed = ui->cbSpeed->currentText().toInt(); + + /* add bus to model */ + connModel->addBus(bus); + + /* set bus settings (send message to thread) */ + QMetaObject::invokeMethod(conn, "updateBusSettings", + Qt::QueuedConnection, + Q_ARG(CANBus, bus)); } } } @@ -221,7 +265,7 @@ void ConnectionWindow::handleOKButton() void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) { qDebug() << "bus " << bus << " speed " << speed << " status " << status; - CAN_Bus *busRef = connModel->getBus(bus); + CANBus *busRef = connModel->getBus(bus); if (status & 40) busRef->setSpeed(speed); if (status & 8) //update enabled status { @@ -261,10 +305,10 @@ void ConnectionWindow::handleConnSelectionChanged() ui->rbGVRET->setEnabled(false); ui->rbKvaser->setEnabled(false); ui->rbSocketCAN->setEnabled(false); - CAN_Bus *bus = connModel->getBus(selIdx); - if (bus->connection->getConnTypeName() == "GVRET") ui->rbGVRET->setChecked(true); - if (bus->connection->getConnTypeName() == "KVASER") ui->rbKvaser->setChecked(true); - if (bus->connection->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); + CANBus *bus = connModel->getBus(selIdx); + if (bus->getContainer()->getRef()->getConnTypeName() == "GVRET") ui->rbGVRET->setChecked(true); + if (bus->getContainer()->getRef()->getConnTypeName() == "KVASER") ui->rbKvaser->setChecked(true); + if (bus->getContainer()->getRef()->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); ui->ckListenOnly->setChecked(bus->isListenOnly()); ui->ckSingleWire->setChecked(bus->isSingleWire()); ui->ckEnabled->setChecked(bus->isActive()); @@ -273,8 +317,12 @@ void ConnectionWindow::handleConnSelectionChanged() } } +/*TODO: rename the 3 following functions */ void ConnectionWindow::getSerialPorts() { + /* set combobox page visible */ + ui->stPort->setCurrentWidget(ui->cbPage); + ui->cbPort->clear(); ports = QSerialPortInfo::availablePorts(); @@ -287,26 +335,17 @@ void ConnectionWindow::getSerialPorts() void ConnectionWindow::getKvaserPorts() { - +#ifdef Q_OS_WIN + /* set combobox page visible */ + ui->stPort->setCurrentWidget(ui->cbPage); +#endif } void ConnectionWindow::getSocketcanPorts() { #ifdef Q_OS_LINUX - QList interfaces = QNetworkInterface::allInterfaces(); - QString interfaceName; - - ui->cbPort->clear(); - - foreach (QNetworkInterface interface, interfaces) - { - interfaceName = interface.name().toLower(); - qDebug() << "Interface: " << interface.name(); - if (interfaceName.contains("can")) - { - ui->cbPort->addItem(interfaceName); - } - } + /* set edit text page visible */ + ui->stPort->setCurrentWidget(ui->etPage); #endif } @@ -378,7 +417,22 @@ bool ConnectionWindow::getSWMode() void ConnectionWindow::handleRemoveConn() { +#if 0 + int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); + if (selIdx <=0) return; + CANBus* bus = conModel->getBus(selIdx); + if(!bus) return; + + /* remove connection to model (this creates the thread) */ + connModel->removeConnection(bus->connection); + + /* remove connection and reset model */ + conModel->removeBus(selIdx); + qDebug() << "remove connection at index: " << selIdx; + + selIdx +#endif } void ConnectionWindow::handleRevert() @@ -386,21 +440,11 @@ void ConnectionWindow::handleRevert() } -void ConnectionWindow::handleEnableAll() -{ - -} - -void ConnectionWindow::handleDisableAll() -{ - -} - void ConnectionWindow::sendFrame(const CANFrame *frame) { - CAN_Bus *bus = connModel->getBus(frame->bus); + CANBus *bus = connModel->getBus(frame->bus); if (bus == NULL) return; - QMetaObject::invokeMethod(bus->connection, "sendFrame", + QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrame", Qt::QueuedConnection, Q_ARG(const CANFrame *, frame)); } @@ -408,9 +452,21 @@ void ConnectionWindow::sendFrame(const CANFrame *frame) void ConnectionWindow::sendFrameBatch(const QList *frames) { if (frames->count() == 0) return; - CAN_Bus *bus = connModel->getBus(frames->at(0).bus); + CANBus *bus = connModel->getBus(frames->at(0).bus); if (bus == NULL) return; - QMetaObject::invokeMethod(bus->connection, "sendFrameBatch", + QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrameBatch", Qt::QueuedConnection, Q_ARG(const QList *, frames)); } + +bool ConnectionWindow::isSocketCanAvailable() +{ +#ifdef Q_OS_LINUX + foreach (const QByteArray &backend, QCanBus::instance()->plugins()) { + if (backend == "socketcan") { + return true; + } + } +#endif + return false; +} diff --git a/connectionwindow.h b/connectionwindow.h index 6d91216..5b0d9c0 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -40,7 +40,7 @@ public: bool getSWMode(); signals: - void updateBusSettings(CAN_Bus *bus); + void updateBusSettings(CANBus *bus); void updatePortName(QString port); public slots: @@ -58,8 +58,6 @@ private slots: void handleDisableAll(); void handleRevert(); void handleNewConn(); - void handleEnableAll(); - void handleDisableAll(); void receiveBusStatus(int bus, int speed, int status); void connectionSuccess(CANConnection *conn); @@ -74,6 +72,7 @@ private: void getSerialPorts(); void getKvaserPorts(); void getSocketcanPorts(); + bool isSocketCanAvailable(); }; #endif // CONNECTIONWINDOW_H diff --git a/connectionwindow.ui b/connectionwindow.ui index f157991..f3a5b39 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -6,8 +6,8 @@ 0 0 - 1009 - 433 + 956 + 527 @@ -129,7 +129,69 @@ - + + + + 0 + 0 + + + + + 0 + 22 + + + + Qt::LeftToRight + + + 0 + + + + + 0 + 0 + + + + Qt::LeftToRight + + + + + + + 0 + 0 + + + + + 341 + 16777215 + + + + + + + + + + + + + 0 + 0 + + + + + + + diff --git a/mainwindow.cpp b/mainwindow.cpp index 07aa433..68e27c0 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -47,7 +47,8 @@ MainWindow::MainWindow(QWidget *parent) : this->setWindowTitle("Savvy CAN V" + QString::number(VERSION)); - model = new CANFrameModel(); + model = new CANFrameModel(this); // set parent to mainwindow to prevent canframemodel to change thread (might be done by setModel but just in case) + ui->canFramesView->setModel(model); readSettings(); @@ -510,7 +511,7 @@ void MainWindow::gotFrames(int framesSinceLastUpdate) void MainWindow::addFrameToDisplay(CANFrame &frame, bool autoRefresh = false) { - model->addFrame(frame, autoRefresh); + model->addFrame(frame, autoRefresh); if (autoRefresh) { if (ui->cbAutoScroll->isChecked()) ui->canFramesView->scrollToBottom(); From 64079e8dcf6c02a84779132ab2548fc7d156e026 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:46:07 +0200 Subject: [PATCH 16/86] slight changes due to change of pointer for object --- serialworker.cpp | 76 +++++++++++++++++++++++++++--------------------- serialworker.h | 5 ++-- 2 files changed, 46 insertions(+), 35 deletions(-) diff --git a/serialworker.cpp b/serialworker.cpp index 36c26e7..281c050 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -11,7 +11,7 @@ SerialWorker::SerialWorker(CANFrameModel *model, int base) : CANConnection(model serial = NULL; rx_state = IDLE; rx_step = 0; - buildFrame = new CANFrame; + buildFrame; ticker = NULL; framesRapid = 0; gotValidated = true; @@ -166,8 +166,13 @@ void SerialWorker::sendFrame(const CANFrame *frame) //qDebug() << "Sending out frame with id " << frame->ID; - //show our sent frames in the list too. This happens even if we're not connected. - model->addFrame(tempFrame, false); + //show our sent frames in the list too. This happens even if we're not connected. + /* model lives in UI thread, we need to call invokeMethod */ + QMetaObject::invokeMethod(model, "addFrame", + Qt::QueuedConnection, + Q_ARG(CANFrame, tempFrame), + Q_ARG(bool, false)); + framesRapid++; if (serial == NULL) return; @@ -275,56 +280,61 @@ void SerialWorker::procRXChar(unsigned char c) switch (rx_step) { case 0: - buildFrame->timestamp = c; + buildFrame.timestamp = c; break; case 1: - buildFrame->timestamp |= (uint)(c << 8); + buildFrame.timestamp |= (uint)(c << 8); break; case 2: - buildFrame->timestamp |= (uint)c << 16; + buildFrame.timestamp |= (uint)c << 16; break; case 3: - buildFrame->timestamp |= (uint)c << 24; + buildFrame.timestamp |= (uint)c << 24; break; case 4: - buildFrame->ID = c; + buildFrame.ID = c; break; case 5: - buildFrame->ID |= c << 8; + buildFrame.ID |= c << 8; break; case 6: - buildFrame->ID |= c << 16; + buildFrame.ID |= c << 16; break; case 7: - buildFrame->ID |= c << 24; - if ((buildFrame->ID & 1 << 31) == 1 << 31) + buildFrame.ID |= c << 24; + if ((buildFrame.ID & 1 << 31) == 1 << 31) { - buildFrame->ID &= 0x7FFFFFFF; - buildFrame->extended = true; + buildFrame.ID &= 0x7FFFFFFF; + buildFrame.extended = true; } - else buildFrame->extended = false; + else buildFrame.extended = false; break; case 8: - buildFrame->len = c & 0xF; - if (buildFrame->len > 8) buildFrame->len = 8; - buildFrame->bus = (c & 0xF0) >> 4; + buildFrame.len = c & 0xF; + if (buildFrame.len > 8) buildFrame.len = 8; + buildFrame.bus = (c & 0xF0) >> 4; break; default: - if (rx_step < buildFrame->len + 9) + if (rx_step < buildFrame.len + 9) { - buildFrame->data[rx_step - 9] = c; + buildFrame.data[rx_step - 9] = c; } else { rx_state = IDLE; rx_step = 0; - //qDebug() << "emit from serial handler to main form id: " << buildFrame->ID; + //qDebug() << "emit from serial handler to main form id: " << buildFrame.ID; //if (capturing) //{ - buildFrame->isReceived = true; - model->addFrame(*buildFrame, false); + buildFrame.isReceived = true; + /* model lives in UI thread, we need to call invokeMethod */ + QMetaObject::invokeMethod(model, "addFrame", + Qt::QueuedConnection, + Q_ARG(CANFrame, buildFrame), + Q_ARG(bool, false)); + //take the time the frame came in and try to resync the time base. - if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame->timestamp / 1000); + if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame.timestamp / 1000); framesRapid++; //} } @@ -576,24 +586,24 @@ QString SerialWorker::getConnTypeName() return QString("GVRET"); } -void SerialWorker::updateBusSettings(CAN_Bus *bus) +void SerialWorker::updateBusSettings(CANBus bus) { - int busNum = bus->busNum - busBase; + int busNum = bus.busNum - busBase; if (busNum < 0) return; if (busNum >= numBuses) return; qDebug() << "About to update bus " << busNum << " on GVRET"; if (busNum == 0) { - can0Baud = bus->getSpeed(); + can0Baud = bus.getSpeed(); can0Baud |= 0x80000000; - if (bus->isActive()) + if (bus.isActive()) { can0Baud |= 0x40000000; can0Enabled = true; } else can0Enabled = false; - if (bus->isListenOnly()) + if (bus.isListenOnly()) { can0Baud |= 0x20000000; can0ListenOnly = true; @@ -602,23 +612,23 @@ void SerialWorker::updateBusSettings(CAN_Bus *bus) } if (busNum == 1) { - can1Baud = bus->getSpeed(); + can1Baud = bus.getSpeed(); can1Baud |= 0x80000000; - if (bus->isActive()) + if (bus.isActive()) { can1Baud |= 0x40000000; can1Enabled = true; } else can1Enabled = false; - if (bus->isListenOnly()) + if (bus.isListenOnly()) { can1Baud |= 0x20000000; can1ListenOnly = true; } else can1ListenOnly = false; - if (bus->isSingleWire()) + if (bus.isSingleWire()) { can1Baud |= 0x10000000; deviceSingleWireMode = 1; diff --git a/serialworker.h b/serialworker.h index 9505281..f9e57ec 100644 --- a/serialworker.h +++ b/serialworker.h @@ -10,6 +10,7 @@ #include "canframemodel.h" #include "canconnection.h" + namespace SERIALSTATE { enum STATE //keep this enum synchronized with the Arduino firmware project @@ -57,7 +58,7 @@ public slots: //void stopFrameCapture(int) override; //void startFrameCapture(int) override; void updatePortName(QString) override; //string version of the port to connect to. This base doesnt know a thing about this value - void updateBusSettings(CAN_Bus *bus) override; + void updateBusSettings(CANBus) override; private: bool doValidation; @@ -71,7 +72,7 @@ private: int framesRapid; STATE rx_state; int rx_step; - CANFrame *buildFrame; + CANFrame buildFrame; int can0Baud, can1Baud; bool can0Enabled, can1Enabled; bool can0ListenOnly, can1ListenOnly; From f36d432b501356facacae66dafa3bc731a4e81e9 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 8 Jun 2016 11:51:54 +0200 Subject: [PATCH 17/86] update .pro --- SavvyCAN.pro | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index ef81cb2..5dcd015 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -4,7 +4,7 @@ # #------------------------------------------------- -QT += core gui +QT += core gui serialbus greaterThan(QT_MAJOR_VERSION, 4): QT += widgets serialport printsupport qml @@ -51,7 +51,9 @@ SOURCES += main.cpp\ isotp_handler.cpp \ canconnectionmodel.cpp \ canconnection.cpp \ - canconnectioncontainer.cpp + canconnectioncontainer.cpp \ + socketcanconnection.cpp \ + canbus.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -89,7 +91,9 @@ HEADERS += mainwindow.h \ isotp_handler.h \ canconnectionmodel.h \ canconnection.h \ - canconnectioncontainer.h + canconnectioncontainer.h \ + socketcanconnection.h \ + canbus.h FORMS += mainwindow.ui \ graphingwindow.ui \ From 80719b253b8ae4490ca796bba7d81dc7021ff6e6 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:18:56 +0200 Subject: [PATCH 18/86] add lock free queue --- canconnection.cpp => canconnection_old.cpp | 0 canconnection.h => canconnection_old.h | 0 connections/canconconst.h | 4 + connections/canconfactory.cpp | 6 + connections/canconfactory.h | 11 ++ connections/canconnection.cpp | 6 + connections/canconnection.h | 11 ++ connections/gvretserial.cpp | 6 + connections/gvretserial.h | 11 ++ connections/socketcan.cpp | 157 +++++++++++++++++++++ connections/socketcan.h | 44 ++++++ test/test.pro | 12 ++ test/tst_lfqueue.cpp | 8 ++ utils/lfqueue.h | 91 ++++++++++++ 14 files changed, 367 insertions(+) rename canconnection.cpp => canconnection_old.cpp (100%) rename canconnection.h => canconnection_old.h (100%) create mode 100644 connections/canconconst.h create mode 100644 connections/canconfactory.cpp create mode 100644 connections/canconfactory.h create mode 100644 connections/canconnection.cpp create mode 100644 connections/canconnection.h create mode 100644 connections/gvretserial.cpp create mode 100644 connections/gvretserial.h create mode 100644 connections/socketcan.cpp create mode 100644 connections/socketcan.h create mode 100644 test/test.pro create mode 100644 test/tst_lfqueue.cpp create mode 100644 utils/lfqueue.h diff --git a/canconnection.cpp b/canconnection_old.cpp similarity index 100% rename from canconnection.cpp rename to canconnection_old.cpp diff --git a/canconnection.h b/canconnection_old.h similarity index 100% rename from canconnection.h rename to canconnection_old.h diff --git a/connections/canconconst.h b/connections/canconconst.h new file mode 100644 index 0000000..73cf76a --- /dev/null +++ b/connections/canconconst.h @@ -0,0 +1,4 @@ +#ifndef CANCONCONST_H +#define CANCONCONST_H + +#endif // CANCONCONST_H diff --git a/connections/canconfactory.cpp b/connections/canconfactory.cpp new file mode 100644 index 0000000..54095ab --- /dev/null +++ b/connections/canconfactory.cpp @@ -0,0 +1,6 @@ +#include "canconfactory.h" + +CanConFactory::CanConFactory() +{ + +} diff --git a/connections/canconfactory.h b/connections/canconfactory.h new file mode 100644 index 0000000..a2d8cbc --- /dev/null +++ b/connections/canconfactory.h @@ -0,0 +1,11 @@ +#ifndef CANCONFACTORY_H +#define CANCONFACTORY_H + + +class CanConFactory +{ +public: + CanConFactory(); +}; + +#endif // CANCONFACTORY_H \ No newline at end of file diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp new file mode 100644 index 0000000..8d3d73c --- /dev/null +++ b/connections/canconnection.cpp @@ -0,0 +1,6 @@ +#include "canconnection.h" + +CanConnection::CanConnection() +{ + +} diff --git a/connections/canconnection.h b/connections/canconnection.h new file mode 100644 index 0000000..8d740b7 --- /dev/null +++ b/connections/canconnection.h @@ -0,0 +1,11 @@ +#ifndef CANCONNECTION_H +#define CANCONNECTION_H + + +class CanConnection +{ +public: + CanConnection(); +}; + +#endif // CANCONNECTION_H \ No newline at end of file diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp new file mode 100644 index 0000000..6e163d7 --- /dev/null +++ b/connections/gvretserial.cpp @@ -0,0 +1,6 @@ +#include "cvretserial.h" + +CVRetSerial::CVRetSerial() +{ + +} diff --git a/connections/gvretserial.h b/connections/gvretserial.h new file mode 100644 index 0000000..12857c0 --- /dev/null +++ b/connections/gvretserial.h @@ -0,0 +1,11 @@ +#ifndef CVRETSERIAL_H +#define CVRETSERIAL_H + + +class CVRetSerial +{ +public: + CVRetSerial(); +}; + +#endif // CVRETSERIAL_H \ No newline at end of file diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp new file mode 100644 index 0000000..94eb4b7 --- /dev/null +++ b/connections/socketcan.cpp @@ -0,0 +1,157 @@ +#include +#include +#include + + +#include "canframemodel.h" +#include "canconnection_old.h" +#include "socketcanconnection.h" + +/***********************************/ +/**** nested class ****/ +/***********************************/ + + +BUSConfig::BUSConfig():isConfigured(false){} + +void BUSConfig::reset() { + isConfigured = false; +} + +bool BUSConfig::operator==(CANBus& bus) { + return isConfigured && speed == bus.speed && + listenOnly == bus.listenOnly && active == bus.active; +} + +void BUSConfig::operator=(CANBus& bus) { + isConfigured = true; + speed = bus.speed; + listenOnly = bus.listenOnly; + active = bus.active; +} + + + +/***********************************/ +/**** class definition ****/ +/***********************************/ + +SocketCanConnection::SocketCanConnection(CANFrameModel *model, int base) : CANConnection(model, base), mDev_p(NULL) +{ + qDebug() << "SocketCanConnection()"; + qRegisterMetaType("CANFrame"); +} + +SocketCanConnection::~SocketCanConnection() +{ + qDebug() << "~SocketCanConnection()"; + /* stop device */ +} + +void SocketCanConnection::updateBusSettings(CANBus bus) +{ + qDebug()<<"updateBusSettings"; + + if(mConf == bus) return; + + /* disconnect device if we have one connected */ + if(mDev_p) disconnect(); + + /* if bus is not active we are done */ + if(!bus.active) return; + + /* create device */ + mDev_p = QCanBus::instance()->createDevice("socketcan", portName); + if (!mDev_p) { + qDebug() << "can't create device"; + return; + } + + /* connect slots */ + connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCanConnection::errorReceived); + connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); + connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCanConnection::framesWritten); + + /* set configuration */ + /*if (p.useConfigurationEnabled) { + foreach (const SettingsDialog::ConfigurationItem &item, p.configurations) + mDev->setConfigurationParameter(item.first, item.second); + }*/ + + /* connect device */ + if (!mDev_p->connectDevice()) { + disconnect(); + qDebug() << "can't connect device"; + } +} + + +/***********************************/ +/**** private methods ****/ +/***********************************/ + + +/* connect device */ +void SocketCanConnection::disconnect() { + if(mDev_p) { + mDev_p->disconnectDevice(); + delete mDev_p; + mDev_p = Q_NULLPTR; + } +} + + +void SocketCanConnection::errorReceived(QCanBusDevice::CanBusError error) const +{ + switch (error) { + case QCanBusDevice::ReadError: + case QCanBusDevice::WriteError: + case QCanBusDevice::ConnectionError: + case QCanBusDevice::ConfigurationError: + case QCanBusDevice::UnknownError: + qWarning() << mDev_p->errorString(); + default: + break; + } +} + +void SocketCanConnection::framesWritten(qint64 count) +{ + qDebug() << "Number of frames written:" << count; +} + +void SocketCanConnection::framesReceived() +{ + /* sanity checks */ + if(!mDev_p) return; + + /* read frame */ + while(true) + { + const QCanBusFrame recFrame = mDev_p->readFrame(); + /* exit case */ + if(!recFrame.isValid()) return; + + if(!recFrame.payload().isEmpty() && + recFrame.payload().length()<=8) + { + CANFrame frame; + frame.len = recFrame.payload().length(); + frame.bus = 0; + memcpy(frame.data, recFrame.payload().data(), frame.len); + frame.extended = false; + frame.ID = recFrame.frameId(); + frame.isReceived = true; + frame.timestamp = recFrame.timeStamp().microSeconds(); + + /* send frame */ + QMetaObject::invokeMethod(model, "addFrame", + Qt::QueuedConnection, + Q_ARG(CANFrame, frame), + Q_ARG(bool, false)); + } + else { + qDebug() << "invalid frame"; + } + } +} diff --git a/connections/socketcan.h b/connections/socketcan.h new file mode 100644 index 0000000..1662501 --- /dev/null +++ b/connections/socketcan.h @@ -0,0 +1,44 @@ +#ifndef SOCKETCANCONNECTION_H +#define SOCKETCANCONNECTION_H + +#include +#include + +#include "canframemodel.h" +#include "canconnection_old.h" + +class BUSConfig { +public: + BUSConfig(); + void reset(); + bool operator ==(CANBus&); + void operator =(CANBus&); + bool isConfigured; + int speed; + bool listenOnly; + bool active; +}; + + +class SocketCanConnection : public CANConnection +{ + Q_OBJECT + +public: + SocketCanConnection(CANFrameModel *, int); + virtual ~SocketCanConnection() override; + +public slots: + virtual void updateBusSettings(CANBus) override; + +private: + void errorReceived(QCanBusDevice::CanBusError error) const; + void framesWritten(qint64 count); + void framesReceived(); + void disconnect(); + + QCanBusDevice* mDev_p; + BUSConfig mConf; +}; + +#endif // SOCKETCANCONNECTION_H diff --git a/test/test.pro b/test/test.pro new file mode 100644 index 0000000..58486c6 --- /dev/null +++ b/test/test.pro @@ -0,0 +1,12 @@ +QT += core +QT -= gui + +CONFIG += c++11 + +TARGET = test +CONFIG += console +CONFIG -= app_bundle + +TEMPLATE = app + +SOURCES += main.cpp diff --git a/test/tst_lfqueue.cpp b/test/tst_lfqueue.cpp new file mode 100644 index 0000000..470a030 --- /dev/null +++ b/test/tst_lfqueue.cpp @@ -0,0 +1,8 @@ +#include + +int main(int argc, char *argv[]) +{ + QCoreApplication a(argc, argv); + + return a.exec(); +} diff --git a/utils/lfqueue.h b/utils/lfqueue.h new file mode 100644 index 0000000..8a7d6d0 --- /dev/null +++ b/utils/lfqueue.h @@ -0,0 +1,91 @@ +#ifndef LFQUEUE_H +#define LFQUEUE_H + +#include +#include + + +/* macros */ +#define IS_EMPTY() ( mWIdx.load() == mRIdx.load() ) +#define IS_FULL() ( (mWIdx.load()+1)%mSize == mRIdx.load() ) + + +template +class LFQueue +{ +public: + LFQueue() : mSize(0), mArray(NULL){} + + ~LFQueue() {setSize(0);} + + bool setSize(int size) { + if(size<0) + return false; + + if(mArray) { + delete[] mArray; + mArray = NULL; + } + + if(size>0) { + mArray = new T[size]; + if(mArray) + mSize = size; + return ( mArray!=NULL ); + } + + return true; + } + + void flush() { + mRIdx.store(0); + mWIdx.store(0); + } + + T* get() { + if(IS_FULL()) + return NULL; + + return &(mArray[mWIdx.loadAcquire()]); /* prevent memory reordering (belt and braces) */ + } + + + void queue() { + #ifdef QT_DEBUG + if(IS_FULL()) + qCritical() << "BUG: queueing in full queue"; + #endif + + int wIdx = mWIdx.load(); + mWIdx.storeRelease((wIdx+1)%mSize); + } + + + T* peek() { + if(IS_EMPTY()) + return NULL; + + return &(mArray[mRIdx.loadAcquire()]); /* prevent memory reordering (belt and braces) */ + } + + + void dequeue() { + #ifdef QT_DEBUG + if(IS_EMPTY()) + qCritical() << "BUG: dequeueing an empty queue"; + #endif + + int rIdx = mRIdx.load(); + mRIdx.storeRelease((rIdx+1)%mSize); + } + + +private: + int mSize; + T* mArray; + + QAtomicInt mRIdx; + QAtomicInt mWIdx; +}; + +#endif // LFQUEUE_H From b83af0cfbde2d7e32c8bf78dfaffbb0dc2098a01 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:20:26 +0200 Subject: [PATCH 19/86] removed old files --- canconnection_old.cpp | 65 ------------------------------------------- canconnection_old.h | 60 --------------------------------------- 2 files changed, 125 deletions(-) delete mode 100644 canconnection_old.cpp delete mode 100644 canconnection_old.h diff --git a/canconnection_old.cpp b/canconnection_old.cpp deleted file mode 100644 index 70cf602..0000000 --- a/canconnection_old.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "canconnection.h" - - - -CANConnection::CANConnection(CANFrameModel *pModel, int base) -{ - model = pModel; - numBuses = getNumBuses(); - busBase = base; -} - -int CANConnection::getNumBuses() -{ - return 1; -} - -int CANConnection::getBusBase() -{ - return busBase; -} - -QString CANConnection::getConnTypeName() -{ - return QString("Generic"); -} - -QString CANConnection::getConnPortName() -{ - return portName; -} - -void CANConnection::run() -{ - -} - -void CANConnection::sendFrame(const CANFrame * frame) -{ - -} - -void CANConnection::sendFrameBatch(const QList *frames) -{ - -} - -void CANConnection::updatePortName(QString portName) -{ - this->portName = portName; -} - -void CANConnection::stopFrameCapture(int bus) -{ - -} - -void CANConnection::startFrameCapture(int bus) -{ - -} - -void CANConnection::updateBusSettings(CANBus bus) -{ - -} diff --git a/canconnection_old.h b/canconnection_old.h deleted file mode 100644 index d2aa0cb..0000000 --- a/canconnection_old.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef CANCONNECTION_H -#define CANCONNECTION_H - -#include -#include -#include "can_structs.h" -#include "canbus.h" -#include "canframemodel.h" - - -//Gentle reminder, CANConnection objects run in their own thread (each one, different thread) -//so, for the love of God, do not try to access them directly. -//Use the signal/slots system to do indirect calls. -//Please and thank you. -class CANConnection : public QObject -{ - Q_OBJECT - -public: - CANConnection(CANFrameModel *, int); - virtual int getNumBuses(); - int getBusBase(); - virtual QString getConnTypeName(); - QString getConnPortName(); - -signals: - void error(const QString &); - void frameUpdateRapid(int); - void frameUpdate(int); - void connectionSuccess(CANConnection *); - void connectionFailure(CANConnection *); - void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte - - //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) - //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only - //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really - //being passed. Just set for things that really are being updated. - void busStatus(int, int, int); - -public slots: - virtual void run(); - virtual void sendFrame(const CANFrame *); - virtual void sendFrameBatch(const QList *); - virtual void updatePortName(QString); //string version of the port to connect to. This base doesnt know a thing about this value - virtual void stopFrameCapture(int); //pass bus number - virtual void startFrameCapture(int); //pass bus number. Only if stopped. Defaults to started anyway - /* this is not safe to use pointers with QueuedConnection */ - virtual void updateBusSettings(CANBus); //reference to the bus that changed. - -protected: - bool quit; - int numBuses; - int busBase; //first bus this class is supposed to handle - QString portName; //for easy access later on - QString connType; //what kind of connection this is (socketcan, kvaser, etc) - bool isConnected; //is the whole device connected? (Is the code connected to the device itself) - CANFrameModel *model; -}; - -#endif // CANCONNECTION_H From 7192e11f38c095fa7edb09d9954121eaf490c9c6 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:21:41 +0200 Subject: [PATCH 20/86] removed old socketcanconnection --- socketcanconnection.cpp | 157 ---------------------------------------- socketcanconnection.h | 44 ----------- 2 files changed, 201 deletions(-) delete mode 100644 socketcanconnection.cpp delete mode 100644 socketcanconnection.h diff --git a/socketcanconnection.cpp b/socketcanconnection.cpp deleted file mode 100644 index c39c7c0..0000000 --- a/socketcanconnection.cpp +++ /dev/null @@ -1,157 +0,0 @@ -#include -#include -#include - - -#include "canframemodel.h" -#include "canconnection.h" -#include "socketcanconnection.h" - -/***********************************/ -/**** nested class ****/ -/***********************************/ - - -BUSConfig::BUSConfig():isConfigured(false){} - -void BUSConfig::reset() { - isConfigured = false; -} - -bool BUSConfig::operator==(CANBus& bus) { - return isConfigured && speed == bus.speed && - listenOnly == bus.listenOnly && active == bus.active; -} - -void BUSConfig::operator=(CANBus& bus) { - isConfigured = true; - speed = bus.speed; - listenOnly = bus.listenOnly; - active = bus.active; -} - - - -/***********************************/ -/**** class definition ****/ -/***********************************/ - -SocketCanConnection::SocketCanConnection(CANFrameModel *model, int base) : CANConnection(model, base), mDev_p(NULL) -{ - qDebug() << "SocketCanConnection()"; - qRegisterMetaType("CANFrame"); -} - -SocketCanConnection::~SocketCanConnection() -{ - qDebug() << "~SocketCanConnection()"; - /* stop device */ -} - -void SocketCanConnection::updateBusSettings(CANBus bus) -{ - qDebug()<<"updateBusSettings"; - - if(mConf == bus) return; - - /* disconnect device if we have one connected */ - if(mDev_p) disconnect(); - - /* if bus is not active we are done */ - if(!bus.active) return; - - /* create device */ - mDev_p = QCanBus::instance()->createDevice("socketcan", portName); - if (!mDev_p) { - qDebug() << "can't create device"; - return; - } - - /* connect slots */ - connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCanConnection::errorReceived); - connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); - connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCanConnection::framesWritten); - - /* set configuration */ - /*if (p.useConfigurationEnabled) { - foreach (const SettingsDialog::ConfigurationItem &item, p.configurations) - mDev->setConfigurationParameter(item.first, item.second); - }*/ - - /* connect device */ - if (!mDev_p->connectDevice()) { - disconnect(); - qDebug() << "can't connect device"; - } -} - - -/***********************************/ -/**** private methods ****/ -/***********************************/ - - -/* connect device */ -void SocketCanConnection::disconnect() { - if(mDev_p) { - mDev_p->disconnectDevice(); - delete mDev_p; - mDev_p = Q_NULLPTR; - } -} - - -void SocketCanConnection::errorReceived(QCanBusDevice::CanBusError error) const -{ - switch (error) { - case QCanBusDevice::ReadError: - case QCanBusDevice::WriteError: - case QCanBusDevice::ConnectionError: - case QCanBusDevice::ConfigurationError: - case QCanBusDevice::UnknownError: - qWarning() << mDev_p->errorString(); - default: - break; - } -} - -void SocketCanConnection::framesWritten(qint64 count) -{ - qDebug() << "Number of frames written:" << count; -} - -void SocketCanConnection::framesReceived() -{ - /* sanity checks */ - if(!mDev_p) return; - - /* read frame */ - while(true) - { - const QCanBusFrame recFrame = mDev_p->readFrame(); - /* exit case */ - if(!recFrame.isValid()) return; - - if(!recFrame.payload().isEmpty() && - recFrame.payload().length()<=8) - { - CANFrame frame; - frame.len = recFrame.payload().length(); - frame.bus = 0; - memcpy(frame.data, recFrame.payload().data(), frame.len); - frame.extended = false; - frame.ID = recFrame.frameId(); - frame.isReceived = true; - frame.timestamp = recFrame.timeStamp().microSeconds(); - - /* send frame */ - QMetaObject::invokeMethod(model, "addFrame", - Qt::QueuedConnection, - Q_ARG(CANFrame, frame), - Q_ARG(bool, false)); - } - else { - qDebug() << "invalid frame"; - } - } -} diff --git a/socketcanconnection.h b/socketcanconnection.h deleted file mode 100644 index 18f5251..0000000 --- a/socketcanconnection.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SOCKETCANCONNECTION_H -#define SOCKETCANCONNECTION_H - -#include -#include - -#include "canframemodel.h" -#include "canconnection.h" - -class BUSConfig { -public: - BUSConfig(); - void reset(); - bool operator ==(CANBus&); - void operator =(CANBus&); - bool isConfigured; - int speed; - bool listenOnly; - bool active; -}; - - -class SocketCanConnection : public CANConnection -{ - Q_OBJECT - -public: - SocketCanConnection(CANFrameModel *, int); - virtual ~SocketCanConnection() override; - -public slots: - virtual void updateBusSettings(CANBus) override; - -private: - void errorReceived(QCanBusDevice::CanBusError error) const; - void framesWritten(qint64 count); - void framesReceived(); - void disconnect(); - - QCanBusDevice* mDev_p; - BUSConfig mConf; -}; - -#endif // SOCKETCANCONNECTION_H From 4553dd59ee19c9785fae7a2804b8898acc63118c Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:22:39 +0200 Subject: [PATCH 21/86] new connection interface --- connections/canconconst.h | 20 ++++ connections/canconnection.cpp | 99 +++++++++++++++++- connections/canconnection.h | 186 +++++++++++++++++++++++++++++++++- 3 files changed, 301 insertions(+), 4 deletions(-) diff --git a/connections/canconconst.h b/connections/canconconst.h index 73cf76a..707355d 100644 --- a/connections/canconconst.h +++ b/connections/canconconst.h @@ -1,4 +1,24 @@ #ifndef CANCONCONST_H #define CANCONCONST_H +namespace CANCon { + + /** + * @brief The status enum + */ + enum status + { + NOT_CONNECTED, /*!< device is not connected */ + CONNECTED /*!< device is connected */ + }; + + enum type + { + GVRET_SERIAL, + KVASER, + SOCKETCAN, + NONE + }; +} + #endif // CANCONCONST_H diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 8d3d73c..b3059b8 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -1,6 +1,103 @@ #include "canconnection.h" -CanConnection::CanConnection() +CANConnection::CANConnection(QString pPort, CANCon::type pType, int pNumBuses) : + mQueue(), + mNumBuses(pNumBuses), + mPort(pPort), + mType(pType), + mIsCapSuspended(false), + mStatus(CANCon::NOT_CONNECTED) { + qDebug() << "CANConnection()"; + /* register types */ + qRegisterMetaType("CANBus"); + qRegisterMetaType("CANCon::status"); + + mBus = new CANBus[mNumBuses]; + mConfigured = new bool[mNumBuses]; + + for(int i=0 ; i= mNumBuses) + return false; + return mConfigured[pBusId]; +} + +void CANConnection::setConfigured(int pBusId, bool pConfigured) { + if( pBusId < 0 || pBusId >= mNumBuses) + return; + mConfigured[pBusId] = pConfigured; +} + + +bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) { + if( pBusId < 0 || pBusId >= mNumBuses || !isConfigured(pBusId)) + return false; + + pBus = mBus[pBusId]; + return true; +} + + +void CANConnection::setBusConfig(int pBusId, CANBus& pBus) { + if( pBusId < 0 || pBusId >= mNumBuses) + return; + + mConfigured[pBusId] = true; + mBus[pBusId] = pBus; +} + + +QString CANConnection::getPort() { + return mPort; +} + + +LFQueue& CANConnection::getQueue() { + return mQueue; +} + + +CANCon::type CANConnection::getType() { + return mType; +} + + +CANCon::status CANConnection::getStatus() { + return (CANCon::status) mStatus.load(); +} + + +void CANConnection::setStatus(CANCon::status pStatus) { + mStatus.store(pStatus); +} + +bool CANConnection::isCapSuspended() { + return mIsCapSuspended; +} + +void CANConnection::setCapSuspended(bool pIsSuspended) { + mIsCapSuspended = pIsSuspended; +} + diff --git a/connections/canconnection.h b/connections/canconnection.h index 8d740b7..5c9c68f 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -1,11 +1,191 @@ #ifndef CANCONNECTION_H #define CANCONNECTION_H +#include +#include +#include "utils/lfqueue.h" +#include "can_structs.h" +#include "canbus.h" +#include "canconconst.h" -class CanConnection + +class CANConnection : public QObject { + Q_OBJECT + public: - CanConnection(); + + /** + * @brief CANConnection constructor + * @param pPort: string containing port name + * @param pType: the type of connection @ref CANCon::type + * @param pNumBuses: the number of buses the device has + */ + CANConnection(QString pPort, CANCon::type pType, int pNumBuses); + /** + * @brief CANConnection destructor + */ + + virtual ~CANConnection(); + + /** + * @brief getNumBuses + * @return returns the number of buses of the device + * @note multithread safe + */ + int getNumBuses(); + + /** + * @brief getPort + * @return returns the port name of the device + * @note multithread safe + */ + QString getPort(); + + /** + * @brief getQueue is call by reader to get a reference on the queue to monitor + * @return the lock free queue of the device + * @note multithread safe + */ + LFQueue& getQueue(); + + /** + * @brief getType + * @return the @ref CANCon::type of the device + * @note multithread safe + */ + CANCon::type getType(); + + /** + * @brief getStatus + * @return the @ref CANCon::status of the device (either connected or not) + * @note multithread safe + */ + CANCon::status getStatus(); + + /** + * @brief start the device + * @note start a working thread here if needed + */ + virtual void start() = 0; + + /** + * @brief stop the device + * @note stop the working thread here if one has been started + */ + virtual void stop() = 0; + + +signals: + void error(const QString &); + void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte + + //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) + //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only + //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really + //being passed. Just set for things that really are being updated. + void busStatus(int, int, int); + + /** + * @brief event sent when the CANCon::status of the connection changes (connected->not_connected or the other way round) + * @param pStatus: the new status of the device + */ + void status(CANCon::status pStatus); + + +public slots: + + virtual void sendFrame(const CANFrame *) = 0; + virtual void sendFrameBatch(const QList *) = 0; + + /** + * @brief setBusSettings + * @param pBusIdx: the index of the bus for which settings have to be set + * @param pBus: the settings to set + */ + virtual void setBusSettings(int pBusIdx, CANBus pBus) = 0; + + /** + * @brief getBusSettings + * @param pBusIdx: the index of the bus for which settings have to be retrieved + * @param pBus: the CANBus struct to fill with information + * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet + */ + virtual bool getBusSettings(int pBusIdx, CANBus& pBus) = 0; + + /** + * @brief suspends/restarts data capture + * @param pSuspend: suspends capture if true else restarts it + * @note the caller will not access the queue when capture is suspended, so it is safe for callee to flush the queue + */ + virtual void suspend(bool pSuspend) = 0; + +protected: + + /** + * @brief setStatus + * @param pStatus: the status to set + * @note multithread safe (can be used while another thread calls @ref getStatus) + */ + void setStatus(CANCon::status pStatus); + + /** + * @brief isConfigured + * @param pBusId + * @return true if bus is configured + * @note NOT multithread safe + */ + bool isConfigured(int pBusId); + + /** + * @brief setConfigured + * @param pBusId + * @param pConfigured + * @note it is not necessary to call this function to set pBusId configured, it is enough to call @ref setBusConfig + * @note NOT multithread safe + */ + void setConfigured(int pBusId, bool pConfigured); + + /** + * @brief getBusConfig + * @param pBusId + * @param pBus + * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet + * @note NOT multithread safe + */ + bool getBusConfig(int pBusId, CANBus& pBus); + + /** + * @brief setBusConfig + * @param pBusId: the index of the bus for which settings have to be set + * @param pBus: the settings to set + * @note NOT multithread safe + */ + void setBusConfig(int pBusId, CANBus& pBus); + + /** + * @brief isCapSuspended + * @return true if the capture is suspended + * @note NOT multithread safe + */ + bool isCapSuspended(); + + /** + * @brief setCapSuspended + * @param pIsSuspended + * @note NOT multithread safe + */ + void setCapSuspended(bool pIsSuspended); + +private: + CANBus* mBus; + bool* mConfigured; + LFQueue mQueue; + const int mNumBuses; + const QString mPort; + const CANCon::type mType; + bool mIsCapSuspended; + QAtomicInt mStatus; }; -#endif // CANCONNECTION_H \ No newline at end of file +#endif // CANCONNECTION_H From cdff06ebe31bd1eaf0cf0448b54c089e99007502 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:23:21 +0200 Subject: [PATCH 22/86] new socketcan connection --- connections/socketcan.cpp | 221 ++++++++++++++++++++++++++++---------- connections/socketcan.h | 62 +++++++---- 2 files changed, 203 insertions(+), 80 deletions(-) diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 94eb4b7..76b6fe3 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -2,33 +2,7 @@ #include #include - -#include "canframemodel.h" -#include "canconnection_old.h" -#include "socketcanconnection.h" - -/***********************************/ -/**** nested class ****/ -/***********************************/ - - -BUSConfig::BUSConfig():isConfigured(false){} - -void BUSConfig::reset() { - isConfigured = false; -} - -bool BUSConfig::operator==(CANBus& bus) { - return isConfigured && speed == bus.speed && - listenOnly == bus.listenOnly && active == bus.active; -} - -void BUSConfig::operator=(CANBus& bus) { - isConfigured = true; - speed = bus.speed; - listenOnly = bus.listenOnly; - active = bus.active; -} +#include "socketcan.h" @@ -36,41 +10,120 @@ void BUSConfig::operator=(CANBus& bus) { /**** class definition ****/ /***********************************/ -SocketCanConnection::SocketCanConnection(CANFrameModel *model, int base) : CANConnection(model, base), mDev_p(NULL) +SocketCanConnection::SocketCanConnection(QString portName) : + CANConnection(portName, CANCon::SOCKETCAN, 1), + mDev_p(NULL), + mThread(NULL) { + getQueue().setSize(2000); /*TODO add check on returned value */ + /* move ourself to the thread */ + moveToThread(&mThread); + qDebug() << "SocketCanConnection()"; - qRegisterMetaType("CANFrame"); } + SocketCanConnection::~SocketCanConnection() { + stop(); qDebug() << "~SocketCanConnection()"; - /* stop device */ } -void SocketCanConnection::updateBusSettings(CANBus bus) -{ - qDebug()<<"updateBusSettings"; - if(mConf == bus) return; +void SocketCanConnection::start() { + + qDebug() << "enter thread"; + mThread.start(QThread::HighPriority); + + connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection())); + mTimer.setInterval(1000); + mTimer.setSingleShot(false); //keep ticking + mTimer.start(); +} + + +void SocketCanConnection::suspend(bool pSuspend) { + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + QMetaObject::invokeMethod(this, "suspend", + Qt::BlockingQueuedConnection, + Q_ARG(bool, pSuspend)); + return; + } + + /* update capSuspended */ + setCapSuspended(pSuspend); + + /* flush queue if we are suspended */ + if(isCapSuspended()) + getQueue().flush(); +} + + +void SocketCanConnection::stop() { + mTimer.stop(); + mThread.quit(); + if(!mThread.wait()) { + qDebug() << "can't stop thread"; + } + disconnectDevice(); +} + + +bool SocketCanConnection::getBusSettings(int pBusIdx, CANBus& pBus) { + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + bool ret; + QMetaObject::invokeMethod(this, "getBusSettings", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), + Q_ARG(int , pBusIdx), + Q_ARG(CANBus& , pBus)); + return ret; + } + + return getBusConfig(pBusIdx, pBus); +} + + +void SocketCanConnection::setBusSettings(int pBusIdx, CANBus bus) +{ + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + QMetaObject::invokeMethod(this, "setBusSettings", + Qt::BlockingQueuedConnection, + Q_ARG(int, pBusIdx), + Q_ARG(CANBus, bus)); + return; + } + + /* sanity checks */ + if(0 != pBusIdx) + return; /* disconnect device if we have one connected */ - if(mDev_p) disconnect(); + if(mDev_p) + disconnectDevice(); + + /* copy bus config */ + setBusConfig(0, bus); /* if bus is not active we are done */ - if(!bus.active) return; + if(!bus.active) + return; /* create device */ - mDev_p = QCanBus::instance()->createDevice("socketcan", portName); + mDev_p = QCanBus::instance()->createDevice("socketcan", getPort()); if (!mDev_p) { - qDebug() << "can't create device"; - return; + disconnectDevice(); + qDebug() << "can't create device"; + return; } /* connect slots */ connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCanConnection::errorReceived); - connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCanConnection::framesWritten); + connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); /* set configuration */ /*if (p.useConfigurationEnabled) { @@ -80,19 +133,23 @@ void SocketCanConnection::updateBusSettings(CANBus bus) /* connect device */ if (!mDev_p->connectDevice()) { - disconnect(); + disconnectDevice(); qDebug() << "can't connect device"; } } +void SocketCanConnection::sendFrame(const CANFrame *) {} +void SocketCanConnection::sendFrameBatch(const QList *){} + + /***********************************/ /**** private methods ****/ /***********************************/ -/* connect device */ -void SocketCanConnection::disconnect() { +/* disconnect device */ +void SocketCanConnection::disconnectDevice() { if(mDev_p) { mDev_p->disconnectDevice(); delete mDev_p; @@ -123,35 +180,81 @@ void SocketCanConnection::framesWritten(qint64 count) void SocketCanConnection::framesReceived() { /* sanity checks */ - if(!mDev_p) return; + if(!mDev_p) + return; /* read frame */ while(true) { const QCanBusFrame recFrame = mDev_p->readFrame(); - /* exit case */ - if(!recFrame.isValid()) return; + /* exit case */ + if(!recFrame.isValid()) + return; + + /* drop frame if capture is suspended */ + if(isCapSuspended()) + continue; + + /* check frame */ if(!recFrame.payload().isEmpty() && recFrame.payload().length()<=8) { - CANFrame frame; - frame.len = recFrame.payload().length(); - frame.bus = 0; - memcpy(frame.data, recFrame.payload().data(), frame.len); - frame.extended = false; - frame.ID = recFrame.frameId(); - frame.isReceived = true; - frame.timestamp = recFrame.timeStamp().microSeconds(); + CANFrame* frame_p = getQueue().get(); + if(frame_p) { + frame_p->len = recFrame.payload().length(); + frame_p->bus = 0; + memcpy(frame_p->data, recFrame.payload().data(), frame_p->len); + frame_p->extended = false; + frame_p->ID = recFrame.frameId(); + frame_p->isReceived = true; + frame_p->timestamp = recFrame.timeStamp().seconds()*1000000 + recFrame.timeStamp().microSeconds(); - /* send frame */ - QMetaObject::invokeMethod(model, "addFrame", - Qt::QueuedConnection, - Q_ARG(CANFrame, frame), - Q_ARG(bool, false)); + /* enqueue frame */ + getQueue().queue(); + } + else + qDebug() << "can't get a frame, ERROR"; } else { qDebug() << "invalid frame"; } } } + + +void SocketCanConnection::testConnection() { + QCanBusDevice* dev_p = QCanBus::instance()->createDevice("socketcan", getPort()); + + switch(getStatus()) + { + case CANCon::CONNECTED: + if (!dev_p || !dev_p->connectDevice()) { + /* we have lost connectivity */ + disconnectDevice(); + + setStatus(CANCon::NOT_CONNECTED); + emit status(getStatus()); + } + break; + case CANCon::NOT_CONNECTED: + if (dev_p && dev_p->connectDevice()) { + + /* try to reconnect */ + CANBus bus; + if(getBusConfig(0, bus)) + setBusSettings(0, bus); + + /* disconnect test instance */ + dev_p->disconnectDevice(); + + setStatus(CANCon::CONNECTED); + emit status(getStatus()); + } + break; + default: {} + } + + if(dev_p) + delete dev_p; +} diff --git a/connections/socketcan.h b/connections/socketcan.h index 1662501..eea37a9 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -3,21 +3,11 @@ #include #include +#include +#include #include "canframemodel.h" -#include "canconnection_old.h" - -class BUSConfig { -public: - BUSConfig(); - void reset(); - bool operator ==(CANBus&); - void operator =(CANBus&); - bool isConfigured; - int speed; - bool listenOnly; - bool active; -}; +#include "canconnection.h" class SocketCanConnection : public CANConnection @@ -25,20 +15,50 @@ class SocketCanConnection : public CANConnection Q_OBJECT public: - SocketCanConnection(CANFrameModel *, int); - virtual ~SocketCanConnection() override; + SocketCanConnection(QString portName); + virtual ~SocketCanConnection(); + + virtual void start(); + virtual void stop(); + + +signals: + void error(const QString &); + + void status(CANCon::status); + void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte + + //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) + //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only + //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really + //being passed. Just set for things that really are being updated. + void busStatus(int, int, int); + public slots: - virtual void updateBusSettings(CANBus) override; -private: - void errorReceived(QCanBusDevice::CanBusError error) const; + virtual void sendFrame(const CANFrame *); + virtual void sendFrameBatch(const QList *); + + virtual void setBusSettings(int, CANBus); + virtual bool getBusSettings(int pBusIdx, CANBus& pBus); + + virtual void suspend(bool); + +protected: + void disconnectDevice(); + +private slots: + void errorReceived(QCanBusDevice::CanBusError) const; void framesWritten(qint64 count); void framesReceived(); - void disconnect(); + void testConnection(); - QCanBusDevice* mDev_p; - BUSConfig mConf; +protected: + QCanBusDevice* mDev_p; + QTimer mTimer; + QThread mThread; }; + #endif // SOCKETCANCONNECTION_H From 6e623015dd39c83a2ce496e273ba901d6dd8ba79 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:24:01 +0200 Subject: [PATCH 23/86] attempt to adapt GVRET to the new interface --- connections/gvretserial.cpp | 609 +++++++++++++++++++++++++++++++++++- connections/gvretserial.h | 114 ++++++- 2 files changed, 715 insertions(+), 8 deletions(-) diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index 6e163d7..96666d5 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -1,6 +1,611 @@ -#include "cvretserial.h" +#include +#include +#include +#include +#include -CVRetSerial::CVRetSerial() +#include "gvretserial.h" + +GVRetSerial::GVRetSerial(QString portName) : + CANConnection(portName, CANCon::GVRET_SERIAL, 2), + mThread(NULL) { + getQueue().setSize(2000); /*TODO add check on returned value */ + /* move ourself to the thread */ + moveToThread(&mThread); + qDebug() << "GVRetSerial()"; + + serial = NULL; + rx_state = IDLE; + rx_step = 0; + gotValidated = true; + isAutoRestart = false; + + txTimestampBasis = QDateTime::currentMSecsSinceEpoch(); + + readSettings(); +} + + +GVRetSerial::~GVRetSerial() +{ + stop(); + qDebug() << "~GVRetSerial()"; +} + + +void GVRetSerial::start() +{ + qDebug() << "enter thread"; + /* start thread */ + mThread.start(QThread::HighPriority); + /* connect device in thread context */ + connect(&mThread, SIGNAL(started()), this, SLOT(connectDevice())); + + /* start timer */ + connect(&mTimer, SIGNAL(timeout()), this, SLOT(handleTick())); + mTimer.setInterval(250); //tick four times per second + mTimer.setSingleShot(false); //keep ticking + mTimer.start(); +} + + +void GVRetSerial::suspend(bool pSuspend) { + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + QMetaObject::invokeMethod(this, "suspend", + Qt::BlockingQueuedConnection, + Q_ARG(bool, pSuspend)); + return; + } + + /* update capSuspended */ + setCapSuspended(pSuspend); + + /* flush queue if we are suspended */ + if(isCapSuspended()) + getQueue().flush(); +} + + +void GVRetSerial::stop() { + mTimer.stop(); + mThread.quit(); + if(!mThread.wait()) { + qDebug() << "can't stop thread"; + } + disconnectDevice(); +} + + +bool GVRetSerial::getBusSettings(int pBusIdx, CANBus& pBus) { + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + bool ret; + QMetaObject::invokeMethod(this, "getBusSettings", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), + Q_ARG(int , pBusIdx), + Q_ARG(CANBus& , pBus)); + return ret; + } + + return getBusConfig(pBusIdx, pBus); +} + + +void GVRetSerial::sendFrame(const CANFrame *) {} +void GVRetSerial::sendFrameBatch(const QList *){} + + + +void GVRetSerial::readSettings() +{ + QSettings settings; + + if (settings.value("Main/ValidateComm", true).toBool()) + { + doValidation = true; + } + else doValidation = false; +} + + +void GVRetSerial::connectDevice() +{ + QSettings settings; + + /* disconnect device */ + if(serial) + disconnectDevice(); + + /* open new device */ + serial = new QSerialPort(QSerialPortInfo(getPort())); + if(!serial) { + qDebug() << "can't open serial port " << getPort(); + return; + } + + /* configure */ + serial->setDataBits(serial->Data8); + serial->setFlowControl(serial->HardwareControl); //this is important though + if (!serial->open(QIODevice::ReadWrite)) + { + qDebug() << serial->errorString(); + } + serial->setDataTerminalReady(true); //you do need to set these or the fan gets dirty + serial->setRequestToSend(true); + + + QByteArray output; + output.append((char)0xE7); //this puts the device into binary comm mode + output.append((char)0xE7); + + output.append((char)0xF1); //signal we want to issue a command + output.append((char)0x06); //request canbus stats from the board + + 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 + if (settings.value("Main/SingleWireMode", false).toBool()) + { + output.append((char)0x10); //signal that we do want single wire mode + } + else + { + output.append((char)0xFF); //signal we don't want single wire mode + } + + output.append((char)0xF1); //yet another command + output.append((char)0x09); //comm validation command + + output.append((char)0xF1); //and another command + output.append((char)0x01); //Time Sync - Not implemented until 333 but we can try + + continuousTimeSync = true; + + serial->write(output); + + if(doValidation) { + QTimer::singleShot(1000, this, SLOT(connectionTimeout())); + } + else { + setStatus(CANCon::CONNECTED); + emit status(getStatus()); + } + + /* connect reading event */ + connect(serial, SIGNAL(readyRead()), this, SLOT(readSerialData())); +} + + +void GVRetSerial::disconnectDevice() { + if (serial != NULL) + { + if (serial->isOpen()) + { + serial->clear(); + serial->close(); + + } + serial->disconnect(); //disconnect all signals + delete serial; + serial = NULL; + } +} + + +void GVRetSerial::connectionTimeout() +{ + //one second after trying to connect are we actually connected? + if (CANCon::NOT_CONNECTED==getStatus()) //no? + { + //then emit the the failure signal and see if anyone cares + qDebug() << "Failed to connect to GVRET at that com port"; + + disconnectDevice(); + } +} + + +void GVRetSerial::readSerialData() +{ + QByteArray data = serial->readAll(); + unsigned char c; + //qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); + for (int i = 0; i < data.length(); i++) + { + c = data.at(i); + procRXChar(c); + } +} + + +void GVRetSerial::procRXChar(unsigned char c) +{ + switch (rx_state) + { + case IDLE: + if (c == 0xF1) rx_state = GET_COMMAND; + break; + case GET_COMMAND: + switch (c) + { + case 0: //receiving a can frame + rx_state = BUILD_CAN_FRAME; + rx_step = 0; + break; + case 1: //time sync + rx_state = TIME_SYNC; + rx_step = 0; + break; + case 2: //process a return reply for digital input states. + rx_state = GET_DIG_INPUTS; + rx_step = 0; + break; + case 3: //process a return reply for analog inputs + rx_state = GET_ANALOG_INPUTS; + break; + case 4: //we set digital outputs we don't accept replies so nothing here. + rx_state = IDLE; + break; + case 5: //we set canbus specs we don't accept replies. + rx_state = IDLE; + break; + case 6: //get canbus parameters from GVRET + rx_state = GET_CANBUS_PARAMS; + rx_step = 0; + break; + case 7: //get device info + rx_state = GET_DEVICE_INFO; + rx_step = 0; + break; + case 9: + gotValidated = true; + //qDebug() << "Got validated"; + rx_state = IDLE; + break; + } + break; + case BUILD_CAN_FRAME: + switch (rx_step) + { + case 0: + buildFrame.timestamp = c; + break; + case 1: + buildFrame.timestamp |= (uint)(c << 8); + break; + case 2: + buildFrame.timestamp |= (uint)c << 16; + break; + case 3: + buildFrame.timestamp |= (uint)c << 24; + break; + case 4: + buildFrame.ID = c; + break; + case 5: + buildFrame.ID |= c << 8; + break; + case 6: + buildFrame.ID |= c << 16; + break; + case 7: + buildFrame.ID |= c << 24; + if ((buildFrame.ID & 1 << 31) == 1 << 31) + { + buildFrame.ID &= 0x7FFFFFFF; + buildFrame.extended = true; + } + else buildFrame.extended = false; + break; + case 8: + buildFrame.len = c & 0xF; + if (buildFrame.len > 8) buildFrame.len = 8; + buildFrame.bus = (c & 0xF0) >> 4; + break; + default: + if (rx_step < buildFrame.len + 9) + { + buildFrame.data[rx_step - 9] = c; + } + else + { + rx_state = IDLE; + rx_step = 0; + buildFrame.isReceived = true; + + if (!isCapSuspended()) + { + /* get frame from queue */ + CANFrame* frame_p = getQueue().get(); + if(frame_p) { + /* copy frame */ + *frame_p = buildFrame; + /* enqueue frame */ + getQueue().queue(); + } + else + qDebug() << "can't get a frame, ERROR"; + + //take the time the frame came in and try to resync the time base. + if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame.timestamp / 1000); + } + } + break; + } + rx_step++; + break; + case TIME_SYNC: //gives a pretty good base guess for the proper timestamp. Can be refined when traffic starts to flow (if wanted) + switch (rx_step) + { + case 0: + buildTimeBasis = c; + break; + case 1: + buildTimeBasis += ((uint32_t)c << 8); + break; + case 2: + buildTimeBasis += ((uint32_t)c << 16); + break; + case 3: + buildTimeBasis += ((uint32_t)c << 24); + qDebug() << "GVRET firmware reports timestamp of " << buildTimeBasis; + txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - ((uint64_t)buildTimeBasis / (uint64_t)1000ull); + continuousTimeSync = false; + rx_state = IDLE; + break; + } + rx_step++; + break; + + case GET_ANALOG_INPUTS: //get 9 bytes - 2 per analog input plus checksum + switch (rx_step) + { + case 0: + break; + } + rx_step++; + break; + case GET_DIG_INPUTS: //get two bytes. One for digital in status and one for checksum. + switch (rx_step) + { + case 0: + break; + case 1: + rx_state = IDLE; + break; + } + rx_step++; + break; + case GET_CANBUS_PARAMS: + switch (rx_step) + { + case 0: + can0Enabled = (c & 0xF); + can0ListenOnly = (c >> 4); + break; + case 1: + can0Baud = c; + break; + case 2: + can0Baud |= c << 8; + break; + case 3: + can0Baud |= c << 16; + break; + case 4: + can0Baud |= c << 24; + break; + case 5: + can1Enabled = (c & 0xF); + can1ListenOnly = (c >> 4); + deviceSingleWireMode = (c >> 6); + break; + case 6: + can1Baud = c; + break; + case 7: + can1Baud |= c << 8; + break; + case 8: + can1Baud |= c << 16; + break; + case 9: + can1Baud |= c << 24; + rx_state = IDLE; + qDebug() << "Baud 0 = " << can0Baud; + qDebug() << "Baud 1 = " << can1Baud; + + can0Baud |= 0x80000000; + if (can0Enabled) can0Baud |= 0x40000000; + if (can0ListenOnly) can0Baud |= 0x20000000; + + can1Baud |= 0x80000000; + if (can1Enabled) can1Baud |= 0x40000000; + if (can1ListenOnly) can1Baud |= 0x20000000; + if (deviceSingleWireMode > 0) can1Baud |= 0x10000000; + + setStatus(CANCon::CONNECTED); + emit status(getStatus()); + + int can0Status = 0x78; //updating everything we can update + int can1Status = 0x78; + if (can0Enabled) can0Status +=1; + if (can0ListenOnly) can0Status += 4; + if (can1Enabled) can1Status += 1; + if (deviceSingleWireMode > 0) can1Status += 2; + if (can1ListenOnly) can1Status += 4; + //emit busStatus(busBase, can0Baud & 0xFFFFF, can0Status); + //emit busStatus(busBase + 1, can1Baud & 0xFFFFF, can1Status); + break; + } + rx_step++; + break; + case GET_DEVICE_INFO: + switch (rx_step) + { + case 0: + deviceBuildNum = c; + break; + case 1: + deviceBuildNum |= c << 8; + break; + case 2: + break; //don't care about eeprom version + case 3: + break; //don't care about file type + case 4: + break; //don't care about whether it auto logs or not + case 5: + deviceSingleWireMode = c; + rx_state = IDLE; + qDebug() << "build num: " << deviceBuildNum; + qDebug() << "single wire can: " << deviceSingleWireMode; + emit deviceInfo(deviceBuildNum, deviceSingleWireMode); + break; + } + rx_step++; + break; + case SET_DIG_OUTPUTS: + rx_state = IDLE; + break; + case SETUP_CANBUS: + rx_state = IDLE; + break; + case SET_SINGLEWIRE_MODE: + rx_state = IDLE; + break; + + } +} + + +void GVRetSerial::handleTick() +{ + //qDebug() << "Tick!"; + + if( CANCon::CONNECTED == getStatus() ) + { + if (!gotValidated && doValidation) + { + if (serial == NULL) return; + if (serial->isOpen()) //if it's still false we have a problem... + { + qDebug() << "Comm validation failed. "; + + setStatus(CANCon::NOT_CONNECTED); + emit status(getStatus()); + + disconnectDevice(); //start by stopping everything. + //Then wait 500ms and restart the connection automatically + QTimer::singleShot(500, this, SLOT(connectDevice())); + return; + } + } + } + + if (doValidation && serial && serial->isOpen()) sendCommValidation(); +} + + +void GVRetSerial::sendCommValidation() +{ + QByteArray output; + + gotValidated = false; + output.append((char)0xF1); //another command to the GVRET + output.append((char)0x09); //request a reply to get validation + //send it twice for good measure. + output.append((char)0xF1); //another command to the GVRET + output.append((char)0x09); //request a reply to get validation + + serial->write(output); +} + + +void GVRetSerial::setBusSettings(int pBusIdx, CANBus bus) +{ + /* make sure we execute in mThread context */ + if(QThread::currentThread() != &mThread) { + QMetaObject::invokeMethod(this, "setBusSettings", + Qt::BlockingQueuedConnection, + Q_ARG(int, pBusIdx), + Q_ARG(CANBus, bus)); + return; + } + + /* sanity checks */ + if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) + return; + + /* copy bus config */ + setBusConfig(pBusIdx, bus); + + qDebug() << "About to update bus " << pBusIdx << " on GVRET"; + if (pBusIdx == 0) + { + can0Baud = bus.getSpeed(); + can0Baud |= 0x80000000; + if (bus.isActive()) + { + can0Baud |= 0x40000000; + can0Enabled = true; + } + else can0Enabled = false; + + if (bus.isListenOnly()) + { + can0Baud |= 0x20000000; + can0ListenOnly = true; + } + else can0ListenOnly = false; + } + else if (pBusIdx == 1) + { + can1Baud = bus.getSpeed(); + can1Baud |= 0x80000000; + if (bus.isActive()) + { + can1Baud |= 0x40000000; + can1Enabled = true; + } + else can1Enabled = false; + + if (bus.isListenOnly()) + { + can1Baud |= 0x20000000; + can1ListenOnly = true; + } + else can1ListenOnly = false; + + if (bus.isSingleWire()) + { + can1Baud |= 0x10000000; + deviceSingleWireMode = 1; + } + else deviceSingleWireMode = 0; + } + + /* update baud rates */ + QByteArray buffer; + qDebug() << "Got signal to update bauds. 1: " << can0Baud <<" 2: " << can1Baud; + 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[10] = 0; + if (serial == NULL) return; + if (!serial->isOpen()) return; + serial->write(buffer); } diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 12857c0..94f90e1 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -1,11 +1,113 @@ -#ifndef CVRETSERIAL_H -#define CVRETSERIAL_H +#ifndef GVRETSERIAL_H +#define GVRETSERIAL_H + +#include +#include +#include +#include + +/*************/ +#include +#include +/*************/ -class CVRetSerial +#include "canframemodel.h" +#include "canconnection.h" + + +namespace SERIALSTATE { + +enum STATE //keep this enum synchronized with the Arduino firmware project { -public: - CVRetSerial(); + IDLE, + GET_COMMAND, + BUILD_CAN_FRAME, + TIME_SYNC, + GET_DIG_INPUTS, + GET_ANALOG_INPUTS, + SET_DIG_OUTPUTS, + SETUP_CANBUS, + GET_CANBUS_PARAMS, + GET_DEVICE_INFO, + SET_SINGLEWIRE_MODE }; -#endif // CVRETSERIAL_H \ No newline at end of file +} + + +using namespace SERIALSTATE; +class GVRetSerial : public CANConnection +{ + Q_OBJECT + +public: + GVRetSerial(QString portName); + virtual ~GVRetSerial(); + + virtual void start(); + virtual void stop(); + + +signals: + void error(const QString &); + + void status(CANCon::status); + void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte + + //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) + //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only + //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really + //being passed. Just set for things that really are being updated. + void busStatus(int, int, int); + + +public slots: + + virtual void sendFrame(const CANFrame *); + virtual void sendFrameBatch(const QList *); + + virtual void setBusSettings(int, CANBus); + virtual bool getBusSettings(int pBusIdx, CANBus& pBus); + + virtual void suspend(bool); + +protected: + void disconnectDevice(); + +private slots: + void connectDevice(); + void connectionTimeout(); + void readSerialData(); + void handleTick(); + +private: + void readSettings(); + void procRXChar(unsigned char); + void sendCommValidation(); + +protected: + QTimer mTimer; + QThread mThread; + + + bool doValidation; + bool gotValidated; + bool isAutoRestart; + bool continuousTimeSync; + QSerialPort *serial; + QMutex sendBulkMutex; + int framesRapid; + STATE rx_state; + int rx_step; + CANFrame buildFrame; + int can0Baud, can1Baud; + bool can0Enabled, can1Enabled; + bool can0ListenOnly, can1ListenOnly; + int deviceBuildNum; + int deviceSingleWireMode; + uint64_t txTimestampBasis; + uint32_t buildTimeBasis; +}; + +#endif // GVRETSERIAL_H From 6d20a0665d8f9030a0dd8094899ed9232460ef0e Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:25:58 +0200 Subject: [PATCH 24/86] add a factory for the different connection types --- connections/canconfactory.cpp | 15 ++++++++++++++- connections/canconfactory.h | 6 ++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/connections/canconfactory.cpp b/connections/canconfactory.cpp index 54095ab..93b618e 100644 --- a/connections/canconfactory.cpp +++ b/connections/canconfactory.cpp @@ -1,6 +1,19 @@ +#include #include "canconfactory.h" +#include "socketcan.h" +#include "gvretserial.h" -CanConFactory::CanConFactory() +using namespace CANCon; + +CANConnection* CanConFactory::create(type pType, QString pPortName) { + switch(pType) { + case SOCKETCAN: + return new SocketCanConnection(pPortName); + case GVRET_SERIAL: + return new GVRetSerial(pPortName); + default: {} + } + return NULL; } diff --git a/connections/canconfactory.h b/connections/canconfactory.h index a2d8cbc..2b482f5 100644 --- a/connections/canconfactory.h +++ b/connections/canconfactory.h @@ -1,11 +1,13 @@ #ifndef CANCONFACTORY_H #define CANCONFACTORY_H +#include "canconconst.h" +#include "canconnection.h" class CanConFactory { public: - CanConFactory(); + static CANConnection* create(CANCon::type, QString pPortName); }; -#endif // CANCONFACTORY_H \ No newline at end of file +#endif // CANCONFACTORY_H From 45752d137a041a194d36237ace1cebe3a86f7000 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:27:22 +0200 Subject: [PATCH 25/86] changed the way connections are organized and retrieved by connection window --- canconnectionmodel.cpp | 154 ++++++++++++++++++++++++----------------- canconnectionmodel.h | 27 ++++---- 2 files changed, 101 insertions(+), 80 deletions(-) diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 7ec8ca7..3f96f94 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -1,5 +1,4 @@ -#include "canconnection.h" -#include "canconnectioncontainer.h" +#include "connections/canconnection.h" #include "canconnectionmodel.h" CANConnectionModel::CANConnectionModel(QObject *parent) @@ -7,11 +6,6 @@ CANConnectionModel::CANConnectionModel(QObject *parent) { } -void CANConnectionModel::refreshView() -{ - beginResetModel(); - endResetModel(); -} QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation, int role) const { @@ -41,6 +35,9 @@ QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation return QString(tr("Single Wire")); break; case 6: + return QString(tr("Status")); + break; + case 7: return QString(tr("Active")); break; } @@ -52,97 +49,124 @@ QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation return QVariant(); } -int CANConnectionModel::rowCount(const QModelIndex &parent) const -{ - return buses.count(); -} int CANConnectionModel::columnCount(const QModelIndex &parent) const { return 7; } + +int CANConnectionModel::rowCount(const QModelIndex &parent) const { + int rows=0; + QList::const_iterator iter; + + for (iter = mConns.begin() ; iter != mConns.end() ; ++iter) { + rows+=(*iter)->getNumBuses(); + } + + return rows; +} + + QVariant CANConnectionModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); - if (index.row() >= (buses.count())) - return QVariant(); if (role == Qt::DisplayRole) { - CANBus bus = buses[index.row()]; - CANConnection *conn = bus.getContainer()->getRef(); + int busId; + CANConnection *conn_p = getAtIdx(index.row(), busId); + if(!conn_p) + return QVariant(); + + CANBus bus; + bool ret; + ret = conn_p->getBusSettings(busId, bus); + if(!ret) return QVariant(); + switch (index.column()) { - case 0: //bus - return QString::number(bus.busNum); - break; - case 1: //type - if (conn) return conn->getConnTypeName(); - else qDebug() << "Tried to show connection type but connection was NULL"; - break; - case 2: //port - if (conn) return conn->getConnPortName(); - else qDebug() << "Tried to show connection port but connection was NULL"; - break; - case 3: //speed - return QString::number(bus.speed); - break; - case 4: //Listen Only - if (bus.listenOnly) return QString("True"); - else return QString("False"); - break; - case 5: //Single Wire - if (bus.singleWire) return QString("True"); - else return QString("False"); - break; - case 6: //Active - if (bus.active) return QString("True"); - else return QString("False"); - break; - default: - return QVariant(); + case 0: //bus + return QString::number(busId); + break; + case 1: //type + if (conn_p) + switch (conn_p->getType()) { + case CANCon::KVASER: return "KVASER"; + case CANCon::SOCKETCAN: return "SocketCAN"; + case CANCon::GVRET_SERIAL: return "GVRET"; + default: {} + } + else qDebug() << "Tried to show connection type but connection was NULL"; + break; + case 2: //port + if (conn_p) return conn_p->getPort(); + else qDebug() << "Tried to show connection port but connection was NULL"; + break; + case 3: //speed + return QString::number(bus.speed); + case 4: //Listen Only + return (bus.listenOnly) ? "True" : "False"; + case 5: //Single Wire + return (bus.singleWire) ? "True" : "False"; + case 6: //Status + return (conn_p->getStatus()==CANCon::CONNECTED) ? "Connected" : "Not Connected"; + case 7: //Active + return (bus.active) ? "True" : "False"; + default: {} } } - else - return QVariant(); + + return QVariant(); } -void CANConnectionModel::addBus(CANBus &bus) +void CANConnectionModel::add(CANConnection* pConn_p) { beginResetModel(); - buses.append(bus); + mConns.append(pConn_p); endResetModel(); } -void CANConnectionModel::removeBus(int busIdx) -{ - if (busIdx>=0 && busIdx < buses.count()) { - beginResetModel(); - buses.removeAt(busIdx); - endResetModel(); - } -} -CANBus* CANConnectionModel::getBus(int bus) +void CANConnectionModel::remove(CANConnection* pConn_p) { - if (bus < 0) return NULL; - if (bus >= buses.count()) return NULL; - return &buses[bus]; + beginResetModel(); + mConns.removeOne(pConn_p); + endResetModel(); } -CANBus* CANConnectionModel::findBusByNum(int bus) +QList& CANConnectionModel::getConnections() { - for (int i = 0; i < buses.count(); i++) - { - if (buses[i].busNum == bus) - { - return &buses[i]; + return mConns; +} + + +CANConnection* CANConnectionModel::getAtIdx(int pIdx, int& pBusId) const +{ + if (pIdx < 0) + return NULL; + + int i=0; + QList::const_iterator iter = mConns.begin(); + + for (iter = mConns.begin() ; iter != mConns.end() ; ++iter) { + if( i <= pIdx && pIdx < i+(*iter)->getNumBuses() ) { + pBusId = pIdx - i; + return (*iter); } + + i+= (*iter)->getNumBuses(); } + return NULL; } + +void CANConnectionModel::refreshView() +{ + beginResetModel(); + endResetModel(); +} diff --git a/canconnectionmodel.h b/canconnectionmodel.h index 22dacdc..c91c9e2 100644 --- a/canconnectionmodel.h +++ b/canconnectionmodel.h @@ -1,13 +1,13 @@ #ifndef CANCONNECTIONMODEL_H #define CANCONNECTIONMODEL_H -#include "canconnection.h" -#include "canbus.h" -#include "canconnectioncontainer.h" #include -class CANConnectionContainer; +#include "canbus.h" +#include "connections/canconnection.h" +#include "connectionwindow.h" + class CANConnectionModel : public QAbstractTableModel { @@ -19,24 +19,21 @@ public: // Header: QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - void addConnection(CANConnectionContainer *conn); - void removeConnection(CANConnection*); - void addBus(CANBus &bus); - void removeBus(int busIdx); - CANBus* getBus(int bus); - CANConnection* getConnection(int conn); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + + void add(CANConnection* pConn_p); + void remove(CANConnection* pConn_p); + + QList& getConnections(); + CANConnection* getAtIdx(int, int&) const; void refreshView(); private: - QList connections; - QList buses; - - CANBus *findBusByNum(int bus); + QList mConns; }; #endif // CANCONNECTIONMODEL_H From ec57d30fd1740f4263563b616ef7a2a1eaf234e8 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:29:04 +0200 Subject: [PATCH 26/86] removed canconnectioncontainer --- canconnectioncontainer.cpp | 32 -------------------------------- canconnectioncontainer.h | 22 ---------------------- 2 files changed, 54 deletions(-) delete mode 100644 canconnectioncontainer.cpp delete mode 100644 canconnectioncontainer.h diff --git a/canconnectioncontainer.cpp b/canconnectioncontainer.cpp deleted file mode 100644 index 302a3be..0000000 --- a/canconnectioncontainer.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "canconnection.h" -#include "canconnectioncontainer.h" -#include "mainwindow.h" - -CANConnectionContainer::CANConnectionContainer(CANConnection *conn) -{ - thread = new QThread(); - connection = conn; - connection->moveToThread(thread); - - connect(thread, &QThread::started, conn, &CANConnection::run); //setup timers within the proper thread - connect(conn, &CANConnection::frameUpdateRapid, MainWindow::getReference(), &MainWindow::gotFrames, Qt::QueuedConnection); - connect(MainWindow::getReference(), &MainWindow::sendCANFrame, conn, &CANConnection::sendFrame, Qt::QueuedConnection); - thread->start(); - thread->setPriority(QThread::HighPriority); -} - -CANConnectionContainer::~CANConnectionContainer() -{ - //have to stop the actual execution first before deleting - thread->quit(); - if(!thread->wait()) { - qDebug() << "can't stop thread"; - } - delete thread; - delete connection; -} - -CANConnection* CANConnectionContainer::getRef() -{ - return connection; -} diff --git a/canconnectioncontainer.h b/canconnectioncontainer.h deleted file mode 100644 index 8a4a429..0000000 --- a/canconnectioncontainer.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef CANCONNECTIONCONTAINER_H -#define CANCONNECTIONCONTAINER_H - -#include -#include -#include "canconnection.h" - -class CANConnectionContainer : public QObject -{ - Q_OBJECT -public: - CANConnectionContainer(CANConnection *conn); - ~CANConnectionContainer(); - - CANConnection* getRef(); - -private: - CANConnection *connection; - QThread *thread; -}; - -#endif // CANCONNECTIONCONTAINER_H From f17b64e9f589291c310be3ab11da26f22ebdcbdc Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:31:44 +0200 Subject: [PATCH 27/86] renamed an signal --- mainwindow.cpp | 9 +++------ mainwindow.h | 3 +-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index 68e27c0..b456467 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -181,6 +181,7 @@ MainWindow::MainWindow(QWidget *parent) : //Automatically create the connection window so it can be updated even if we never opened it. connectionWindow = new ConnectionWindow(model); connect(connectionWindow, SIGNAL(updateConnectionSettings(QString,QString,int,int)), this, SLOT(updateConnectionSettings(QString,QString,int,int))); + connect(this, SIGNAL(suspendCapturing(bool)), connectionWindow, SLOT(setSuspendAll(bool))); } MainWindow::~MainWindow() @@ -713,15 +714,11 @@ void MainWindow::toggleCapture() { allowCapture = !allowCapture; if (allowCapture) - { ui->btnCaptureToggle->setText("Suspend Capturing"); - emit startFrameCapturing(); - } else - { ui->btnCaptureToggle->setText("Restart Capturing"); - emit stopFrameCapturing(); - } + + emit suspendCapturing(!allowCapture); } void MainWindow::connectionSucceeded(int baud0, int baud1) diff --git a/mainwindow.h b/mainwindow.h index cbe0c0d..191008a 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -92,8 +92,7 @@ public slots: signals: void sendCANFrame(const CANFrame *, int); - void stopFrameCapturing(); - void startFrameCapturing(); + void suspendCapturing(bool); //-1 = frames cleared, -2 = a new file has been loaded (so all frames are different), otherwise # of new frames void framesUpdated(int numFrames); //something has updated the frame list From c3c6ff3acdff5d53bc5f1ab0d6a3536cfa153fc8 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:38:43 +0200 Subject: [PATCH 28/86] removed mutex --- connections/gvretserial.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 94f90e1..b223aee 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -7,7 +7,6 @@ #include /*************/ -#include #include /*************/ @@ -96,7 +95,6 @@ protected: bool isAutoRestart; bool continuousTimeSync; QSerialPort *serial; - QMutex sendBulkMutex; int framesRapid; STATE rx_state; int rx_step; From 65528fdf121862a5d734076075a5e164511d1621 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:40:36 +0200 Subject: [PATCH 29/86] #if 0 --- serialworker.cpp | 24 ++++++++++++++++-------- serialworker.h | 5 +++-- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/serialworker.cpp b/serialworker.cpp index 281c050..f3b35d1 100644 --- a/serialworker.cpp +++ b/serialworker.cpp @@ -5,6 +5,7 @@ #include #include +#if 0 SerialWorker::SerialWorker(CANFrameModel *model, int base) : CANConnection(model, base) { qDebug() << "Serial Worker constructor"; @@ -576,15 +577,7 @@ void SerialWorker::updatePortName(QString portName) } } -int SerialWorker::getNumBuses() -{ - return 2; -} -QString SerialWorker::getConnTypeName() -{ - return QString("GVRET"); -} void SerialWorker::updateBusSettings(CANBus bus) { @@ -638,3 +631,18 @@ void SerialWorker::updateBusSettings(CANBus bus) updateBaudRates(can0Baud,can1Baud); } + + +/************************************/ + +int SerialWorker::getNumBuses() +{ + return 2; +} + +QString SerialWorker::getConnTypeName() +{ + return QString("GVRET"); +} + +#endif diff --git a/serialworker.h b/serialworker.h index f9e57ec..dc1a9a9 100644 --- a/serialworker.h +++ b/serialworker.h @@ -8,7 +8,7 @@ #include #include "can_structs.h" #include "canframemodel.h" -#include "canconnection.h" +//#include "canconnection_old.h" namespace SERIALSTATE { @@ -30,6 +30,7 @@ enum STATE //keep this enum synchronized with the Arduino firmware project } +#if 0 using namespace SERIALSTATE; class SerialWorker : public CANConnection { @@ -84,5 +85,5 @@ private: void procRXChar(unsigned char); void sendCommValidation(); }; - +#endif #endif // SERIALTHREAD_H From 87c302c79583b17c3ed91342e495e0c95273e1f6 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:41:39 +0200 Subject: [PATCH 30/86] removed unneeded functions --- canbus.cpp | 34 ++++++++++------------------------ canbus.h | 10 ++-------- 2 files changed, 12 insertions(+), 32 deletions(-) diff --git a/canbus.cpp b/canbus.cpp index 6a8b35b..c01f274 100644 --- a/canbus.cpp +++ b/canbus.cpp @@ -7,17 +7,22 @@ CANBus::CANBus() listenOnly = false; singleWire = false; active = false; - container = Q_NULLPTR; - busNum = 0; } + CANBus::CANBus(const CANBus& pBus) : speed(pBus.speed), listenOnly(pBus.listenOnly), singleWire(pBus.singleWire), - active(pBus.active), - container(pBus.container), /* TODO: check if container is really needed */ - busNum(pBus.busNum) {} + active(pBus.active) {} + + +bool CANBus::operator==(CANBus& bus) { + return speed == bus.speed && + listenOnly == bus.listenOnly && + singleWire == bus.singleWire && + active == bus.active; +} void CANBus::setSpeed(int newSpeed) @@ -40,26 +45,11 @@ void CANBus::setEnabled(bool mode) active = mode; } -void CANBus::setContainer(CANConnectionContainer* pContainer) -{ - container = pContainer; -} - -void CANBus::setBusNum(int num) -{ - busNum = num; -} - int CANBus::getSpeed() { return speed; } -int CANBus::getBusNum() -{ - return busNum; -} - bool CANBus::isListenOnly() { return listenOnly; @@ -75,7 +65,3 @@ bool CANBus::isActive() return active; } -CANConnectionContainer* CANBus::getContainer() -{ - return container; -} diff --git a/canbus.h b/canbus.h index a343c92..c8b4e88 100644 --- a/canbus.h +++ b/canbus.h @@ -2,30 +2,24 @@ #define CANBus_H -class CANConnectionContainer; - class CANBus { public: CANBus(); CANBus(const CANBus&); + bool operator==(CANBus&); virtual ~CANBus(){}; /*TODO: remove connection from CANBus and add CANBus as an element of CANConnection */ - int busNum; int speed; bool listenOnly; bool singleWire; bool active; //is this bus turned on? - CANConnectionContainer* container; + void setSpeed(int); // new speed void setListenOnly(bool); //bool for whether to only listen void setSingleWire(bool); //bool for whether to use single wire mode void setEnabled(bool); //whether this bus should be enabled or not. - void setContainer(CANConnectionContainer *); - CANConnectionContainer* getContainer(); - void setBusNum(int); int getSpeed(); - int getBusNum(); bool isListenOnly(); bool isSingleWire(); bool isActive(); From ae7dbd4a841a0b1b87efcf8dba33299a533b9567 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:42:13 +0200 Subject: [PATCH 31/86] added test for lock free queue --- test/test.pro | 16 +++++--- test/tst_lfqueue.cpp | 98 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 104 insertions(+), 10 deletions(-) diff --git a/test/test.pro b/test/test.pro index 58486c6..56c22c3 100644 --- a/test/test.pro +++ b/test/test.pro @@ -1,12 +1,16 @@ -QT += core +QT += widgets testlib QT -= gui CONFIG += c++11 -TARGET = test -CONFIG += console -CONFIG -= app_bundle +INCLUDEPATH += ../utils -TEMPLATE = app +SOURCES += \ + tst_lfqueue.cpp -SOURCES += main.cpp + +#HEADERS += \ +# ../utils/lfqueue.h + +target.path= . +INSTALLS += target diff --git a/test/tst_lfqueue.cpp b/test/tst_lfqueue.cpp index 470a030..1120de5 100644 --- a/test/tst_lfqueue.cpp +++ b/test/tst_lfqueue.cpp @@ -1,8 +1,98 @@ -#include +#include +#include -int main(int argc, char *argv[]) +#include "lfqueue.h" + +class TestLFQueue: public QObject { - QCoreApplication a(argc, argv); + Q_OBJECT +private: + +private slots: + void setSize_data(); + void setSize(); + void exchange_data(); + void exchange(); +}; + + +void TestLFQueue::setSize_data() +{ + QTest::addColumn("size"); + QTest::addColumn("result"); + + QTest::newRow("-1") << -1 << false; + QTest::newRow("0") << 0 << true; + QTest::newRow("10") << 10 << true; + QTest::newRow("2000") << 20000 << true; - return a.exec(); } + + +void TestLFQueue::setSize() +{ + QFETCH(int, size); + QFETCH(bool, result); + + LFQueue queue; + QCOMPARE(queue.setSize(size), result); +} + + +void readerThread(LFQueue* pQueue_p, int pSize, bool pSleep) { + int* val_p; + + for(int i=0; ipeek()) ); + QVERIFY(val_p); + + QCOMPARE(*val_p, i); + pQueue_p->dequeue(); + + if(pSleep) + QThread::msleep(1); + } +} + + +void TestLFQueue::exchange_data() +{ + QTest::addColumn("size"); + QTest::addColumn("writerSleep"); + QTest::addColumn("readerSleep"); + + QTest::newRow("nosleep") << 1000 << false << false; + QTest::newRow("readersleep") << 1000 << false << true; + QTest::newRow("writersleep") << 1000 << true << false; +} + + +void TestLFQueue::exchange() +{ + LFQueue queue; + QFETCH(int, size); + QFETCH(bool, writerSleep); + QFETCH(bool, readerSleep); + + int* val_p; + QCOMPARE(queue.setSize(2), true); + + QFuture thread = QtConcurrent::run(readerThread, &queue, size, readerSleep); + + for(int i=0; i Date: Wed, 15 Jun 2016 18:43:17 +0200 Subject: [PATCH 32/86] change a method signature --- canframemodel.cpp | 3 ++- canframemodel.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index 57d542d..02fc0cf 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -282,8 +282,9 @@ QVariant CANFrameModel::headerData(int section, Qt::Orientation orientation, } -void CANFrameModel::addFrame(CANFrame frame, bool autoRefresh = false) +void CANFrameModel::addFrame(CANFrame& frame, bool autoRefresh = false) { + /*TODO: remove mutex */ mutex.lock(); CANFrame tempFrame; tempFrame = frame; diff --git a/canframemodel.h b/canframemodel.h index f53db11..ddea3ce 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -46,7 +46,7 @@ public: const QMap *getFiltersReference() const; //this neither public slots: - void addFrame(CANFrame, bool); + void addFrame(CANFrame&, bool); signals: void updatedFiltersList(); From ed1b9b082bcc88721fcb6ebc9b13319c4b79251e Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:44:45 +0200 Subject: [PATCH 33/86] severals changes to adapt to new connection model and connection API --- connectionwindow.cpp | 295 +++++++++++++++++++++++++------------------ connectionwindow.h | 35 ++--- 2 files changed, 193 insertions(+), 137 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 8014093..bab8cf3 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -2,8 +2,7 @@ #include "connectionwindow.h" #include "ui_connectionwindow.h" -#include "socketcanconnection.h" - +#include "connections/canconfactory.h" ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : @@ -26,10 +25,11 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : ui->tableConnections->setColumnWidth(0, 50); ui->tableConnections->setColumnWidth(1, 110); ui->tableConnections->setColumnWidth(2, 110); - ui->tableConnections->setColumnWidth(3, 150); + ui->tableConnections->setColumnWidth(3, 110); ui->tableConnections->setColumnWidth(4, 75); ui->tableConnections->setColumnWidth(5, 75); ui->tableConnections->setColumnWidth(6, 75); + ui->tableConnections->setColumnWidth(7, 75); int temp = settings->value("Main/DefaultConnectionType", 0).toInt(); @@ -40,7 +40,6 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : ui->ckSingleWire->setChecked(settings->value("Main/SingleWireMode", false).toBool()); ui->cbSpeed->addItem(tr("")); - ui->cbSpeed->addItem(tr("Disabled")); ui->cbSpeed->addItem(tr("125000")); ui->cbSpeed->addItem(tr("250000")); ui->cbSpeed->addItem(tr("500000")); @@ -66,10 +65,19 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : connect(ui->btnActivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleEnableAll); connect(ui->btnDeactivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleDisableAll); connect(ui->btnRemoveBus, &QPushButton::clicked, this, &ConnectionWindow::handleRemoveConn); + + + qDebug() << "Serial worker thread starting"; + + connect(&mTicker, SIGNAL(timeout()), this, SLOT(refreshCanList())); + mTicker.setInterval(250); //tick 4 times a second (TODO: make this configurable?) */ + mTicker.setSingleShot(false); + mTicker.start(); } ConnectionWindow::~ConnectionWindow() { + mTicker.stop(); delete settings; delete ui; } @@ -81,6 +89,20 @@ void ConnectionWindow::showEvent(QShowEvent* event) handleConnTypeChanged(); } +void ConnectionWindow::refreshCanList() { + QList::iterator conn_p; + QList& conns = connModel->getConnections(); + + CANFrame* frame_p = NULL; + + for (conn_p = conns.begin(); conn_p != conns.end(); ++conn_p) { + while( (frame_p = (*conn_p)->getQueue().peek() ) ) { + canModel->addFrame(*frame_p, true); + (*conn_p)->getQueue().dequeue(); + } + } +} + void ConnectionWindow::handleNewConn() { ui->tableConnections->selectionModel()->clearSelection(); @@ -88,91 +110,101 @@ void ConnectionWindow::handleNewConn() handleConnSelectionChanged(); } +void ConnectionWindow::setSuspendAll(bool pSuspend) +{ + qDebug() << "setSuspendAll"; + + QList::iterator iter; + QList& conns = connModel->getConnections(); + + for (iter = conns.begin(); iter != conns.end(); ++iter) + (*iter)->suspend(pSuspend); +} + +void ConnectionWindow::setActiveAll(bool pActive) +{ + QList::iterator iter; + QList& conns = connModel->getConnections(); + CANBus bus; + + for (iter = conns.begin(); iter != conns.end(); ++iter) { + for(int i=0 ; i<(*iter)->getNumBuses() ; i++) { + if( (*iter)->getBusSettings(i, bus) ) { + bus.active = pActive; + (*iter)->setBusSettings(i, bus); + } + } + } +} + void ConnectionWindow::handleEnableAll() { - + setActiveAll(true); } void ConnectionWindow::handleDisableAll() { - + setActiveAll(false); } void ConnectionWindow::handleConnTypeChanged() { - if (ui->rbGVRET->isChecked()) getSerialPorts(); - if (ui->rbKvaser->isChecked()) getKvaserPorts(); - if (ui->rbSocketCAN->isChecked()) getSocketcanPorts(); + if (ui->rbGVRET->isChecked()) selectSerial(); + if (ui->rbKvaser->isChecked()) selectKvaser(); + if (ui->rbSocketCAN->isChecked()) selectSocketCan(); } -void ConnectionWindow::connectionSuccess(CANConnection *conn) + +/* status */ +void ConnectionWindow::connectionStatus(CANCon::status pStatus) { -#if 0 - CANBus bus; - bus.active = true; - bus.busNum = conn->getBusBase(); - bus.connection = conn; - bus.listenOnly = ui->ckListenOnly->isChecked(); - bus.singleWire = ui->ckSingleWire->isChecked(); - - if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed - else if (ui->cbSpeed->currentIndex() == 1) - { - bus.speed = 0; - bus.active = false; - } - else bus.speed = ui->cbSpeed->currentText().toInt(); - connModel->addBus(bus); - - int numBuses = conn->getNumBuses(); - for (int i = 1; i < numBuses; i++) - { - bus.active = false; - bus.listenOnly = false; - bus.singleWire = false; - bus.speed = 250000; - bus.busNum = conn->getBusBase() + i; - bus.connection = conn; - connModel->addBus(bus); - qDebug() << "Added bus " << bus.busNum; - } -#endif + qDebug() << "Connectionstatus changed"; + connModel->refreshView(); } + void ConnectionWindow::handleOKButton() { - QString conn; - int connType = 0; int whichRow = ui->tableConnections->selectionModel()->currentIndex().row(); - qDebug() << "OK pressed. Row " << whichRow; + + CANConnection* conn_p = NULL; if (whichRow > -1) { - //load settings from GUI into appropriate CANBus entry and then send it off to the appropriate - //CANConnection object - CANBus *bus = connModel->getBus(whichRow); - bus->setListenOnly(ui->ckListenOnly->isChecked()); - bus->setSingleWire(ui->ckSingleWire->isChecked()); - bus->setEnabled(ui->ckEnabled->isChecked()); - if (ui->cbSpeed->currentIndex() == 1) + int busId; + CANBus bus; + bool ret; + + conn_p = connModel->getAtIdx(whichRow, busId); + if(!conn_p) return; + + ret = conn_p->getBusSettings(busId, bus); + if(!ret) return; + + + bus.setListenOnly(ui->ckListenOnly->isChecked()); + bus.setSingleWire(ui->ckSingleWire->isChecked()); + bus.setEnabled(ui->ckEnabled->isChecked()); + if (ui->cbSpeed->currentIndex() == 0) { - bus->speed = 0; - bus->setEnabled(false); + bus.speed = 0; + bus.setEnabled(false); } - else if (ui->cbSpeed->currentIndex() > 1) + else if (ui->cbSpeed->currentIndex() >= 1) { - bus->setSpeed(ui->cbSpeed->currentText().toInt()); + bus.setSpeed(ui->cbSpeed->currentText().toInt()); } - //call through signal/slot interface without using connect - QMetaObject::invokeMethod(bus->getContainer()->getRef(), "updateBusSettings", - Qt::QueuedConnection, - Q_ARG(CANBus, *bus)); + /* update bus settings */ + conn_p->setBusSettings(busId, bus); + connModel->refreshView(); } else //new connection { +#if 0 if (ui->rbGVRET->isChecked()) - { + { + SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); connect(serial, SIGNAL(busStatus(int,int,int)), this, SLOT(receiveBusStatus(int,int,int))); connect(serial, SIGNAL(connectionSuccess(CANConnection*)), this, SLOT(connectionSuccess(CANConnection*))); @@ -215,55 +247,43 @@ void ConnectionWindow::handleOKButton() QMetaObject::invokeMethod(serial, "updatePortName", Qt::QueuedConnection, Q_ARG(QString, ui->cbPort->currentText())); - } - else if (ui->rbKvaser->isChecked()) - { +#endif - } - else if (ui->rbSocketCAN->isChecked()) - { - /* TODO: sanity checks here */ - /* text, port, etc, ... */ - /* factorize code with other probes */ + /* create connection */ + conn_p = CanConFactory::create(getConnectionType(), getPortName()); + if(!conn_p) + return; - /* create connection */ - SocketCanConnection* conn = new SocketCanConnection(canModel, 0); /* what is base? (second param) */ + /* connect signal */ + connect(conn_p, SIGNAL(status(CANCon::status)), + this, SLOT(connectionStatus(CANCon::status))); - /* set port name */ - conn->updatePortName(ui->lePort->text()); - - /* add connection to a container (this creates the thread) */ - CANConnectionContainer* container = new CANConnectionContainer(conn); + /*TODO add return value and checks */ + conn_p->start(); + for (int i=0 ; igetNumBuses() ; i++) { /* set bus configuration */ CANBus bus; bus.active = ui->ckEnabled->isChecked(); - bus.busNum = 0; // not used - bus.container = container; bus.listenOnly = ui->ckListenOnly->isChecked(); bus.singleWire = ui->ckSingleWire->isChecked(); - if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed - else if (ui->cbSpeed->currentIndex() == 1) - { - bus.speed = 0; - bus.active = false; - } + if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; else bus.speed = ui->cbSpeed->currentText().toInt(); - /* add bus to model */ - connModel->addBus(bus); - - /* set bus settings (send message to thread) */ - QMetaObject::invokeMethod(conn, "updateBusSettings", - Qt::QueuedConnection, - Q_ARG(CANBus, bus)); + /* update bus settings */ + conn_p->setBusSettings(i, bus); } + + /* add connection to model */ + connModel->add(conn_p); } } + void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) { +#if 0 qDebug() << "bus " << bus << " speed " << speed << " status " << status; CANBus *busRef = connModel->getBus(bus); if (status & 40) busRef->setSpeed(speed); @@ -280,6 +300,7 @@ void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) busRef->setListenOnly((status & 4)?true:false); } connModel->refreshView(); +#endif } void ConnectionWindow::handleConnSelectionChanged() @@ -289,10 +310,13 @@ void ConnectionWindow::handleConnSelectionChanged() if (selIdx == -1) { ui->btnOK->setText(tr("Create New Connection")); + ui->cbPort->setEnabled(true); ui->rbGVRET->setEnabled(true); ui->rbKvaser->setEnabled(true); ui->rbSocketCAN->setEnabled(true); + ui->cbSpeed->setEnabled(false); + ui->cbPort->setCurrentIndex(0); ui->ckListenOnly->setChecked(false); ui->ckSingleWire->setChecked(false); @@ -300,25 +324,39 @@ void ConnectionWindow::handleConnSelectionChanged() } else { + int busId; + bool ret; + CANBus bus; + CANConnection* conn_p = connModel->getAtIdx(selIdx, busId); + if(!conn_p) return; + ret = conn_p->getBusSettings(busId, bus); + if(!ret) return; + ui->btnOK->setText(tr("Update Connection Settings")); + ui->cbPort->setEnabled(false); ui->rbGVRET->setEnabled(false); ui->rbKvaser->setEnabled(false); - ui->rbSocketCAN->setEnabled(false); - CANBus *bus = connModel->getBus(selIdx); - if (bus->getContainer()->getRef()->getConnTypeName() == "GVRET") ui->rbGVRET->setChecked(true); - if (bus->getContainer()->getRef()->getConnTypeName() == "KVASER") ui->rbKvaser->setChecked(true); - if (bus->getContainer()->getRef()->getConnTypeName() == "SOCKETCAN") ui->rbSocketCAN->setChecked(true); - ui->ckListenOnly->setChecked(bus->isListenOnly()); - ui->ckSingleWire->setChecked(bus->isSingleWire()); - ui->ckEnabled->setChecked(bus->isActive()); - int speed = bus->getSpeed(); + ui->rbSocketCAN->setEnabled(false); + ui->cbSpeed->setEnabled(true); + + switch(conn_p->getType()) { + case CANCon::GVRET_SERIAL: ui->rbGVRET->setChecked(true); break; + case CANCon::KVASER: ui->rbKvaser->setChecked(true); break; + case CANCon::SOCKETCAN: ui->rbSocketCAN->setChecked(true); break; + default: {} + } + + ui->ckListenOnly->setChecked(bus.isListenOnly()); + ui->ckSingleWire->setChecked(bus.isSingleWire()); + ui->ckEnabled->setChecked(bus.isActive()); + int speed = bus.getSpeed(); setSpeed(speed); } } -/*TODO: rename the 3 following functions */ -void ConnectionWindow::getSerialPorts() + +void ConnectionWindow::selectSerial() { /* set combobox page visible */ ui->stPort->setCurrentWidget(ui->cbPage); @@ -333,7 +371,7 @@ void ConnectionWindow::getSerialPorts() } } -void ConnectionWindow::getKvaserPorts() +void ConnectionWindow::selectKvaser() { #ifdef Q_OS_WIN /* set combobox page visible */ @@ -341,7 +379,7 @@ void ConnectionWindow::getKvaserPorts() #endif } -void ConnectionWindow::getSocketcanPorts() +void ConnectionWindow::selectSocketCan() { #ifdef Q_OS_LINUX /* set edit text page visible */ @@ -394,16 +432,30 @@ int ConnectionWindow::getSpeed() QString ConnectionWindow::getPortName() { - return (ui->cbPort->currentText()); + switch( getConnectionType() ) { + case CANCon::GVRET_SERIAL: + case CANCon::KVASER: + return ui->cbPort->currentText(); + case CANCon::SOCKETCAN: + return ui->lePort->text(); + default: + qDebug() << "getPortName: can't get port"; + } + + return ""; } -ConnectionType::ConnectionType ConnectionWindow::getConnectionType() +CANCon::type ConnectionWindow::getConnectionType() { - if (ui->rbGVRET->isChecked()) return ConnectionType::GVRET_SERIAL; - if (ui->rbKvaser->isChecked()) return ConnectionType::KVASER; - if (ui->rbSocketCAN->isChecked()) return ConnectionType::SOCKETCAN; + if (ui->rbGVRET->isChecked()) return CANCon::GVRET_SERIAL; + if (ui->rbKvaser->isChecked()) return CANCon::KVASER; + if (ui->rbSocketCAN->isChecked()) return CANCon::SOCKETCAN; + + qDebug() << "getConnectionType: error"; + return CANCon::NONE; } + void ConnectionWindow::setSWMode(bool mode) { ui->ckSingleWire->setChecked(mode); @@ -417,22 +469,21 @@ bool ConnectionWindow::getSWMode() void ConnectionWindow::handleRemoveConn() { -#if 0 int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); - if (selIdx <=0) return; + if (selIdx <0) return; - CANBus* bus = conModel->getBus(selIdx); - if(!bus) return; - - /* remove connection to model (this creates the thread) */ - connModel->removeConnection(bus->connection); - - /* remove connection and reset model */ - conModel->removeBus(selIdx); qDebug() << "remove connection at index: " << selIdx; - selIdx -#endif + int busId; + CANConnection* conn_p = connModel->getAtIdx(selIdx, busId); + if(!conn_p) return; + + /* remove connection from model */ + connModel->remove(conn_p); + + /* stop and delete connection */ + conn_p->stop(); + delete conn_p; } void ConnectionWindow::handleRevert() @@ -442,21 +493,25 @@ void ConnectionWindow::handleRevert() void ConnectionWindow::sendFrame(const CANFrame *frame) { +#if 0 CANBus *bus = connModel->getBus(frame->bus); if (bus == NULL) return; QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrame", Qt::QueuedConnection, Q_ARG(const CANFrame *, frame)); +#endif } void ConnectionWindow::sendFrameBatch(const QList *frames) { +#if 0 if (frames->count() == 0) return; CANBus *bus = connModel->getBus(frames->at(0).bus); if (bus == NULL) return; QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrameBatch", Qt::QueuedConnection, Q_ARG(const QList *, frames)); +#endif } bool ConnectionWindow::isSocketCanAvailable() diff --git a/connectionwindow.h b/connectionwindow.h index 5b0d9c0..066cad0 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -1,14 +1,18 @@ #ifndef CONNECTIONWINDOW_H #define CONNECTIONWINDOW_H -#include "canconnectionmodel.h" + #include #include #include #include -#include "canconnection.h" -#include "serialworker.h" +#include +//#include "canconnection_old.h" +//#include "serialworker.h" +#include "canconnectionmodel.h" +#include "canframemodel.h" + class CANConnectionModel; @@ -16,15 +20,6 @@ namespace Ui { class ConnectionWindow; } -namespace ConnectionType -{ - enum ConnectionType - { - GVRET_SERIAL, - KVASER, - SOCKETCAN - }; -} class ConnectionWindow : public QDialog { @@ -36,7 +31,7 @@ public: void showEvent(QShowEvent *); int getSpeed(); QString getPortName(); //name of port to connect to - ConnectionType::ConnectionType getConnectionType(); + CANCon::type getConnectionType(); bool getSWMode(); signals: @@ -48,6 +43,8 @@ public slots: void setSWMode(bool mode); void sendFrame(const CANFrame *); void sendFrameBatch(const QList *); + void setSuspendAll(bool); + private slots: void handleOKButton(); @@ -59,7 +56,9 @@ private slots: void handleRevert(); void handleNewConn(); void receiveBusStatus(int bus, int speed, int status); - void connectionSuccess(CANConnection *conn); + void connectionStatus(CANCon::status); + + void refreshCanList(); private: Ui::ConnectionWindow *ui; @@ -67,12 +66,14 @@ private: QSettings *settings; CANConnectionModel *connModel; CANFrameModel *canModel; + QTimer mTicker; - void getSerialPorts(); - void getKvaserPorts(); - void getSocketcanPorts(); + void selectSerial(); + void selectKvaser(); + void selectSocketCan(); bool isSocketCanAvailable(); + void setActiveAll(bool pActive); }; #endif // CONNECTIONWINDOW_H From 71e989ad05795cddd9ed57b2de7dd56a86a460b1 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 15 Jun 2016 18:45:40 +0200 Subject: [PATCH 34/86] .pro update --- SavvyCAN.pro | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index 5dcd015..34879f4 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -50,10 +50,11 @@ SOURCES += main.cpp\ isotp_interpreterwindow.cpp \ isotp_handler.cpp \ canconnectionmodel.cpp \ - canconnection.cpp \ - canconnectioncontainer.cpp \ - socketcanconnection.cpp \ - canbus.cpp + canbus.cpp \ + connections/canconnection.cpp \ + connections/socketcan.cpp \ + connections/canconfactory.cpp \ + connections/gvretserial.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -90,10 +91,13 @@ HEADERS += mainwindow.h \ isotp_interpreterwindow.h \ isotp_handler.h \ canconnectionmodel.h \ - canconnection.h \ - canconnectioncontainer.h \ - socketcanconnection.h \ - canbus.h + canbus.h \ + utils/lfqueue.h \ + connections/canconnection.h \ + connections/socketcan.h \ + connections/canconconst.h \ + connections/canconfactory.h \ + connections/gvretserial.h FORMS += mainwindow.ui \ graphingwindow.ui \ From d1c56426685109b07b2b8900faae2940ec9a90d1 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 16 Jun 2016 13:25:56 +0200 Subject: [PATCH 35/86] more thread abstraction --- connections/canconnection.cpp | 148 +++++++++++++++++++++++- connections/canconnection.h | 88 +++++++++++---- connections/gvretserial.cpp | 207 ++++++++++++++-------------------- connections/gvretserial.h | 24 ++-- connections/socketcan.cpp | 73 +++--------- connections/socketcan.h | 25 ++-- 6 files changed, 334 insertions(+), 231 deletions(-) diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index b3059b8..7ec3ab7 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -1,35 +1,179 @@ +#include #include "canconnection.h" -CANConnection::CANConnection(QString pPort, CANCon::type pType, int pNumBuses) : +CANConnection::CANConnection(QString pPort, + CANCon::type pType, + int pNumBuses, + int pQueueLen, + bool pUseThread) : mQueue(), mNumBuses(pNumBuses), mPort(pPort), mType(pType), mIsCapSuspended(false), - mStatus(CANCon::NOT_CONNECTED) + mStatus(CANCon::NOT_CONNECTED), + mThread_p(NULL) { qDebug() << "CANConnection()"; /* register types */ qRegisterMetaType("CANBus"); + qRegisterMetaType("CANFrame"); qRegisterMetaType("CANCon::status"); + /* set queue size */ + mQueue.setSize(pQueueLen); /*TODO add check on returned value */ + + /* allocate buses */ mBus = new CANBus[mNumBuses]; mConfigured = new bool[mNumBuses]; for(int i=0 ; iquit(); + mThread_p->wait(); + delete mThread_p; + mThread_p = NULL; + } + /* delete bus table */ delete[] mBus; mBus = NULL; + /* configured table */ delete[] mConfigured; mConfigured = NULL; + /* delete queue table */ + mQueue.setSize(0); +} + + +void CANConnection::start() +{ + if( mThread_p && (mThread_p != QThread::currentThread()) ) + { + /* move ourself to the thread */ + moveToThread(mThread_p); /*TODO handle errors */ + /* connect started() */ + connect(mThread_p, SIGNAL(started()), this, SLOT(start())); + /* start the thread */ + mThread_p->start(QThread::HighPriority); + return; + } + + /* in multithread case, this will be called before entering thread event loop */ + return piStarted(); +} + + +void CANConnection::suspend(bool pSuspend) +{ + /* execute in mThread_p context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + QMetaObject::invokeMethod(this, "suspend", + Qt::BlockingQueuedConnection, + Q_ARG(bool, pSuspend)); + return; + } + + return piSuspend(pSuspend); +} + + +void CANConnection::stop() +{ + /* 1) execute in mThread_p context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) + { + /* if thread is finished, it means we call this function for the second time so we can leave */ + if( !mThread_p->isFinished() ) + { + /* we need to call piStop() */ + QMetaObject::invokeMethod(this, "stop", + Qt::BlockingQueuedConnection); + /* 3) stop thread */ + mThread_p->quit(); + if(!mThread_p->wait()) { + qDebug() << "can't stop thread"; + } + } + return; + } + + /* 2) call piStop in mThread context */ + return piStop(); +} + + +bool CANConnection::getBusSettings(int pBusIdx, CANBus& pBus) +{ + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + bool ret; + QMetaObject::invokeMethod(this, "getBusSettings", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), + Q_ARG(int , pBusIdx), + Q_ARG(CANBus& , pBus)); + return ret; + } + + return piGetBusSettings(pBusIdx, pBus); +} + + +void CANConnection::setBusSettings(int pBusIdx, CANBus pBus) +{ + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + QMetaObject::invokeMethod(this, "setBusSettings", + Qt::BlockingQueuedConnection, + Q_ARG(int, pBusIdx), + Q_ARG(CANBus, pBus)); + return; + } + + return piSetBusSettings(pBusIdx, pBus); +} + + +void CANConnection::sendFrame(const CANFrame& pFrame) +{ + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + QMetaObject::invokeMethod(this, "sendFrame", + Qt::BlockingQueuedConnection, + Q_ARG(const CANFrame&, pFrame)); + return; + } + + return piSendFrame(pFrame); +} + + +void CANConnection::sendFrameBatch(const QList& pFrames) +{ + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + QMetaObject::invokeMethod(this, "sendFrameBatch", + Qt::BlockingQueuedConnection, + Q_ARG(const QList&, pFrames)); + return; + } + + return piSendFrameBatch(pFrames); } diff --git a/connections/canconnection.h b/connections/canconnection.h index 5c9c68f..eb02f60 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -20,8 +20,11 @@ public: * @param pPort: string containing port name * @param pType: the type of connection @ref CANCon::type * @param pNumBuses: the number of buses the device has + * @param pQueueLen: the length of the lock free queue to use + * @param pUseThread: if set to true, object will be execute in a dedicated thread */ - CANConnection(QString pPort, CANCon::type pType, int pNumBuses); + CANConnection(QString pPort, CANCon::type pType, int pNumBuses, + int pQueueLen, bool pUseThread); /** * @brief CANConnection destructor */ @@ -31,50 +34,33 @@ public: /** * @brief getNumBuses * @return returns the number of buses of the device - * @note multithread safe */ int getNumBuses(); /** * @brief getPort * @return returns the port name of the device - * @note multithread safe */ QString getPort(); /** * @brief getQueue is call by reader to get a reference on the queue to monitor * @return the lock free queue of the device - * @note multithread safe */ LFQueue& getQueue(); /** * @brief getType * @return the @ref CANCon::type of the device - * @note multithread safe */ CANCon::type getType(); /** * @brief getStatus * @return the @ref CANCon::status of the device (either connected or not) - * @note multithread safe */ CANCon::status getStatus(); - /** - * @brief start the device - * @note start a working thread here if needed - */ - virtual void start() = 0; - - /** - * @brief stop the device - * @note stop the working thread here if one has been started - */ - virtual void stop() = 0; - signals: void error(const QString &); @@ -95,30 +81,45 @@ signals: public slots: - virtual void sendFrame(const CANFrame *) = 0; - virtual void sendFrameBatch(const QList *) = 0; + /** + * @brief start the device, this calls piStarted + * @note starts the working thread if required (piStarted in the working thread context) + */ + void start(); + + /** + * @brief stop the device, this calls piStop + * @note if a working thread is used, piStop is called before exiting the working thread + */ + void stop(); /** * @brief setBusSettings * @param pBusIdx: the index of the bus for which settings have to be set * @param pBus: the settings to set + * @note this calls piSetBusSettings in the working thread context (if one has been started) */ - virtual void setBusSettings(int pBusIdx, CANBus pBus) = 0; + void setBusSettings(int pBusIdx, CANBus pBus); /** * @brief getBusSettings * @param pBusIdx: the index of the bus for which settings have to be retrieved * @param pBus: the CANBus struct to fill with information * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet + * @note this calls piGetBusSettings in the working thread context (if one has been started) */ - virtual bool getBusSettings(int pBusIdx, CANBus& pBus) = 0; + bool getBusSettings(int pBusIdx, CANBus& pBus); /** * @brief suspends/restarts data capture * @param pSuspend: suspends capture if true else restarts it + * @note this calls piSuspend in the working thread context (if one has been started) * @note the caller will not access the queue when capture is suspended, so it is safe for callee to flush the queue */ - virtual void suspend(bool pSuspend) = 0; + void suspend(bool pSuspend); + + void sendFrame(const CANFrame&); + void sendFrameBatch(const QList&); protected: @@ -177,6 +178,46 @@ protected: */ void setCapSuspended(bool pIsSuspended); +protected: + + /** + * @brief start the device + * @note start a working thread here if needed + */ + virtual void piStarted() = 0; + + /** + * @brief stop the device + * @note stop the working thread here if one has been started + */ + virtual void piStop() = 0; + + /** + * @brief setBusSettings + * @param pBusIdx: the index of the bus for which settings have to be set + * @param pBus: the settings to set + */ + virtual void piSetBusSettings(int pBusIdx, CANBus pBus) = 0; + + /** + * @brief getBusSettings + * @param pBusIdx: the index of the bus for which settings have to be retrieved + * @param pBus: the CANBus struct to fill with information + * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet + */ + virtual bool piGetBusSettings(int pBusIdx, CANBus& pBus) = 0; + + /** + * @brief suspends/restarts data capture + * @param pSuspend: suspends capture if true else restarts it + * @note the caller will not access the queue when capture is suspended, so it is safe for callee to flush the queue + */ + virtual void piSuspend(bool pSuspend) = 0; + + virtual void piSendFrame(const CANFrame&) = 0; + virtual void piSendFrameBatch(const QList&) = 0; + + private: CANBus* mBus; bool* mConfigured; @@ -186,6 +227,7 @@ private: const CANCon::type mType; bool mIsCapSuspended; QAtomicInt mStatus; + QThread* mThread_p; }; #endif // CANCONNECTION_H diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index 96666d5..1d34f38 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -7,13 +7,9 @@ #include "gvretserial.h" GVRetSerial::GVRetSerial(QString portName) : - CANConnection(portName, CANCon::GVRET_SERIAL, 2), - mThread(NULL) + CANConnection(portName, CANCon::GVRET_SERIAL, 2, 4000, true), + mTimer(this) /*NB: set this as parent of timer to manage it from working thread */ { - getQueue().setSize(2000); /*TODO add check on returned value */ - /* move ourself to the thread */ - moveToThread(&mThread); - qDebug() << "GVRetSerial()"; serial = NULL; @@ -35,13 +31,9 @@ GVRetSerial::~GVRetSerial() } -void GVRetSerial::start() +void GVRetSerial::piStarted() { - qDebug() << "enter thread"; - /* start thread */ - mThread.start(QThread::HighPriority); - /* connect device in thread context */ - connect(&mThread, SIGNAL(started()), this, SLOT(connectDevice())); + connectDevice(); /* start timer */ connect(&mTimer, SIGNAL(timeout()), this, SLOT(handleTick())); @@ -51,15 +43,8 @@ void GVRetSerial::start() } -void GVRetSerial::suspend(bool pSuspend) { - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - QMetaObject::invokeMethod(this, "suspend", - Qt::BlockingQueuedConnection, - Q_ARG(bool, pSuspend)); - return; - } - +void GVRetSerial::piSuspend(bool pSuspend) +{ /* update capSuspended */ setCapSuspended(pSuspend); @@ -69,36 +54,98 @@ void GVRetSerial::suspend(bool pSuspend) { } -void GVRetSerial::stop() { +void GVRetSerial::piStop() +{ mTimer.stop(); - mThread.quit(); - if(!mThread.wait()) { - qDebug() << "can't stop thread"; - } disconnectDevice(); } -bool GVRetSerial::getBusSettings(int pBusIdx, CANBus& pBus) { - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - bool ret; - QMetaObject::invokeMethod(this, "getBusSettings", - Qt::BlockingQueuedConnection, - Q_RETURN_ARG(bool, ret), - Q_ARG(int , pBusIdx), - Q_ARG(CANBus& , pBus)); - return ret; - } - +bool GVRetSerial::piGetBusSettings(int pBusIdx, CANBus& pBus) +{ return getBusConfig(pBusIdx, pBus); } -void GVRetSerial::sendFrame(const CANFrame *) {} -void GVRetSerial::sendFrameBatch(const QList *){} +void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) +{ + /* sanity checks */ + if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) + return; + + /* copy bus config */ + setBusConfig(pBusIdx, bus); + + qDebug() << "About to update bus " << pBusIdx << " on GVRET"; + if (pBusIdx == 0) + { + can0Baud = bus.getSpeed(); + can0Baud |= 0x80000000; + if (bus.isActive()) + { + can0Baud |= 0x40000000; + can0Enabled = true; + } + else can0Enabled = false; + + if (bus.isListenOnly()) + { + can0Baud |= 0x20000000; + can0ListenOnly = true; + } + else can0ListenOnly = false; + } + else if (pBusIdx == 1) + { + can1Baud = bus.getSpeed(); + can1Baud |= 0x80000000; + if (bus.isActive()) + { + can1Baud |= 0x40000000; + can1Enabled = true; + } + else can1Enabled = false; + + if (bus.isListenOnly()) + { + can1Baud |= 0x20000000; + can1ListenOnly = true; + } + else can1ListenOnly = false; + + if (bus.isSingleWire()) + { + can1Baud |= 0x10000000; + deviceSingleWireMode = 1; + } + else deviceSingleWireMode = 0; + } + + /* update baud rates */ + QByteArray buffer; + qDebug() << "Got signal to update bauds. 1: " << can0Baud <<" 2: " << can1Baud; + 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[10] = 0; + if (serial == NULL) return; + if (!serial->isOpen()) return; + serial->write(buffer); +} +void GVRetSerial::piSendFrame(const CANFrame&) {} +void GVRetSerial::piSendFrameBatch(const QList&){} + + +/****************************************************************/ void GVRetSerial::readSettings() { @@ -528,84 +575,4 @@ void GVRetSerial::sendCommValidation() } -void GVRetSerial::setBusSettings(int pBusIdx, CANBus bus) -{ - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - QMetaObject::invokeMethod(this, "setBusSettings", - Qt::BlockingQueuedConnection, - Q_ARG(int, pBusIdx), - Q_ARG(CANBus, bus)); - return; - } - /* sanity checks */ - if( (pBusIdx < 0) || pBusIdx >= getNumBuses()) - return; - - /* copy bus config */ - setBusConfig(pBusIdx, bus); - - qDebug() << "About to update bus " << pBusIdx << " on GVRET"; - if (pBusIdx == 0) - { - can0Baud = bus.getSpeed(); - can0Baud |= 0x80000000; - if (bus.isActive()) - { - can0Baud |= 0x40000000; - can0Enabled = true; - } - else can0Enabled = false; - - if (bus.isListenOnly()) - { - can0Baud |= 0x20000000; - can0ListenOnly = true; - } - else can0ListenOnly = false; - } - else if (pBusIdx == 1) - { - can1Baud = bus.getSpeed(); - can1Baud |= 0x80000000; - if (bus.isActive()) - { - can1Baud |= 0x40000000; - can1Enabled = true; - } - else can1Enabled = false; - - if (bus.isListenOnly()) - { - can1Baud |= 0x20000000; - can1ListenOnly = true; - } - else can1ListenOnly = false; - - if (bus.isSingleWire()) - { - can1Baud |= 0x10000000; - deviceSingleWireMode = 1; - } - else deviceSingleWireMode = 0; - } - - /* update baud rates */ - QByteArray buffer; - qDebug() << "Got signal to update bauds. 1: " << can0Baud <<" 2: " << can1Baud; - 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[10] = 0; - if (serial == NULL) return; - if (!serial->isOpen()) return; - serial->write(buffer); -} diff --git a/connections/gvretserial.h b/connections/gvretserial.h index b223aee..350277f 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -44,10 +44,6 @@ public: GVRetSerial(QString portName); virtual ~GVRetSerial(); - virtual void start(); - virtual void stop(); - - signals: void error(const QString &); @@ -60,18 +56,16 @@ signals: //being passed. Just set for things that really are being updated. void busStatus(int, int, int); - -public slots: - - virtual void sendFrame(const CANFrame *); - virtual void sendFrameBatch(const QList *); - - virtual void setBusSettings(int, CANBus); - virtual bool getBusSettings(int pBusIdx, CANBus& pBus); - - virtual void suspend(bool); - 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 void piSendFrame(const CANFrame&) ; + virtual void piSendFrameBatch(const QList&); + void disconnectDevice(); private slots: diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 76b6fe3..2b41f2e 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -11,14 +11,10 @@ /***********************************/ SocketCanConnection::SocketCanConnection(QString portName) : - CANConnection(portName, CANCon::SOCKETCAN, 1), + CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true), mDev_p(NULL), - mThread(NULL) + mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */ { - getQueue().setSize(2000); /*TODO add check on returned value */ - /* move ourself to the thread */ - moveToThread(&mThread); - qDebug() << "SocketCanConnection()"; } @@ -30,11 +26,8 @@ SocketCanConnection::~SocketCanConnection() } -void SocketCanConnection::start() { - - qDebug() << "enter thread"; - mThread.start(QThread::HighPriority); - +void SocketCanConnection::piStarted() +{ connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection())); mTimer.setInterval(1000); mTimer.setSingleShot(false); //keep ticking @@ -42,15 +35,8 @@ void SocketCanConnection::start() { } -void SocketCanConnection::suspend(bool pSuspend) { - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - QMetaObject::invokeMethod(this, "suspend", - Qt::BlockingQueuedConnection, - Q_ARG(bool, pSuspend)); - return; - } - +void SocketCanConnection::piSuspend(bool pSuspend) +{ /* update capSuspended */ setCapSuspended(pSuspend); @@ -60,43 +46,20 @@ void SocketCanConnection::suspend(bool pSuspend) { } -void SocketCanConnection::stop() { +void SocketCanConnection::piStop() { mTimer.stop(); - mThread.quit(); - if(!mThread.wait()) { - qDebug() << "can't stop thread"; - } disconnectDevice(); } -bool SocketCanConnection::getBusSettings(int pBusIdx, CANBus& pBus) { - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - bool ret; - QMetaObject::invokeMethod(this, "getBusSettings", - Qt::BlockingQueuedConnection, - Q_RETURN_ARG(bool, ret), - Q_ARG(int , pBusIdx), - Q_ARG(CANBus& , pBus)); - return ret; - } - +bool SocketCanConnection::piGetBusSettings(int pBusIdx, CANBus& pBus) +{ return getBusConfig(pBusIdx, pBus); } -void SocketCanConnection::setBusSettings(int pBusIdx, CANBus bus) +void SocketCanConnection::piSetBusSettings(int pBusIdx, CANBus bus) { - /* make sure we execute in mThread context */ - if(QThread::currentThread() != &mThread) { - QMetaObject::invokeMethod(this, "setBusSettings", - Qt::BlockingQueuedConnection, - Q_ARG(int, pBusIdx), - Q_ARG(CANBus, bus)); - return; - } - /* sanity checks */ if(0 != pBusIdx) return; @@ -139,8 +102,8 @@ void SocketCanConnection::setBusSettings(int pBusIdx, CANBus bus) } -void SocketCanConnection::sendFrame(const CANFrame *) {} -void SocketCanConnection::sendFrameBatch(const QList *){} +void SocketCanConnection::piSendFrame(const CANFrame&) {} +void SocketCanConnection::piSendFrameBatch(const QList&){} /***********************************/ @@ -239,12 +202,12 @@ void SocketCanConnection::testConnection() { break; case CANCon::NOT_CONNECTED: if (dev_p && dev_p->connectDevice()) { - - /* try to reconnect */ - CANBus bus; - if(getBusConfig(0, bus)) - setBusSettings(0, bus); - + if(!mDev_p) { + /* try to reconnect */ + CANBus bus; + if(getBusConfig(0, bus)) + setBusSettings(0, bus); + } /* disconnect test instance */ dev_p->disconnectDevice(); diff --git a/connections/socketcan.h b/connections/socketcan.h index eea37a9..315aad1 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -18,10 +18,6 @@ public: SocketCanConnection(QString portName); virtual ~SocketCanConnection(); - virtual void start(); - virtual void stop(); - - signals: void error(const QString &); @@ -34,18 +30,16 @@ signals: //being passed. Just set for things that really are being updated. void busStatus(int, int, int); - -public slots: - - virtual void sendFrame(const CANFrame *); - virtual void sendFrameBatch(const QList *); - - virtual void setBusSettings(int, CANBus); - virtual bool getBusSettings(int pBusIdx, CANBus& pBus); - - virtual void suspend(bool); - 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 void piSendFrame(const CANFrame&) ; + virtual void piSendFrameBatch(const QList&); + void disconnectDevice(); private slots: @@ -57,7 +51,6 @@ private slots: protected: QCanBusDevice* mDev_p; QTimer mTimer; - QThread mThread; }; From e2d0033099434f40dbd6b0531cfe1eadd3d5b5f7 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 16 Jun 2016 13:28:29 +0200 Subject: [PATCH 36/86] add connection deletion --- connectionwindow.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index bab8cf3..d9237e6 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -70,13 +70,27 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : qDebug() << "Serial worker thread starting"; connect(&mTicker, SIGNAL(timeout()), this, SLOT(refreshCanList())); - mTicker.setInterval(250); //tick 4 times a second (TODO: make this configurable?) */ + /* tick frequency has a huge impact on performances */ + /* TODO: make this configurable and part of the connection constructor to let connection configure the length of the queue */ + mTicker.setInterval(500); /*tick twice a second */ mTicker.setSingleShot(false); mTicker.start(); } ConnectionWindow::~ConnectionWindow() { + QList& conns = connModel->getConnections(); + CANConnection* conn_p; + + /* delete connections */ + while(!conns.isEmpty()) { + conn_p = conns.takeFirst(); + conn_p->stop(); + delete conn_p; + } + + delete connModel; + mTicker.stop(); delete settings; delete ui; @@ -306,7 +320,6 @@ void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) void ConnectionWindow::handleConnSelectionChanged() { int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); - qDebug() << "Selection: " << selIdx; if (selIdx == -1) { ui->btnOK->setText(tr("Create New Connection")); From 893aab56002b737a376dc7d493eb670d80c86787 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 16 Jun 2016 13:59:06 +0200 Subject: [PATCH 37/86] renamed socketcan class --- connections/canconfactory.cpp | 2 +- connections/canconnection.h | 67 ++++++++++++++++++++++------------- connections/socketcan.cpp | 38 ++++++++++---------- connections/socketcan.h | 12 +++---- 4 files changed, 69 insertions(+), 50 deletions(-) diff --git a/connections/canconfactory.cpp b/connections/canconfactory.cpp index 93b618e..7926001 100644 --- a/connections/canconfactory.cpp +++ b/connections/canconfactory.cpp @@ -9,7 +9,7 @@ CANConnection* CanConFactory::create(type pType, QString pPortName) { switch(pType) { case SOCKETCAN: - return new SocketCanConnection(pPortName); + return new SocketCan(pPortName); case GVRET_SERIAL: return new GVRetSerial(pPortName); default: {} diff --git a/connections/canconnection.h b/connections/canconnection.h index eb02f60..9199c7b 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -23,8 +23,11 @@ public: * @param pQueueLen: the length of the lock free queue to use * @param pUseThread: if set to true, object will be execute in a dedicated thread */ - CANConnection(QString pPort, CANCon::type pType, int pNumBuses, - int pQueueLen, bool pUseThread); + CANConnection(QString pPort, + CANCon::type pType, + int pNumBuses, + int pQueueLen, + bool pUseThread); /** * @brief CANConnection destructor */ @@ -44,7 +47,7 @@ public: QString getPort(); /** - * @brief getQueue is call by reader to get a reference on the queue to monitor + * @brief getQueue * @return the lock free queue of the device */ LFQueue& getQueue(); @@ -63,6 +66,7 @@ public: signals: + /*not implemented yet */ void error(const QString &); void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte @@ -73,7 +77,7 @@ signals: void busStatus(int, int, int); /** - * @brief event sent when the CANCon::status of the connection changes (connected->not_connected or the other way round) + * @brief event emitted when the CANCon::status of the connection changes (connected->not_connected or the other way round) * @param pStatus: the new status of the device */ void status(CANCon::status pStatus); @@ -82,13 +86,13 @@ signals: public slots: /** - * @brief start the device, this calls piStarted - * @note starts the working thread if required (piStarted in the working thread context) + * @brief start the device. This calls piStarted + * @note starts the working thread if required (piStarted is called in the working thread context) */ void start(); /** - * @brief stop the device, this calls piStop + * @brief stop the device. This calls piStop * @note if a working thread is used, piStop is called before exiting the working thread */ void stop(); @@ -113,20 +117,30 @@ public slots: /** * @brief suspends/restarts data capture * @param pSuspend: suspends capture if true else restarts it - * @note this calls piSuspend in the working thread context (if one has been started) - * @note the caller will not access the queue when capture is suspended, so it is safe for callee to flush the queue + * @note this calls piSuspend (in the working thread context if one has been started) + * @note the caller shall not access the queue when capture is suspended, it is then safe for callee to flush the queue */ void suspend(bool pSuspend); - void sendFrame(const CANFrame&); - void sendFrameBatch(const QList&); + /** + * @brief provides device with the frame to send + * @param pFrame: the frame to send + * @note this calls piSendFrame (in the working thread context if one has been started) + */ + void sendFrame(const CANFrame& pFrame); + + /** + * @brief provides device with a list of frames to send + * @param pFrame: the list of frames to send + * @note this calls piSendFrameBatch (in the working thread context if one has been started) + */ + void sendFrameBatch(const QList& pFrames); protected: /** * @brief setStatus * @param pStatus: the status to set - * @note multithread safe (can be used while another thread calls @ref getStatus) */ void setStatus(CANCon::status pStatus); @@ -134,7 +148,6 @@ protected: * @brief isConfigured * @param pBusId * @return true if bus is configured - * @note NOT multithread safe */ bool isConfigured(int pBusId); @@ -143,7 +156,6 @@ protected: * @param pBusId * @param pConfigured * @note it is not necessary to call this function to set pBusId configured, it is enough to call @ref setBusConfig - * @note NOT multithread safe */ void setConfigured(int pBusId, bool pConfigured); @@ -152,7 +164,6 @@ protected: * @param pBusId * @param pBus * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet - * @note NOT multithread safe */ bool getBusConfig(int pBusId, CANBus& pBus); @@ -160,47 +171,46 @@ protected: * @brief setBusConfig * @param pBusId: the index of the bus for which settings have to be set * @param pBus: the settings to set - * @note NOT multithread safe */ void setBusConfig(int pBusId, CANBus& pBus); /** * @brief isCapSuspended * @return true if the capture is suspended - * @note NOT multithread safe */ bool isCapSuspended(); /** * @brief setCapSuspended * @param pIsSuspended - * @note NOT multithread safe */ void setCapSuspended(bool pIsSuspended); protected: + /**************************************************************/ + /*********** protected interface to implement *******/ + /**************************************************************/ + /** - * @brief start the device - * @note start a working thread here if needed + * @brief starts the device */ virtual void piStarted() = 0; /** - * @brief stop the device - * @note stop the working thread here if one has been started + * @brief stops the device */ virtual void piStop() = 0; /** - * @brief setBusSettings + * @brief piSetBusSettings * @param pBusIdx: the index of the bus for which settings have to be set * @param pBus: the settings to set */ virtual void piSetBusSettings(int pBusIdx, CANBus pBus) = 0; /** - * @brief getBusSettings + * @brief piGetBusSettings * @param pBusIdx: the index of the bus for which settings have to be retrieved * @param pBus: the CANBus struct to fill with information * @return true if operation succeeds, false if pBusIdx is invalid or bus has not been configured yet @@ -214,7 +224,16 @@ protected: */ virtual void piSuspend(bool pSuspend) = 0; + /** + * @brief provides device with the frame to send + * @param pFrame: the frame to send + */ virtual void piSendFrame(const CANFrame&) = 0; + + /** + * @brief provides device with a list of frames to send + * @param pFrame: the list of frames to send + */ virtual void piSendFrameBatch(const QList&) = 0; diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 2b41f2e..16fff23 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -10,23 +10,23 @@ /**** class definition ****/ /***********************************/ -SocketCanConnection::SocketCanConnection(QString portName) : +SocketCan::SocketCan(QString portName) : CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true), mDev_p(NULL), mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */ { - qDebug() << "SocketCanConnection()"; + qDebug() << "SocketCan()"; } -SocketCanConnection::~SocketCanConnection() +SocketCan::~SocketCan() { stop(); - qDebug() << "~SocketCanConnection()"; + qDebug() << "~SocketCan()"; } -void SocketCanConnection::piStarted() +void SocketCan::piStarted() { connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection())); mTimer.setInterval(1000); @@ -35,7 +35,7 @@ void SocketCanConnection::piStarted() } -void SocketCanConnection::piSuspend(bool pSuspend) +void SocketCan::piSuspend(bool pSuspend) { /* update capSuspended */ setCapSuspended(pSuspend); @@ -46,19 +46,19 @@ void SocketCanConnection::piSuspend(bool pSuspend) } -void SocketCanConnection::piStop() { +void SocketCan::piStop() { mTimer.stop(); disconnectDevice(); } -bool SocketCanConnection::piGetBusSettings(int pBusIdx, CANBus& pBus) +bool SocketCan::piGetBusSettings(int pBusIdx, CANBus& pBus) { return getBusConfig(pBusIdx, pBus); } -void SocketCanConnection::piSetBusSettings(int pBusIdx, CANBus bus) +void SocketCan::piSetBusSettings(int pBusIdx, CANBus bus) { /* sanity checks */ if(0 != pBusIdx) @@ -84,9 +84,9 @@ void SocketCanConnection::piSetBusSettings(int pBusIdx, CANBus bus) } /* connect slots */ - connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCanConnection::errorReceived); - connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCanConnection::framesWritten); - connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCanConnection::framesReceived); + connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SocketCan::errorReceived); + connect(mDev_p, &QCanBusDevice::framesWritten, this, &SocketCan::framesWritten); + connect(mDev_p, &QCanBusDevice::framesReceived, this, &SocketCan::framesReceived); /* set configuration */ /*if (p.useConfigurationEnabled) { @@ -102,8 +102,8 @@ void SocketCanConnection::piSetBusSettings(int pBusIdx, CANBus bus) } -void SocketCanConnection::piSendFrame(const CANFrame&) {} -void SocketCanConnection::piSendFrameBatch(const QList&){} +void SocketCan::piSendFrame(const CANFrame&) {} +void SocketCan::piSendFrameBatch(const QList&){} /***********************************/ @@ -112,7 +112,7 @@ void SocketCanConnection::piSendFrameBatch(const QList&){} /* disconnect device */ -void SocketCanConnection::disconnectDevice() { +void SocketCan::disconnectDevice() { if(mDev_p) { mDev_p->disconnectDevice(); delete mDev_p; @@ -121,7 +121,7 @@ void SocketCanConnection::disconnectDevice() { } -void SocketCanConnection::errorReceived(QCanBusDevice::CanBusError error) const +void SocketCan::errorReceived(QCanBusDevice::CanBusError error) const { switch (error) { case QCanBusDevice::ReadError: @@ -135,12 +135,12 @@ void SocketCanConnection::errorReceived(QCanBusDevice::CanBusError error) const } } -void SocketCanConnection::framesWritten(qint64 count) +void SocketCan::framesWritten(qint64 count) { qDebug() << "Number of frames written:" << count; } -void SocketCanConnection::framesReceived() +void SocketCan::framesReceived() { /* sanity checks */ if(!mDev_p) @@ -186,7 +186,7 @@ void SocketCanConnection::framesReceived() } -void SocketCanConnection::testConnection() { +void SocketCan::testConnection() { QCanBusDevice* dev_p = QCanBus::instance()->createDevice("socketcan", getPort()); switch(getStatus()) diff --git a/connections/socketcan.h b/connections/socketcan.h index 315aad1..dd1877b 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -1,5 +1,5 @@ -#ifndef SOCKETCANCONNECTION_H -#define SOCKETCANCONNECTION_H +#ifndef SocketCan_H +#define SocketCan_H #include #include @@ -10,13 +10,13 @@ #include "canconnection.h" -class SocketCanConnection : public CANConnection +class SocketCan : public CANConnection { Q_OBJECT public: - SocketCanConnection(QString portName); - virtual ~SocketCanConnection(); + SocketCan(QString portName); + virtual ~SocketCan(); signals: void error(const QString &); @@ -54,4 +54,4 @@ protected: }; -#endif // SOCKETCANCONNECTION_H +#endif // SocketCan_H From 89ad77eab972519d430d7b4b951f63041e1b1966 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 16 Jun 2016 15:52:47 +0200 Subject: [PATCH 38/86] removed uneeded queue resizing --- connections/canconnection.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 7ec3ab7..526d88e 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -55,8 +55,6 @@ CANConnection::~CANConnection() /* configured table */ delete[] mConfigured; mConfigured = NULL; - /* delete queue table */ - mQueue.setSize(0); } From 8216e152c90919a6ac71b7a730221d0c6d73f6fe Mon Sep 17 00:00:00 2001 From: canpadawan Date: Mon, 20 Jun 2016 17:20:35 +0200 Subject: [PATCH 39/86] adding CANFlt struct --- can_structs.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/can_structs.h b/can_structs.h index d118dc8..b45034e 100644 --- a/can_structs.h +++ b/can_structs.h @@ -16,6 +16,13 @@ public: uint64_t timestamp; }; +struct CANFlt +{ + quint32 id; + quint32 mask; + bool notify; +}; + struct J1939ID { public: From 1a195fe36082e6f579c7bb610d7f39448958e84b Mon Sep 17 00:00:00 2001 From: canpadawan Date: Mon, 20 Jun 2016 17:34:30 +0200 Subject: [PATCH 40/86] add filters & callback support --- connections/canconconst.h | 7 ++ connections/canconnection.cpp | 120 ++++++++++++++++++++++++++++------ connections/canconnection.h | 49 +++++++++++++- connections/gvretserial.h | 12 ---- connections/socketcan.cpp | 24 +++++-- connections/socketcan.h | 12 ---- 6 files changed, 172 insertions(+), 52 deletions(-) diff --git a/connections/canconconst.h b/connections/canconconst.h index 707355d..b31301b 100644 --- a/connections/canconconst.h +++ b/connections/canconconst.h @@ -19,6 +19,13 @@ namespace CANCon { SOCKETCAN, NONE }; + + /* test */ + enum cbtype + { + READ, + WRITE + }; } #endif // CANCONCONST_H diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 526d88e..d0d8014 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -1,6 +1,15 @@ #include #include "canconnection.h" + +struct BusData { + CANBus mBus; + bool mConfigured; + QVector mFilters; + bool mFilterOut; +}; + + CANConnection::CANConnection(QString pPort, CANCon::type pType, int pNumBuses, @@ -12,6 +21,8 @@ CANConnection::CANConnection(QString pPort, mType(pType), mIsCapSuspended(false), mStatus(CANCon::NOT_CONNECTED), + mStarted(false), + mCallback(NULL), mThread_p(NULL) { qDebug() << "CANConnection()"; @@ -20,16 +31,18 @@ CANConnection::CANConnection(QString pPort, qRegisterMetaType("CANBus"); qRegisterMetaType("CANFrame"); qRegisterMetaType("CANCon::status"); + qRegisterMetaType("CANFlt"); /* set queue size */ mQueue.setSize(pQueueLen); /*TODO add check on returned value */ /* allocate buses */ - mBus = new CANBus[mNumBuses]; - mConfigured = new bool[mNumBuses]; - - for(int i=0 ; i= mNumBuses) + if( pBusId < 0 || pBusId >= getNumBuses()) return false; - return mConfigured[pBusId]; + return mBusData_p[pBusId].mConfigured; } void CANConnection::setConfigured(int pBusId, bool pConfigured) { - if( pBusId < 0 || pBusId >= mNumBuses) + if( pBusId < 0 || pBusId >= getNumBuses()) return; - mConfigured[pBusId] = pConfigured; + mBusData_p[pBusId].mConfigured = pConfigured; } bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) { - if( pBusId < 0 || pBusId >= mNumBuses || !isConfigured(pBusId)) + if( pBusId < 0 || pBusId >= getNumBuses() || !isConfigured(pBusId)) return false; - pBus = mBus[pBusId]; + pBus = mBusData_p[pBusId].mBus; return true; } void CANConnection::setBusConfig(int pBusId, CANBus& pBus) { - if( pBusId < 0 || pBusId >= mNumBuses) + if( pBusId < 0 || pBusId >= getNumBuses()) return; - mConfigured[pBusId] = true; - mBus[pBusId] = pBus; + mBusData_p[pBusId].mConfigured = true; + mBusData_p[pBusId].mBus = pBus; } @@ -231,6 +245,13 @@ CANCon::status CANConnection::getStatus() { } +bool CANConnection::setCallback(std::function pCallback) { + if(mStarted || !pCallback) return false; + mCallback = pCallback; + return true; +} + + void CANConnection::setStatus(CANCon::status pStatus) { mStatus.store(pStatus); } @@ -243,3 +264,62 @@ void CANConnection::setCapSuspended(bool pIsSuspended) { mIsCapSuspended = pIsSuspended; } +void CANConnection::callback(CANCon::cbtype pCbType) { + if(mCallback) + mCallback(pCbType); +} + +bool CANConnection::setFilters(int pBusId, const QVector& pFilters, bool pFilterOut) +{ + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + bool ret; + QMetaObject::invokeMethod(this, "setFilters", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), + Q_ARG(int , pBusId), + Q_ARG(const QVector&, pFilters), + Q_ARG(bool , pFilterOut)); + return ret; + } + + /* sanity checks */ + if(pBusId<0 || pBusId>=getNumBuses()) + return false; + + /* copy filters */ + mBusData_p[pBusId].mFilters = pFilters; + mBusData_p[pBusId].mFilterOut = pFilterOut; + + /* set hardware filtering if available */ + if(pFilterOut) + piSetFilters(pBusId, pFilters); + + return true; +} + + +bool CANConnection::discard(int pBusId, quint32 pId, bool& pNotify) +{ + if(pBusId<0 || pBusId>=getNumBuses()) + return true; + + foreach (const CANFlt& filter, mBusData_p[pBusId].mFilters) + { + if( (filter.id & filter.mask) == (pId & filter.mask) ) + { + if(filter.notify) + pNotify = true; + return false; + } + } + return mBusData_p[pBusId].mFilterOut; +} + + +/* default implementation of piSetFilters */ +void CANConnection::piSetFilters(int pBusId, const QVector& pFilters) +{ + Q_UNUSED(pBusId); + Q_UNUSED(pFilters); +} diff --git a/connections/canconnection.h b/connections/canconnection.h index 9199c7b..99cd668 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -8,6 +8,7 @@ #include "canbus.h" #include "canconconst.h" +struct BusData; class CANConnection : public QObject { @@ -64,6 +65,13 @@ public: */ CANCon::status getStatus(); + /** + * @brief set the callback function, this call has to be placed before calling start + * @param pCallback + * @return true if callback can be set + */ + bool setCallback(std::function pCallback); + signals: /*not implemented yet */ @@ -76,6 +84,11 @@ signals: //being passed. Just set for things that really are being updated. void busStatus(int, int, int); + /** + * @brief event sent when a frame matching a filter set with notification hs been received + */ + void notify(); + /** * @brief event emitted when the CANCon::status of the connection changes (connected->not_connected or the other way round) * @param pStatus: the new status of the device @@ -136,6 +149,14 @@ public slots: */ void sendFrameBatch(const QList& pFrames); + /** + * @brief sets a filter list. Filters can be used to send a signal or filter out messages + * @param pFilters: a vector of can filters + * @param pFilterOut: if set to true, can frames not matching a filter are discarded + * @return true if filters have been set, false if busid is invalid + */ + bool setFilters(int pBusId, const QVector& pFilters, bool pFilterOut); + protected: /** @@ -186,6 +207,22 @@ protected: */ void setCapSuspended(bool pIsSuspended); + /** + * @brief call callback function + * @param pCbType callback type (read or write) + */ + void callback(CANCon::cbtype pCbType); + + /** + * @brief used to check if a message shall be discarded. The function also update pNotify if a notification is expected for that message + * @param pBusId: the bus id on which the frame has been received + * @param pId: the id of the message to filter + * @param pNotify: set to true if a notification is expected, else pNotify is not set + * @return true if message shall be discarded + */ + bool discard(int pBusId, quint32 pId, bool& pNotify); + + protected: /**************************************************************/ @@ -236,16 +273,24 @@ protected: */ virtual void piSendFrameBatch(const QList&) = 0; + /** + * @brief sets a hardware filter list + * @param pBusId: the bus id on which filters have to be set + * @param pFilters: a vector of can filters, the notification flag of CANFilter is ignored + * @note implementing this function is optional + */ + virtual void piSetFilters(int pBusId, const QVector& pFilters); private: - CANBus* mBus; - bool* mConfigured; LFQueue mQueue; const int mNumBuses; const QString mPort; const CANCon::type mType; bool mIsCapSuspended; QAtomicInt mStatus; + bool mStarted; + std::function mCallback; + BusData* mBusData_p; QThread* mThread_p; }; diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 350277f..4ef824c 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -44,18 +44,6 @@ public: GVRetSerial(QString portName); virtual ~GVRetSerial(); -signals: - void error(const QString &); - - void status(CANCon::status); - void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte - - //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) - //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only - //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really - //being passed. Just set for things that really are being updated. - void busStatus(int, int, int); - protected: virtual void piStarted(); diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 16fff23..7da09f0 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -142,6 +142,10 @@ void SocketCan::framesWritten(qint64 count) void SocketCan::framesReceived() { + /* test */ + bool enqueued = false; + bool sndNotif = false; + /* sanity checks */ if(!mDev_p) return; @@ -153,15 +157,16 @@ void SocketCan::framesReceived() /* exit case */ if(!recFrame.isValid()) - return; + break; /* drop frame if capture is suspended */ if(isCapSuspended()) continue; /* check frame */ - if(!recFrame.payload().isEmpty() && - recFrame.payload().length()<=8) + if( !recFrame.payload().isEmpty() && + recFrame.payload().length()<=8 && + !discard(0, recFrame.frameId(), sndNotif) ) { CANFrame* frame_p = getQueue().get(); if(frame_p) { @@ -175,13 +180,20 @@ void SocketCan::framesReceived() /* enqueue frame */ getQueue().queue(); + /* set enqueued */ + enqueued = true; } else qDebug() << "can't get a frame, ERROR"; } - else { - qDebug() << "invalid frame"; - } + } + + if(enqueued) { + callback(CANCon::READ); + } + + if(sndNotif) { + emit notify(); } } diff --git a/connections/socketcan.h b/connections/socketcan.h index dd1877b..0d0af5b 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -18,18 +18,6 @@ public: SocketCan(QString portName); virtual ~SocketCan(); -signals: - void error(const QString &); - - void status(CANCon::status); - void deviceInfo(int, int); //First param = driver version (or version of whatever you want), second param a status byte - - //bus number, bus speed, status (bit 0 = enabled, 1 = single wire, 2 = listen only) - //3 = Use value stored for enabled, 4 = use value passed for single wire, 5 = use value passed for listen only - //6 = use value passed for speed. This allows bus status to be updated but set that some things aren't really - //being passed. Just set for things that really are being updated. - void busStatus(int, int, int); - protected: virtual void piStarted(); From adb70d233393cea0b9b0d0f84fab5a53c45e1848 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Mon, 20 Jun 2016 17:35:42 +0200 Subject: [PATCH 41/86] added basic tests for callback & filters --- connectionwindow.cpp | 46 ++++++++++++++++++++++++++++++++++++++------ connectionwindow.h | 11 +++++++++-- mainwindow.cpp | 2 +- 3 files changed, 50 insertions(+), 9 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index d9237e6..69b42c6 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -1,13 +1,18 @@ #include +#include #include "connectionwindow.h" #include "ui_connectionwindow.h" #include "connections/canconfactory.h" +#define FALSE 0 +#define TRUE 1 + ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : QDialog(parent), - ui(new Ui::ConnectionWindow) + ui(new Ui::ConnectionWindow), + mRefreshReqOngoing(FALSE) { ui->setupUi(this); @@ -75,6 +80,11 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : mTicker.setInterval(500); /*tick twice a second */ mTicker.setSingleShot(false); mTicker.start(); + + /*test*/ + /* retrieve pointer on method */ + int methodIndex = metaObject()->indexOfMethod(QMetaObject::normalizedSignature("refreshCanList()")); + mRefreshM = metaObject()->method(methodIndex); } ConnectionWindow::~ConnectionWindow() @@ -104,17 +114,33 @@ void ConnectionWindow::showEvent(QShowEvent* event) } void ConnectionWindow::refreshCanList() { - QList::iterator conn_p; - QList& conns = connModel->getConnections(); + QList& conns = connModel->getConnections(); CANFrame* frame_p = NULL; - for (conn_p = conns.begin(); conn_p != conns.end(); ++conn_p) { - while( (frame_p = (*conn_p)->getQueue().peek() ) ) { + foreach (CANConnection* conn_p, conns) + { + while( (frame_p = conn_p->getQueue().peek() ) ) { canModel->addFrame(*frame_p, true); - (*conn_p)->getQueue().dequeue(); + conn_p->getQueue().dequeue(); } } + + /* erase flag (this should be done before we start dequeuing...) */ + mRefreshReqOngoing.store(FALSE); +} + +/*test*/ +void ConnectionWindow::callback(CANCon::cbtype pType) +{ + if(mRefreshReqOngoing.testAndSetRelaxed(FALSE, TRUE)) + { + /* ask for a refresh */ + mRefreshM.invoke(this, Qt::AutoConnection); + } + else { + //qDebug() << "skip event"; + } } void ConnectionWindow::handleNewConn() @@ -272,8 +298,16 @@ void ConnectionWindow::handleOKButton() connect(conn_p, SIGNAL(status(CANCon::status)), this, SLOT(connectionStatus(CANCon::status))); + //conn_p->setCallback(std::bind(&ConnectionWindow::callback, this, std::placeholders::_1)); + /*TODO add return value and checks */ conn_p->start(); + /*{ + QVector flters; + flters.append({0x305, 0xFFFF, true}); + conn_p->setFilters(0, flters, false); + connect(conn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); + }*/ for (int i=0 ; igetNumBuses() ; i++) { /* set bus configuration */ diff --git a/connectionwindow.h b/connectionwindow.h index 066cad0..91f292d 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -8,8 +8,9 @@ #include #include #include -//#include "canconnection_old.h" -//#include "serialworker.h" +/*test*/ +#include +/******/ #include "canconnectionmodel.h" #include "canframemodel.h" @@ -33,6 +34,7 @@ public: QString getPortName(); //name of port to connect to CANCon::type getConnectionType(); bool getSWMode(); + void callback(CANCon::cbtype pType); signals: void updateBusSettings(CANBus *bus); @@ -68,6 +70,11 @@ private: CANFrameModel *canModel; QTimer mTicker; + QAtomicInt mRefreshReqOngoing; + + /*test*/ + QMetaMethod mRefreshM; + void selectSerial(); void selectKvaser(); diff --git a/mainwindow.cpp b/mainwindow.cpp index b456467..01fd54c 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -157,7 +157,7 @@ MainWindow::MainWindow(QWidget *parent) : ui->lbNumFrames->setText("0"); connect(&updateTimer, &QTimer::timeout, this, &MainWindow::tickGUIUpdate); - updateTimer.setInterval(250); + updateTimer.setInterval(500); //test 250); updateTimer.start(); elapsedTime = new QTime; From a9f4c38cbcd91264c792431be787f882f8a570c6 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:24:29 +0200 Subject: [PATCH 42/86] add test for can connection --- test/main.cpp | 0 test/tst_cancon.cpp | 366 ++++++++++++++++++++++++++++++++++++++++++++ test/tst_cancon.h | 33 ++++ test/tst_lfqueue.h | 4 + 4 files changed, 403 insertions(+) create mode 100644 test/main.cpp create mode 100644 test/tst_cancon.cpp create mode 100644 test/tst_cancon.h create mode 100644 test/tst_lfqueue.h diff --git a/test/main.cpp b/test/main.cpp new file mode 100644 index 0000000..e69de29 diff --git a/test/tst_cancon.cpp b/test/tst_cancon.cpp new file mode 100644 index 0000000..eaf1eac --- /dev/null +++ b/test/tst_cancon.cpp @@ -0,0 +1,366 @@ +#include +#include + +#include "tst_cancon.h" +#include "canconnection.h" +#include "canconfactory.h" + + +#define QVERIFYB(statement) \ +do {\ + if (!QTest::qVerify((statement), #statement, "", __FILE__, __LINE__))\ + return false;\ +} while (0) + +#define QCOMPAREB(actual, expected) \ +do {\ + if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))\ + return false;\ +} while (0) + +Q_DECLARE_METATYPE(QVector); + + + +TestCanCon::TestCanCon(CANCon::type pType, QString pPortName, int pNbBus): + mType(pType), + mPortName(pPortName), + mNbBus(pNbBus){} + +void TestCanCon::create() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + /* try to get an element from the queue */ + QVERIFY(conn_p->getQueue().get()); + + if(conn_p) + delete conn_p; +} + +void TestCanCon::connectToDevice() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + QSignalSpy spy(conn_p, SIGNAL(status(CANCon::status))); + + /* start connection */ + conn_p->start(); + + /* wait for a signal */ + for(int i=0 ; (spy.count() != 1) && (i < 10) ; i++) + QTest::qWait(500); + + + QCOMPARE(spy.count(), 1); // make sure the signal was emitted exactly one time + QList arguments = spy.takeFirst(); // take the first signal + + QVERIFY(arguments.at(0).toInt() == CANCon::CONNECTED); // verify the first argument + + /* stop connection */ + conn_p->stop(); + delete conn_p; +} + +void TestCanCon::recvFrames() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + /* start connection */ + conn_p->start(); + + /* configure */ + QVERIFY(pConfig(conn_p)); + + LFQueue& queue = conn_p->getQueue(); + + /* wait for frames to arrive */ + QTest::qWait(1000); + + int i; + for(i=0 ; queue.peek() && i<1000 ; i++) + { + CANFrame* canf_p = queue.peek(); + QVERIFY(pValidateFrame(conn_p, canf_p)); + + queue.dequeue(); + } + + QVERIFY(i>0); + + /* stop connection */ + conn_p->stop(); + delete conn_p; +} + + +void TestCanCon::suspend() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + /* start connection */ + conn_p->start(); + + /* configure */ + QVERIFY(pConfig(conn_p)); + + LFQueue& queue = conn_p->getQueue(); + + /* wait for frames to arrive */ + QTest::qWait(1000); + + CANFrame* canf_p = queue.peek(); + QVERIFY(pValidateFrame(conn_p, canf_p)); + + conn_p->suspend(true); + + /* the queue should be flushed */ + canf_p = queue.peek(); + QVERIFY(!canf_p); + + /* restart capture */ + conn_p->suspend(false); + + /* wait for frames to arrive */ + QTest::qWait(1000); + + /* get a frame */ + canf_p = queue.peek(); + QVERIFY(pValidateFrame(conn_p, canf_p)); + + /* stop connection */ + conn_p->stop(); + delete conn_p; +} + + +void TestCanCon::filter_data() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + /* start connection */ + conn_p->start(); + + /* configure */ + QVERIFY(pConfig(conn_p)); + + LFQueue& queue = conn_p->getQueue(); + + /* wait for frames to arrive */ + QTest::qWait(1000); + + /* find 3 different ids */ + QVector ids; + + while( queue.peek() && ids.count()!=3 ) + { + CANFrame* canf_p = queue.peek(); + QVERIFY(pValidateFrame(conn_p, canf_p)); + + if(!ids.contains(canf_p->ID)) + ids.append(canf_p->ID); + + queue.dequeue(); + } + + QCOMPARE(ids.count(), 3); + + /* stop connection */ + conn_p->stop(); + delete conn_p; + + /* prepare test vector */ + + QTest::addColumn>("filters"); + QTest::addColumn("filterOut"); + QTest::addColumn("signalReceived"); + QTest::addColumn>("filtered"); + + QVector filters; + QVector filteredIds; + + /* one filter no signal*/ + filters.clear(); + filteredIds.clear(); + filters.append({ids[0], 0xFFFF, false}); + filteredIds.append(ids[0]); + QTest::newRow("1filternosignal") << filters << false << false << filteredIds; + + /* one filter & signal*/ + filters.clear(); + filteredIds.clear(); + filters.append({ids[0], 0xFFFF, true}); + filteredIds.append(ids[0]); + QTest::newRow("1filtersignal") << filters << false << true << filteredIds; + + /* 3 filters */ + filters.clear(); + filteredIds.clear(); + foreach(quint32 id, ids) { + filters.append({id, 0xFFFF, false}); + filteredIds.append(id); + } + QTest::newRow("3filters") << filters << false << false << filteredIds; +} + + +void TestCanCon::filter() +{ + QFETCH(QVector, filters); + QFETCH(bool, filterOut); + QFETCH(bool, signalReceived); + QFETCH(QVector, filtered); + + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + /* start connection */ + conn_p->start(); + + /* set filters */ + for(int i=0 ; igetNumBuses() ; i++) + QVERIFY(conn_p->setFilters(i, filters, filterOut)); + + /* spy signal */ + QSignalSpy spy(conn_p, SIGNAL(notify())); + + /* configure */ + QVERIFY(pConfig(conn_p)); + + LFQueue& queue = conn_p->getQueue(); + + /* wait for frames to arrive */ + QTest::qWait(1000); + + if(signalReceived) + QVERIFY(spy.count()>0); + + int i; + for(i=0 ; queue.peek() && i<1000 ; i++) + { + CANFrame* canf_p = queue.peek(); + QVERIFY(pValidateFrame(conn_p, canf_p)); + + if(filterOut) + QVERIFY(filtered.contains(canf_p->ID)); + + queue.dequeue(); + } + + QVERIFY(i>0); + + conn_p->stop(); + delete conn_p; +} + + +void TestCanCon::write() +{ + CANConnection* conn_p; + QVERIFY(pCreate(conn_p)); + + /* start connection */ + conn_p->start(); + + /* configure */ + QVERIFY(pConfig(conn_p)); + + QList frames; + /* build frames */ + CANFrame frame; + frame.bus = 0; + frame.ID = 0x1DE; + frame.data[0] = 0xDE; + frame.data[1] = 0xAD; + frame.data[2] = 0xC0; + frame.data[3] = 0xDE; + frame.len = 4; + + frames.append(frame); + + frame.data[2] = 0xBE; + frame.data[3] = 0xEF; + frames.append(frame); + + frame.data[2] = 0xDE; + frame.data[3] = 0xAD; + + + /* bad frame length */ + unsigned int oldVal = frame.len; + frame.len = 9; + QCOMPARE(conn_p->sendFrame(frame), false); + frame.len = oldVal; + + /* bad bus id */ + oldVal = frame.bus; + frame.bus = 48; + QCOMPARE(conn_p->sendFrame(frame), false); + frame.bus = oldVal; + + qDebug() << "Sending DE AD DE AD"; + /* send */ + QVERIFY(conn_p->sendFrame(frame)); + + /* leave some time for the frame to be sent */ + QTest::qWait(1000); + + qDebug() << "Sending DE AD C0 DE"; + qDebug() << "Sending DE AD BE EF"; + /* send */ + QVERIFY(conn_p->sendFrames(frames)); + + /* leave some time for the frame to be sent */ + QTest::qWait(1000); + + conn_p->stop(); + delete conn_p; +} + + +/*********************************************************/ + +bool TestCanCon::pCreate(CANConnection*& pConn_p) +{ + pConn_p = CanConFactory::create(mType, mPortName); + QVERIFYB(pConn_p); + + QCOMPAREB(pConn_p->getPort(), mPortName); + QCOMPAREB(pConn_p->getNumBuses(), mNbBus); + QCOMPAREB(pConn_p->getType(), mType); + QCOMPAREB(pConn_p->getStatus(), CANCon::NOT_CONNECTED); + + return true; +} + +bool TestCanCon::pConfig(CANConnection* pConn_p) +{ + /*configure buses */ + CANBus bus; + CANBus retBus; + for(int i=0 ; igetNumBuses() ; i++) + { + /* TODO: fix configuration */ + bus.active = true; + pConn_p->setBusSettings(i, bus); + QVERIFYB(pConn_p->getBusSettings(i, retBus)); + QCOMPAREB(bus, retBus); + } + + return true; +} + +bool TestCanCon::pValidateFrame(CANConnection* pConn_p, CANFrame* pCan_p) +{ + QVERIFYB( pCan_p ); + QVERIFYB( (0<=pCan_p->bus) && (pCan_p->bus <= pConn_p->getNumBuses()) ); + QVERIFYB( pCan_p->isReceived); + QVERIFYB( pCan_p->len<=8 ); + QVERIFYB( (0<=pCan_p->ID) && (pCan_p->ID<2048) ); + + return true; +} diff --git a/test/tst_cancon.h b/test/tst_cancon.h new file mode 100644 index 0000000..2d79bd4 --- /dev/null +++ b/test/tst_cancon.h @@ -0,0 +1,33 @@ +#ifndef TESTCANCON_H +#define TESTCANCON_H + +#include +#include "canconconst.h" +#include "canconnection.h" + +class TestCanCon: public QObject +{ + Q_OBJECT +public: + TestCanCon(CANCon::type, QString pPortName, int pNbBus); +private: + CANCon::type mType; + QString mPortName; + int mNbBus; + +private slots: + void create(); + void connectToDevice(); + void recvFrames(); + void suspend(); + void filter(); + void filter_data(); + void write(); + +private: + bool pCreate(CANConnection*& pConn_p); + bool pConfig(CANConnection* pConn_p); + bool pValidateFrame(CANConnection* pConn_p, CANFrame* pCan_p); +}; + +#endif // TESTCANCON_H diff --git a/test/tst_lfqueue.h b/test/tst_lfqueue.h new file mode 100644 index 0000000..19ee4cf --- /dev/null +++ b/test/tst_lfqueue.h @@ -0,0 +1,4 @@ +#ifndef TST_LFQUEUE_H +#define TST_LFQUEUE_H + +#endif // TST_LFQUEUE_H From 10515e4cdf1b91a8130a5d5c927bf2b210a89052 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:25:17 +0200 Subject: [PATCH 43/86] add test header --- test/tst_lfqueue.cpp | 21 ++++----------------- test/tst_lfqueue.h | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/test/tst_lfqueue.cpp b/test/tst_lfqueue.cpp index 1120de5..4343f47 100644 --- a/test/tst_lfqueue.cpp +++ b/test/tst_lfqueue.cpp @@ -1,19 +1,10 @@ -#include +#include + #include -#include "lfqueue.h" +#include "utils/lfqueue.h" +#include "tst_lfqueue.h" -class TestLFQueue: public QObject -{ - Q_OBJECT -private: - -private slots: - void setSize_data(); - void setSize(); - void exchange_data(); - void exchange(); -}; void TestLFQueue::setSize_data() @@ -92,7 +83,3 @@ void TestLFQueue::exchange() thread.waitForFinished(); } - - -QTEST_MAIN(TestLFQueue) -#include "tst_lfqueue.moc" diff --git a/test/tst_lfqueue.h b/test/tst_lfqueue.h index 19ee4cf..315bf75 100644 --- a/test/tst_lfqueue.h +++ b/test/tst_lfqueue.h @@ -1,4 +1,18 @@ #ifndef TST_LFQUEUE_H #define TST_LFQUEUE_H +#include + +class TestLFQueue: public QObject +{ + Q_OBJECT +private: + +private slots: + void setSize_data(); + void setSize(); + void exchange_data(); + void exchange(); +}; + #endif // TST_LFQUEUE_H From d4f0bd4b196b81439dfd372e151cf061c61490a8 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:26:30 +0200 Subject: [PATCH 44/86] add frame write support --- connections/canconconst.h | 7 ----- connections/canconnection.cpp | 53 ++++++++++++++++++----------------- connections/canconnection.h | 35 ++++++++++------------- connections/gvretserial.cpp | 4 +-- connections/gvretserial.h | 3 +- connections/socketcan.cpp | 27 ++++++++++-------- connections/socketcan.h | 3 +- 7 files changed, 62 insertions(+), 70 deletions(-) diff --git a/connections/canconconst.h b/connections/canconconst.h index b31301b..707355d 100644 --- a/connections/canconconst.h +++ b/connections/canconconst.h @@ -19,13 +19,6 @@ namespace CANCon { SOCKETCAN, NONE }; - - /* test */ - enum cbtype - { - READ, - WRITE - }; } #endif // CANCONCONST_H diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index d0d8014..cb88194 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -22,11 +22,8 @@ CANConnection::CANConnection(QString pPort, mIsCapSuspended(false), mStatus(CANCon::NOT_CONNECTED), mStarted(false), - mCallback(NULL), mThread_p(NULL) { - qDebug() << "CANConnection()"; - /* register types */ qRegisterMetaType("CANBus"); qRegisterMetaType("CANFrame"); @@ -53,7 +50,6 @@ CANConnection::CANConnection(QString pPort, CANConnection::~CANConnection() { - qDebug() << "~CANConnection()"; /* stop and delete thread */ if(mThread_p) { mThread_p->quit(); @@ -107,7 +103,7 @@ void CANConnection::suspend(bool pSuspend) void CANConnection::stop() { /* 1) execute in mThread_p context */ - if( mThread_p && (mThread_p != QThread::currentThread()) ) + if( mThread_p && mStarted && (mThread_p != QThread::currentThread()) ) { /* if thread is finished, it means we call this function for the second time so we can leave */ if( !mThread_p->isFinished() ) @@ -161,31 +157,37 @@ void CANConnection::setBusSettings(int pBusIdx, CANBus pBus) } -void CANConnection::sendFrame(const CANFrame& pFrame) +bool CANConnection::sendFrame(const CANFrame& pFrame) { /* make sure we execute in mThread context */ - if( mThread_p && (mThread_p != QThread::currentThread()) ) { + if( mThread_p && (mThread_p != QThread::currentThread()) ) + { + bool ret; QMetaObject::invokeMethod(this, "sendFrame", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), Q_ARG(const CANFrame&, pFrame)); - return; + return ret; } return piSendFrame(pFrame); } -void CANConnection::sendFrameBatch(const QList& pFrames) +bool CANConnection::sendFrames(const QList& pFrames) { /* make sure we execute in mThread context */ - if( mThread_p && (mThread_p != QThread::currentThread()) ) { - QMetaObject::invokeMethod(this, "sendFrameBatch", + if( mThread_p && (mThread_p != QThread::currentThread()) ) + { + bool ret; + QMetaObject::invokeMethod(this, "sendFrames", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), Q_ARG(const QList&, pFrames)); - return; + return ret; } - return piSendFrameBatch(pFrames); + return piSendFrames(pFrames); } @@ -244,14 +246,6 @@ CANCon::status CANConnection::getStatus() { return (CANCon::status) mStatus.load(); } - -bool CANConnection::setCallback(std::function pCallback) { - if(mStarted || !pCallback) return false; - mCallback = pCallback; - return true; -} - - void CANConnection::setStatus(CANCon::status pStatus) { mStatus.store(pStatus); } @@ -264,11 +258,6 @@ void CANConnection::setCapSuspended(bool pIsSuspended) { mIsCapSuspended = pIsSuspended; } -void CANConnection::callback(CANCon::cbtype pCbType) { - if(mCallback) - mCallback(pCbType); -} - bool CANConnection::setFilters(int pBusId, const QVector& pFilters, bool pFilterOut) { /* make sure we execute in mThread context */ @@ -317,6 +306,18 @@ bool CANConnection::discard(int pBusId, quint32 pId, bool& pNotify) } +bool CANConnection::piSendFrames(const QList& pFrames) +{ + foreach(const CANFrame& frame, pFrames) + { + if(!piSendFrame(frame)) + return false; + } + + return true; +} + + /* default implementation of piSetFilters */ void CANConnection::piSetFilters(int pBusId, const QVector& pFilters) { diff --git a/connections/canconnection.h b/connections/canconnection.h index 99cd668..117b0c7 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -14,7 +14,7 @@ class CANConnection : public QObject { Q_OBJECT -public: +protected: /** * @brief CANConnection constructor @@ -29,6 +29,9 @@ public: int pNumBuses, int pQueueLen, bool pUseThread); + +public: + /** * @brief CANConnection destructor */ @@ -65,13 +68,6 @@ public: */ CANCon::status getStatus(); - /** - * @brief set the callback function, this call has to be placed before calling start - * @param pCallback - * @return true if callback can be set - */ - bool setCallback(std::function pCallback); - signals: /*not implemented yet */ @@ -131,23 +127,26 @@ public slots: * @brief suspends/restarts data capture * @param pSuspend: suspends capture if true else restarts it * @note this calls piSuspend (in the working thread context if one has been started) - * @note the caller shall not access the queue when capture is suspended, it is then safe for callee to flush the queue + * @note the caller shall not access the queue when capture is suspended, + * @note the callee is expected to flush the queue */ void suspend(bool pSuspend); /** * @brief provides device with the frame to send * @param pFrame: the frame to send + * @return false if parameter is invalid (bus id for instance) * @note this calls piSendFrame (in the working thread context if one has been started) */ - void sendFrame(const CANFrame& pFrame); + bool sendFrame(const CANFrame& pFrame); /** * @brief provides device with a list of frames to send * @param pFrame: the list of frames to send + * @return false if parameter is invalid (bus id for instance) * @note this calls piSendFrameBatch (in the working thread context if one has been started) */ - void sendFrameBatch(const QList& pFrames); + bool sendFrames(const QList& pFrames); /** * @brief sets a filter list. Filters can be used to send a signal or filter out messages @@ -207,12 +206,6 @@ protected: */ void setCapSuspended(bool pIsSuspended); - /** - * @brief call callback function - * @param pCbType callback type (read or write) - */ - void callback(CANCon::cbtype pCbType); - /** * @brief used to check if a message shall be discarded. The function also update pNotify if a notification is expected for that message * @param pBusId: the bus id on which the frame has been received @@ -264,14 +257,17 @@ protected: /** * @brief provides device with the frame to send * @param pFrame: the frame to send + * @return false if parameter is invalid (bus id for instance) */ - virtual void piSendFrame(const CANFrame&) = 0; + virtual bool piSendFrame(const CANFrame&) = 0; /** * @brief provides device with a list of frames to send * @param pFrame: the list of frames to send + * @return false if parameter is invalid (bus id for instance) + * @note implementing this function is optional */ - virtual void piSendFrameBatch(const QList&) = 0; + virtual bool piSendFrames(const QList&); /** * @brief sets a hardware filter list @@ -289,7 +285,6 @@ private: bool mIsCapSuspended; QAtomicInt mStatus; bool mStarted; - std::function mCallback; BusData* mBusData_p; QThread* mThread_p; }; diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index 1d34f38..d9408b3 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -141,8 +141,8 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) } -void GVRetSerial::piSendFrame(const CANFrame&) {} -void GVRetSerial::piSendFrameBatch(const QList&){} +bool GVRetSerial::piSendFrame(const CANFrame&) {return false;} + /****************************************************************/ diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 4ef824c..4038a01 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -51,8 +51,7 @@ protected: virtual void piSetBusSettings(int pBusIdx, CANBus pBus); virtual bool piGetBusSettings(int pBusIdx, CANBus& pBus); virtual void piSuspend(bool pSuspend); - virtual void piSendFrame(const CANFrame&) ; - virtual void piSendFrameBatch(const QList&); + virtual bool piSendFrame(const CANFrame&) ; void disconnectDevice(); diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 7da09f0..64eaa0f 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -15,14 +15,12 @@ SocketCan::SocketCan(QString portName) : mDev_p(NULL), mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */ { - qDebug() << "SocketCan()"; } SocketCan::~SocketCan() { stop(); - qDebug() << "~SocketCan()"; } @@ -102,8 +100,20 @@ void SocketCan::piSetBusSettings(int pBusIdx, CANBus bus) } -void SocketCan::piSendFrame(const CANFrame&) {} -void SocketCan::piSendFrameBatch(const QList&){} +bool SocketCan::piSendFrame(const CANFrame& pFrame) +{ + /* sanity checks */ + if(0 != pFrame.bus || pFrame.len>8) + return false; + + /* fill frame */ + QCanBusFrame frame; + frame.setFrameId(pFrame.ID); + frame.setExtendedFrameFormat(false); + frame.setPayload(QByteArray((const char*)pFrame.data, pFrame.len)); + + return mDev_p->writeFrame(frame); +} /***********************************/ @@ -143,7 +153,6 @@ void SocketCan::framesWritten(qint64 count) void SocketCan::framesReceived() { /* test */ - bool enqueued = false; bool sndNotif = false; /* sanity checks */ @@ -180,18 +189,14 @@ void SocketCan::framesReceived() /* enqueue frame */ getQueue().queue(); - /* set enqueued */ - enqueued = true; } +#if 0 else qDebug() << "can't get a frame, ERROR"; +#endif } } - if(enqueued) { - callback(CANCon::READ); - } - if(sndNotif) { emit notify(); } diff --git a/connections/socketcan.h b/connections/socketcan.h index 0d0af5b..c303236 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -25,8 +25,7 @@ protected: virtual void piSetBusSettings(int pBusIdx, CANBus pBus); virtual bool piGetBusSettings(int pBusIdx, CANBus& pBus); virtual void piSuspend(bool pSuspend); - virtual void piSendFrame(const CANFrame&) ; - virtual void piSendFrameBatch(const QList&); + virtual bool piSendFrame(const CANFrame&); void disconnectDevice(); From b7daf0f40022b2ba337c8af7411d6e1cabcec40a Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:27:15 +0200 Subject: [PATCH 45/86] add main for tests --- test/main.cpp | 21 +++++++++++++++++++++ test/test.pro | 25 +++++++++++++++++++++---- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/test/main.cpp b/test/main.cpp index e69de29..26abd34 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -0,0 +1,21 @@ +#include + +#include "tst_lfqueue.h" +#include "tst_cancon.h" + + +int main(int argc, char** argv) +{ + QCoreApplication app(argc, argv); + + int status = 0; + auto ASSERT_TEST = [&status, argc, argv](QObject* obj) { + status |= QTest::qExec(obj, argc, argv); + delete obj; + }; + + ASSERT_TEST(new TestLFQueue()); + ASSERT_TEST(new TestCanCon(CANCon::SOCKETCAN, "vcan0", 1)); + + return status; +} diff --git a/test/test.pro b/test/test.pro index 56c22c3..40c53f2 100644 --- a/test/test.pro +++ b/test/test.pro @@ -1,12 +1,19 @@ -QT += widgets testlib -QT -= gui +QT += core gui serialbus widgets testlib serialbus + CONFIG += c++11 -INCLUDEPATH += ../utils +INCLUDEPATH += ../ ../connections SOURCES += \ - tst_lfqueue.cpp + tst_lfqueue.cpp \ + main.cpp \ + tst_cancon.cpp \ + ../connections/canconfactory.cpp \ + ../connections/canconnection.cpp \ + ../connections/gvretserial.cpp \ + ../connections/socketcan.cpp \ + ../canbus.cpp #HEADERS += \ @@ -14,3 +21,13 @@ SOURCES += \ target.path= . INSTALLS += target + +HEADERS += \ + tst_lfqueue.h \ + tst_cancon.h \ + ../connections/canconconst.h \ + ../connections/canconfactory.h \ + ../connections/canconnection.h \ + ../connections/gvretserial.h \ + ../connections/socketcan.h \ + ../canbus.h From d173e26f9aa7a9c475193f73e5bea051625a4af5 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:28:30 +0200 Subject: [PATCH 46/86] == operator is now const --- canbus.cpp | 2 +- canbus.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/canbus.cpp b/canbus.cpp index c01f274..91e83ad 100644 --- a/canbus.cpp +++ b/canbus.cpp @@ -17,7 +17,7 @@ CANBus::CANBus(const CANBus& pBus) : active(pBus.active) {} -bool CANBus::operator==(CANBus& bus) { +bool CANBus::operator==(const CANBus& bus) const{ return speed == bus.speed && listenOnly == bus.listenOnly && singleWire == bus.singleWire && diff --git a/canbus.h b/canbus.h index c8b4e88..8dd8044 100644 --- a/canbus.h +++ b/canbus.h @@ -7,7 +7,7 @@ class CANBus public: CANBus(); CANBus(const CANBus&); - bool operator==(CANBus&); + bool operator==(const CANBus&) const; virtual ~CANBus(){}; /*TODO: remove connection from CANBus and add CANBus as an element of CANConnection */ int speed; bool listenOnly; From d422a5c592590817315656557a8da4676dbe8e31 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:30:22 +0200 Subject: [PATCH 47/86] CANFrame.len is now unsigned int --- can_structs.h | 2 +- canframemodel.cpp | 2 +- filecomparatorwindow.cpp | 6 ++--- framefileio.cpp | 51 +++++++++++++++++++--------------------- scriptcontainer.cpp | 7 +++--- 5 files changed, 32 insertions(+), 36 deletions(-) diff --git a/can_structs.h b/can_structs.h index b45034e..d9fa1c5 100644 --- a/can_structs.h +++ b/can_structs.h @@ -11,7 +11,7 @@ public: int bus; bool extended; bool isReceived; //did we receive this or send it? - int len; + uint32_t len; unsigned char data[8]; uint64_t timestamp; }; diff --git a/canframemodel.cpp b/canframemodel.cpp index 02fc0cf..f1a3b64 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -207,7 +207,7 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const return QString::number(thisFrame.len); break; case 6: //data - for (int i = 0; i < thisFrame.len; i++) + for (unsigned int i = 0; i < thisFrame.len; i++) { tempString.append(Utility::formatNumber(thisFrame.data[i])); tempString.append(" "); diff --git a/filecomparatorwindow.cpp b/filecomparatorwindow.cpp index 83f120e..c7aeea2 100644 --- a/filecomparatorwindow.cpp +++ b/filecomparatorwindow.cpp @@ -112,7 +112,7 @@ void FileComparatorWindow::calculateDetails() CANFrame frame = interestedFrames.at(x); if (interestedIDs.contains(frame.ID)) //if we saw this ID before then add to the QList in there { - for (int y = 0; y < frame.len; y++) + for (unsigned int y = 0; y < frame.len; y++) { interestedIDs[frame.ID].values[y][frame.data[y]]++; tmp = frame.data[y]; @@ -137,7 +137,7 @@ void FileComparatorWindow::calculateDetails() } } //memset(newData->values, 0, 256 * 8); - for (int y = 0; y < frame.len; y++) + for (unsigned int y = 0; y < frame.len; y++) { newData->values[y][frame.data[y]] = 1; tmp = frame.data[y]; @@ -177,7 +177,7 @@ void FileComparatorWindow::calculateDetails() } } //memset(newData->values, 0, 256 * 8); - for (int y = 0; y < frame.len; y++) + for (unsigned int y = 0; y < frame.len; y++) { newData->values[y][frame.data[y]] = 1; tmp = frame.data[y]; diff --git a/framefileio.cpp b/framefileio.cpp index 2e96149..94c612d 100644 --- a/framefileio.cpp +++ b/framefileio.cpp @@ -322,7 +322,7 @@ bool FrameFileIO::loadCRTDFile(QString filename, QVector* frames) else thisFrame.isReceived = true; thisFrame.bus = 0; thisFrame.len = tokens.length() - 3; - for (int d = 0; d < thisFrame.len; d++) + for (unsigned int d = 0; d < thisFrame.len; d++) { if (tokens[d + 3] != "") { @@ -379,7 +379,7 @@ bool FrameFileIO::saveCRTDFile(QString filename, const QVector* frames outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->putChar(' '); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); @@ -446,9 +446,9 @@ bool FrameFileIO::loadNativeCSVFile(QString filename, QVector* frames) { thisFrame.isReceived = true; thisFrame.bus = tokens[3].toInt(); - thisFrame.len = tokens[4].toInt(); + thisFrame.len = tokens[4].toUInt(); for (int c = 0; c < 8; c++) thisFrame.data[c] = 0; - for (int d = 0; d < thisFrame.len; d++) + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[5 + d].toInt(NULL, 16); } else if (fileVersion == 2) @@ -456,10 +456,10 @@ bool FrameFileIO::loadNativeCSVFile(QString filename, QVector* frames) 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 + 6 > tokens.length()) thisFrame.len = tokens.length() - 6; + thisFrame.len = tokens[5].toUInt(); + if (thisFrame.len + 6 > (unsigned int) 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++) + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[6 + d].toInt(NULL, 16); } @@ -570,7 +570,7 @@ bool FrameFileIO::loadGenericCSVFile(QString filename, QVector* frames 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] = dataTok[d].toInt(NULL, 16); + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = dataTok[d].toInt(NULL, 16); frames->append(thisFrame); } @@ -608,7 +608,7 @@ bool FrameFileIO::saveGenericCSVFile(QString filename, const QVector* outFile->write(QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8()); outFile->putChar(44); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); @@ -696,10 +696,9 @@ bool FrameFileIO::loadLogFile(QString filename, QVector* frames) if (tokens[4] == "s") thisFrame.extended = false; else thisFrame.extended = true; thisFrame.bus = tokens[2].toInt() - 1; - thisFrame.len = tokens[5].toInt(); + thisFrame.len = tokens[5].toUInt(); if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len < 0) thisFrame.len = 0; - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[d + 6].toInt(NULL, 16); + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = tokens[d + 6].toInt(NULL, 16); frames->append(thisFrame); } else foundErrors = true; @@ -759,7 +758,7 @@ bool FrameFileIO::saveLogFile(QString filename, const QVector* frames) else outFile->write(" s "); outFile->write(QString::number(frames->at(c).len).toUtf8() + " "); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); @@ -836,7 +835,7 @@ bool FrameFileIO::loadIXXATFile(QString filename, QVector* frames) QStringList dataToks = unQuote(tokens[4]).simplified().split(' '); thisFrame.len = dataToks.length(); - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = dataToks[d].toInt(NULL, 16); + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = dataToks[d].toInt(NULL, 16); frames->append(thisFrame); } else foundErrors = true; @@ -889,7 +888,7 @@ bool FrameFileIO::saveIXXATFile(QString filename, const QVector* frame else outFile->write(",\"Std\""); outFile->write(",\"\",\""); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); @@ -952,7 +951,7 @@ bool FrameFileIO::loadCANDOFile(QString filename, QVector* frames) if (thisFrame.len <= 8 && thisFrame.ID <= 0x7FF) { - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)data[4 + d]; + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)data[4 + d]; frames->append(thisFrame); } else foundErrors = true; @@ -1008,7 +1007,7 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame data[1] = (char)(ms & 0xFF); data[2] = (char)(id & 0xFF); data[3] = (char)((id >> 8) + (thisFrame.len << 4)); - for (int d = 0; d < thisFrame.len; d++) data[4 + d] = (char)thisFrame.data[d]; + for (unsigned int d = 0; d < thisFrame.len; d++) data[4 + d] = (char)thisFrame.data[d]; outFile->write(data); } } @@ -1074,11 +1073,10 @@ bool FrameFileIO::loadMicrochipFile(QString filename, QVector* frames) if (thisFrame.ID <= 0x7FF) thisFrame.extended = false; else thisFrame.extended = true; thisFrame.bus = 0; - thisFrame.len = tokens[3].toInt(); + thisFrame.len = tokens[3].toUInt(); if (thisFrame.len > 8) thisFrame.len = 8; - if (thisFrame.len < 0) thisFrame.len = 0; - if (thisFrame.len + 4 > tokens.length()) thisFrame.len = tokens.length() - 4; - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)Utility::ParseStringToNum(tokens[4 + d]); + 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]); frames->append(thisFrame); } else foundErrors = true; @@ -1140,7 +1138,7 @@ bool FrameFileIO::saveMicrochipFile(QString filename, const QVector* f outFile->write("0x" + QString::number(frames->at(c).ID, 16).toUpper().rightJustified(8, '0').toUtf8() + ";"); outFile->write(QString::number(frames->at(c).len).toUtf8() + ";"); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write("0x" + QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(';'); @@ -1233,12 +1231,11 @@ bool FrameFileIO::loadTraceFile(QString filename, QVector* frames) if (thisFrame.ID <= 0x7FF) thisFrame.extended = false; else thisFrame.extended = true; thisFrame.bus = 0; - thisFrame.len = tokens[3].toInt(); - if (thisFrame.len < 0) thisFrame.len = 0; + thisFrame.len = tokens[3].toUInt(); if (thisFrame.len > 8) thisFrame.len = 8; QList dataToks = tokens[4].split(' '); - if (thisFrame.len > dataToks.length()) thisFrame.len = dataToks.length(); - for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)dataToks[d].toInt(NULL, 16); + if (thisFrame.len > (unsigned int) dataToks.length()) thisFrame.len = (unsigned int) dataToks.length(); + for (unsigned int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (unsigned char)dataToks[d].toInt(NULL, 16); frames->append(thisFrame); } else foundErrors = true; @@ -1325,7 +1322,7 @@ bool FrameFileIO::saveTraceFile(QString filename, const QVector * fram outFile->write(QString::number(frames->at(c).len).toUtf8() + "\t"); - for (int temp = 0; temp < frames->at(c).len; temp++) + for (unsigned int temp = 0; temp < frames->at(c).len; temp++) { outFile->write(QString::number(frames->at(c).data[temp], 16).toUpper().rightJustified(2, '0').toUtf8()); outFile->putChar(' '); diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 9e14e2d..84b7280 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -93,13 +93,12 @@ void ScriptContainer::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSV CANFrame frame; frame.extended = false; frame.ID = id.toInt(); - frame.len = length.toInt(); - if (frame.len < 0) frame.len = 0; + frame.len = length.toUInt(); if (frame.len > 8) frame.len = 8; if (!data.isArray()) qDebug() << "data isn't an array"; - for (int i = 0; i < frame.len; i++) + for (unsigned int i = 0; i < frame.len; i++) { frame.data[i] = (uint8_t)data.property(i).toInt(); } @@ -125,7 +124,7 @@ void ScriptContainer::gotFrame(const CANFrame &frame) QJSValueList args; args << frame.bus << frame.ID << frame.len; QJSValue dataBytes = scriptEngine.newArray(frame.len); - for (int j = 0; j < frame.len; j++) dataBytes.setProperty(j, QJSValue(frame.data[j])); + for (unsigned int j = 0; j < frame.len; j++) dataBytes.setProperty(j, QJSValue(frame.data[j])); args.append(dataBytes); gotFrameFunction.call(args); return; //as soon as one filter matches we jump out From 7ed160f527e91e1c283a21129c50906abd02227b Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:31:20 +0200 Subject: [PATCH 48/86] removed callback support --- connectionwindow.cpp | 18 ------------------ connectionwindow.h | 8 -------- 2 files changed, 26 deletions(-) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 69b42c6..9ef7f3b 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -80,11 +80,6 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : mTicker.setInterval(500); /*tick twice a second */ mTicker.setSingleShot(false); mTicker.start(); - - /*test*/ - /* retrieve pointer on method */ - int methodIndex = metaObject()->indexOfMethod(QMetaObject::normalizedSignature("refreshCanList()")); - mRefreshM = metaObject()->method(methodIndex); } ConnectionWindow::~ConnectionWindow() @@ -130,19 +125,6 @@ void ConnectionWindow::refreshCanList() { mRefreshReqOngoing.store(FALSE); } -/*test*/ -void ConnectionWindow::callback(CANCon::cbtype pType) -{ - if(mRefreshReqOngoing.testAndSetRelaxed(FALSE, TRUE)) - { - /* ask for a refresh */ - mRefreshM.invoke(this, Qt::AutoConnection); - } - else { - //qDebug() << "skip event"; - } -} - void ConnectionWindow::handleNewConn() { ui->tableConnections->selectionModel()->clearSelection(); diff --git a/connectionwindow.h b/connectionwindow.h index 91f292d..5cc9b4c 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -8,9 +8,6 @@ #include #include #include -/*test*/ -#include -/******/ #include "canconnectionmodel.h" #include "canframemodel.h" @@ -34,7 +31,6 @@ public: QString getPortName(); //name of port to connect to CANCon::type getConnectionType(); bool getSWMode(); - void callback(CANCon::cbtype pType); signals: void updateBusSettings(CANBus *bus); @@ -72,10 +68,6 @@ private: QAtomicInt mRefreshReqOngoing; - /*test*/ - QMetaMethod mRefreshM; - - void selectSerial(); void selectKvaser(); void selectSocketCan(); From 830ca75fba548e9978d983bbabdb72a62517baae Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 24 Jun 2016 17:32:05 +0200 Subject: [PATCH 49/86] warning fix --- mainwindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index 01fd54c..f19f682 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -679,7 +679,7 @@ Data Bytes: 88 10 00 13 BB 00 06 00 outFile->write(builderString.toUtf8()); builderString = tr("Data Bytes: "); - for (int temp = 0; temp < thisFrame.len; temp++) + for (unsigned int temp = 0; temp < thisFrame.len; temp++) { builderString += Utility::formatNumber(thisFrame.data[temp]) + " "; } From db7ad421990a8e236f2cdbb3d2fe2a93808edbfc Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 11:54:36 +0200 Subject: [PATCH 50/86] add << and >> for serialization --- canbus.cpp | 51 ++++++++++++++++++++--------------- canbus.h | 10 +++++-- connections/canconmanager.cpp | 6 +++++ connections/canconmanager.h | 11 ++++++++ 4 files changed, 55 insertions(+), 23 deletions(-) create mode 100644 connections/canconmanager.cpp create mode 100644 connections/canconmanager.h diff --git a/canbus.cpp b/canbus.cpp index 91e83ad..d0f4646 100644 --- a/canbus.cpp +++ b/canbus.cpp @@ -3,10 +3,10 @@ CANBus::CANBus() { - speed = 250000; - listenOnly = false; - singleWire = false; - active = false; + speed = 250000; + listenOnly = false; + singleWire = false; + active = false; } @@ -24,44 +24,53 @@ bool CANBus::operator==(const CANBus& bus) const{ active == bus.active; } - -void CANBus::setSpeed(int newSpeed) -{ +void CANBus::setSpeed(int newSpeed){ speed = newSpeed; } -void CANBus::setListenOnly(bool mode) -{ +void CANBus::setListenOnly(bool mode){ listenOnly = mode; } -void CANBus::setSingleWire(bool mode) -{ +void CANBus::setSingleWire(bool mode){ singleWire = mode; } -void CANBus::setEnabled(bool mode) -{ +void CANBus::setEnabled(bool mode){ active = mode; } -int CANBus::getSpeed() -{ +int CANBus::getSpeed(){ return speed; } -bool CANBus::isListenOnly() -{ +bool CANBus::isListenOnly(){ return listenOnly; } -bool CANBus::isSingleWire() -{ +bool CANBus::isSingleWire(){ return singleWire; } -bool CANBus::isActive() -{ +bool CANBus::isActive(){ return active; } + +QDataStream& operator<<( QDataStream & pStream, const CANBus& pCanBus ) +{ + pStream << pCanBus.speed; + pStream << pCanBus.listenOnly; + pStream << pCanBus.singleWire; + pStream << pCanBus.active; + return pStream; +} + +QDataStream & operator>>(QDataStream & pStream, CANBus& pCanBus) +{ + pStream >> pCanBus.speed; + pStream >> pCanBus.listenOnly; + pStream >> pCanBus.singleWire; + pStream >> pCanBus.active; + return pStream; +} diff --git a/canbus.h b/canbus.h index 8dd8044..9b39358 100644 --- a/canbus.h +++ b/canbus.h @@ -1,6 +1,6 @@ #ifndef CANBus_H #define CANBus_H - +#include class CANBus { @@ -8,7 +8,8 @@ public: CANBus(); CANBus(const CANBus&); bool operator==(const CANBus&) const; - virtual ~CANBus(){}; /*TODO: remove connection from CANBus and add CANBus as an element of CANConnection */ + virtual ~CANBus(){}; + int speed; bool listenOnly; bool singleWire; @@ -25,4 +26,9 @@ public: bool isActive(); }; +QDataStream& operator<<( QDataStream & pStream, const CANBus& pCanBus ); +QDataStream & operator>>(QDataStream & pStream, CANBus& pCanBus); + +Q_DECLARE_METATYPE(CANBus); + #endif // CANBus_H diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp new file mode 100644 index 0000000..c363d2a --- /dev/null +++ b/connections/canconmanager.cpp @@ -0,0 +1,6 @@ +#include "canconmanager.h" + +CANConManager::CANConManager() +{ + +} diff --git a/connections/canconmanager.h b/connections/canconmanager.h new file mode 100644 index 0000000..fd17d6e --- /dev/null +++ b/connections/canconmanager.h @@ -0,0 +1,11 @@ +#ifndef CANCONMANAGER_H +#define CANCONMANAGER_H + + +class CANConManager +{ +public: + CANConManager(); +}; + +#endif // CANCONMANAGER_H \ No newline at end of file From e402ea76fa427897fd346a0a04d7e5c646bbfa98 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 11:55:58 +0200 Subject: [PATCH 51/86] add CANConManager --- connections/canconmanager.cpp | 92 ++++++++++++++++++++++++++++++++++- connections/canconmanager.h | 34 +++++++++++-- connections/canconnection.cpp | 2 +- connections/canconnection.h | 2 +- connections/socketcan.cpp | 2 +- 5 files changed, 124 insertions(+), 8 deletions(-) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index c363d2a..b0b5a37 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -1,6 +1,94 @@ #include "canconmanager.h" -CANConManager::CANConManager() -{ +CANConManager* CANConManager::mInstance = NULL; + +CANConManager* CANConManager::getInstance() +{ + if(!mInstance) + mInstance = new CANConManager(); + + return mInstance; +} + + +CANConManager::CANConManager(QObject *parent): QObject(parent) +{ + connect(&mTimer, SIGNAL(timeout()), this, SLOT(refreshCanList())); + mTimer.setInterval(500); /*tick twice a second */ + mTimer.setSingleShot(false); + mTimer.start(); +} + + +CANConManager::~CANConManager() +{ + mTimer.stop(); + mInstance = NULL; +} + + +void CANConManager::add(CANConnection* pConn_p) +{ + connect(pConn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); + mConns.append(pConn_p); +} + + +void CANConManager::remove(CANConnection* pConn_p) +{ + disconnect(pConn_p, 0, this, 0); + mConns.removeOne(pConn_p); +} + + +void CANConManager::refreshCanList() +{ + QObject* sender_p = QObject::sender(); + + if( sender_p != &mTimer) + { + /* if we are not the sender, the signal is coming from a connection */ + /* refresh only the given connection */ + if(mConns.contains((CANConnection*) sender_p)) + refreshConnection((CANConnection*)sender_p); + } + else + { + foreach (CANConnection* conn_p, mConns) + refreshConnection((CANConnection*)conn_p); + } +} + + +QList& CANConManager::getConnections() +{ + return mConns; +} + + +CANConnection* CANConManager::getByName(const QString& pName) const +{ + foreach(CANConnection* conn_p, mConns) + { + if(conn_p->getPort() == pName) + return conn_p; + } + + return NULL; +} + + +void CANConManager::refreshConnection(CANConnection* pConn_p) +{ + CANFrame* frame_p = NULL; + QVector frames; + + while( (frame_p = pConn_p->getQueue().peek() ) ) { + frames.append(*frame_p); + pConn_p->getQueue().dequeue(); + } + + if(frames.size()) + emit framesReceived(pConn_p, frames); } diff --git a/connections/canconmanager.h b/connections/canconmanager.h index fd17d6e..66896f1 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -1,11 +1,39 @@ #ifndef CANCONMANAGER_H #define CANCONMANAGER_H +#include +#include -class CANConManager +#include "canconnection.h" + +class CANConManager : public QObject { + Q_OBJECT + public: - CANConManager(); + static CANConManager* getInstance(); + virtual ~CANConManager(); + + void add(CANConnection* pConn_p); + void remove(CANConnection* pConn_p); + QList& getConnections(); + + CANConnection* getByName(const QString& pName) const; + +signals: + void framesReceived(CANConnection* pConn_p, QVector& pFrames); + +private slots: + void refreshCanList(); + +private: + explicit CANConManager(QObject *parent = 0); + void refreshConnection(CANConnection* pConn_p); + + static CANConManager* mInstance; + QList mConns; + QTimer mTimer; }; -#endif // CANCONMANAGER_H \ No newline at end of file +#endif // CANCONNECTIONMODEL_H + diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index cb88194..778890f 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -191,7 +191,7 @@ bool CANConnection::sendFrames(const QList& pFrames) } -int CANConnection::getNumBuses() { +int CANConnection::getNumBuses() const{ return mNumBuses; } diff --git a/connections/canconnection.h b/connections/canconnection.h index 117b0c7..b0c8f51 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -42,7 +42,7 @@ public: * @brief getNumBuses * @return returns the number of buses of the device */ - int getNumBuses(); + int getNumBuses() const; /** * @brief getPort diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 64eaa0f..b49e1fe 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -147,7 +147,7 @@ void SocketCan::errorReceived(QCanBusDevice::CanBusError error) const void SocketCan::framesWritten(qint64 count) { - qDebug() << "Number of frames written:" << count; + //qDebug() << "Number of frames written:" << count; } void SocketCan::framesReceived() From 9addf436517c43473714f7027ba27d541ae92eb4 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 11:57:05 +0200 Subject: [PATCH 52/86] attempt to use new canconnection abstraction --- scriptcontainer.cpp | 45 ++++++++++++++++++++++++++++++++++--------- scriptcontainer.h | 3 ++- scriptingwindow.cpp | 47 ++++++++++++++++++++++++++------------------- scriptingwindow.h | 8 ++------ 4 files changed, 67 insertions(+), 36 deletions(-) diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 84b7280..5c4bfa4 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -1,14 +1,12 @@ -#include "scriptcontainer.h" - #include #include -ScriptContainer::ScriptContainer() -{ - fileName = QString(); - filePath = QString(); - scriptText = QString(); +#include "scriptcontainer.h" +#include "connections/canconmanager.h" +ScriptContainer::ScriptContainer(QString& pConName): + mConName(pConName) +{ connect(&timer, SIGNAL(timeout()), this, SLOT(tick())); } @@ -68,6 +66,25 @@ void ScriptContainer::setFilter(QJSValue id, QJSValue mask, QJSValue bus) CANFilter filter; filter.setFilter(idVal, maskVal, busVal); filters.append(filter); + + qDebug() << "FIXME setFilter"; + CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); + if(conn_p) + { + for(int i=0 ; igetNumBuses() ; i++) + { + QVector fltrs; + foreach(const CANFilter& flt, filters) + { + if(flt.bus==i) { + fltrs.append({flt.ID, flt.mask, true}); + } + } + + if(fltrs.size()) + conn_p->setFilters(i, fltrs, false); + } + } } void ScriptContainer::setTickInterval(QJSValue interval) @@ -86,6 +103,14 @@ void ScriptContainer::clearFilters() { qDebug() << "Called clear filters"; filters.clear(); + + qDebug() << "FIXME clearFilters"; + CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); + if(conn_p) + { + for(int i=0 ; igetNumBuses() ; i++) + conn_p->setFilters(i, QVector(), false); + } } void ScriptContainer::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSValue data) @@ -109,8 +134,10 @@ void ScriptContainer::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSV if (frame.ID > 0x7FF) frame.extended = true; - //qDebug() << "Sending frame from script"; - emit sendCANFrame(&frame); + qDebug() << "sending frame from script"; + CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); + if(conn_p) + conn_p->sendFrame(frame); } void ScriptContainer::gotFrame(const CANFrame &frame) diff --git a/scriptcontainer.h b/scriptcontainer.h index fd4b33d..75caec2 100644 --- a/scriptcontainer.h +++ b/scriptcontainer.h @@ -13,12 +13,13 @@ class ScriptContainer : public QObject Q_OBJECT public: - ScriptContainer(); + ScriptContainer(QString&); void gotFrame(const CANFrame &frame); QString fileName; QString filePath; QString scriptText; + QString mConName; public slots: void compileScript(); diff --git a/scriptingwindow.cpp b/scriptingwindow.cpp index 19ab11d..58115dd 100644 --- a/scriptingwindow.cpp +++ b/scriptingwindow.cpp @@ -3,9 +3,10 @@ #include #include +#include #include -#include "mainwindow.h" +#include "connections/canconmanager.h" ScriptingWindow::ScriptingWindow(const QVector *frames, QWidget *parent) : QDialog(parent), @@ -23,7 +24,8 @@ ScriptingWindow::ScriptingWindow(const QVector *frames, QWidget *paren connect(ui->btnRemoveScript, &QAbstractButton::pressed, this, &ScriptingWindow::deleteCurrentScript); connect(ui->btnRevertScript, &QAbstractButton::pressed, this, &ScriptingWindow::revertScript); connect(ui->btnSaveScript, &QAbstractButton::pressed, this, &ScriptingWindow::saveScript); - connect(MainWindow::getReference(), &MainWindow::framesUpdated, this, &ScriptingWindow::updatedFrames); + + connect(CANConManager::getInstance(), &CANConManager::framesReceived, this, &ScriptingWindow::newFrames); ui->txtScriptSource->setLexer(new QsciLexerJavaScript(ui->txtScriptSource)); } @@ -33,27 +35,22 @@ ScriptingWindow::~ScriptingWindow() delete ui; } -void ScriptingWindow::updatedFrames(int numFrames) + +void ScriptingWindow::newFrames(const CANConnection* pConn, const QVector& pFrames) { - CANFrame thisFrame; - //-1 means all frames deleted and -2 means a full refresh, neither of which we care about here. - if (numFrames > 0) + /*FIXME: name of the probe and bus should be checked */ + Q_UNUSED(pConn); + + for (int j = 0; j < scripts.length(); j++) { - if (numFrames > modelFrames->count()) return; - qDebug() << "Got frames into script window: " << numFrames; - //for every new frame pass it on to each script container. The container will determine if it needs to actually - //notify the script and do that if applicable. - for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++) + foreach(const CANFrame& frame, pFrames) { - thisFrame = modelFrames->at(i); - for (int j = 0; j < scripts.length(); j++) - { - scripts[j]->gotFrame(thisFrame); - } + scripts[j]->gotFrame(frame); } } } + void ScriptingWindow::closeEvent(QCloseEvent *event) { Q_UNUSED(event); @@ -115,13 +112,19 @@ void ScriptingWindow::loadNewScript() QStringList fileList = filename.split('/'); QString justFileName = fileList[fileList.length() - 1]; ui->listLoadedScripts->addItem(justFileName); - container = new ScriptContainer(); + /* get the first connection in the list for now */ + qDebug() << "FIXME: connection is always the first in list"; + QString portName; + QList list = CANConManager::getInstance()->getConnections(); + if(!list.isEmpty()) + portName = list.first()->getPort(); + + container = new ScriptContainer(portName); container->fileName = justFileName; container->filePath = filename; container->scriptText = contents; container->setErrorWidget(ui->listErrors); container->compileScript(); - connect(container, &ScriptContainer::sendCANFrame, this, &ScriptingWindow::sendCANFrame); scripts.append(container); currentScript = container; ui->txtScriptSource->setText(container->scriptText); @@ -135,13 +138,17 @@ void ScriptingWindow::createNewScript() { ScriptContainer *container; - container = new ScriptContainer(); + QString portName; + QList list = CANConManager::getInstance()->getConnections(); + if(!list.isEmpty()) + portName = list.first()->getPort(); + + container = new ScriptContainer(portName); container->fileName = "UNNAMED_" + QString::number((qrand() % 10000)) + ".js"; container->filePath = QString(); container->scriptText = QString(); container->setErrorWidget(ui->listErrors); - connect(container, &ScriptContainer::sendCANFrame, this, &ScriptingWindow::sendCANFrame); scripts.append(container); ui->listLoadedScripts->addItem(container->fileName); currentScript = container; diff --git a/scriptingwindow.h b/scriptingwindow.h index 179e672..6713460 100644 --- a/scriptingwindow.h +++ b/scriptingwindow.h @@ -3,6 +3,7 @@ #include "can_structs.h" #include "scriptcontainer.h" +#include "connections/canconnection.h" #include #include @@ -28,12 +29,7 @@ private slots: void saveScript(); void revertScript(); void recompileScript(); - void updatedFrames(int); - -public slots: - -signals: - void sendCANFrame(const CANFrame *); + void newFrames(const CANConnection*, const QVector&); private: void closeEvent(QCloseEvent *event); From 916ed4e6577ea9c325591ac80720e799c944eb8f Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 11:57:52 +0200 Subject: [PATCH 53/86] canframemodel now receives frames from CANConManager --- canframemodel.cpp | 45 +++++++++++++++++++-------------------------- canframemodel.h | 6 ++++-- 2 files changed, 23 insertions(+), 28 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index f1a3b64..e1cb200 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -282,7 +282,7 @@ QVariant CANFrameModel::headerData(int section, Qt::Orientation orientation, } -void CANFrameModel::addFrame(CANFrame& frame, bool autoRefresh = false) +void CANFrameModel::addFrame(const CANFrame& frame, bool autoRefresh = false) { /*TODO: remove mutex */ mutex.lock(); @@ -346,6 +346,15 @@ void CANFrameModel::addFrame(CANFrame& frame, bool autoRefresh = false) mutex.unlock(); } + +void CANFrameModel::addFrames(const CANConnection*, const QVector& pFrames) +{ + foreach(const CANFrame& frame, pFrames) + { + addFrame(frame); + } +} + void CANFrameModel::sendRefresh() { qDebug() << "Sending mass refresh"; @@ -377,38 +386,22 @@ void CANFrameModel::sendRefresh(int pos) //issue a refresh for the last num entries in the model. //used by the serial worker to do batch updates so it doesn't //have to send thousands of messages per second -void CANFrameModel::sendBulkRefresh(int num) +int CANFrameModel::sendBulkRefresh() { - //yes, num was sent to us by the serial worker but we actually have a better idea - //of how many by tracking the number we last knew about as opposed to how many rows there - //are now. - num = filteredFrames.count() - lastUpdateNumFrames; + int num = filteredFrames.count() - lastUpdateNumFrames; + if (num <= 0) return 0; - if (num < 0) return; - - //qDebug() << "Num: " << num; - - if (num == 0 && !overwriteDups) return; - if (filteredFrames.count() == 0) return; + if (num == 0 && !overwriteDups) return 0; + if (filteredFrames.count() == 0) return 0; lastUpdateNumFrames += num; //done this way to avoid asking for filteredFrames.count() again qDebug() << "Bulk refresh of " << num; - if (!overwriteDups) - { - //if (num > filteredFrames.count()) num = filteredFrames.count(); - //qDebug() << "From " << (filteredFrames.count() - num) << " to " << (filteredFrames.count() - 1); - //beginInsertRows(QModelIndex(), filteredFrames.count() - num, filteredFrames.count() - 1); - //endInsertRows(); - beginResetModel(); - endResetModel(); - } - else - { - beginResetModel(); - endResetModel(); - } + beginResetModel(); + endResetModel(); + + return num; } void CANFrameModel::clearFrames() diff --git a/canframemodel.h b/canframemodel.h index ddea3ce..57e6e6a 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -8,6 +8,7 @@ #include #include "can_structs.h" #include "dbchandler.h" +#include "connections/canconnection.h" class CANFrameModel: public QAbstractTableModel { @@ -25,7 +26,7 @@ public: void sendRefresh(); void sendRefresh(int); - void sendBulkRefresh(int); + int sendBulkRefresh(); void clearFrames(); void setDBCHandler(DBCHandler *); void setInterpetMode(bool); @@ -46,7 +47,8 @@ public: const QMap *getFiltersReference() const; //this neither public slots: - void addFrame(CANFrame&, bool); + void addFrame(const CANFrame&, bool); + void addFrames(const CANConnection*, const QVector&); signals: void updatedFiltersList(); From a9fa6dcd907c55d13ea645b749c9af9264dcd460 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 12:00:05 +0200 Subject: [PATCH 54/86] fix several UI weirdness --- canconnectionmodel.cpp | 69 +++++--- canconnectionmodel.h | 12 +- connectionwindow.cpp | 384 ++++++++++++++++++----------------------- connectionwindow.h | 28 ++- 4 files changed, 234 insertions(+), 259 deletions(-) diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 3f96f94..404b3cd 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -1,11 +1,16 @@ -#include "connections/canconnection.h" #include "canconnectionmodel.h" +#include "connections/canconnection.h" +#include "connections/canconmanager.h" CANConnectionModel::CANConnectionModel(QObject *parent) : QAbstractTableModel(parent) { } +CANConnectionModel::~CANConnectionModel() +{ +} + QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation, int role) const { @@ -52,17 +57,20 @@ QVariant CANConnectionModel::headerData(int section, Qt::Orientation orientation int CANConnectionModel::columnCount(const QModelIndex &parent) const { + Q_UNUSED(parent); return 7; } -int CANConnectionModel::rowCount(const QModelIndex &parent) const { - int rows=0; - QList::const_iterator iter; +int CANConnectionModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); - for (iter = mConns.begin() ; iter != mConns.end() ; ++iter) { - rows+=(*iter)->getNumBuses(); - } + int rows=0; + QList& conns = CANConManager::getInstance()->getConnections(); + + foreach(const CANConnection* conn_p, conns) + rows+=conn_p->getNumBuses(); return rows; } @@ -124,49 +132,64 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const void CANConnectionModel::add(CANConnection* pConn_p) { + CANConManager* manager = CANConManager::getInstance(); + + connect(pConn_p, SIGNAL(notify()), manager, SLOT(refreshCanList())); + beginResetModel(); - mConns.append(pConn_p); + manager->getConnections().append(pConn_p); endResetModel(); } void CANConnectionModel::remove(CANConnection* pConn_p) { + CANConManager* manager = CANConManager::getInstance(); + + disconnect(pConn_p, 0, manager, 0); + beginResetModel(); - mConns.removeOne(pConn_p); + manager->getConnections().removeOne(pConn_p); endResetModel(); } -QList& CANConnectionModel::getConnections() -{ - return mConns; -} - - CANConnection* CANConnectionModel::getAtIdx(int pIdx, int& pBusId) const { if (pIdx < 0) return NULL; int i=0; - QList::const_iterator iter = mConns.begin(); + QList& conns = CANConManager::getInstance()->getConnections(); - for (iter = mConns.begin() ; iter != mConns.end() ; ++iter) { - if( i <= pIdx && pIdx < i+(*iter)->getNumBuses() ) { + foreach(CANConnection* conn_p, conns) + { + if( i <= pIdx && pIdx < i+conn_p->getNumBuses() ) { pBusId = pIdx - i; - return (*iter); + return conn_p; } - i+= (*iter)->getNumBuses(); + i+= conn_p->getNumBuses(); } return NULL; } -void CANConnectionModel::refreshView() +void CANConnectionModel::refresh(int pIndex) { - beginResetModel(); - endResetModel(); + QModelIndex begin; + QModelIndex end; + + if(pIndex>=0) { + begin = createIndex(pIndex, 0); + end = begin; + } + else { + begin = createIndex(0, 0); + begin = createIndex(rowCount()-1, 0); + /*beginResetModel(); + endResetModel();*/ + } + dataChanged(begin, end); } diff --git a/canconnectionmodel.h b/canconnectionmodel.h index c91c9e2..68a8d45 100644 --- a/canconnectionmodel.h +++ b/canconnectionmodel.h @@ -15,25 +15,19 @@ class CANConnectionModel : public QAbstractTableModel public: explicit CANConnectionModel(QObject *parent = 0); + virtual ~CANConnectionModel(); - // Header: + // from abstractmodel: QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; void add(CANConnection* pConn_p); void remove(CANConnection* pConn_p); - QList& getConnections(); CANConnection* getAtIdx(int, int&) const; - void refreshView(); - -private: - QList mConns; + void refresh(int pIndex=-1); }; #endif // CANCONNECTIONMODEL_H diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 9ef7f3b..6b1fc77 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -4,29 +4,31 @@ #include "connectionwindow.h" #include "ui_connectionwindow.h" #include "connections/canconfactory.h" - -#define FALSE 0 -#define TRUE 1 +#include "connections/canconmanager.h" +#include "canbus.h" -ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : + +ConnectionWindow::ConnectionWindow(QWidget *parent) : QDialog(parent), - ui(new Ui::ConnectionWindow), - mRefreshReqOngoing(FALSE) + ui(new Ui::ConnectionWindow) { ui->setupUi(this); - settings = new QSettings(); + QSettings settings; qRegisterMetaType("CANBus"); qRegisterMetaType("const CANFrame *"); qRegisterMetaType *>("const QList *"); - connModel = new CANConnectionModel(); + qRegisterMetaTypeStreamOperators>(); + qRegisterMetaTypeStreamOperators>(); + qRegisterMetaTypeStreamOperators(); + qRegisterMetaTypeStreamOperators>(); + + + connModel = new CANConnectionModel(this); ui->tableConnections->setModel(connModel); - - canModel = cModel; - ui->tableConnections->setColumnWidth(0, 50); ui->tableConnections->setColumnWidth(1, 110); ui->tableConnections->setColumnWidth(2, 110); @@ -36,13 +38,8 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : ui->tableConnections->setColumnWidth(6, 75); ui->tableConnections->setColumnWidth(7, 75); - int temp = settings->value("Main/DefaultConnectionType", 0).toInt(); - - //currentPortName = settings->value("Main/DefaultConnectionPort", "").toString(); - - //currentSpeed1 = -1; - - ui->ckSingleWire->setChecked(settings->value("Main/SingleWireMode", false).toBool()); + //int temp = settings.value("Main/DefaultConnectionType", 0).toInt(); + ui->ckSingleWire->setChecked(settings.value("Main/SingleWireMode", false).toBool()); ui->cbSpeed->addItem(tr("")); ui->cbSpeed->addItem(tr("125000")); @@ -51,6 +48,9 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : ui->cbSpeed->addItem(tr("1000000")); ui->cbSpeed->addItem(tr("33333")); + /* load connection configuration */ + loadConnections(); + #ifdef Q_OS_LINUX ui->rbSocketCAN->setEnabled(isSocketCanAvailable()); #endif @@ -60,105 +60,81 @@ ConnectionWindow::ConnectionWindow(CANFrameModel *cModel, QWidget *parent) : #endif connect(ui->btnOK, &QAbstractButton::clicked, this, &ConnectionWindow::handleOKButton); - connect(ui->rbGVRET, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); - connect(ui->rbKvaser, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); - connect(ui->rbSocketCAN, &QAbstractButton::toggled, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->rbGVRET, &QAbstractButton::clicked, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->rbKvaser, &QAbstractButton::clicked, this, &ConnectionWindow::handleConnTypeChanged); + connect(ui->rbSocketCAN, &QAbstractButton::clicked, this, &ConnectionWindow::handleConnTypeChanged); connect(ui->btnRevert, &QPushButton::clicked, this, &ConnectionWindow::handleRevert); - connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ConnectionWindow::handleConnSelectionChanged); - connect(connModel, &QAbstractItemModel::modelReset, this, &ConnectionWindow::handleConnSelectionChanged); + connect(ui->tableConnections->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &ConnectionWindow::currentRowChanged); connect(ui->btnNewConn, &QPushButton::clicked, this, &ConnectionWindow::handleNewConn); connect(ui->btnActivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleEnableAll); connect(ui->btnDeactivateAll, &QPushButton::clicked, this, &ConnectionWindow::handleDisableAll); connect(ui->btnRemoveBus, &QPushButton::clicked, this, &ConnectionWindow::handleRemoveConn); - - - qDebug() << "Serial worker thread starting"; - - connect(&mTicker, SIGNAL(timeout()), this, SLOT(refreshCanList())); - /* tick frequency has a huge impact on performances */ - /* TODO: make this configurable and part of the connection constructor to let connection configure the length of the queue */ - mTicker.setInterval(500); /*tick twice a second */ - mTicker.setSingleShot(false); - mTicker.start(); } ConnectionWindow::~ConnectionWindow() { - QList& conns = connModel->getConnections(); + QList& conns = CANConManager::getInstance()->getConnections(); CANConnection* conn_p; + /* save configuration */ + saveConnections(); + /* delete connections */ - while(!conns.isEmpty()) { + while(!conns.isEmpty()) + { conn_p = conns.takeFirst(); conn_p->stop(); delete conn_p; } - delete connModel; - - mTicker.stop(); - delete settings; delete ui; } + void ConnectionWindow::showEvent(QShowEvent* event) { QDialog::showEvent(event); qDebug() << "Show connectionwindow"; - handleConnTypeChanged(); + ui->tableConnections->selectRow(0); } -void ConnectionWindow::refreshCanList() { - - QList& conns = connModel->getConnections(); - CANFrame* frame_p = NULL; - - foreach (CANConnection* conn_p, conns) - { - while( (frame_p = conn_p->getQueue().peek() ) ) { - canModel->addFrame(*frame_p, true); - conn_p->getQueue().dequeue(); - } - } - - /* erase flag (this should be done before we start dequeuing...) */ - mRefreshReqOngoing.store(FALSE); -} - -void ConnectionWindow::handleNewConn() -{ - ui->tableConnections->selectionModel()->clearSelection(); - ui->tableConnections->selectionModel()->clearCurrentIndex(); - handleConnSelectionChanged(); -} void ConnectionWindow::setSuspendAll(bool pSuspend) { - qDebug() << "setSuspendAll"; + QList& conns = CANConManager::getInstance()->getConnections(); - QList::iterator iter; - QList& conns = connModel->getConnections(); + foreach(CANConnection* conn_p, conns) + conn_p->suspend(pSuspend); - for (iter = conns.begin(); iter != conns.end(); ++iter) - (*iter)->suspend(pSuspend); + connModel->refresh(); } + void ConnectionWindow::setActiveAll(bool pActive) { - QList::iterator iter; - QList& conns = connModel->getConnections(); CANBus bus; + QList& conns = CANConManager::getInstance()->getConnections(); - for (iter = conns.begin(); iter != conns.end(); ++iter) { - for(int i=0 ; i<(*iter)->getNumBuses() ; i++) { - if( (*iter)->getBusSettings(i, bus) ) { + foreach(CANConnection* conn_p, conns) + { + for(int i=0 ; igetNumBuses() ; i++) { + if( conn_p->getBusSettings(i, bus) ) { bus.active = pActive; - (*iter)->setBusSettings(i, bus); + conn_p->setBusSettings(i, bus); } } } + + connModel->refresh(); } + +void ConnectionWindow::handleNewConn() +{ + ui->tableConnections->setCurrentIndex(QModelIndex()); +} + + void ConnectionWindow::handleEnableAll() { setActiveAll(true); @@ -180,8 +156,10 @@ void ConnectionWindow::handleConnTypeChanged() /* status */ void ConnectionWindow::connectionStatus(CANCon::status pStatus) { + Q_UNUSED(pStatus); + qDebug() << "Connectionstatus changed"; - connModel->refreshView(); + connModel->refresh(); } @@ -219,78 +197,15 @@ void ConnectionWindow::handleOKButton() /* update bus settings */ conn_p->setBusSettings(busId, bus); - connModel->refreshView(); + connModel->refresh(whichRow); } - else //new connection + else if( ! CANConManager::getInstance()->getByName(getPortName()) ) { -#if 0 - if (ui->rbGVRET->isChecked()) - { - - SerialWorker *serial = new SerialWorker(canModel, connModel->rowCount()); - connect(serial, SIGNAL(busStatus(int,int,int)), this, SLOT(receiveBusStatus(int,int,int))); - connect(serial, SIGNAL(connectionSuccess(CANConnection*)), this, SLOT(connectionSuccess(CANConnection*))); - CANConnectionContainer* container = new CANConnectionContainer(serial); - - - qDebug() << "Setup initial connection object"; - - CANBus bus; - bus.active = ui->ckEnabled->isChecked(); - bus.busNum = serial->getBusBase(); - bus.container = container; - bus.listenOnly = ui->ckListenOnly->isChecked(); - bus.singleWire = ui->ckSingleWire->isChecked(); - - if (ui->cbSpeed->currentIndex() < 1) bus.speed = 0; //default speed - else if (ui->cbSpeed->currentIndex() == 1) - { - bus.speed = 0; - bus.active = false; - } - else bus.speed = ui->cbSpeed->currentText().toInt(); - - connModel->addBus(bus); - - int numBuses = serial->getNumBuses(); - for (int i = 1; i < numBuses; i++) - { - bus.active = false; - bus.listenOnly = false; - bus.singleWire = false; - bus.speed = 250000; - bus.busNum = serial->getBusBase() + i; - bus.container = container; - connModel->addBus(bus); - qDebug() << "Added bus " << bus.busNum; - } - - //call through signal/slot interface without using connect - QMetaObject::invokeMethod(serial, "updatePortName", - Qt::QueuedConnection, - Q_ARG(QString, ui->cbPort->currentText())); -#endif - /* create connection */ - conn_p = CanConFactory::create(getConnectionType(), getPortName()); + conn_p = create(getConnectionType(), getPortName()); if(!conn_p) return; - /* connect signal */ - connect(conn_p, SIGNAL(status(CANCon::status)), - this, SLOT(connectionStatus(CANCon::status))); - - //conn_p->setCallback(std::bind(&ConnectionWindow::callback, this, std::placeholders::_1)); - - /*TODO add return value and checks */ - conn_p->start(); - /*{ - QVector flters; - flters.append({0x305, 0xFFFF, true}); - conn_p->setFilters(0, flters, false); - connect(conn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); - }*/ - for (int i=0 ; igetNumBuses() ; i++) { /* set bus configuration */ CANBus bus; @@ -311,45 +226,27 @@ void ConnectionWindow::handleOKButton() } -void ConnectionWindow::receiveBusStatus(int bus, int speed, int status) -{ -#if 0 - qDebug() << "bus " << bus << " speed " << speed << " status " << status; - CANBus *busRef = connModel->getBus(bus); - if (status & 40) busRef->setSpeed(speed); - if (status & 8) //update enabled status - { - busRef->setEnabled((status & 1)?true:false); - } - if (status & 0x10) //update single wire status - { - busRef->setSingleWire((status & 2)?true:false); - } - if (status & 0x20) //update listen only status - { - busRef->setListenOnly((status & 4)?true:false); - } - connModel->refreshView(); -#endif -} -void ConnectionWindow::handleConnSelectionChanged() +void ConnectionWindow::currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous) { - int selIdx = ui->tableConnections->selectionModel()->currentIndex().row(); + Q_UNUSED(previous); + + int selIdx = current.row(); + + /* enable / diable connection type */ + ui->stPort->setEnabled(selIdx==-1); + ui->gbType->setEnabled(selIdx==-1); + ui->lPort->setEnabled(selIdx==-1); + + /* set parameters */ if (selIdx == -1) { ui->btnOK->setText(tr("Create New Connection")); - - ui->cbPort->setEnabled(true); - ui->rbGVRET->setEnabled(true); - ui->rbKvaser->setEnabled(true); - ui->rbSocketCAN->setEnabled(true); - ui->cbSpeed->setEnabled(false); - + ui->rbGVRET->setChecked(true); ui->cbPort->setCurrentIndex(0); ui->ckListenOnly->setChecked(false); ui->ckSingleWire->setChecked(false); - ui->ckEnabled->setChecked(true); + ui->ckEnabled->setChecked(false); } else { @@ -363,25 +260,16 @@ void ConnectionWindow::handleConnSelectionChanged() ui->btnOK->setText(tr("Update Connection Settings")); - ui->cbPort->setEnabled(false); - ui->rbGVRET->setEnabled(false); - ui->rbKvaser->setEnabled(false); - ui->rbSocketCAN->setEnabled(false); - ui->cbSpeed->setEnabled(true); - - switch(conn_p->getType()) { - case CANCon::GVRET_SERIAL: ui->rbGVRET->setChecked(true); break; - case CANCon::KVASER: ui->rbKvaser->setChecked(true); break; - case CANCon::SOCKETCAN: ui->rbSocketCAN->setChecked(true); break; - default: {} - } + setPortName(conn_p->getType(), conn_p->getPort()); + setSpeed(bus.getSpeed()); ui->ckListenOnly->setChecked(bus.isListenOnly()); ui->ckSingleWire->setChecked(bus.isSingleWire()); ui->ckEnabled->setChecked(bus.isActive()); - int speed = bus.getSpeed(); - setSpeed(speed); + /* this won't be called if elements are disabled */ } + + handleConnTypeChanged(); } @@ -394,10 +282,7 @@ void ConnectionWindow::selectSerial() ports = QSerialPortInfo::availablePorts(); for (int i = 0; i < ports.count(); i++) - { ui->cbPort->addItem(ports[i].portName()); - //if (currentPortName == ports[i].portName()) ui->cbPort->setCurrentIndex(i); - } } void ConnectionWindow::selectKvaser() @@ -438,6 +323,32 @@ void ConnectionWindow::setSpeed(int speed0) } +void ConnectionWindow::setPortName(CANCon::type pType, QString pPortName) +{ + switch(pType) + { + case CANCon::GVRET_SERIAL: + { + ui->rbGVRET->setChecked(true); + + break; + } + case CANCon::KVASER: + { + ui->rbKvaser->setChecked(true); + break; + } + case CANCon::SOCKETCAN: + { + ui->rbSocketCAN->setChecked(true); + ui->lePort->setText(pPortName); + break; + } + default: {} + } +} + + //-1 means leave it at whatever it booted up to. 0 means disable. Otherwise the actual rate we want. int ConnectionWindow::getSpeed() @@ -507,7 +418,7 @@ void ConnectionWindow::handleRemoveConn() CANConnection* conn_p = connModel->getAtIdx(selIdx, busId); if(!conn_p) return; - /* remove connection from model */ + /* remove connection from model & manager */ connModel->remove(conn_p); /* stop and delete connection */ @@ -520,28 +431,6 @@ void ConnectionWindow::handleRevert() } -void ConnectionWindow::sendFrame(const CANFrame *frame) -{ -#if 0 - CANBus *bus = connModel->getBus(frame->bus); - if (bus == NULL) return; - QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrame", - Qt::QueuedConnection, - Q_ARG(const CANFrame *, frame)); -#endif -} - -void ConnectionWindow::sendFrameBatch(const QList *frames) -{ -#if 0 - if (frames->count() == 0) return; - CANBus *bus = connModel->getBus(frames->at(0).bus); - if (bus == NULL) return; - QMetaObject::invokeMethod(bus->getContainer()->getRef(), "sendFrameBatch", - Qt::QueuedConnection, - Q_ARG(const QList *, frames)); -#endif -} bool ConnectionWindow::isSocketCanAvailable() { @@ -554,3 +443,74 @@ bool ConnectionWindow::isSocketCanAvailable() #endif return false; } + + +CANConnection* ConnectionWindow::create(CANCon::type pTye, QString pPortName) +{ + CANConnection* conn_p; + + /* create connection */ + conn_p = CanConFactory::create(pTye, pPortName); + if(conn_p) + { + /* connect signal */ + connect(conn_p, SIGNAL(status(CANCon::status)), + this, SLOT(connectionStatus(CANCon::status))); + + /*TODO add return value and checks */ + conn_p->start(); + } + return conn_p; +} + + +void ConnectionWindow::loadConnections() +{ + QSettings settings; + + /* fill connection list */ + QVector portNames = settings.value("connections/portNames").value>(); + QVector devTypes = settings.value("connections/types").value>(); + QList busses = settings.value("connections/busses").value>(); + + + for(int i=0 ; igetNumBuses() ; j++) + conn_p->setBusSettings(j, busses.takeFirst()); + } + /* add connection to model */ + connModel->add(conn_p); + } +} + +void ConnectionWindow::saveConnections() +{ + QList& conns = CANConManager::getInstance()->getConnections(); + + QSettings settings; + QVector portNames; + QVector devTypes; + QList busses; + + /* delete connections */ + foreach(CANConnection* conn_p, conns) + { + portNames.append(conn_p->getPort()); + devTypes.append(conn_p->getType()); + + for(int i=0 ; igetNumBuses() ; i++) + { + CANBus bus; + conn_p->getBusSettings(i, bus); + busses.append(bus); + } + } + + settings.setValue("connections/portNames", QVariant::fromValue(portNames)); + settings.setValue("connections/types", QVariant::fromValue(devTypes)); + settings.setValue("connections/busses", QVariant::fromValue(busses)); +} diff --git a/connectionwindow.h b/connectionwindow.h index 5cc9b4c..56062da 100644 --- a/connectionwindow.h +++ b/connectionwindow.h @@ -8,8 +8,9 @@ #include #include #include +#include #include "canconnectionmodel.h" -#include "canframemodel.h" +#include "connections/canconnection.h" class CANConnectionModel; @@ -24,11 +25,10 @@ class ConnectionWindow : public QDialog Q_OBJECT public: - explicit ConnectionWindow(CANFrameModel *canModel, QWidget *parent = 0); + explicit ConnectionWindow(QWidget *parent = 0); ~ConnectionWindow(); void showEvent(QShowEvent *); - int getSpeed(); - QString getPortName(); //name of port to connect to + CANCon::type getConnectionType(); bool getSWMode(); @@ -39,40 +39,38 @@ signals: public slots: void setSpeed(int speed0); void setSWMode(bool mode); - void sendFrame(const CANFrame *); - void sendFrameBatch(const QList *); - void setSuspendAll(bool); + void setSuspendAll(bool pSuspend); private slots: void handleOKButton(); void handleConnTypeChanged(); - void handleConnSelectionChanged(); + void currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous); void handleRemoveConn(); void handleEnableAll(); void handleDisableAll(); void handleRevert(); void handleNewConn(); - void receiveBusStatus(int bus, int speed, int status); void connectionStatus(CANCon::status); - void refreshCanList(); - private: Ui::ConnectionWindow *ui; QList ports; QSettings *settings; CANConnectionModel *connModel; - CANFrameModel *canModel; - QTimer mTicker; - - QAtomicInt mRefreshReqOngoing; void selectSerial(); void selectKvaser(); void selectSocketCan(); bool isSocketCanAvailable(); + int getSpeed(); + QString getPortName(); + void setPortName(CANCon::type pType, QString pPortName); + void setActiveAll(bool pActive); + CANConnection* create(CANCon::type pTye, QString pPortName); + void loadConnections(); + void saveConnections(); }; #endif // CONNECTIONWINDOW_H From d4b6575f5da44310c1c94ad8ae8d8378cdb338b6 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 12:02:16 +0200 Subject: [PATCH 55/86] minor changes and fixes --- SavvyCAN.pro | 6 ++-- canfilter.h | 2 +- connectionwindow.ui | 4 +-- mainwindow.cpp | 83 +++++++++++++++++---------------------------- mainwindow.ui | 5 ++- 5 files changed, 42 insertions(+), 58 deletions(-) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index 34879f4..b1369e2 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -54,7 +54,8 @@ SOURCES += main.cpp\ connections/canconnection.cpp \ connections/socketcan.cpp \ connections/canconfactory.cpp \ - connections/gvretserial.cpp + connections/gvretserial.cpp \ + connections/canconmanager.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -97,7 +98,8 @@ HEADERS += mainwindow.h \ connections/socketcan.h \ connections/canconconst.h \ connections/canconfactory.h \ - connections/gvretserial.h + connections/gvretserial.h \ + connections/canconmanager.h FORMS += mainwindow.ui \ graphingwindow.ui \ diff --git a/canfilter.h b/canfilter.h index 91a84e3..c2cb71b 100644 --- a/canfilter.h +++ b/canfilter.h @@ -10,7 +10,7 @@ public: void setFilter(uint32_t id, uint32_t mask, int bus); bool checkFilter(uint32_t id, int bus); -private: +public: uint32_t ID; uint32_t mask; int bus; diff --git a/connectionwindow.ui b/connectionwindow.ui index f3a5b39..5e7ffc4 100644 --- a/connectionwindow.ui +++ b/connectionwindow.ui @@ -74,7 +74,7 @@ - + Connection Type @@ -116,7 +116,7 @@ - + 0 diff --git a/mainwindow.cpp b/mainwindow.cpp index f19f682..59a8d84 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -4,7 +4,7 @@ #include #include #include -#include "canframemodel.h" +#include "connections/canconmanager.h" #include "utility.h" #include "serialworker.h" @@ -62,28 +62,6 @@ MainWindow::MainWindow(QWidget *parent) : ui->canFramesView->setColumnWidth(6, 275); QHeaderView *HorzHdr = ui->canFramesView->horizontalHeader(); HorzHdr->setStretchLastSection(true); //causes the data column to automatically fill the tableview - //enabling the below line kills performance in every way imaginable. Left here as a warning. Do not do this. - //ui->canFramesView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - - /* - worker = new SerialWorker(model); - worker->moveToThread(&serialWorkerThread); - connect(&serialWorkerThread, &QThread::finished, worker, &QObject::deleteLater); - connect(&serialWorkerThread, &QThread::started, worker, &SerialWorker::run); //setup timers within the proper thread - connect(this, &MainWindow::sendSerialPort, worker, &SerialWorker::setSerialPort, Qt::QueuedConnection); - connect(worker, &SerialWorker::frameUpdateRapid, this, &MainWindow::gotFrames, Qt::QueuedConnection); - connect(this, &MainWindow::updateBaudRates, worker, &SerialWorker::updateBaudRates, Qt::QueuedConnection); - connect(this, &MainWindow::sendCANFrame, worker, &SerialWorker::sendFrame, Qt::QueuedConnection); - connect(worker, &SerialWorker::connectionSuccess, this, &MainWindow::connectionSucceeded, Qt::QueuedConnection); - connect(worker, &SerialWorker::connectionFailure, this, &MainWindow::connectionFailed, Qt::QueuedConnection); - connect(worker, &SerialWorker::deviceInfo, this, &MainWindow::gotDeviceInfo, Qt::QueuedConnection); - connect(this, &MainWindow::closeSerialPort, worker, &SerialWorker::closeSerialPort, Qt::QueuedConnection); - connect(this, &MainWindow::startFrameCapturing, worker, &SerialWorker::startFrameCapture); - connect(this, &MainWindow::stopFrameCapturing, worker, &SerialWorker::stopFrameCapture); - connect(this, &MainWindow::settingsUpdated, worker, &SerialWorker::readSettings); - serialWorkerThread.start(); - serialWorkerThread.setPriority(QThread::HighPriority); - */ graphingWindow = NULL; frameInfoWindow = NULL; @@ -146,6 +124,8 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionUDS_Scanner, &QAction::triggered, this, &MainWindow::showUDSScanWindow); connect(ui->actionISO_TP_Decoder, &QAction::triggered, this, &MainWindow::showISOInterpreterWindow); + connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames); + lbStatusConnected.setText(tr("Not connected")); updateFileStatus(); lbStatusDatabase.setText(tr("No DBC database loaded")); @@ -179,8 +159,7 @@ MainWindow::MainWindow(QWidget *parent) : model->clearFrames(); //Automatically create the connection window so it can be updated even if we never opened it. - connectionWindow = new ConnectionWindow(model); - connect(connectionWindow, SIGNAL(updateConnectionSettings(QString,QString,int,int)), this, SLOT(updateConnectionSettings(QString,QString,int,int))); + connectionWindow = new ConnectionWindow(); connect(this, SIGNAL(suspendCapturing(bool)), connectionWindow, SLOT(setSuspendAll(bool))); } @@ -480,28 +459,30 @@ void MainWindow::filterClearAll() void MainWindow::tickGUIUpdate() { - int elapsed = elapsedTime->elapsed(); - if(elapsed) { - framesPerSec += rxFrames * 1000 / elapsed - (framesPerSec / 4); - elapsedTime->restart(); - } - else - framesPerSec = 0; - - model->sendBulkRefresh(rxFrames); - - ui->lbNumFrames->setText(QString::number(model->rowCount())); - if (ui->cbAutoScroll->isChecked()) ui->canFramesView->scrollToBottom(); - ui->lbFPS->setText(QString::number(framesPerSec / 4)); - if (rxFrames > 0) + rxFrames = model->sendBulkRefresh(); + if(rxFrames>0) { - bDirty = true; - emit framesUpdated(rxFrames); //anyone care that frames were updated? + int elapsed = elapsedTime->elapsed(); + if(elapsed) { + framesPerSec = rxFrames * 1000 / elapsed; + elapsedTime->restart(); + } + else + framesPerSec = 0; + + ui->lbNumFrames->setText(QString::number(model->rowCount())); + if (ui->cbAutoScroll->isChecked()) ui->canFramesView->scrollToBottom(); + ui->lbFPS->setText(QString::number(framesPerSec)); + if (rxFrames > 0) + { + bDirty = true; + emit framesUpdated(rxFrames); //anyone care that frames were updated? + } + + if (model->needsFilterRefresh()) updateFilterList(); + + rxFrames = 0; } - - if (model->needsFilterRefresh()) updateFilterList(); - - rxFrames = 0; } void MainWindow::gotFrames(int framesSinceLastUpdate) @@ -867,7 +848,7 @@ void MainWindow::showFrameSenderWindow() else frameSenderWindow = new FrameSenderWindow(model->getFilteredListReference()); - connect(frameSenderWindow, &FrameSenderWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); + //connect(frameSenderWindow, &FrameSenderWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); } frameSenderWindow->show(); } @@ -881,8 +862,8 @@ void MainWindow::showPlaybackWindow() else playbackWindow = new FramePlaybackWindow(model->getFilteredListReference()); - connect(playbackWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*)), Qt::QueuedConnection); - connect(playbackWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*)), Qt::QueuedConnection); + //connect(playbackWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*)), Qt::QueuedConnection); + //connect(playbackWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*)), Qt::QueuedConnection); } playbackWindow->show(); } @@ -892,7 +873,7 @@ void MainWindow::showFirmwareUploaderWindow() if (!firmwareUploaderWindow) { firmwareUploaderWindow = new FirmwareUploaderWindow(model->getListReference()); - connect(firmwareUploaderWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); + //connect(firmwareUploaderWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); //connect(worker, SIGNAL(gotTargettedFrame(int)), firmwareUploaderWindow, SLOT(gotTargettedFrame(int))); } firmwareUploaderWindow->show(); @@ -942,7 +923,6 @@ void MainWindow::showScriptingWindow() if (!scriptingWindow) { scriptingWindow = new ScriptingWindow(model->getListReference()); - connect(scriptingWindow, &ScriptingWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); } scriptingWindow->show(); } @@ -995,8 +975,7 @@ void MainWindow::showConnectionSettingsWindow() { if (!connectionWindow) { - connectionWindow = new ConnectionWindow(model); - connect(connectionWindow, SIGNAL(updateConnectionSettings(QString,QString,int,int)), this, SLOT(updateConnectionSettings(QString,QString,int,int))); + connectionWindow = new ConnectionWindow(); } connectionWindow->show(); } diff --git a/mainwindow.ui b/mainwindow.ui index 327ac92..a4850ac 100644 --- a/mainwindow.ui +++ b/mainwindow.ui @@ -103,6 +103,9 @@ Suspend Capturing + + false + @@ -197,7 +200,7 @@ 0 0 800 - 27 + 19 From fb768245b300e6202dcbd8960eddb5fffbe31e52 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Wed, 29 Jun 2016 13:19:36 +0200 Subject: [PATCH 56/86] a couple more bugfix for connectionwindow --- canconnectionmodel.cpp | 12 +++--- connectionwindow.cpp | 97 ++++++++++++++++++------------------------ 2 files changed, 47 insertions(+), 62 deletions(-) diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 404b3cd..084d2cc 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -182,14 +182,12 @@ void CANConnectionModel::refresh(int pIndex) QModelIndex end; if(pIndex>=0) { - begin = createIndex(pIndex, 0); - end = begin; + begin = createIndex(pIndex, 0); + end = createIndex(pIndex, columnCount()-1); } else { - begin = createIndex(0, 0); - begin = createIndex(rowCount()-1, 0); - /*beginResetModel(); - endResetModel();*/ + begin = createIndex(0, 0); + end = createIndex(rowCount()-1, columnCount()-1); } - dataChanged(begin, end); + dataChanged(begin, end, QVector(Qt::DisplayRole)); } diff --git a/connectionwindow.cpp b/connectionwindow.cpp index 6b1fc77..5919e06 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -21,11 +21,6 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : qRegisterMetaType("const CANFrame *"); qRegisterMetaType *>("const QList *"); - qRegisterMetaTypeStreamOperators>(); - qRegisterMetaTypeStreamOperators>(); - qRegisterMetaTypeStreamOperators(); - qRegisterMetaTypeStreamOperators>(); - connModel = new CANConnectionModel(this); ui->tableConnections->setModel(connModel); @@ -37,8 +32,6 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : ui->tableConnections->setColumnWidth(5, 75); ui->tableConnections->setColumnWidth(6, 75); ui->tableConnections->setColumnWidth(7, 75); - - //int temp = settings.value("Main/DefaultConnectionType", 0).toInt(); ui->ckSingleWire->setChecked(settings.value("Main/SingleWireMode", false).toBool()); ui->cbSpeed->addItem(tr("")); @@ -51,10 +44,7 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : /* load connection configuration */ loadConnections(); -#ifdef Q_OS_LINUX ui->rbSocketCAN->setEnabled(isSocketCanAvailable()); -#endif - #ifdef Q_OS_WIN ui->rbKvaser->setEnabled(true); #endif @@ -171,6 +161,7 @@ void ConnectionWindow::handleOKButton() if (whichRow > -1) { + /* set information for selected connection */ int busId; CANBus bus; bool ret; @@ -243,10 +234,11 @@ void ConnectionWindow::currentRowChanged(const QModelIndex ¤t, const QMode { ui->btnOK->setText(tr("Create New Connection")); ui->rbGVRET->setChecked(true); - ui->cbPort->setCurrentIndex(0); ui->ckListenOnly->setChecked(false); ui->ckSingleWire->setChecked(false); ui->ckEnabled->setChecked(false); + setSpeed(0); + setPortName(CANCon::GVRET_SERIAL, ""); } else { @@ -259,17 +251,12 @@ void ConnectionWindow::currentRowChanged(const QModelIndex ¤t, const QMode if(!ret) return; ui->btnOK->setText(tr("Update Connection Settings")); - - setPortName(conn_p->getType(), conn_p->getPort()); - setSpeed(bus.getSpeed()); - ui->ckListenOnly->setChecked(bus.isListenOnly()); ui->ckSingleWire->setChecked(bus.isSingleWire()); ui->ckEnabled->setChecked(bus.isActive()); - /* this won't be called if elements are disabled */ + setSpeed(bus.getSpeed()); + setPortName(conn_p->getType(), conn_p->getPort()); } - - handleConnTypeChanged(); } @@ -287,40 +274,30 @@ void ConnectionWindow::selectSerial() void ConnectionWindow::selectKvaser() { -#ifdef Q_OS_WIN /* set combobox page visible */ ui->stPort->setCurrentWidget(ui->cbPage); -#endif } void ConnectionWindow::selectSocketCan() { -#ifdef Q_OS_LINUX /* set edit text page visible */ ui->stPort->setCurrentWidget(ui->etPage); -#endif } void ConnectionWindow::setSpeed(int speed0) { - bool found = false; - - qDebug() << "Set Speed " << speed0; - for (int i = 0; i < ui->cbSpeed->count(); i++) { if (ui->cbSpeed->itemText(i).toInt() == speed0) { ui->cbSpeed->setCurrentIndex(i); - found = true; + return; } } - if (!found) - { - ui->cbSpeed->addItem(QString::number(speed0)); - ui->cbSpeed->setCurrentIndex(ui->cbSpeed->count() - 1); - } + /* add custom speed */ + ui->cbSpeed->addItem(QString::number(speed0)); + ui->cbSpeed->setCurrentIndex(ui->cbSpeed->count() - 1); } void ConnectionWindow::setPortName(CANCon::type pType, QString pPortName) @@ -328,19 +305,28 @@ void ConnectionWindow::setPortName(CANCon::type pType, QString pPortName) switch(pType) { case CANCon::GVRET_SERIAL: - { - ui->rbGVRET->setChecked(true); - - break; - } + ui->rbGVRET->setChecked(true); break; case CANCon::KVASER: + ui->rbKvaser->setChecked(true); break; + case CANCon::SOCKETCAN: + ui->rbSocketCAN->setChecked(true); break; + default: {} + } + + /* refresh names whenever needed */ + handleConnTypeChanged(); + + switch(pType) + { + case CANCon::GVRET_SERIAL: { - ui->rbKvaser->setChecked(true); + int idx = ui->cbPort->findText(pPortName); + if( idx<0 ) idx=0; + ui->cbPort->setCurrentIndex(idx); break; } case CANCon::SOCKETCAN: { - ui->rbSocketCAN->setChecked(true); ui->lePort->setText(pPortName); break; } @@ -349,24 +335,18 @@ void ConnectionWindow::setPortName(CANCon::type pType, QString pPortName) } - //-1 means leave it at whatever it booted up to. 0 means disable. Otherwise the actual rate we want. int ConnectionWindow::getSpeed() { switch (ui->cbSpeed->currentIndex()) { - case -1: - return -1; - break; - case 0: - return -1; - break; - case 1: - return 0; - break; - default: - return (ui->cbSpeed->currentText().toInt()); - break; + case -1: + case 0: + return -1; + case 1: + return 0; + default: + return (ui->cbSpeed->currentText().toInt()); } } @@ -424,6 +404,9 @@ void ConnectionWindow::handleRemoveConn() /* stop and delete connection */ conn_p->stop(); delete conn_p; + + /* select first connection in list */ + ui->tableConnections->selectRow(0); } void ConnectionWindow::handleRevert() @@ -436,9 +419,8 @@ bool ConnectionWindow::isSocketCanAvailable() { #ifdef Q_OS_LINUX foreach (const QByteArray &backend, QCanBus::instance()->plugins()) { - if (backend == "socketcan") { + if (backend == "socketcan") return true; - } } #endif return false; @@ -466,6 +448,11 @@ CANConnection* ConnectionWindow::create(CANCon::type pTye, QString pPortName) void ConnectionWindow::loadConnections() { + qRegisterMetaTypeStreamOperators>(); + qRegisterMetaTypeStreamOperators>(); + qRegisterMetaTypeStreamOperators(); + qRegisterMetaTypeStreamOperators>(); + QSettings settings; /* fill connection list */ @@ -496,7 +483,7 @@ void ConnectionWindow::saveConnections() QVector devTypes; QList busses; - /* delete connections */ + /* save connections */ foreach(CANConnection* conn_p, conns) { portNames.append(conn_p->getPort()); From 314ea0769d445d24ee3d4c6cb425420311bc6f63 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 7 Jul 2016 16:47:43 +0200 Subject: [PATCH 57/86] add sniffer --- mainwindow.cpp | 17 +++ mainwindow.h | 3 + mainwindow.ui | 6 + re/sniffer/snifferitem.cpp | 86 +++++++++++ re/sniffer/snifferitem.h | 49 +++++++ re/sniffer/sniffermodel.cpp | 267 +++++++++++++++++++++++++++++++++++ re/sniffer/sniffermodel.h | 58 ++++++++ re/sniffer/snifferwindow.cpp | 132 +++++++++++++++++ re/sniffer/snifferwindow.h | 56 ++++++++ snifferwindow.ui | 188 ++++++++++++++++++++++++ 10 files changed, 862 insertions(+) create mode 100644 re/sniffer/snifferitem.cpp create mode 100644 re/sniffer/snifferitem.h create mode 100644 re/sniffer/sniffermodel.cpp create mode 100644 re/sniffer/sniffermodel.h create mode 100644 re/sniffer/snifferwindow.cpp create mode 100644 re/sniffer/snifferwindow.h create mode 100644 snifferwindow.ui diff --git a/mainwindow.cpp b/mainwindow.cpp index 59a8d84..d5826c0 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -80,6 +80,7 @@ MainWindow::MainWindow(QWidget *parent) : fuzzingWindow = NULL; udsScanWindow = NULL; isoWindow = NULL; + snifferWindow = NULL; dbcHandler = new DBCHandler; bDirty = false; inhibitFilterUpdate = false; @@ -123,6 +124,7 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionFuzzing, &QAction::triggered, this, &MainWindow::showFuzzingWindow); connect(ui->actionUDS_Scanner, &QAction::triggered, this, &MainWindow::showUDSScanWindow); connect(ui->actionISO_TP_Decoder, &QAction::triggered, this, &MainWindow::showISOInterpreterWindow); + connect(ui->actionSniffer, &QAction::triggered, this, &MainWindow::showSnifferWindow); connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames); @@ -264,6 +266,12 @@ MainWindow::~MainWindow() isoWindow->close(); delete isoWindow; } + if (snifferWindow) + { + snifferWindow->close(); + delete snifferWindow; + snifferWindow = NULL; + } delete elapsedTime; @@ -291,6 +299,7 @@ void MainWindow::exitApp() if (fuzzingWindow) fuzzingWindow->close(); if (udsScanWindow) udsScanWindow->close(); if (isoWindow) isoWindow->close(); + if (snifferWindow) snifferWindow->close(); this->close(); } @@ -839,6 +848,14 @@ void MainWindow::showISOInterpreterWindow() isoWindow->show(); } +void MainWindow::showSnifferWindow() +{ + if (!snifferWindow) + snifferWindow = new SnifferWindow(this); + snifferWindow->show(); +} + + void MainWindow::showFrameSenderWindow() { if (!frameSenderWindow) diff --git a/mainwindow.h b/mainwindow.h index 191008a..a2925f5 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -25,6 +25,7 @@ #include "dbcloadsavewindow.h" #include "fuzzingwindow.h" #include "udsscanwindow.h" +#include "re/sniffer/snifferwindow.h" #include "isotp_interpreterwindow.h" class ConnectionWindow; @@ -67,6 +68,7 @@ private slots: void showFuzzingWindow(); void showUDSScanWindow(); void showISOInterpreterWindow(); + void showSnifferWindow(); void exitApp(); void handleSaveDecoded(); void connectionFailed(); @@ -137,6 +139,7 @@ private: FuzzingWindow *fuzzingWindow; UDSScanWindow *udsScanWindow; ISOTP_InterpreterWindow *isoWindow; + SnifferWindow* snifferWindow; //various private storage QLabel lbStatusConnected; diff --git a/mainwindow.ui b/mainwindow.ui index a4850ac..1c6437c 100644 --- a/mainwindow.ui +++ b/mainwindow.ui @@ -214,6 +214,7 @@ + @@ -395,6 +396,11 @@ ISO-TP Decoder + + + Sniffer + + diff --git a/re/sniffer/snifferitem.cpp b/re/sniffer/snifferitem.cpp new file mode 100644 index 0000000..0fe870b --- /dev/null +++ b/re/sniffer/snifferitem.cpp @@ -0,0 +1,86 @@ +#include +#include +#include "snifferitem.h" + + +SnifferItem::SnifferItem(const CANFrame& pFrame): + mNotch(0) +{ + mID = pFrame.ID; + mMarker = {0,0}; + mLastMarker = {0,0}; + /* that's dirty */ + update(pFrame); + update(pFrame); +} + + +SnifferItem::~SnifferItem() +{ + +} + +quint64 SnifferItem::getId() const +{ + return mID; +} + +float SnifferItem::getDelta() const +{ + return ((float)(mCurrentTime-mLastTime))/1000000; +} + +int SnifferItem::getData(uchar i) const +{ + return (i>=mCurrent.len) ? -1 : ((uchar*) &mCurrent.data)[i]; +} + +dc SnifferItem::dataChange(uchar i) const +{ + if( i= ((uchar*) &mLast.data)[i] ? dc::INC : dc::DEC; + } + + return dc::NO; +} + +int SnifferItem::elapsed() const +{ + return mTime.elapsed(); +} + +void SnifferItem::update(const CANFrame& pFrame) +{ + /* copy current to last */ + mLast = mCurrent; + mLastTime = mCurrentTime; + + /* copy new value */ + memcpy(&mCurrent.data, pFrame.data, 8); + mCurrent.len = pFrame.len; + mCurrentTime = pFrame.timestamp; + + /* update marker */ + mMarker.data |= mLast.data ^ mCurrent.data; + mMarker.len |= mLast.len ^ mCurrent.data; + + /* restart timeout */ + mTime.restart(); +} + +void SnifferItem::updateMarker() +{ + mLastMarker = mMarker; + mMarker = {0, 0}; +} + +void SnifferItem::notch(bool pNotch) +{ + if(pNotch) + mNotch |= mLastMarker.data; + else + mNotch = 0; +} diff --git a/re/sniffer/snifferitem.h b/re/sniffer/snifferitem.h new file mode 100644 index 0000000..cc06c3a --- /dev/null +++ b/re/sniffer/snifferitem.h @@ -0,0 +1,49 @@ +#ifndef SNIFFERITEM_H +#define SNIFFERITEM_H + +#include +#include +#include "can_structs.h" + +struct fstCan +{ + quint64 data; + int len; +}; + +enum dc +{ + NO, + INC, + DEC +}; + + +class SnifferItem +{ +public: + explicit SnifferItem(const CANFrame& pFrame); + virtual ~SnifferItem(); + + quint64 getId() const; + float getDelta() const; + int getData(uchar i) const; + dc dataChange(uchar) const; + int elapsed() const; + void update(const CANFrame& pFrame); + void updateMarker(); + void notch(bool); +private: + quint64 mID; + struct fstCan mLast; + struct fstCan mCurrent; + struct fstCan mLastMarker; + struct fstCan mMarker; + quint64 mNotch; + quint64 mLastTime; + quint64 mCurrentTime; + + QTime mTime; +}; + +#endif // SNIFFERITEM_H diff --git a/re/sniffer/sniffermodel.cpp b/re/sniffer/sniffermodel.cpp new file mode 100644 index 0000000..a762346 --- /dev/null +++ b/re/sniffer/sniffermodel.cpp @@ -0,0 +1,267 @@ +#include +#include "sniffermodel.h" +#include "snifferwindow.h" + + +SnifferModel::SnifferModel(QObject *parent) + : QAbstractItemModel(parent), + mFilter(false) +{ +} + +SnifferModel::~SnifferModel() +{ + clear(); +} + + +int SnifferModel::columnCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : tc::LAST+1; +} + + +int SnifferModel::rowCount(const QModelIndex &parent) const +{ + const QMap& map = mFilter ? mFilters : mMap; + return parent.isValid() ? 0 : map.size(); +} + + +QVariant SnifferModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + const QMap& map = mFilter ? mFilters : mMap; + + if(index.row()<=map.size()) + { + quint64 key = map.keys()[index.row()]; + SnifferItem* item = map[key]; + + int col = index.column(); + + switch(role) + { + case Qt::DisplayRole: + { + switch(col) + { + case tc::DELTA: + return QString::number(item->getDelta(), 'f'); + case tc::ID: + return QString("%1").arg(item->getId(), 5, 16, QLatin1Char(' ')).toUpper(); + default: + break; + } + if(tc::DATA_0<=col && col <=tc::DATA_7) + { + int data = item->getData(col-tc::DATA_0); + if(data>=0) + return QString("%1").arg(data, 2, 16, QLatin1Char('0')).toUpper(); + } + break; + } + case Qt::BackgroundRole: + { + if(tc::ID==col) + { + if(item->elapsed()>4000) + return QBrush(Qt::red); + } + else if(tc::DATA_0<=col && col<=tc::DATA_7) + { + dc change = item->dataChange(col-tc::DATA_0); + switch(change) + { + case dc::INC: + return QBrush(Qt::green); + case dc::DEC: + return QBrush(Qt::red); + default: + break; + } + } + break; + } + } + } + + return QVariant(); +} + + +Qt::ItemFlags SnifferModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + + return QAbstractItemModel::flags(index); +} + + +QVariant SnifferModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + { + switch(section) + { + case tc::DELTA: + return QString("Delta"); + case tc::ID: + return QString("ID"); + default: + break; + } + if(tc::DATA_0<=section && section <=tc::DATA_7) + return QString::number(section-tc::DATA_0); + } + + return QVariant(); +} + + +QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) + const +{ + if (parent.isValid()) + return QModelIndex(); + + const QMap& map = mFilter ? mFilters : mMap; + + if(column>tc::LAST || row>=map.size()) + return QModelIndex(); + + return createIndex(row, column); +} + + +QModelIndex SnifferModel::parent(const QModelIndex &) const +{ + return QModelIndex(); +} + + +void SnifferModel::clear() +{ + beginResetModel(); + qDeleteAll(mMap); + mMap.clear(); + mFilters.clear(); + endResetModel(); + + mFilter = false; +} + + +void SnifferModel::refresh() +{ + QMap::iterator i; + QVector toRemove; + SnifferItem* item; + + /* update markers */ + + + for (i = mMap.begin(); i != mMap.end(); ++i) + { + i.value()->updateMarker(); + if(i.value()->elapsed()>5000) + toRemove.append(i.key()); + } + + if(toRemove.size()) + { + beginResetModel(); + foreach(quint32 id, toRemove) + { + /* remove element */ + item = mMap.take(id); + mFilters.remove(id); + delete item; + /* send notification */ + emit idChange(id, false); + } + endResetModel(); + } + else + /* refresh data */ + dataChanged(createIndex(0, 0), + createIndex(rowCount()-1, columnCount()-1), QVector(Qt::DisplayRole)); +} + + +void SnifferModel::filter(fltType pType, int pId) +{ + beginResetModel(); + switch(pType) + { + case fltType::NONE: + /* erase everything */ + mFilter = true; + mFilters.clear(); + break; + case fltType::ADD: + /* add filter to list */ + mFilter = true; + mFilters[pId] = mMap[pId]; + break; + case fltType::REMOVE: + /* remove filter */ + if(!mFilter) + mFilters = mMap; + mFilter = true; + mFilters.remove(pId); + break; + case fltType::ALL: + /* stop filtering */ + mFilter = false; + mFilters.clear(); + break; + } + endResetModel(); +} + + +/***********************************************/ +/********** slots ****************/ +/***********************************************/ + +void SnifferModel::update(CANConnection*, QVector& pFrames) +{ + foreach(const CANFrame& frame, pFrames) + { + if(!mMap.contains(frame.ID)) + { + int index = std::distance(mMap.begin(), mMap.lowerBound(frame.ID)); + /* add the frame */ + beginInsertRows(QModelIndex(), index, index); + mMap[frame.ID] = new SnifferItem(frame); + endInsertRows(); + + emit idChange(frame.ID, true); + } + else + //updateData + mMap[frame.ID]->update(frame); + } +} + +void SnifferModel::notch() +{ + QMap& map = mFilter ? mFilters : mMap; + + foreach(SnifferItem* item, map) + item->notch(true); +} + +void SnifferModel::unNotch() +{ + QMap& map = mFilter ? mFilters : mMap; + + foreach(SnifferItem* item, map) + item->notch(false); +} + + diff --git a/re/sniffer/sniffermodel.h b/re/sniffer/sniffermodel.h new file mode 100644 index 0000000..7c3fc19 --- /dev/null +++ b/re/sniffer/sniffermodel.h @@ -0,0 +1,58 @@ +#ifndef SNIFFERMODEL_H +#define SNIFFERMODEL_H + +#include +#include +#include +#include + +#include "can_structs.h" +#include "connections/canconnection.h" +#include "snifferitem.h" + + +enum fltType +{ + ALL, + ADD, + REMOVE, + NONE +}; + +class SnifferModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + explicit SnifferModel(QObject *parent = 0); + virtual ~SnifferModel(); + + /* from QAbstractItemModel */ + QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; + Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + void refresh(); + void clear(); + void filter(fltType pType, int pId=0); + +public slots: + void update(CANConnection*, QVector&); + void notch(); + void unNotch(); + +signals: + void idChange(int, bool); + +private: + QMap mMap; + QMap mFilters; + bool mFilter; +}; + +#endif // SNIFFERMODEL_H diff --git a/re/sniffer/snifferwindow.cpp b/re/sniffer/snifferwindow.cpp new file mode 100644 index 0000000..cab2a88 --- /dev/null +++ b/re/sniffer/snifferwindow.cpp @@ -0,0 +1,132 @@ +#include +#include +#include "snifferwindow.h" +#include "ui_snifferwindow.h" +#include "connections/canconmanager.h" + +SnifferWindow::SnifferWindow(QWidget *parent) : + QDialog(parent), + ui(new Ui::snifferWindow), + mModel(this), + mTimer(this), + mFilter(false) +{ + ui->setupUi(this); + ui->treeView->setModel(&mModel); + + /* set column width */ + ui->treeView->setColumnWidth(tc::ID, 50); + ui->treeView->setColumnWidth(tc::LAST, 1); + for(int i=tc::DATA_0 ; i<=tc::DATA_7 ; i++) + ui->treeView->setColumnWidth(i, 30); + ui->treeView->header()->setDefaultAlignment(Qt::AlignCenter); + + /* activate sorting */ + ui->listWidget->setSortingEnabled(true); + + /* connect timer */ + connect(&mTimer, &QTimer::timeout, this, &SnifferWindow::update); + mTimer.setInterval(200); + + /* connect buttons */ + connect(ui->btNotch, &QPushButton::clicked, &mModel, &SnifferModel::notch); + connect(ui->btUnNotch, &QPushButton::clicked, &mModel, &SnifferModel::unNotch); + connect(ui->btAll, &QPushButton::clicked, this, &SnifferWindow::fltAll); + connect(ui->btNone, &QPushButton::clicked, this, &SnifferWindow::fltNone); + connect(&mModel, &SnifferModel::idChange, this, &SnifferWindow::idChange); + connect(ui->listWidget, &QListWidget::itemChanged, this, &SnifferWindow::itemChanged); + +} + +SnifferWindow::~SnifferWindow() +{ + closeEvent(NULL); + delete ui; +} + + +void SnifferWindow::showEvent(QShowEvent* event) +{ + QDialog::showEvent(event); + connect(CANConManager::getInstance(), &CANConManager::framesReceived, &mModel, &SnifferModel::update); + mTimer.start(); + + qDebug() << "show"; +} + + +void SnifferWindow::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); + /* stop timer */ + mTimer.stop(); + /* disconnect reception of frames */ + disconnect(CANConManager::getInstance(), 0, this, 0); + /* clear model */ + mModel.clear(); + /* clean list */ + qDeleteAll(mMap); + mMap.clear(); + /* reset filtering */ + mFilter = false; +} + + +void SnifferWindow::update() +{ + mModel.refresh(); +} + + +void SnifferWindow::fltAll() +{ + filter(false); +} + + +void SnifferWindow::fltNone() +{ + filter(true); +} + +void SnifferWindow::filter(bool pFilter) +{ + mFilter = pFilter; + mModel.filter(mFilter ? fltType::NONE : fltType::ALL); + + foreach(QListWidgetItem* item, mMap) + item->setCheckState(mFilter ? Qt::Unchecked : Qt::Checked); +} + +void SnifferWindow::idChange(int pId, bool pAdd) +{ + QListWidgetItem* item; + + if(pAdd) + { + QString text = QString("0x") + QString("%1").arg(pId, 3, 16, QLatin1Char('0')).toUpper(); + item = new QListWidgetItem(text); + item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); + item->setCheckState(mFilter ? Qt::Unchecked : Qt::Checked); + ui->listWidget->addItem(item); + mMap[pId] = item; + } + else + { + item = mMap.take(pId); + ui->listWidget->removeItemWidget(item); + delete item; + } +} + + +void SnifferWindow::itemChanged(QListWidgetItem * item) +{ + bool checked = (Qt::Checked == item->checkState()); + + if( !mFilter && checked ) + return; + + mModel.filter(checked ? fltType::ADD : fltType::REMOVE, mMap.key(item)); + mFilter = true; +} diff --git a/re/sniffer/snifferwindow.h b/re/sniffer/snifferwindow.h new file mode 100644 index 0000000..2d2cb1d --- /dev/null +++ b/re/sniffer/snifferwindow.h @@ -0,0 +1,56 @@ +#ifndef SNIFFER_H +#define SNIFFER_H + +#include +#include +#include "sniffermodel.h" + +namespace Ui { +class snifferWindow; +} + +enum tc +{ + DELTA = 0, + ID, + DATA_0, + DATA_1, + DATA_2, + DATA_3, + DATA_4, + DATA_5, + DATA_6, + DATA_7, + LAST +}; + + +class SnifferWindow : public QDialog +{ + Q_OBJECT + +public: + explicit SnifferWindow(QWidget *parent = 0); + ~SnifferWindow(); + + void showEvent(QShowEvent*); + void closeEvent(QCloseEvent*); + +public slots: + void update(); + void idChange(int, bool); + void fltAll(); + void fltNone(); + void itemChanged(QListWidgetItem*); + +private: + void filter(bool pFilter); + + Ui::snifferWindow* ui; + SnifferModel mModel; + QTimer mTimer; + QMap mMap; + bool mFilter; +}; + +#endif // SNIFFER_H diff --git a/snifferwindow.ui b/snifferwindow.ui new file mode 100644 index 0000000..44d36a0 --- /dev/null +++ b/snifferwindow.ui @@ -0,0 +1,188 @@ + + + snifferWindow + + + + 0 + 0 + 602 + 752 + + + + Sniffer + + + + QLayout::SetDefaultConstraint + + + + + QAbstractItemView::NoSelection + + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Maximum + + + + 20 + 40 + + + + + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + Notch + + + + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + Unnotch + + + + + + + Qt::Vertical + + + QSizePolicy::Maximum + + + + 20 + 40 + + + + + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + Filters: + + + + QLayout::SetDefaultConstraint + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + + + + + QLayout::SetDefaultConstraint + + + + + + 75 + 16777215 + + + + All + + + + + + + + 75 + 16777215 + + + + None + + + + + + + + + + + + + + + + + From 92955101687b7cf97776c9a7b99932304c3be3a1 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 7 Jul 2016 16:48:14 +0200 Subject: [PATCH 58/86] change refresh rate to 250ms --- connections/canconmanager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index b0b5a37..5f645d1 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -15,7 +15,7 @@ CANConManager* CANConManager::getInstance() CANConManager::CANConManager(QObject *parent): QObject(parent) { connect(&mTimer, SIGNAL(timeout()), this, SLOT(refreshCanList())); - mTimer.setInterval(500); /*tick twice a second */ + mTimer.setInterval(250); /*tick 4 times a second */ mTimer.setSingleShot(false); mTimer.start(); } From 6cd79c7f710532c41801cb4e92bb11873338e813 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Thu, 7 Jul 2016 16:50:24 +0200 Subject: [PATCH 59/86] add sniffer files to project --- SavvyCAN.pro | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index b1369e2..ed7f854 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -55,7 +55,10 @@ SOURCES += main.cpp\ connections/socketcan.cpp \ connections/canconfactory.cpp \ connections/gvretserial.cpp \ - connections/canconmanager.cpp + connections/canconmanager.cpp \ + re/sniffer/snifferitem.cpp \ + re/sniffer/sniffermodel.cpp \ + re/sniffer/snifferwindow.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -99,7 +102,10 @@ HEADERS += mainwindow.h \ connections/canconconst.h \ connections/canconfactory.h \ connections/gvretserial.h \ - connections/canconmanager.h + connections/canconmanager.h \ + re/sniffer/snifferitem.h \ + re/sniffer/sniffermodel.h \ + re/sniffer/snifferwindow.h FORMS += mainwindow.ui \ graphingwindow.ui \ @@ -121,7 +127,8 @@ FORMS += mainwindow.ui \ dbcloadsavewindow.ui \ fuzzingwindow.ui \ udsscanwindow.ui \ - isotp_interpreterwindow.ui + isotp_interpreterwindow.ui \ + snifferwindow.ui DISTFILES += From 5162769712f3b69895f26154e64a0ebefd08704b Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 8 Jul 2016 11:01:53 +0200 Subject: [PATCH 60/86] bug fix: use after free --- canframemodel.cpp | 9 +++++++++ canframemodel.h | 1 + mainwindow.cpp | 7 +++---- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index e1cb200..799ae10 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -3,6 +3,15 @@ #include #include "utility.h" + +CANFrameModel::~CANFrameModel() +{ + frames.clear(); + filteredFrames.clear(); + filters.clear(); +} + + int CANFrameModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); diff --git a/canframemodel.h b/canframemodel.h index 57e6e6a..f69858a 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -16,6 +16,7 @@ class CANFrameModel: public QAbstractTableModel public: CANFrameModel(QObject *parent = 0); + virtual ~CANFrameModel(); int rowCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; diff --git a/mainwindow.cpp b/mainwindow.cpp index d5826c0..27546b4 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -273,12 +273,11 @@ MainWindow::~MainWindow() snifferWindow = NULL; } - delete elapsedTime; - delete ui; - delete dbcHandler; - model->clearFrames(); delete model; + delete elapsedTime; + delete dbcHandler; + delete ui; } void MainWindow::exitApp() From d36b437239f57a0c3f58a76d9482c87828a40663 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Fri, 8 Jul 2016 11:02:23 +0200 Subject: [PATCH 61/86] optimization --- re/sniffer/snifferitem.cpp | 6 +-- re/sniffer/sniffermodel.cpp | 95 +++++++++++++++++++------------------ 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/re/sniffer/snifferitem.cpp b/re/sniffer/snifferitem.cpp index 0fe870b..af8bee1 100644 --- a/re/sniffer/snifferitem.cpp +++ b/re/sniffer/snifferitem.cpp @@ -4,9 +4,9 @@ SnifferItem::SnifferItem(const CANFrame& pFrame): - mNotch(0) + mNotch(0), + mID(pFrame.ID) { - mID = pFrame.ID; mMarker = {0,0}; mLastMarker = {0,0}; /* that's dirty */ @@ -65,7 +65,7 @@ void SnifferItem::update(const CANFrame& pFrame) /* update marker */ mMarker.data |= mLast.data ^ mCurrent.data; - mMarker.len |= mLast.len ^ mCurrent.data; + mMarker.len |= mLast.len ^ mCurrent.len; /* restart timeout */ mTime.restart(); diff --git a/re/sniffer/sniffermodel.cpp b/re/sniffer/sniffermodel.cpp index a762346..3bedbbc 100644 --- a/re/sniffer/sniffermodel.cpp +++ b/re/sniffer/sniffermodel.cpp @@ -11,7 +11,9 @@ SnifferModel::SnifferModel(QObject *parent) SnifferModel::~SnifferModel() { - clear(); + qDeleteAll(mMap); + mMap.clear(); + mFilters.clear(); } @@ -33,58 +35,53 @@ QVariant SnifferModel::data(const QModelIndex &index, int role) const if (!index.isValid()) return QVariant(); - const QMap& map = mFilter ? mFilters : mMap; + SnifferItem *item = static_cast(index.internalPointer()); + if(!item) QVariant(); - if(index.row()<=map.size()) + int col = index.column(); + + switch(role) { - quint64 key = map.keys()[index.row()]; - SnifferItem* item = map[key]; - - int col = index.column(); - - switch(role) + case Qt::DisplayRole: { - case Qt::DisplayRole: + switch(col) { - switch(col) + case tc::DELTA: + return QString::number(item->getDelta(), 'f'); + case tc::ID: + return QString("%1").arg(item->getId(), 5, 16, QLatin1Char(' ')).toUpper(); + default: + break; + } + if(tc::DATA_0<=col && col <=tc::DATA_7) + { + int data = item->getData(col-tc::DATA_0); + if(data>=0) + return QString("%1").arg(data, 2, 16, QLatin1Char('0')).toUpper(); + } + break; + } + case Qt::BackgroundRole: + { + if(tc::ID==col) + { + if(item->elapsed()>4000) + return QBrush(Qt::red); + } + else if(tc::DATA_0<=col && col<=tc::DATA_7) + { + dc change = item->dataChange(col-tc::DATA_0); + switch(change) { - case tc::DELTA: - return QString::number(item->getDelta(), 'f'); - case tc::ID: - return QString("%1").arg(item->getId(), 5, 16, QLatin1Char(' ')).toUpper(); + case dc::INC: + return QBrush(Qt::green); + case dc::DEC: + return QBrush(Qt::red); default: break; } - if(tc::DATA_0<=col && col <=tc::DATA_7) - { - int data = item->getData(col-tc::DATA_0); - if(data>=0) - return QString("%1").arg(data, 2, 16, QLatin1Char('0')).toUpper(); - } - break; - } - case Qt::BackgroundRole: - { - if(tc::ID==col) - { - if(item->elapsed()>4000) - return QBrush(Qt::red); - } - else if(tc::DATA_0<=col && col<=tc::DATA_7) - { - dc change = item->dataChange(col-tc::DATA_0); - switch(change) - { - case dc::INC: - return QBrush(Qt::green); - case dc::DEC: - return QBrush(Qt::red); - default: - break; - } - } - break; } + break; } } @@ -122,8 +119,7 @@ QVariant SnifferModel::headerData(int section, Qt::Orientation orientation, int } -QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) - const +QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); @@ -133,7 +129,12 @@ QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) if(column>tc::LAST || row>=map.size()) return QModelIndex(); - return createIndex(row, column); + /* ugly but I can't find best without creating a list to keep indexes */ + QMap::const_iterator iter; + int i; + for(iter = map.begin(), i=0 ; i Date: Fri, 8 Jul 2016 11:24:21 +0200 Subject: [PATCH 62/86] bug fix: race condition --- re/sniffer/sniffermodel.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/re/sniffer/sniffermodel.cpp b/re/sniffer/sniffermodel.cpp index 3bedbbc..031b487 100644 --- a/re/sniffer/sniffermodel.cpp +++ b/re/sniffer/sniffermodel.cpp @@ -150,9 +150,8 @@ void SnifferModel::clear() qDeleteAll(mMap); mMap.clear(); mFilters.clear(); - endResetModel(); - mFilter = false; + endResetModel(); } From 1e3192fc48f9af4da1a8d985b78d35cfdaa70011 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Mon, 18 Jul 2016 17:12:14 +0200 Subject: [PATCH 63/86] removed extra "\r" --- canframemodel.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index 799ae10..fa3aba7 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -227,15 +227,15 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const DBC_MESSAGE *msg = dbcHandler->findMessage(thisFrame); if (msg != NULL) { - tempString.append("\r\n"); - tempString.append(msg->name + " " + msg->comment + "\r\n"); + tempString.append("\n"); + tempString.append(msg->name + " " + msg->comment + "\n"); for (int j = 0; j < msg->sigHandler->getCount(); j++) { QString sigString; if (msg->sigHandler->findSignalByIdx(j)->processAsText(thisFrame, sigString)) { tempString.append(sigString); - tempString.append("\r\n"); + tempString.append("\n"); } } } From 0bfdfb740321ffd02a1c2eb7d7bb0f2659b88e91 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Mon, 18 Jul 2016 17:14:14 +0200 Subject: [PATCH 64/86] bug fix when changing MsgID --- dbcmaineditor.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/dbcmaineditor.cpp b/dbcmaineditor.cpp index 596346e..118f07c 100644 --- a/dbcmaineditor.cpp +++ b/dbcmaineditor.cpp @@ -259,17 +259,16 @@ void DBCMainEditor::onCellChangedMessage(int row,int col) } } dbcFile->messageHandler->addMessage(newMsg); + + /* insert message in table */ + inhibitCellChanged = true; + replacement = new QTableWidgetItem(Utility::formatNumber(msgID)); + replacement->setFlags(replacement->flags() ^ Qt::ItemIsEditable); + ui->MessagesTable->setItem(row, col, replacement); + replacement = new QTableWidgetItem(QString::number(newMsg.len)); + ui->MessagesTable->setItem(row, 2, replacement); + inhibitCellChanged = false; } - else //editing an existing record - { - if (msg != NULL) msg->ID = msgID; - } - inhibitCellChanged = true; - replacement = new QTableWidgetItem(Utility::formatNumber(msgID)); - ui->MessagesTable->setItem(row, col, replacement); - replacement = new QTableWidgetItem(QString::number(newMsg.len)); - ui->MessagesTable->setItem(row, 2, replacement); - inhibitCellChanged = false; break; case 1: //msg name From 72ee2148128298b21cc50b2efa08ccf50b0ae0e1 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Tue, 19 Jul 2016 10:33:53 +0200 Subject: [PATCH 65/86] simplification of messagestable management --- dbcmaineditor.cpp | 192 ++++++++++++++++++++++------------------------ dbcmaineditor.h | 1 + 2 files changed, 93 insertions(+), 100 deletions(-) diff --git a/dbcmaineditor.cpp b/dbcmaineditor.cpp index 118f07c..d51fcc1 100644 --- a/dbcmaineditor.cpp +++ b/dbcmaineditor.cpp @@ -5,6 +5,8 @@ #include #include +#define MT_COLUMN_COUNT 5 + DBCMainEditor::DBCMainEditor(DBCHandler *handler, const QVector *frames, QWidget *parent) : QDialog(parent), ui(new Ui::DBCMainEditor) @@ -26,7 +28,7 @@ DBCMainEditor::DBCMainEditor(DBCHandler *handler, const QVector *frame QStringList headers2; headers2 << "Msg ID" << "Msg Name" << "Data Len" << "Signals" << "Comment"; - ui->MessagesTable->setColumnCount(5); + ui->MessagesTable->setColumnCount(MT_COLUMN_COUNT); ui->MessagesTable->setColumnWidth(0, 80); ui->MessagesTable->setColumnWidth(1, 240); ui->MessagesTable->setColumnWidth(2, 80); @@ -210,49 +212,57 @@ void DBCMainEditor::onCellChangedNode(int row,int col) void DBCMainEditor::onCellChangedMessage(int row,int col) { + QTableWidgetItem* item = NULL; + bool ret = false; + DBC_MESSAGE *msg = NULL; + uint msgID; + if (inhibitCellChanged) return; - qDebug() << "Editing row: " << row << " col: " << col; - - QTableWidgetItem *replacement = NULL; - int msgID; - QString msgName; - int msgLen; - QString msgComment; - DBC_MESSAGE newMsg; DBC_NODE *node = dbcFile->findNodeByIdx(ui->NodesTable->currentRow()); - DBC_MESSAGE *msg; if (node == NULL) { qDebug() << "No node set?!? This is bad!"; return; - //dbcHandler->findNodeByIdx(0); } - msgID = Utility::ParseStringToNum(ui->MessagesTable->item(row, 0)->text()); - qDebug() << "Msg ID of edited: " << msgID; + item = ui->MessagesTable->item(row, 0); + if(!item) return; + + msgID = Utility::ParseStringToNum2(item->text(), &ret); msg = dbcFile->messageHandler->findMsgByID(msgID); switch(col) { - case 0: //msg id - if (row == ui->MessagesTable->rowCount() - 1) //new record - { - if (dbcFile->messageHandler->findMsgByID(msgID) != NULL) + case 0: //msg id + { + /* sanity checks */ + if(!ret) + { + /* bad message id */ + ui->MessagesTable->item(row, 0)->setText(""); + return; + } + if (msg != NULL) { 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; for (int i = 0; i < referenceFrames->length(); i++) { - if (referenceFrames->at(i).ID == msgID) + if ((uint) referenceFrames->at(i).ID == msgID) { newMsg.len = referenceFrames->at(i).len; break; @@ -262,95 +272,65 @@ void DBCMainEditor::onCellChangedMessage(int row,int col) /* insert message in table */ inhibitCellChanged = true; - replacement = new QTableWidgetItem(Utility::formatNumber(msgID)); - replacement->setFlags(replacement->flags() ^ Qt::ItemIsEditable); - ui->MessagesTable->setItem(row, col, replacement); - replacement = new QTableWidgetItem(QString::number(newMsg.len)); - ui->MessagesTable->setItem(row, 2, replacement); - inhibitCellChanged = false; - } - break; - case 1: //msg name - msgName = ui->MessagesTable->item(row, col)->text().simplified().replace(' ', '_'); - if (msgName.length() == 0) return; - if (row == ui->MessagesTable->rowCount() - 1) //new record - { - if (dbcFile->messageHandler->findMsgByName(msgName) != NULL) + item = ui->MessagesTable->item(row, 0); + item->setFlags(item->flags() & ~Qt::ItemIsEditable); + item->setText(Utility::formatNumber(msgID)); + + for(int i=1 ; iMessagesTable->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!=NULL) ) + 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; } - newMsg.ID = -1; - newMsg.name = msgName; - newMsg.sender = node; - dbcFile->messageHandler->addMessage(newMsg); - } - else - { - if (msg != NULL) msg->name = msgName; - } - inhibitCellChanged = true; - replacement = new QTableWidgetItem(msgName); - ui->MessagesTable->setItem(row, col, replacement); - inhibitCellChanged = false; - break; + if (msgLen > 8) + { + msgLen = 8; + ui->MessagesTable->item(row, col)->setText(QString::number(msgLen)); + } - case 2: //data length - msgLen = ui->MessagesTable->item(row, col)->text().toInt(); - if (msgLen < 0) msgLen = 0; - if (msgLen > 8) msgLen = 8; - if (row == ui->MessagesTable->rowCount() - 1) //new record - { - DBC_MESSAGE newMsg; - newMsg.ID = -1; - newMsg.name = ""; - newMsg.len = msgLen; - newMsg.sender = node; - dbcFile->messageHandler->addMessage(newMsg); + if( ret && (msg!=NULL) ) + msg->len = msgLen; + break; } - else //editing an existing record + case 3: //signals (number) - we don't handle anything here. User cannot directly change this value + break; + case 4: //comment { - if (msg != NULL) msg->len = msgLen; + QString msgComment = ui->MessagesTable->item(row, col)->text().simplified(); + if( ret && (msgComment!=NULL) ) + msg->comment = msgComment; + break; } - inhibitCellChanged = true; - replacement = new QTableWidgetItem(QString::number(msgLen, 16)); - ui->MessagesTable->setItem(row, col, replacement); - inhibitCellChanged = false; - - break; - case 3: //signals (number) - we don't handle anything here. User cannot directly change this value - break; - case 4: //comment - msgComment = ui->MessagesTable->item(row, col)->text().simplified(); - if (row == ui->MessagesTable->rowCount() - 1) //new record - { - DBC_MESSAGE newMsg; - newMsg.ID = -1; - newMsg.name = ""; - newMsg.len = 0; - newMsg.comment = msgComment; - newMsg.sender = node; - dbcFile->messageHandler->addMessage(newMsg); - } - else //editing an existing record - { - if (msg != NULL) msg->comment = msgComment; - } - inhibitCellChanged = true; - replacement = new QTableWidgetItem(msgComment); - ui->MessagesTable->setItem(row, col, replacement); - inhibitCellChanged = false; - break; - - } - - if (row == ui->MessagesTable->rowCount() - 1) - { - ui->MessagesTable->insertRow(ui->MessagesTable->rowCount()); } ui->MessagesTable->setCurrentCell(row, col); @@ -465,5 +445,17 @@ void DBCMainEditor::refreshMessagesTable(const DBC_NODE *node) } //insert blank record that can be used to add new messages - ui->MessagesTable->insertRow(ui->MessagesTable->rowCount()); + insertBlankRow(); +} + +void DBCMainEditor::insertBlankRow() +{ + int rowIdx = ui->MessagesTable->rowCount(); + ui->MessagesTable->insertRow(rowIdx); + for(int i=1 ; isetFlags(item->flags() & ~Qt::ItemIsEditable); + ui->MessagesTable->setItem(rowIdx, i, item); + } } diff --git a/dbcmaineditor.h b/dbcmaineditor.h index 07e8e11..4067693 100644 --- a/dbcmaineditor.h +++ b/dbcmaineditor.h @@ -46,6 +46,7 @@ private: void closeEvent(QCloseEvent *event); void readSettings(); void writeSettings(); + void insertBlankRow(); }; From 7bede56e6892711f2dba5d085728e52eea77a327 Mon Sep 17 00:00:00 2001 From: canpadawan Date: Tue, 19 Jul 2016 10:34:43 +0200 Subject: [PATCH 66/86] add temporary ParseStringToNum2 --- utility.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/utility.h b/utility.h index d5614e8..e2792ad 100644 --- a/utility.h +++ b/utility.h @@ -23,7 +23,7 @@ public: if (input.length() < 3) temp = 0; else temp = input.right(input.size() - 2).toLongLong(NULL, 16); } - else if (input.startsWith("B")) //binary number + else if (input.startsWith("0B") || input.startsWith("B")) //binary number { input = input.right(input.size() - 1); //remove the B for (int i = 0; i < input.length(); i++) @@ -44,6 +44,17 @@ public: return ParseStringToNum(input.toUtf8()); } + static uint ParseStringToNum2(QString pInput, bool* pOk_p = NULL) + { + if(pInput.startsWith("0b")) + { + pInput.remove(0, 2); + return pInput.toUInt(pOk_p, 2); + } + + return pInput.toUInt(pOk_p, 0); + } + static long GetTimeMS() { QDateTime stamp = QDateTime::currentDateTime(); From 4885b4b24bb61b7927550e24f70f8880375fad76 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Mon, 8 Aug 2016 15:30:33 -0400 Subject: [PATCH 67/86] Updated version number --- config.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.h b/config.h index 5b093e6..f9f4eb6 100644 --- a/config.h +++ b/config.h @@ -1,7 +1,7 @@ #ifndef CONFIG #define CONFIG -#define VERSION 155 +#define VERSION 160 //try to keep this in sync. //SavvyCAN will complain if you connect a GVRET board with a revision From b4c8aa49db50f46c56f34225c5bf71f3ead2463a Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 9 Aug 2016 20:03:57 -0400 Subject: [PATCH 68/86] First pass at turning on functionality to allow frame sending from the new connection system. The fuzzing window has been modified to use the new system. This validates that it mostly works now. More screens will be modified to work soon. --- canconnectionmodel.cpp | 3 +- connections/canconmanager.cpp | 54 +++++++++++++++++++++++++++++++++++ connections/canconmanager.h | 13 +++++++++ connections/gvretserial.cpp | 47 +++++++++++++++++++++++++++++- fuzzingwindow.cpp | 27 +++++++++++------- mainwindow.cpp | 4 +-- 6 files changed, 132 insertions(+), 16 deletions(-) diff --git a/canconnectionmodel.cpp b/canconnectionmodel.cpp index 084d2cc..b7216aa 100644 --- a/canconnectionmodel.cpp +++ b/canconnectionmodel.cpp @@ -96,7 +96,8 @@ QVariant CANConnectionModel::data(const QModelIndex &index, int role) const switch (index.column()) { case 0: //bus - return QString::number(busId); + //return QString::number(busId); + return QString::number(index.row()); break; case 1: //type if (conn_p) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 5f645d1..33c4892 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -41,6 +41,16 @@ void CANConManager::remove(CANConnection* pConn_p) mConns.removeOne(pConn_p); } +//Get total number of buses currently registered with the program +int CANConManager::getNumBuses() +{ + int buses = 0; + foreach(CANConnection* conn_p, mConns) + { + buses += conn_p->getNumBuses(); + } + return buses; +} void CANConManager::refreshCanList() { @@ -92,3 +102,47 @@ void CANConManager::refreshConnection(CANConnection* pConn_p) if(frames.size()) emit framesReceived(pConn_p, frames); } + +/* + * Uses the requested bus to look up which CANConnection object handles this bus based on the order of + * the objects and how many buses they implement. For instance, if the request is to send on bus 2 + * and there is a GVRET object first then a socketcan object it'll send on the socketcan object as + * gvret will have claimed buses 0 and 1 and socketcan bus 2. But, each actual CANConnection expects + * its own bus numbers to start at zero so the frame bus number has to be offset accordingly. + * Also keep in mind that the CANConnection "sendFrame" function uses a blocking queued connection + * and so will force the frame to be delivered before it keeps going. This allows on the stack variables + * to be used but is slow. This function uses an on the stack copy of the frame so the way it works + * is a good thing but performance will suffer. TODO: Investigate a way to use non-blocking calls. +*/ +bool CANConManager::sendFrame(const CANFrame& pFrame) +{ + int busBase = 0; + CANFrame workingFrame = pFrame; + CANFrame *txFrame; + + foreach (CANConnection* conn, mConns) + { + //check if this CAN connection is supposed to handle the requested bus + if (pFrame.bus <= busBase + conn->getNumBuses()) + { + workingFrame.bus -= busBase; + txFrame = conn->getQueue().get(); + *txFrame = workingFrame; + conn->getQueue().queue(); + return conn->sendFrame(workingFrame); + } + busBase += conn->getNumBuses(); + } + return false; +} + +bool CANConManager::sendFrames(const QList& pFrames) +{ + foreach(const CANFrame& frame, pFrames) + { + if(!sendFrame(frame)) + return false; + } + + return true; +} diff --git a/connections/canconmanager.h b/connections/canconmanager.h index 66896f1..d9c7e40 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -20,6 +20,19 @@ public: CANConnection* getByName(const QString& pName) const; + int getNumBuses(); + + /** + * @brief sendFrame sends a single frame out the desired bus + * @param pFrame - reference to a CANFrame struct that has been filled out for sending + * @return bool specifying whether the send succeeded or not + * @note Finds which CANConnection object is responsible for this bus and automatically converts bus number to pass properly to CANConnection + */ + bool sendFrame(const CANFrame& pFrame); + + //just the multi-frame version of above function. + bool sendFrames(const QList& pFrames); + signals: void framesReceived(CANConnection* pConn_p, QVector& pFrames); diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index d9408b3..c76a5ee 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -141,7 +141,52 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) } -bool GVRetSerial::piSendFrame(const CANFrame&) {return false;} +bool GVRetSerial::piSendFrame(const CANFrame& frame) +{ + QByteArray buffer; + int c; + int ID; + CANFrame tempFrame = frame; + tempFrame.isReceived = false; + tempFrame.timestamp = ((QDateTime::currentMSecsSinceEpoch() - txTimestampBasis) * 1000); + + //qDebug() << "Sending out frame with id " << frame->ID; + + //show our sent frames in the list too. This happens even if we're not connected. + /* model lives in UI thread, we need to call invokeMethod */ + //QMetaObject::invokeMethod(model, "addFrame", + // Qt::QueuedConnection, + // Q_ARG(CANFrame, tempFrame), + // Q_ARG(bool, false)); + + framesRapid++; + + if (serial == NULL) return false; + if (!serial->isOpen()) return false; + //if (!isConnected) return false; + + ID = frame.ID; + if (frame.extended) ID |= 1 << 31; + + 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) & 1); + buffer[7] = (unsigned char)frame.len; + for (c = 0; c < frame.len; c++) + { + buffer[8 + c] = frame.data[c]; + } + buffer[8 + frame.len] = 0; + + //qDebug() << "writing " << buffer.length() << " bytes to serial port"; + serial->write(buffer); + + return true; +} diff --git a/fuzzingwindow.cpp b/fuzzingwindow.cpp index 45e564c..0ae427f 100644 --- a/fuzzingwindow.cpp +++ b/fuzzingwindow.cpp @@ -3,6 +3,7 @@ #include "utility.h" #include #include "mainwindow.h" +#include "connections/canconmanager.h" FuzzingWindow::FuzzingWindow(const QVector *frames, QWidget *parent) : QDialog(parent), @@ -36,9 +37,10 @@ FuzzingWindow::FuzzingWindow(const QVector *frames, QWidget *parent) : fuzzTimer->setInterval(ui->spinTiming->value()); - ui->cbBuses->addItem(tr("0")); - ui->cbBuses->addItem(tr("1")); - ui->cbBuses->addItem(tr("Both")); + int numBuses = CANConManager::getInstance()->getNumBuses(); + for (int n = 0; n < numBuses; n++) ui->cbBuses->addItem(QString::number(n)); + ui->cbBuses->addItem(tr("All")); + } FuzzingWindow::~FuzzingWindow() @@ -111,8 +113,7 @@ void FuzzingWindow::timerTriggered() { CANFrame thisFrame; sendingBuffer.clear(); - int buses = ui->cbBuses->currentIndex() + 1; - if (buses == 0) buses = 1; + int buses = ui->cbBuses->currentIndex(); for (int count = 0; count < ui->spinBurst->value(); count++) { thisFrame.ID = currentID; @@ -121,22 +122,26 @@ void FuzzingWindow::timerTriggered() else thisFrame.extended = false; thisFrame.bus = 0; //hard coded for now. TODO: do not hard code thisFrame.len = ui->spinBytes->value(); - if (buses & 1) + + if (buses < (ui->cbBuses->count() - 1)) { - thisFrame.bus = 0; + thisFrame.bus = buses; sendingBuffer.append(thisFrame); } - if (buses & 2) + else //fuzz all the buses! HACK THE PLANET! Er, something... { - thisFrame.bus = 1; - sendingBuffer.append(thisFrame); + for (int j = 0; j < ui->cbBuses->count() - 1; j++) + { + thisFrame.bus = j; + sendingBuffer.append(thisFrame); + } } calcNextID(); calcNextBitPattern(); numSentFrames++; } - emit sendFrameBatch(&sendingBuffer); + CANConManager::getInstance()->sendFrames(sendingBuffer); ui->lblNumFrames->setText("# of sent frames: " + QString::number(numSentFrames)); } diff --git a/mainwindow.cpp b/mainwindow.cpp index 27546b4..802d571 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -918,8 +918,6 @@ void MainWindow::showFuzzingWindow() if (!fuzzingWindow) { fuzzingWindow = new FuzzingWindow(model->getListReference()); - connect(fuzzingWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); - connect(fuzzingWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*))); } fuzzingWindow->show(); } @@ -929,7 +927,7 @@ void MainWindow::showUDSScanWindow() if (!udsScanWindow) { udsScanWindow = new UDSScanWindow(model->getListReference()); - connect(udsScanWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), connectionWindow, SLOT(sendFrame(const CANFrame*))); + //connect(udsScanWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), connectionWindow, SLOT(sendFrame(const CANFrame*))); } udsScanWindow->show(); } From 42d3223474d22815dd839eea63aa359427c22727 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 8 Dec 2016 20:19:24 -0500 Subject: [PATCH 69/86] Fixes to DBC editor (from Viaccess-Orca commit) --- dbcmaineditor.cpp | 1 + dbcsignaleditor.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/dbcmaineditor.cpp b/dbcmaineditor.cpp index d51fcc1..16fe836 100644 --- a/dbcmaineditor.cpp +++ b/dbcmaineditor.cpp @@ -405,6 +405,7 @@ void DBCMainEditor::refreshNodesTable() //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) diff --git a/dbcsignaleditor.cpp b/dbcsignaleditor.cpp index 9792439..b3a5acf 100644 --- a/dbcsignaleditor.cpp +++ b/dbcsignaleditor.cpp @@ -348,6 +348,10 @@ void DBCSignalEditor::addNewSignal() void DBCSignalEditor::deleteCurrentSignal() { int currIdx = ui->signalsList->currentRow(); + + if(currIdx==ui->signalsList->count()-1) + return; + if (currIdx > -1) { delete(ui->signalsList->item(currIdx)); From 2cfacc651991ad6c720d2a4924dabb5e4306fe3d Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 8 Dec 2016 20:21:24 -0500 Subject: [PATCH 70/86] A few small fixes to connection window --- connections/canconmanager.cpp | 14 ++++++++++++++ connectionwindow.cpp | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 33c4892..4092f86 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -94,7 +94,19 @@ void CANConManager::refreshConnection(CANConnection* pConn_p) CANFrame* frame_p = NULL; QVector frames; + //Each connection only knows about its own bus numbers + //so this variable is used to fix that up to turn local bus numbers + //into system global bus numbers for display. + int busBase = 0; + + foreach (CANConnection* conn, mConns) + { + if (conn != pConn_p) busBase += conn->getNumBuses(); + else break; + } + while( (frame_p = pConn_p->getQueue().peek() ) ) { + frame_p->bus += busBase; frames.append(*frame_p); pConn_p->getQueue().dequeue(); } @@ -126,6 +138,7 @@ bool CANConManager::sendFrame(const CANFrame& pFrame) if (pFrame.bus <= busBase + conn->getNumBuses()) { workingFrame.bus -= busBase; + workingFrame.isReceived = false; txFrame = conn->getQueue().get(); *txFrame = workingFrame; conn->getQueue().queue(); @@ -138,6 +151,7 @@ bool CANConManager::sendFrame(const CANFrame& pFrame) bool CANConManager::sendFrames(const QList& pFrames) { + qDebug() << "CANConManager sendFrames #" << pFrames.count(); foreach(const CANFrame& frame, pFrames) { if(!sendFrame(frame)) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index f5a3904..d5c61b3 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -85,6 +85,7 @@ void ConnectionWindow::showEvent(QShowEvent* event) QDialog::showEvent(event); qDebug() << "Show connectionwindow"; ui->tableConnections->selectRow(0); + currentRowChanged(ui->tableConnections->currentIndex(), ui->tableConnections->currentIndex()); } @@ -462,6 +463,10 @@ void ConnectionWindow::loadConnections() /* add connection to model */ connModel->add(conn_p); } + + if (connModel->rowCount() > 0) { + ui->tableConnections->selectRow(0); + } } void ConnectionWindow::saveConnections() From ddfac100d24c8fd3cd4b504f01160a7bfa280f25 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 8 Dec 2016 20:21:42 -0500 Subject: [PATCH 71/86] Changed sending windows to use new system where there are arbitrary number of buses --- frameplaybackwindow.cpp | 45 +++++++++++++++++++++-------------------- frameplaybackwindow.h | 4 ---- framesenderwindow.cpp | 5 +++-- framesenderwindow.h | 3 --- mainwindow.cpp | 6 ------ scriptcontainer.h | 3 --- scriptingwindow.h | 2 -- udsscanwindow.cpp | 40 ++++++++++++++++++++---------------- udsscanwindow.h | 3 --- 9 files changed, 49 insertions(+), 62 deletions(-) diff --git a/frameplaybackwindow.cpp b/frameplaybackwindow.cpp index da46ac2..f2f631d 100644 --- a/frameplaybackwindow.cpp +++ b/frameplaybackwindow.cpp @@ -4,6 +4,7 @@ #include #include #include +#include "connections/canconmanager.h" /* * Notes about new functionality: @@ -24,10 +25,10 @@ FramePlaybackWindow::FramePlaybackWindow(const QVector *frames, QWidge { ui->setupUi(this); - ui->comboCANBus->addItem(tr("None")); - ui->comboCANBus->addItem(tr("0")); - ui->comboCANBus->addItem(tr("1")); - ui->comboCANBus->addItem(tr("Both")); + + int numBuses = CANConManager::getInstance()->getNumBuses(); + for (int n = 0; n < numBuses; n++) ui->comboCANBus->addItem(QString::number(n)); + ui->comboCANBus->addItem(tr("All")); ui->comboCANBus->addItem(tr("From File")); readSettings(); @@ -399,7 +400,7 @@ void FramePlaybackWindow::btnBackOneClick() playbackActive = false; updatePosition(false); - emit sendFrameBatch(&sendingBuffer); + CANConManager::getInstance()->sendFrames(sendingBuffer); } void FramePlaybackWindow::btnPauseClick() @@ -450,7 +451,7 @@ void FramePlaybackWindow::btnFwdOneClick() playbackTimer->stop(); playbackActive = false; updatePosition(true); - emit sendFrameBatch(&sendingBuffer); + CANConManager::getInstance()->sendFrames(sendingBuffer); } void FramePlaybackWindow::changePlaybackSpeed(int newSpeed) @@ -465,8 +466,6 @@ void FramePlaybackWindow::changeLooping(bool check) void FramePlaybackWindow::changeSendingBus(int newIdx) { - //falls out neatly this way. 0 = no sending, 1 = bus 0, 2 = bus 1, 3 = both, 4 = from file - //the index is exactly the same as the whichSendBus bitfield. whichBusSend = newIdx; } @@ -516,7 +515,7 @@ void FramePlaybackWindow::timerTriggered() updatePosition(false); } } - emit sendFrameBatch(&sendingBuffer); + CANConManager::getInstance()->sendFrames(sendingBuffer); } void FramePlaybackWindow::updatePosition(bool forward) @@ -590,23 +589,25 @@ void FramePlaybackWindow::updatePosition(bool forward) int originalBus = thisFrame->bus; if (currentSeqItem->idFilters.find(thisFrame->ID).value()) { - //index 0 is none, 1 is Bus 0, 2 is bus 1, 3 is both, 4 is from file - if (whichBusSend & 4) + if (whichBusSend < ui->comboCANBus->count() - 2) + { + thisFrame->bus = whichBusSend; + sendingBuffer.append(*thisFrame); + } + else if (whichBusSend = ui->comboCANBus->count() - 2) //all + { + for (int c = 0; c < ui->comboCANBus->count() - 2; c++) + { + thisFrame->bus = c; + sendingBuffer.append(*thisFrame); + } + } + else //from file so retain original bus and send as-is { sendingBuffer.append(*thisFrame); } - if (whichBusSend & 1) - { - thisFrame->bus = 0; - sendingBuffer.append(*thisFrame); - } - if (whichBusSend & 2) - { - thisFrame->bus = 1; - sendingBuffer.append(*thisFrame); - } + thisFrame->bus = originalBus; updateFrameLabel(); } - } diff --git a/frameplaybackwindow.h b/frameplaybackwindow.h index 2c82753..af3e5e2 100644 --- a/frameplaybackwindow.h +++ b/frameplaybackwindow.h @@ -53,10 +53,6 @@ private slots: void saveFilters(); void loadFilters(); -signals: - void sendCANFrame(const CANFrame *); - void sendFrameBatch(const QList *); - private: Ui::FramePlaybackWindow *ui; QList foundID; diff --git a/framesenderwindow.cpp b/framesenderwindow.cpp index e5b722c..77b3490 100644 --- a/framesenderwindow.cpp +++ b/framesenderwindow.cpp @@ -5,6 +5,7 @@ #include #include #include "mainwindow.h" +#include "connections/canconmanager.h" /* * notes: need to ensure that you grab pointers when modifying data structures and dont @@ -151,7 +152,7 @@ void FrameSenderWindow::processIncomingFrame(CANFrame *frame) sendingData[sd].count++; doModifiers(sd); updateGridRow(sd); - sendCANFrame(&sendingData[sd]); + CANConManager::getInstance()->sendFrame(sendingData[sd]); } else //delayed sending frame { @@ -354,7 +355,7 @@ void FrameSenderWindow::handleTick() doModifiers(i); updateGridRow(i); qDebug() << "About to try to send a frame"; - emit sendCANFrame(&sendingData[i]); + CANConManager::getInstance()->sendFrame(sendingData[i]); if (trigger->ID > 0) trigger->readyCount = false; //reset flag if this is a timed ID trigger } } diff --git a/framesenderwindow.h b/framesenderwindow.h index 5560e9e..57642e8 100644 --- a/framesenderwindow.h +++ b/framesenderwindow.h @@ -30,9 +30,6 @@ private slots: void loadGrid(); void updatedFrames(int); -signals: - void sendCANFrame(const CANFrame *); - private: Ui::FrameSenderWindow *ui; QList sendingData; diff --git a/mainwindow.cpp b/mainwindow.cpp index 802d571..53f3e0b 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -863,8 +863,6 @@ void MainWindow::showFrameSenderWindow() frameSenderWindow = new FrameSenderWindow(model->getListReference()); else frameSenderWindow = new FrameSenderWindow(model->getFilteredListReference()); - - //connect(frameSenderWindow, &FrameSenderWindow::sendCANFrame, connectionWindow, &ConnectionWindow::sendFrame); } frameSenderWindow->show(); } @@ -877,9 +875,6 @@ void MainWindow::showPlaybackWindow() playbackWindow = new FramePlaybackWindow(model->getListReference()); else playbackWindow = new FramePlaybackWindow(model->getFilteredListReference()); - - //connect(playbackWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*)), Qt::QueuedConnection); - //connect(playbackWindow, SIGNAL(sendFrameBatch(const QList*)), connectionWindow, SLOT(sendFrameBatch(const QList*)), Qt::QueuedConnection); } playbackWindow->show(); } @@ -927,7 +922,6 @@ void MainWindow::showUDSScanWindow() if (!udsScanWindow) { udsScanWindow = new UDSScanWindow(model->getListReference()); - //connect(udsScanWindow, SIGNAL(sendCANFrame(const CANFrame*,int)), connectionWindow, SLOT(sendFrame(const CANFrame*))); } udsScanWindow->show(); } diff --git a/scriptcontainer.h b/scriptcontainer.h index 75caec2..241ac23 100644 --- a/scriptcontainer.h +++ b/scriptcontainer.h @@ -32,9 +32,6 @@ public slots: private slots: void tick(); -signals: - void sendCANFrame(const CANFrame *); - private: QJSEngine scriptEngine; QJSValue compiledScript; diff --git a/scriptingwindow.h b/scriptingwindow.h index 6713460..38519d9 100644 --- a/scriptingwindow.h +++ b/scriptingwindow.h @@ -40,8 +40,6 @@ private: QList scripts; ScriptContainer *currentScript; const QVector *modelFrames; - - }; #endif // SCRIPTINGWINDOW_H diff --git a/udsscanwindow.cpp b/udsscanwindow.cpp index a4c4f6c..174a65c 100644 --- a/udsscanwindow.cpp +++ b/udsscanwindow.cpp @@ -1,6 +1,7 @@ #include "udsscanwindow.h" #include "ui_udsscanwindow.h" #include "mainwindow.h" +#include "connections/canconmanager.h" UDSScanWindow::UDSScanWindow(const QVector *frames, QWidget *parent) : QDialog(parent), @@ -20,10 +21,9 @@ UDSScanWindow::UDSScanWindow(const QVector *frames, QWidget *parent) : connect(ui->btnScan, &QPushButton::clicked, this, &UDSScanWindow::scanUDS); connect(waitTimer, &QTimer::timeout, this, &UDSScanWindow::timeOut); - ui->cbBuses->addItem("0"); - ui->cbBuses->addItem("1"); - ui->cbBuses->addItem("Both"); - + int numBuses = CANConManager::getInstance()->getNumBuses(); + for (int n = 0; n < numBuses; n++) ui->cbBuses->addItem(QString::number(n)); + ui->cbBuses->addItem(tr("All")); } UDSScanWindow::~UDSScanWindow() @@ -53,8 +53,6 @@ void UDSScanWindow::scanUDS() endID = Utility::ParseStringToNum(ui->txtEndID->text()); int buses = ui->cbBuses->currentIndex(); - buses++; - if (buses < 1) buses = 1; //start out by sending tester present to every address to see if anyone replies for (id = startID; id <= endID; id++) @@ -68,16 +66,20 @@ void UDSScanWindow::scanUDS() frame.data[3] = 0;frame.data[4] = 0;frame.data[5] = 0; frame.data[6] = 0;frame.data[7] = 0; - if (buses & 1) + if (buses < ui->cbBuses->count()- 1) { - frame.bus = 0; + frame.bus = buses; sendingFrames.append(frame); } - if (buses & 2) + else { - frame.bus = 1; - sendingFrames.append(frame); + for (int c = 0; c < ui->cbBuses->count() - 1; c++) + { + frame.bus = c; + sendingFrames.append(frame); + } } + } //then try asking for the various diagnostic session types @@ -94,15 +96,18 @@ void UDSScanWindow::scanUDS() frame.data[3] = 0;frame.data[4] = 0;frame.data[5] = 0; frame.data[6] = 0;frame.data[7] = 0; - if (buses & 1) + if (buses < ui->cbBuses->count()- 1) { - frame.bus = 0; + frame.bus = buses; sendingFrames.append(frame); } - if (buses & 2) + else { - frame.bus = 1; - sendingFrames.append(frame); + for (int c = 0; c < ui->cbBuses->count() - 1; c++) + { + frame.bus = c; + sendingFrames.append(frame); + } } } } @@ -129,6 +134,7 @@ void UDSScanWindow::updatedFrames(int numFrames) } //Updates here are nearly once per millisecond if there is heavy traffic. That's more like it! +//TODO: I really doubt this works anymore with the new connection system. This breaks the UDS scanner for now! ;( void UDSScanWindow::rapidFrames(int numFrames) { CANFrame thisFrame; @@ -210,7 +216,7 @@ void UDSScanWindow::sendNextMsg() currIdx++; if (currIdx < sendingFrames.count()) { - emit sendCANFrame(&sendingFrames[currIdx]); + CANConManager::getInstance()->sendFrame(sendingFrames[currIdx]); waitTimer->start(); } else diff --git a/udsscanwindow.h b/udsscanwindow.h index c53114b..4039345 100644 --- a/udsscanwindow.h +++ b/udsscanwindow.h @@ -17,9 +17,6 @@ public: explicit UDSScanWindow(const QVector *frames, QWidget *parent = 0); ~UDSScanWindow(); -signals: - void sendCANFrame(const CANFrame *); - private slots: void updatedFrames(int numFrames); void rapidFrames(int numFrames); From 43899976347358fc467f216312f2396c34a9f329 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 8 Dec 2016 20:57:39 -0500 Subject: [PATCH 72/86] Update README.md --- README.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ff088d2..0c19021 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # SavvyCAN QT based cross platform canbus tool -(C) 2015-2016 EVTV and Collin Kidder +(C) 2015-2017 EVTV and Collin Kidder A QT5 based cross platform tool which can be used to load, save, and capture canbus frames. This tool is designed to help with visualization, reverse engineering, debugging, and @@ -14,7 +14,7 @@ You are highly recommended to use the CANDue board from EVTV: The CANDue board must be running the GVRET firmware which can also be found within the collin80 repos. -It is very soon to be possible to use any SocketCAN compatible device +It is now possible to use any SocketCAN compatible device under LINUX. There may, however, be some loss of some functionality as some functions of SavvyCAN are designed for use directly with the EVTVDue and CANDue 2.0 boards. @@ -40,6 +40,10 @@ of this program. It can load and save in several formats: 9. Vehicle Spy log files +10. CANDump / Kayak (Read only) + +11. PCAN Viewer (Read Only) + Requires QScintilla library available at: https://www.riverbankcomputing.com/software/qscintilla/download @@ -50,18 +54,20 @@ http://www.qcustomplot.com/ However, this source code is integrated into the source for SavvyCAN and one isn't required to download it separately. -This project will soon require 5.6.0 or higher because of an upcoming dependency on QSerialBus but currently -should compile with QT 5.5 +This project requires 5.6.0 or higher because of a dependency on QSerialBus which is an optional download +with QT 5.6 (so, be sure to select it) -Instructions for compiling with Ubuntu: +Instructions for compiling: -sudo apt-get install qt5-default qtdeclarative5-dev libqt5serialport5-dev libudev-dev +Download the newest stable version of Qt directly from qt.io (You need 5.6.x or newer) download and extract QScintilla (see above for link), assume it is extracted in QScintilla-gpl-2.9.1 cd ~/QScintilla-gpl-2.9.1/Qt4Qt5 -qmake qscintilla.pro +You will need to either put your copy of QT into your path or specify the path to qmake directly + +~/Qt/5.7/gcc_64/bin/qmake qscintilla.pro make @@ -75,7 +81,7 @@ git clone https://github.com/collin80/SavvyCAN.git cd SavvyCAN -qmake +~/Qt/5.7/gcc_64/bin/qmake make From d8ffbcaf5f1c581321bb121f233b1e16b2f846d1 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 8 Dec 2016 21:17:13 -0500 Subject: [PATCH 73/86] Fix to allow creation of a new connection even if another connection exists or the only connection was deleted. --- connectionwindow.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/connectionwindow.cpp b/connectionwindow.cpp index d5c61b3..e8e1477 100644 --- a/connectionwindow.cpp +++ b/connectionwindow.cpp @@ -122,6 +122,7 @@ void ConnectionWindow::setActiveAll(bool pActive) void ConnectionWindow::handleNewConn() { ui->tableConnections->setCurrentIndex(QModelIndex()); + currentRowChanged(ui->tableConnections->currentIndex(), ui->tableConnections->currentIndex()); } From 0b46f564ab0159dd3a8ee816e19c8ed3b868d5bd Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sun, 11 Dec 2016 21:06:41 -0500 Subject: [PATCH 74/86] Reorganized source code --- SavvyCAN.pro | 108 +++++++++--------- canframemodel.h | 2 +- dbc_classes.cpp => dbc/dbc_classes.cpp | 0 dbc_classes.h => dbc/dbc_classes.h | 0 dbchandler.cpp => dbc/dbchandler.cpp | 0 dbchandler.h => dbc/dbchandler.h | 0 .../dbcloadsavewindow.cpp | 0 .../dbcloadsavewindow.h | 0 dbcmaineditor.cpp => dbc/dbcmaineditor.cpp | 0 dbcmaineditor.h => dbc/dbcmaineditor.h | 0 .../dbcsignaleditor.cpp | 0 dbcsignaleditor.h => dbc/dbcsignaleditor.h | 0 graphingwindow.h | 2 +- mainwindow.h | 22 ++-- newgraphdialog.h | 2 +- .../discretestatewindow.cpp | 0 .../discretestatewindow.h | 0 .../filecomparatorwindow.cpp | 0 .../filecomparatorwindow.h | 0 flowviewwindow.cpp => re/flowviewwindow.cpp | 0 flowviewwindow.h => re/flowviewwindow.h | 0 frameinfowindow.cpp => re/frameinfowindow.cpp | 0 frameinfowindow.h => re/frameinfowindow.h | 0 fuzzingwindow.cpp => re/fuzzingwindow.cpp | 0 fuzzingwindow.h => re/fuzzingwindow.h | 0 isotp_handler.cpp => re/isotp_handler.cpp | 0 isotp_handler.h => re/isotp_handler.h | 0 .../isotp_interpreterwindow.cpp | 0 .../isotp_interpreterwindow.h | 0 .../rangestatewindow.cpp | 0 rangestatewindow.h => re/rangestatewindow.h | 0 udsscanwindow.cpp => re/udsscanwindow.cpp | 0 udsscanwindow.h => re/udsscanwindow.h | 0 candatagrid.ui => ui/candatagrid.ui | 0 connectionwindow.ui => ui/connectionwindow.ui | 0 .../dbcloadsavewindow.ui | 0 dbcmaineditor.ui => ui/dbcmaineditor.ui | 0 dbcsignaleditor.ui => ui/dbcsignaleditor.ui | 0 .../discretestatewindow.ui | 0 .../filecomparatorwindow.ui | 0 .../firmwareuploaderwindow.ui | 0 flowviewwindow.ui => ui/flowviewwindow.ui | 0 frameinfowindow.ui => ui/frameinfowindow.ui | 0 .../frameplaybackwindow.ui | 0 .../framesenderwindow.ui | 0 fuzzingwindow.ui => ui/fuzzingwindow.ui | 0 graphingwindow.ui => ui/graphingwindow.ui | 0 .../isotp_interpreterwindow.ui | 0 .../mainsettingsdialog.ui | 0 mainwindow.ui => ui/mainwindow.ui | 0 .../motorcontrollerconfigwindow.ui | 0 newgraphdialog.ui => ui/newgraphdialog.ui | 0 rangestatewindow.ui => ui/rangestatewindow.ui | 0 scriptingwindow.ui => ui/scriptingwindow.ui | 0 snifferwindow.ui => ui/snifferwindow.ui | 0 udsscanwindow.ui => ui/udsscanwindow.ui | 0 56 files changed, 67 insertions(+), 69 deletions(-) rename dbc_classes.cpp => dbc/dbc_classes.cpp (100%) rename dbc_classes.h => dbc/dbc_classes.h (100%) rename dbchandler.cpp => dbc/dbchandler.cpp (100%) rename dbchandler.h => dbc/dbchandler.h (100%) rename dbcloadsavewindow.cpp => dbc/dbcloadsavewindow.cpp (100%) rename dbcloadsavewindow.h => dbc/dbcloadsavewindow.h (100%) rename dbcmaineditor.cpp => dbc/dbcmaineditor.cpp (100%) rename dbcmaineditor.h => dbc/dbcmaineditor.h (100%) rename dbcsignaleditor.cpp => dbc/dbcsignaleditor.cpp (100%) rename dbcsignaleditor.h => dbc/dbcsignaleditor.h (100%) rename discretestatewindow.cpp => re/discretestatewindow.cpp (100%) rename discretestatewindow.h => re/discretestatewindow.h (100%) rename filecomparatorwindow.cpp => re/filecomparatorwindow.cpp (100%) rename filecomparatorwindow.h => re/filecomparatorwindow.h (100%) rename flowviewwindow.cpp => re/flowviewwindow.cpp (100%) rename flowviewwindow.h => re/flowviewwindow.h (100%) rename frameinfowindow.cpp => re/frameinfowindow.cpp (100%) rename frameinfowindow.h => re/frameinfowindow.h (100%) rename fuzzingwindow.cpp => re/fuzzingwindow.cpp (100%) rename fuzzingwindow.h => re/fuzzingwindow.h (100%) rename isotp_handler.cpp => re/isotp_handler.cpp (100%) rename isotp_handler.h => re/isotp_handler.h (100%) rename isotp_interpreterwindow.cpp => re/isotp_interpreterwindow.cpp (100%) rename isotp_interpreterwindow.h => re/isotp_interpreterwindow.h (100%) rename rangestatewindow.cpp => re/rangestatewindow.cpp (100%) rename rangestatewindow.h => re/rangestatewindow.h (100%) rename udsscanwindow.cpp => re/udsscanwindow.cpp (100%) rename udsscanwindow.h => re/udsscanwindow.h (100%) rename candatagrid.ui => ui/candatagrid.ui (100%) rename connectionwindow.ui => ui/connectionwindow.ui (100%) rename dbcloadsavewindow.ui => ui/dbcloadsavewindow.ui (100%) rename dbcmaineditor.ui => ui/dbcmaineditor.ui (100%) rename dbcsignaleditor.ui => ui/dbcsignaleditor.ui (100%) rename discretestatewindow.ui => ui/discretestatewindow.ui (100%) rename filecomparatorwindow.ui => ui/filecomparatorwindow.ui (100%) rename firmwareuploaderwindow.ui => ui/firmwareuploaderwindow.ui (100%) rename flowviewwindow.ui => ui/flowviewwindow.ui (100%) rename frameinfowindow.ui => ui/frameinfowindow.ui (100%) rename frameplaybackwindow.ui => ui/frameplaybackwindow.ui (100%) rename framesenderwindow.ui => ui/framesenderwindow.ui (100%) rename fuzzingwindow.ui => ui/fuzzingwindow.ui (100%) rename graphingwindow.ui => ui/graphingwindow.ui (100%) rename isotp_interpreterwindow.ui => ui/isotp_interpreterwindow.ui (100%) rename mainsettingsdialog.ui => ui/mainsettingsdialog.ui (100%) rename mainwindow.ui => ui/mainwindow.ui (100%) rename motorcontrollerconfigwindow.ui => ui/motorcontrollerconfigwindow.ui (100%) rename newgraphdialog.ui => ui/newgraphdialog.ui (100%) rename rangestatewindow.ui => ui/rangestatewindow.ui (100%) rename scriptingwindow.ui => ui/scriptingwindow.ui (100%) rename snifferwindow.ui => ui/snifferwindow.ui (100%) rename udsscanwindow.ui => ui/udsscanwindow.ui (100%) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index 6c122c2..d97b115 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -22,35 +22,22 @@ SOURCES += main.cpp\ utility.cpp \ qcustomplot.cpp \ graphingwindow.cpp \ - frameinfowindow.cpp \ newgraphdialog.cpp \ frameplaybackwindow.cpp \ serialworker.cpp \ candatagrid.cpp \ - flowviewwindow.cpp \ framesenderwindow.cpp \ - dbchandler.cpp \ - dbcmaineditor.cpp \ - dbcsignaleditor.cpp \ framefileio.cpp \ - filecomparatorwindow.cpp \ mainsettingsdialog.cpp \ firmwareuploaderwindow.cpp \ - discretestatewindow.cpp \ connectionwindow.cpp \ scriptingwindow.cpp \ scriptcontainer.cpp \ canfilter.cpp \ - rangestatewindow.cpp \ - dbc_classes.cpp \ - dbcloadsavewindow.cpp \ - fuzzingwindow.cpp \ - udsscanwindow.cpp \ can_structs.cpp \ - isotp_interpreterwindow.cpp \ - isotp_handler.cpp \ canconnectionmodel.cpp \ canbus.cpp \ + motorcontrollerconfigwindow.cpp \ connections/canconnection.cpp \ connections/socketcan.cpp \ connections/canconfactory.cpp \ @@ -59,8 +46,20 @@ SOURCES += main.cpp\ re/sniffer/snifferitem.cpp \ re/sniffer/sniffermodel.cpp \ re/sniffer/snifferwindow.cpp \ - motorcontrollerconfigwindow.cpp - motorcontrollerconfigwindow.cpp + dbc/dbc_classes.cpp \ + dbc/dbchandler.cpp \ + dbc/dbcloadsavewindow.cpp \ + dbc/dbcmaineditor.cpp \ + dbc/dbcsignaleditor.cpp \ + re/discretestatewindow.cpp \ + re/filecomparatorwindow.cpp \ + re/flowviewwindow.cpp \ + re/frameinfowindow.cpp \ + re/fuzzingwindow.cpp \ + re/isotp_handler.cpp \ + re/isotp_interpreterwindow.cpp \ + re/rangestatewindow.cpp \ + re/udsscanwindow.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -68,37 +67,24 @@ HEADERS += mainwindow.h \ utility.h \ qcustomplot.h \ graphingwindow.h \ - frameinfowindow.h \ newgraphdialog.h \ frameplaybackwindow.h \ serialworker.h \ candatagrid.h \ - flowviewwindow.h \ framesenderwindow.h \ can_trigger_structs.h \ - dbc_classes.h \ - dbchandler.h \ - dbcmaineditor.h \ - dbcsignaleditor.h \ framefileio.h \ config.h \ - filecomparatorwindow.h \ mainsettingsdialog.h \ firmwareuploaderwindow.h \ - discretestatewindow.h \ connectionwindow.h \ scriptingwindow.h \ scriptcontainer.h \ canfilter.h \ - rangestatewindow.h \ - dbcloadsavewindow.h \ - fuzzingwindow.h \ - udsscanwindow.h \ - isotp_interpreterwindow.h \ - isotp_handler.h \ canconnectionmodel.h \ canbus.h \ utils/lfqueue.h \ + motorcontrollerconfigwindow.h \ connections/canconnection.h \ connections/socketcan.h \ connections/canconconst.h \ @@ -108,32 +94,44 @@ HEADERS += mainwindow.h \ re/sniffer/snifferitem.h \ re/sniffer/sniffermodel.h \ re/sniffer/snifferwindow.h \ - motorcontrollerconfigwindow.h - motorcontrollerconfigwindow.h + dbc/dbc_classes.h \ + dbc/dbchandler.h \ + dbc/dbcloadsavewindow.h \ + dbc/dbcmaineditor.h \ + dbc/dbcsignaleditor.h \ + re/discretestatewindow.h \ + re/filecomparatorwindow.h \ + re/flowviewwindow.h \ + re/frameinfowindow.h \ + re/fuzzingwindow.h \ + re/isotp_handler.h \ + re/isotp_interpreterwindow.h \ + re/rangestatewindow.h \ + re/udsscanwindow.h -FORMS += mainwindow.ui \ - graphingwindow.ui \ - frameinfowindow.ui \ - newgraphdialog.ui \ - frameplaybackwindow.ui \ - candatagrid.ui \ - flowviewwindow.ui \ - framesenderwindow.ui \ - dbcmaineditor.ui \ - dbcsignaleditor.ui \ - filecomparatorwindow.ui \ - mainsettingsdialog.ui \ - firmwareuploaderwindow.ui \ - discretestatewindow.ui \ - connectionwindow.ui \ - scriptingwindow.ui \ - rangestatewindow.ui \ - dbcloadsavewindow.ui \ - fuzzingwindow.ui \ - udsscanwindow.ui \ - isotp_interpreterwindow.ui \ - snifferwindow.ui \ - motorcontrollerconfigwindow.ui +FORMS += ui/candatagrid.ui \ + ui/connectionwindow.ui \ + ui/dbcloadsavewindow.ui \ + ui/dbcmaineditor.ui \ + ui/dbcsignaleditor.ui \ + ui/discretestatewindow.ui \ + ui/filecomparatorwindow.ui \ + ui/firmwareuploaderwindow.ui \ + ui/flowviewwindow.ui \ + ui/frameinfowindow.ui \ + ui/frameplaybackwindow.ui \ + ui/framesenderwindow.ui \ + ui/fuzzingwindow.ui \ + ui/graphingwindow.ui \ + ui/isotp_interpreterwindow.ui \ + ui/mainsettingsdialog.ui \ + ui/mainwindow.ui \ + ui/motorcontrollerconfigwindow.ui \ + ui/newgraphdialog.ui \ + ui/rangestatewindow.ui \ + ui/scriptingwindow.ui \ + ui/snifferwindow.ui \ + ui/udsscanwindow.ui DISTFILES += diff --git a/canframemodel.h b/canframemodel.h index c1d17c6..a26e7f3 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -7,7 +7,7 @@ #include #include #include "can_structs.h" -#include "dbchandler.h" +#include "dbc/dbchandler.h" #include "connections/canconnection.h" class CANFrameModel: public QAbstractTableModel diff --git a/dbc_classes.cpp b/dbc/dbc_classes.cpp similarity index 100% rename from dbc_classes.cpp rename to dbc/dbc_classes.cpp diff --git a/dbc_classes.h b/dbc/dbc_classes.h similarity index 100% rename from dbc_classes.h rename to dbc/dbc_classes.h diff --git a/dbchandler.cpp b/dbc/dbchandler.cpp similarity index 100% rename from dbchandler.cpp rename to dbc/dbchandler.cpp diff --git a/dbchandler.h b/dbc/dbchandler.h similarity index 100% rename from dbchandler.h rename to dbc/dbchandler.h diff --git a/dbcloadsavewindow.cpp b/dbc/dbcloadsavewindow.cpp similarity index 100% rename from dbcloadsavewindow.cpp rename to dbc/dbcloadsavewindow.cpp diff --git a/dbcloadsavewindow.h b/dbc/dbcloadsavewindow.h similarity index 100% rename from dbcloadsavewindow.h rename to dbc/dbcloadsavewindow.h diff --git a/dbcmaineditor.cpp b/dbc/dbcmaineditor.cpp similarity index 100% rename from dbcmaineditor.cpp rename to dbc/dbcmaineditor.cpp diff --git a/dbcmaineditor.h b/dbc/dbcmaineditor.h similarity index 100% rename from dbcmaineditor.h rename to dbc/dbcmaineditor.h diff --git a/dbcsignaleditor.cpp b/dbc/dbcsignaleditor.cpp similarity index 100% rename from dbcsignaleditor.cpp rename to dbc/dbcsignaleditor.cpp diff --git a/dbcsignaleditor.h b/dbc/dbcsignaleditor.h similarity index 100% rename from dbcsignaleditor.h rename to dbc/dbcsignaleditor.h diff --git a/graphingwindow.h b/graphingwindow.h index 4887243..e3fad88 100644 --- a/graphingwindow.h +++ b/graphingwindow.h @@ -3,7 +3,7 @@ #include "qcustomplot.h" #include "can_structs.h" -#include "dbchandler.h" +#include "dbc/dbchandler.h" #include diff --git a/mainwindow.h b/mainwindow.h index cfefe35..d5ac430 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -9,24 +9,24 @@ #include "can_structs.h" #include "framefileio.h" #include "graphingwindow.h" -#include "frameinfowindow.h" +#include "re/frameinfowindow.h" #include "frameplaybackwindow.h" -#include "flowviewwindow.h" +#include "re/flowviewwindow.h" #include "framesenderwindow.h" -#include "filecomparatorwindow.h" -#include "dbchandler.h" -#include "dbcmaineditor.h" +#include "re/filecomparatorwindow.h" +#include "dbc/dbchandler.h" +#include "dbc/dbcmaineditor.h" #include "mainsettingsdialog.h" #include "firmwareuploaderwindow.h" -#include "discretestatewindow.h" +#include "re/discretestatewindow.h" #include "connectionwindow.h" #include "scriptingwindow.h" -#include "rangestatewindow.h" -#include "dbcloadsavewindow.h" -#include "fuzzingwindow.h" -#include "udsscanwindow.h" +#include "re/rangestatewindow.h" +#include "dbc/dbcloadsavewindow.h" +#include "re/fuzzingwindow.h" +#include "re/udsscanwindow.h" #include "re/sniffer/snifferwindow.h" -#include "isotp_interpreterwindow.h" +#include "re/isotp_interpreterwindow.h" #include "motorcontrollerconfigwindow.h" class ConnectionWindow; diff --git a/newgraphdialog.h b/newgraphdialog.h index 907a03c..85ce74c 100644 --- a/newgraphdialog.h +++ b/newgraphdialog.h @@ -3,7 +3,7 @@ #include #include "graphingwindow.h" -#include "dbchandler.h" +#include "dbc/dbchandler.h" namespace Ui { class NewGraphDialog; diff --git a/discretestatewindow.cpp b/re/discretestatewindow.cpp similarity index 100% rename from discretestatewindow.cpp rename to re/discretestatewindow.cpp diff --git a/discretestatewindow.h b/re/discretestatewindow.h similarity index 100% rename from discretestatewindow.h rename to re/discretestatewindow.h diff --git a/filecomparatorwindow.cpp b/re/filecomparatorwindow.cpp similarity index 100% rename from filecomparatorwindow.cpp rename to re/filecomparatorwindow.cpp diff --git a/filecomparatorwindow.h b/re/filecomparatorwindow.h similarity index 100% rename from filecomparatorwindow.h rename to re/filecomparatorwindow.h diff --git a/flowviewwindow.cpp b/re/flowviewwindow.cpp similarity index 100% rename from flowviewwindow.cpp rename to re/flowviewwindow.cpp diff --git a/flowviewwindow.h b/re/flowviewwindow.h similarity index 100% rename from flowviewwindow.h rename to re/flowviewwindow.h diff --git a/frameinfowindow.cpp b/re/frameinfowindow.cpp similarity index 100% rename from frameinfowindow.cpp rename to re/frameinfowindow.cpp diff --git a/frameinfowindow.h b/re/frameinfowindow.h similarity index 100% rename from frameinfowindow.h rename to re/frameinfowindow.h diff --git a/fuzzingwindow.cpp b/re/fuzzingwindow.cpp similarity index 100% rename from fuzzingwindow.cpp rename to re/fuzzingwindow.cpp diff --git a/fuzzingwindow.h b/re/fuzzingwindow.h similarity index 100% rename from fuzzingwindow.h rename to re/fuzzingwindow.h diff --git a/isotp_handler.cpp b/re/isotp_handler.cpp similarity index 100% rename from isotp_handler.cpp rename to re/isotp_handler.cpp diff --git a/isotp_handler.h b/re/isotp_handler.h similarity index 100% rename from isotp_handler.h rename to re/isotp_handler.h diff --git a/isotp_interpreterwindow.cpp b/re/isotp_interpreterwindow.cpp similarity index 100% rename from isotp_interpreterwindow.cpp rename to re/isotp_interpreterwindow.cpp diff --git a/isotp_interpreterwindow.h b/re/isotp_interpreterwindow.h similarity index 100% rename from isotp_interpreterwindow.h rename to re/isotp_interpreterwindow.h diff --git a/rangestatewindow.cpp b/re/rangestatewindow.cpp similarity index 100% rename from rangestatewindow.cpp rename to re/rangestatewindow.cpp diff --git a/rangestatewindow.h b/re/rangestatewindow.h similarity index 100% rename from rangestatewindow.h rename to re/rangestatewindow.h diff --git a/udsscanwindow.cpp b/re/udsscanwindow.cpp similarity index 100% rename from udsscanwindow.cpp rename to re/udsscanwindow.cpp diff --git a/udsscanwindow.h b/re/udsscanwindow.h similarity index 100% rename from udsscanwindow.h rename to re/udsscanwindow.h diff --git a/candatagrid.ui b/ui/candatagrid.ui similarity index 100% rename from candatagrid.ui rename to ui/candatagrid.ui diff --git a/connectionwindow.ui b/ui/connectionwindow.ui similarity index 100% rename from connectionwindow.ui rename to ui/connectionwindow.ui diff --git a/dbcloadsavewindow.ui b/ui/dbcloadsavewindow.ui similarity index 100% rename from dbcloadsavewindow.ui rename to ui/dbcloadsavewindow.ui diff --git a/dbcmaineditor.ui b/ui/dbcmaineditor.ui similarity index 100% rename from dbcmaineditor.ui rename to ui/dbcmaineditor.ui diff --git a/dbcsignaleditor.ui b/ui/dbcsignaleditor.ui similarity index 100% rename from dbcsignaleditor.ui rename to ui/dbcsignaleditor.ui diff --git a/discretestatewindow.ui b/ui/discretestatewindow.ui similarity index 100% rename from discretestatewindow.ui rename to ui/discretestatewindow.ui diff --git a/filecomparatorwindow.ui b/ui/filecomparatorwindow.ui similarity index 100% rename from filecomparatorwindow.ui rename to ui/filecomparatorwindow.ui diff --git a/firmwareuploaderwindow.ui b/ui/firmwareuploaderwindow.ui similarity index 100% rename from firmwareuploaderwindow.ui rename to ui/firmwareuploaderwindow.ui diff --git a/flowviewwindow.ui b/ui/flowviewwindow.ui similarity index 100% rename from flowviewwindow.ui rename to ui/flowviewwindow.ui diff --git a/frameinfowindow.ui b/ui/frameinfowindow.ui similarity index 100% rename from frameinfowindow.ui rename to ui/frameinfowindow.ui diff --git a/frameplaybackwindow.ui b/ui/frameplaybackwindow.ui similarity index 100% rename from frameplaybackwindow.ui rename to ui/frameplaybackwindow.ui diff --git a/framesenderwindow.ui b/ui/framesenderwindow.ui similarity index 100% rename from framesenderwindow.ui rename to ui/framesenderwindow.ui diff --git a/fuzzingwindow.ui b/ui/fuzzingwindow.ui similarity index 100% rename from fuzzingwindow.ui rename to ui/fuzzingwindow.ui diff --git a/graphingwindow.ui b/ui/graphingwindow.ui similarity index 100% rename from graphingwindow.ui rename to ui/graphingwindow.ui diff --git a/isotp_interpreterwindow.ui b/ui/isotp_interpreterwindow.ui similarity index 100% rename from isotp_interpreterwindow.ui rename to ui/isotp_interpreterwindow.ui diff --git a/mainsettingsdialog.ui b/ui/mainsettingsdialog.ui similarity index 100% rename from mainsettingsdialog.ui rename to ui/mainsettingsdialog.ui diff --git a/mainwindow.ui b/ui/mainwindow.ui similarity index 100% rename from mainwindow.ui rename to ui/mainwindow.ui diff --git a/motorcontrollerconfigwindow.ui b/ui/motorcontrollerconfigwindow.ui similarity index 100% rename from motorcontrollerconfigwindow.ui rename to ui/motorcontrollerconfigwindow.ui diff --git a/newgraphdialog.ui b/ui/newgraphdialog.ui similarity index 100% rename from newgraphdialog.ui rename to ui/newgraphdialog.ui diff --git a/rangestatewindow.ui b/ui/rangestatewindow.ui similarity index 100% rename from rangestatewindow.ui rename to ui/rangestatewindow.ui diff --git a/scriptingwindow.ui b/ui/scriptingwindow.ui similarity index 100% rename from scriptingwindow.ui rename to ui/scriptingwindow.ui diff --git a/snifferwindow.ui b/ui/snifferwindow.ui similarity index 100% rename from snifferwindow.ui rename to ui/snifferwindow.ui diff --git a/udsscanwindow.ui b/ui/udsscanwindow.ui similarity index 100% rename from udsscanwindow.ui rename to ui/udsscanwindow.ui From b7a1afcd8f308dfca63e23271b5419e90e2f283d Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sun, 11 Dec 2016 21:36:25 -0500 Subject: [PATCH 75/86] Further source file restructuring --- SavvyCAN.pro | 26 +- canbus.cpp => connections/canbus.cpp | 0 canbus.h => connections/canbus.h | 0 .../canconnectionmodel.cpp | 0 .../canconnectionmodel.h | 0 .../connectionwindow.cpp | 0 .../connectionwindow.h | 0 firmwareuploaderwindow.h | 1 - frameplaybackwindow.h | 1 - mainwindow.cpp | 1 - mainwindow.h | 4 +- graphingwindow.cpp => re/graphingwindow.cpp | 0 graphingwindow.h => re/graphingwindow.h | 0 newgraphdialog.cpp => re/newgraphdialog.cpp | 0 newgraphdialog.h => re/newgraphdialog.h | 0 serialworker.cpp | 648 ------------------ serialworker.h | 89 --- 17 files changed, 14 insertions(+), 756 deletions(-) rename canbus.cpp => connections/canbus.cpp (100%) rename canbus.h => connections/canbus.h (100%) rename canconnectionmodel.cpp => connections/canconnectionmodel.cpp (100%) rename canconnectionmodel.h => connections/canconnectionmodel.h (100%) rename connectionwindow.cpp => connections/connectionwindow.cpp (100%) rename connectionwindow.h => connections/connectionwindow.h (100%) rename graphingwindow.cpp => re/graphingwindow.cpp (100%) rename graphingwindow.h => re/graphingwindow.h (100%) rename newgraphdialog.cpp => re/newgraphdialog.cpp (100%) rename newgraphdialog.h => re/newgraphdialog.h (100%) delete mode 100644 serialworker.cpp delete mode 100644 serialworker.h diff --git a/SavvyCAN.pro b/SavvyCAN.pro index d97b115..4346f2e 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -21,22 +21,16 @@ SOURCES += main.cpp\ canframemodel.cpp \ utility.cpp \ qcustomplot.cpp \ - graphingwindow.cpp \ - newgraphdialog.cpp \ frameplaybackwindow.cpp \ - serialworker.cpp \ candatagrid.cpp \ framesenderwindow.cpp \ framefileio.cpp \ mainsettingsdialog.cpp \ firmwareuploaderwindow.cpp \ - connectionwindow.cpp \ scriptingwindow.cpp \ scriptcontainer.cpp \ canfilter.cpp \ can_structs.cpp \ - canconnectionmodel.cpp \ - canbus.cpp \ motorcontrollerconfigwindow.cpp \ connections/canconnection.cpp \ connections/socketcan.cpp \ @@ -59,17 +53,19 @@ SOURCES += main.cpp\ re/isotp_handler.cpp \ re/isotp_interpreterwindow.cpp \ re/rangestatewindow.cpp \ - re/udsscanwindow.cpp + re/udsscanwindow.cpp \ + connections/canbus.cpp \ + connections/canconnectionmodel.cpp \ + connections/connectionwindow.cpp \ + re/graphingwindow.cpp \ + re/newgraphdialog.cpp HEADERS += mainwindow.h \ can_structs.h \ canframemodel.h \ utility.h \ qcustomplot.h \ - graphingwindow.h \ - newgraphdialog.h \ frameplaybackwindow.h \ - serialworker.h \ candatagrid.h \ framesenderwindow.h \ can_trigger_structs.h \ @@ -77,12 +73,9 @@ HEADERS += mainwindow.h \ config.h \ mainsettingsdialog.h \ firmwareuploaderwindow.h \ - connectionwindow.h \ scriptingwindow.h \ scriptcontainer.h \ canfilter.h \ - canconnectionmodel.h \ - canbus.h \ utils/lfqueue.h \ motorcontrollerconfigwindow.h \ connections/canconnection.h \ @@ -107,7 +100,12 @@ HEADERS += mainwindow.h \ re/isotp_handler.h \ re/isotp_interpreterwindow.h \ re/rangestatewindow.h \ - re/udsscanwindow.h + re/udsscanwindow.h \ + connections/canbus.h \ + connections/canconnectionmodel.h \ + connections/connectionwindow.h \ + re/graphingwindow.h \ + re/newgraphdialog.h FORMS += ui/candatagrid.ui \ ui/connectionwindow.ui \ diff --git a/canbus.cpp b/connections/canbus.cpp similarity index 100% rename from canbus.cpp rename to connections/canbus.cpp diff --git a/canbus.h b/connections/canbus.h similarity index 100% rename from canbus.h rename to connections/canbus.h diff --git a/canconnectionmodel.cpp b/connections/canconnectionmodel.cpp similarity index 100% rename from canconnectionmodel.cpp rename to connections/canconnectionmodel.cpp diff --git a/canconnectionmodel.h b/connections/canconnectionmodel.h similarity index 100% rename from canconnectionmodel.h rename to connections/canconnectionmodel.h diff --git a/connectionwindow.cpp b/connections/connectionwindow.cpp similarity index 100% rename from connectionwindow.cpp rename to connections/connectionwindow.cpp diff --git a/connectionwindow.h b/connections/connectionwindow.h similarity index 100% rename from connectionwindow.h rename to connections/connectionwindow.h diff --git a/firmwareuploaderwindow.h b/firmwareuploaderwindow.h index 619a3b7..22221b9 100644 --- a/firmwareuploaderwindow.h +++ b/firmwareuploaderwindow.h @@ -5,7 +5,6 @@ #include #include "can_structs.h" #include "utility.h" -#include "serialworker.h" namespace Ui { class FirmwareUploaderWindow; diff --git a/frameplaybackwindow.h b/frameplaybackwindow.h index af3e5e2..a0a2026 100644 --- a/frameplaybackwindow.h +++ b/frameplaybackwindow.h @@ -5,7 +5,6 @@ #include #include #include "can_structs.h" -#include "serialworker.h" #include "framefileio.h" namespace Ui { diff --git a/mainwindow.cpp b/mainwindow.cpp index 4f1d3aa..a407d5d 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -6,7 +6,6 @@ #include #include "connections/canconmanager.h" #include "utility.h" -#include "serialworker.h" /* Compile for all platforms and create release (remember to include QScintilla libs) and make Win32 binary. diff --git a/mainwindow.h b/mainwindow.h index d5ac430..5061563 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -8,7 +8,7 @@ #include "canframemodel.h" #include "can_structs.h" #include "framefileio.h" -#include "graphingwindow.h" +#include "re/graphingwindow.h" #include "re/frameinfowindow.h" #include "frameplaybackwindow.h" #include "re/flowviewwindow.h" @@ -19,7 +19,7 @@ #include "mainsettingsdialog.h" #include "firmwareuploaderwindow.h" #include "re/discretestatewindow.h" -#include "connectionwindow.h" +#include "connections/connectionwindow.h" #include "scriptingwindow.h" #include "re/rangestatewindow.h" #include "dbc/dbcloadsavewindow.h" diff --git a/graphingwindow.cpp b/re/graphingwindow.cpp similarity index 100% rename from graphingwindow.cpp rename to re/graphingwindow.cpp diff --git a/graphingwindow.h b/re/graphingwindow.h similarity index 100% rename from graphingwindow.h rename to re/graphingwindow.h diff --git a/newgraphdialog.cpp b/re/newgraphdialog.cpp similarity index 100% rename from newgraphdialog.cpp rename to re/newgraphdialog.cpp diff --git a/newgraphdialog.h b/re/newgraphdialog.h similarity index 100% rename from newgraphdialog.h rename to re/newgraphdialog.h diff --git a/serialworker.cpp b/serialworker.cpp deleted file mode 100644 index f3b35d1..0000000 --- a/serialworker.cpp +++ /dev/null @@ -1,648 +0,0 @@ -#include "serialworker.h" - -#include -#include -#include -#include - -#if 0 -SerialWorker::SerialWorker(CANFrameModel *model, int base) : CANConnection(model, base) -{ - qDebug() << "Serial Worker constructor"; - serial = NULL; - rx_state = IDLE; - rx_step = 0; - buildFrame; - ticker = NULL; - framesRapid = 0; - gotValidated = true; - isAutoRestart = false; - - txTimestampBasis = QDateTime::currentMSecsSinceEpoch(); - - readSettings(); -} - -SerialWorker::~SerialWorker() -{ - if (serial != NULL) - { - if (serial->isOpen()) - { - serial->clear(); - serial->close(); - - } - serial->disconnect(); //disconnect all signals - delete serial; - } - if (ticker != NULL) ticker->stop(); -} - -void SerialWorker::run() -{ - qDebug() << "Serial worker thread starting"; - ticker = new QTimer; - connect(ticker, SIGNAL(timeout()), this, SLOT(handleTick())); - - ticker->setInterval(250); //tick four times per second - ticker->setSingleShot(false); //keep ticking - ticker->start(); -} - -void SerialWorker::readSettings() -{ - QSettings settings; - - if (settings.value("Main/ValidateComm", true).toBool()) - { - doValidation = true; - } - else doValidation = false; - //doValidation=false; -} - -void SerialWorker::setSerialPort(QSerialPortInfo *port) -{ - QSettings settings; - - currentPort = port; - - if (serial != NULL) - { - if (serial->isOpen()) - { - serial->clear(); - serial->close(); - } - serial->disconnect(); //disconnect all signals - delete serial; - } - - serial = new QSerialPort(*port); - - qDebug() << "Serial port name is " << port->portName(); - serial->setDataBits(serial->Data8); - serial->setFlowControl(serial->HardwareControl); //this is important though - if (!serial->open(QIODevice::ReadWrite)) - { - qDebug() << serial->errorString(); - } - serial->setDataTerminalReady(true); //you do need to set these or the fan gets dirty - serial->setRequestToSend(true); - QByteArray output; - output.append((char)0xE7); //this puts the device into binary comm mode - output.append((char)0xE7); - - output.append((char)0xF1); //signal we want to issue a command - output.append((char)0x06); //request canbus stats from the board - - 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 - if (settings.value("Main/SingleWireMode", false).toBool()) - { - output.append((char)0x10); //signal that we do want single wire mode - } - else - { - output.append((char)0xFF); //signal we don't want single wire mode - } - - output.append((char)0xF1); //yet another command - output.append((char)0x09); //comm validation command - - output.append((char)0xF1); //and another command - output.append((char)0x01); //Time Sync - Not implemented until 333 but we can try - - continuousTimeSync = true; - - serial->write(output); - if (doValidation) isConnected = false; - else isConnected = true; - connect(serial, SIGNAL(readyRead()), this, SLOT(readSerialData())); - if (doValidation) QTimer::singleShot(1000, this, SLOT(connectionTimeout())); -} - -void SerialWorker::connectionTimeout() -{ - //one second after trying to connect are we actually connected? - if (!isConnected) //no? - { - //then emit the the failure signal and see if anyone cares - qDebug() << "Failed to connect to GVRET at that com port"; - //ticker->stop(); - closeSerialPort(); //make sure it's properly closed anyway - emit connectionFailure(this); - } -} - -void SerialWorker::readSerialData() -{ - QByteArray data = serial->readAll(); - unsigned char c; - //qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); - for (int i = 0; i < data.length(); i++) - { - c = data.at(i); - procRXChar(c); - } - if (framesRapid > 0) - { - emit frameUpdateRapid(framesRapid); - framesRapid = 0; - } -} - -void SerialWorker::sendFrame(const CANFrame *frame) -{ - QByteArray buffer; - int c; - int ID; - CANFrame tempFrame = *frame; - tempFrame.isReceived = false; - tempFrame.timestamp = ((QDateTime::currentMSecsSinceEpoch() - txTimestampBasis) * 1000); - - //qDebug() << "Sending out frame with id " << frame->ID; - - //show our sent frames in the list too. This happens even if we're not connected. - /* model lives in UI thread, we need to call invokeMethod */ - QMetaObject::invokeMethod(model, "addFrame", - Qt::QueuedConnection, - Q_ARG(CANFrame, tempFrame), - Q_ARG(bool, false)); - - framesRapid++; - - if (serial == NULL) return; - if (!serial->isOpen()) return; - if (!isConnected) return; - - ID = frame->ID; - if (frame->extended) ID |= 1 << 31; - - 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 - this->getBusBase()) & 1); - buffer[7] = (unsigned char)frame->len; - for (c = 0; c < frame->len; c++) - { - buffer[8 + c] = frame->data[c]; - } - buffer[8 + frame->len] = 0; - - //qDebug() << "writing " << buffer.length() << " bytes to serial port"; - serial->write(buffer); -} - -//a simple way for another thread to pass us a bunch of frames to send. -//Don't get carried away here. The GVRET firmware only has finite -//buffers and besides, the other end will get buried in traffic. -void SerialWorker::sendFrameBatch(const QList *frames) -{ - sendBulkMutex.lock(); - for (int i = 0; i < frames->length(); i++) sendFrame(&frames->at(i)); - sendBulkMutex.unlock(); -} - -void SerialWorker::updateBaudRates(unsigned int Speed1, unsigned int Speed2) -{ - QByteArray buffer; - qDebug() << "Got signal to update bauds. 1: " << Speed1 <<" 2: " << Speed2; - buffer[0] = (char)0xF1; //start of a command over serial - buffer[1] = 5; //setup canbus - buffer[2] = (unsigned char)(Speed1 & 0xFF); //four bytes of ID LSB first - buffer[3] = (unsigned char)(Speed1 >> 8); - buffer[4] = (unsigned char)(Speed1 >> 16); - buffer[5] = (unsigned char)(Speed1 >> 24); - buffer[6] = (unsigned char)(Speed2 & 0xFF); //four bytes of ID LSB first - buffer[7] = (unsigned char)(Speed2 >> 8); - buffer[8] = (unsigned char)(Speed2 >> 16); - buffer[9] = (unsigned char)(Speed2 >> 24); - buffer[10] = 0; - if (serial == NULL) return; - if (!serial->isOpen()) return; - serial->write(buffer); -} - -void SerialWorker::procRXChar(unsigned char c) -{ - switch (rx_state) - { - case IDLE: - if (c == 0xF1) rx_state = GET_COMMAND; - break; - case GET_COMMAND: - switch (c) - { - case 0: //receiving a can frame - rx_state = BUILD_CAN_FRAME; - rx_step = 0; - break; - case 1: //time sync - rx_state = TIME_SYNC; - rx_step = 0; - break; - case 2: //process a return reply for digital input states. - rx_state = GET_DIG_INPUTS; - rx_step = 0; - break; - case 3: //process a return reply for analog inputs - rx_state = GET_ANALOG_INPUTS; - break; - case 4: //we set digital outputs we don't accept replies so nothing here. - rx_state = IDLE; - break; - case 5: //we set canbus specs we don't accept replies. - rx_state = IDLE; - break; - case 6: //get canbus parameters from GVRET - rx_state = GET_CANBUS_PARAMS; - rx_step = 0; - break; - case 7: //get device info - rx_state = GET_DEVICE_INFO; - rx_step = 0; - break; - case 9: - gotValidated = true; - //qDebug() << "Got validated"; - rx_state = IDLE; - break; - } - break; - case BUILD_CAN_FRAME: - switch (rx_step) - { - case 0: - buildFrame.timestamp = c; - break; - case 1: - buildFrame.timestamp |= (uint)(c << 8); - break; - case 2: - buildFrame.timestamp |= (uint)c << 16; - break; - case 3: - buildFrame.timestamp |= (uint)c << 24; - break; - case 4: - buildFrame.ID = c; - break; - case 5: - buildFrame.ID |= c << 8; - break; - case 6: - buildFrame.ID |= c << 16; - break; - case 7: - buildFrame.ID |= c << 24; - if ((buildFrame.ID & 1 << 31) == 1 << 31) - { - buildFrame.ID &= 0x7FFFFFFF; - buildFrame.extended = true; - } - else buildFrame.extended = false; - break; - case 8: - buildFrame.len = c & 0xF; - if (buildFrame.len > 8) buildFrame.len = 8; - buildFrame.bus = (c & 0xF0) >> 4; - break; - default: - if (rx_step < buildFrame.len + 9) - { - buildFrame.data[rx_step - 9] = c; - } - else - { - rx_state = IDLE; - rx_step = 0; - //qDebug() << "emit from serial handler to main form id: " << buildFrame.ID; - //if (capturing) - //{ - buildFrame.isReceived = true; - /* model lives in UI thread, we need to call invokeMethod */ - QMetaObject::invokeMethod(model, "addFrame", - Qt::QueuedConnection, - Q_ARG(CANFrame, buildFrame), - Q_ARG(bool, false)); - - //take the time the frame came in and try to resync the time base. - if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame.timestamp / 1000); - framesRapid++; - //} - } - break; - } - rx_step++; - break; - case TIME_SYNC: //gives a pretty good base guess for the proper timestamp. Can be refined when traffic starts to flow (if wanted) - switch (rx_step) - { - case 0: - buildTimeBasis = c; - break; - case 1: - buildTimeBasis += ((uint32_t)c << 8); - break; - case 2: - buildTimeBasis += ((uint32_t)c << 16); - break; - case 3: - buildTimeBasis += ((uint32_t)c << 24); - qDebug() << "GVRET firmware reports timestamp of " << buildTimeBasis; - txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - ((uint64_t)buildTimeBasis / (uint64_t)1000ull); - continuousTimeSync = false; - rx_state = IDLE; - break; - } - rx_step++; - break; - - case GET_ANALOG_INPUTS: //get 9 bytes - 2 per analog input plus checksum - switch (rx_step) - { - case 0: - break; - } - rx_step++; - break; - case GET_DIG_INPUTS: //get two bytes. One for digital in status and one for checksum. - switch (rx_step) - { - case 0: - break; - case 1: - rx_state = IDLE; - break; - } - rx_step++; - break; - case GET_CANBUS_PARAMS: - switch (rx_step) - { - case 0: - can0Enabled = (c & 0xF); - can0ListenOnly = (c >> 4); - break; - case 1: - can0Baud = c; - break; - case 2: - can0Baud |= c << 8; - break; - case 3: - can0Baud |= c << 16; - break; - case 4: - can0Baud |= c << 24; - break; - case 5: - can1Enabled = (c & 0xF); - can1ListenOnly = (c >> 4); - deviceSingleWireMode = (c >> 6); - break; - case 6: - can1Baud = c; - break; - case 7: - can1Baud |= c << 8; - break; - case 8: - can1Baud |= c << 16; - break; - case 9: - can1Baud |= c << 24; - rx_state = IDLE; - qDebug() << "Baud 0 = " << can0Baud; - qDebug() << "Baud 1 = " << can1Baud; - - can0Baud |= 0x80000000; - if (can0Enabled) can0Baud |= 0x40000000; - if (can0ListenOnly) can0Baud |= 0x20000000; - - can1Baud |= 0x80000000; - if (can1Enabled) can1Baud |= 0x40000000; - if (can1ListenOnly) can1Baud |= 0x20000000; - if (deviceSingleWireMode > 0) can1Baud |= 0x10000000; - - isConnected = true; - emit connectionSuccess(this); - int can0Status = 0x78; //updating everything we can update - int can1Status = 0x78; - if (can0Enabled) can0Status +=1; - if (can0ListenOnly) can0Status += 4; - if (can1Enabled) can1Status += 1; - if (deviceSingleWireMode > 0) can1Status += 2; - if (can1ListenOnly) can1Status += 4; - emit busStatus(busBase, can0Baud & 0xFFFFF, can0Status); - emit busStatus(busBase + 1, can1Baud & 0xFFFFF, can1Status); - break; - } - rx_step++; - break; - case GET_DEVICE_INFO: - switch (rx_step) - { - case 0: - deviceBuildNum = c; - break; - case 1: - deviceBuildNum |= c << 8; - break; - case 2: - break; //don't care about eeprom version - case 3: - break; //don't care about file type - case 4: - break; //don't care about whether it auto logs or not - case 5: - deviceSingleWireMode = c; - rx_state = IDLE; - qDebug() << "build num: " << deviceBuildNum; - qDebug() << "single wire can: " << deviceSingleWireMode; - emit deviceInfo(deviceBuildNum, deviceSingleWireMode); - break; - } - rx_step++; - break; - case SET_DIG_OUTPUTS: - rx_state = IDLE; - break; - case SETUP_CANBUS: - rx_state = IDLE; - break; - case SET_SINGLEWIRE_MODE: - rx_state = IDLE; - break; - - } -} - -void SerialWorker::handleTick() -{ - //qDebug() << "Tick!"; - - if (isConnected) - { - if (!gotValidated && doValidation) - { - if (serial == NULL) return; - if (serial->isOpen()) //if it's still false we have a problem... - { - qDebug() << "Comm validation failed. "; - closeSerialPort(); //start by stopping everything. - //Then wait 500ms and restart the connection automatically - QTimer::singleShot(500, this, SLOT(handleReconnect())); - return; - } - } - } - - if (doValidation && serial && serial->isOpen()) sendCommValidation(); -} - -void SerialWorker::handleReconnect() -{ - qDebug() << "Automatically reopening the connection"; - setSerialPort(currentPort); //then go back through the re-init -} - -void SerialWorker::sendCommValidation() -{ - QByteArray output; - - gotValidated = false; - output.append((char)0xF1); //another command to the GVRET - output.append((char)0x09); //request a reply to get validation - //send it twice for good measure. - output.append((char)0xF1); //another command to the GVRET - output.append((char)0x09); //request a reply to get validation - - serial->write(output); -} - -//totally shuts down the whole thing -void SerialWorker::closeSerialPort() -{ - if (serial == NULL) return; - if (serial->isOpen()) - { - serial->clear(); - serial->close(); - } - serial->disconnect(); - //do not stop the ticker here. It always stays running now. - //ticker->stop(); - delete serial; - serial = NULL; -} - -/* -void SerialWorker::stopFrameCapture() -{ - qDebug() << "Stopping frame capture"; - capturing = false; -} - -void SerialWorker::startFrameCapture() -{ - qDebug() << "Starting up frame capture"; - capturing = true; -} -*/ - -void SerialWorker::updatePortName(QString portName) -{ - QList ports; - - CANConnection::updatePortName(portName); - - ports = QSerialPortInfo::availablePorts(); - - for (int i = 0; i < ports.count(); i++) - { - if (portName == ports[i].portName()) - { - setSerialPort(&ports[i]); - return; - } - } -} - - - -void SerialWorker::updateBusSettings(CANBus bus) -{ - int busNum = bus.busNum - busBase; - if (busNum < 0) return; - if (busNum >= numBuses) return; - qDebug() << "About to update bus " << busNum << " on GVRET"; - if (busNum == 0) - { - can0Baud = bus.getSpeed(); - can0Baud |= 0x80000000; - if (bus.isActive()) - { - can0Baud |= 0x40000000; - can0Enabled = true; - } - else can0Enabled = false; - - if (bus.isListenOnly()) - { - can0Baud |= 0x20000000; - can0ListenOnly = true; - } - else can0ListenOnly = false; - } - if (busNum == 1) - { - can1Baud = bus.getSpeed(); - can1Baud |= 0x80000000; - if (bus.isActive()) - { - can1Baud |= 0x40000000; - can1Enabled = true; - } - else can1Enabled = false; - - if (bus.isListenOnly()) - { - can1Baud |= 0x20000000; - can1ListenOnly = true; - } - else can1ListenOnly = false; - - if (bus.isSingleWire()) - { - can1Baud |= 0x10000000; - deviceSingleWireMode = 1; - } - else deviceSingleWireMode = 0; - } - - updateBaudRates(can0Baud,can1Baud); -} - - -/************************************/ - -int SerialWorker::getNumBuses() -{ - return 2; -} - -QString SerialWorker::getConnTypeName() -{ - return QString("GVRET"); -} - -#endif diff --git a/serialworker.h b/serialworker.h deleted file mode 100644 index dc1a9a9..0000000 --- a/serialworker.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef SERIALWORKER_H -#define SERIALWORKER_H - -#include -#include -#include -#include -#include -#include "can_structs.h" -#include "canframemodel.h" -//#include "canconnection_old.h" - - -namespace SERIALSTATE { - -enum STATE //keep this enum synchronized with the Arduino firmware project -{ - IDLE, - GET_COMMAND, - BUILD_CAN_FRAME, - TIME_SYNC, - GET_DIG_INPUTS, - GET_ANALOG_INPUTS, - SET_DIG_OUTPUTS, - SETUP_CANBUS, - GET_CANBUS_PARAMS, - GET_DEVICE_INFO, - SET_SINGLEWIRE_MODE -}; - -} - -#if 0 -using namespace SERIALSTATE; -class SerialWorker : public CANConnection -{ - Q_OBJECT - -public: - SerialWorker(CANFrameModel *, int); - ~SerialWorker(); - void readSettings(); - int getNumBuses(); - QString getConnTypeName() override; - -private slots: //we receive things in slots - void readSerialData(); - void connectionTimeout(); - void handleTick(); - void handleReconnect(); - -public slots: - void run() override; - void setSerialPort(QSerialPortInfo*); - void closeSerialPort(); - void sendFrame(const CANFrame *) override; - void sendFrameBatch(const QList *) override; - void updateBaudRates(unsigned int, unsigned int); - //void stopFrameCapture(int) override; - //void startFrameCapture(int) override; - void updatePortName(QString) override; //string version of the port to connect to. This base doesnt know a thing about this value - void updateBusSettings(CANBus) override; - -private: - bool doValidation; - bool gotValidated; - bool isAutoRestart; - bool continuousTimeSync; - QSerialPort *serial; - QSerialPortInfo *currentPort; - QTimer *ticker; - QMutex sendBulkMutex; - int framesRapid; - STATE rx_state; - int rx_step; - CANFrame buildFrame; - int can0Baud, can1Baud; - bool can0Enabled, can1Enabled; - bool can0ListenOnly, can1ListenOnly; - int deviceBuildNum; - int deviceSingleWireMode; - uint64_t txTimestampBasis; - uint32_t buildTimeBasis; - - void procRXChar(unsigned char); - void sendCommValidation(); -}; -#endif -#endif // SERIALTHREAD_H From 8f1280265739e6a42b10cc344fe6e3a27447c359 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 13 Dec 2016 22:35:29 -0500 Subject: [PATCH 76/86] A few small changes, correct dialog title, change memory preallocation, explain file IO a bit. --- canframemodel.cpp | 4 ++-- framefileio.h | 10 ++++++++-- ui/firmwareuploaderwindow.ui | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/canframemodel.cpp b/canframemodel.cpp index 447672c..6263bf9 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -47,12 +47,12 @@ CANFrameModel::CANFrameModel(QObject *parent) if (QSysInfo::WordSize > 32) { qDebug() << "64 bit OS detected. Requesting a large preallocation"; - preallocSize = 50000000; + preallocSize = 20000000; } else //if compiling for 32 bit you can't ask for gigabytes of preallocation so tone it down. { qDebug() << "32 bit OS detected. Requesting a much restricted prealloc"; - preallocSize = 5000000; + preallocSize = 4000000; } frames.reserve(preallocSize); diff --git a/framefileio.h b/framefileio.h index 13f6e59..0c45515 100644 --- a/framefileio.h +++ b/framefileio.h @@ -22,6 +22,14 @@ class FrameFileIO: public QObject public: FrameFileIO(); + //these present a GUI to the user and allow them to pick the file to load/save + //The QString returns the filename that was selected and so is really a sort of return value + //The QVector is used as either the target for loading or the source for saving. + //These routines call the below loading/saving functions so no need to use them directly if you don't want. + static bool loadFrameFile(QString &, QVector*); + static bool saveFrameFile(QString &, const QVector*); + + //These do the actual loading and saving and can be used directly if you'd prefer static bool loadCRTDFile(QString, QVector*); static bool loadNativeCSVFile(QString, QVector*); static bool loadGenericCSVFile(QString, QVector*); @@ -40,8 +48,6 @@ public: static bool saveIXXATFile(QString, const QVector*); static bool saveCANDOFile(QString, const QVector*); static bool saveVehicleSpyFile(QString, const QVector*); - static bool loadFrameFile(QString &, QVector*); - static bool saveFrameFile(QString &, const QVector*); static bool loadCanDumpFile(QString, QVector*); static bool loadPCANFile(QString, QVector*); diff --git a/ui/firmwareuploaderwindow.ui b/ui/firmwareuploaderwindow.ui index c49903a..27a4983 100644 --- a/ui/firmwareuploaderwindow.ui +++ b/ui/firmwareuploaderwindow.ui @@ -11,7 +11,7 @@ - Dialog + Firmware Updater From a5ff16fc20c79ffef7423cd8dc9a47641c0f29af Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 13 Dec 2016 22:38:09 -0500 Subject: [PATCH 77/86] Added a new window that allows for bisecting a CAN log into pieces along a variety of patterns. Not quite complete but what's there works. --- SavvyCAN.pro | 10 +- bisectwindow.cpp | 154 +++++++++++++++++++++++++++++++ bisectwindow.h | 46 ++++++++++ mainwindow.cpp | 17 ++++ mainwindow.h | 3 + ui/bisectwindow.ui | 223 +++++++++++++++++++++++++++++++++++++++++++++ ui/mainwindow.ui | 6 ++ 7 files changed, 456 insertions(+), 3 deletions(-) create mode 100644 bisectwindow.cpp create mode 100644 bisectwindow.h create mode 100644 ui/bisectwindow.ui diff --git a/SavvyCAN.pro b/SavvyCAN.pro index 4346f2e..f293ad7 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -58,7 +58,8 @@ SOURCES += main.cpp\ connections/canconnectionmodel.cpp \ connections/connectionwindow.cpp \ re/graphingwindow.cpp \ - re/newgraphdialog.cpp + re/newgraphdialog.cpp \ + bisectwindow.cpp HEADERS += mainwindow.h \ can_structs.h \ @@ -105,7 +106,9 @@ HEADERS += mainwindow.h \ connections/canconnectionmodel.h \ connections/connectionwindow.h \ re/graphingwindow.h \ - re/newgraphdialog.h + re/newgraphdialog.h \ + ui/bisectwindow.h \ + bisectwindow.h FORMS += ui/candatagrid.ui \ ui/connectionwindow.ui \ @@ -129,7 +132,8 @@ FORMS += ui/candatagrid.ui \ ui/rangestatewindow.ui \ ui/scriptingwindow.ui \ ui/snifferwindow.ui \ - ui/udsscanwindow.ui + ui/udsscanwindow.ui \ + ui/bisectwindow.ui DISTFILES += diff --git a/bisectwindow.cpp b/bisectwindow.cpp new file mode 100644 index 0000000..a404c14 --- /dev/null +++ b/bisectwindow.cpp @@ -0,0 +1,154 @@ +#include "bisectwindow.h" +#include "ui_bisectwindow.h" + +#include "mainwindow.h" +#include "framefileio.h" + +#include +#include + +BisectWindow::BisectWindow(const QVector *frames, QWidget *parent) : + QDialog(parent), + ui(new Ui::BisectWindow) +{ + ui->setupUi(this); + + modelFrames = frames; + + connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int))); + connect(ui->btnCalculate, &QAbstractButton::clicked, this, &BisectWindow::handleCalculateButton); + connect(ui->btnReplaceFrames, &QAbstractButton::clicked, this, &BisectWindow::handleReplaceButton); + connect(ui->btnSaveFrames, &QAbstractButton::clicked, this, &BisectWindow::handleSaveButton); + connect(ui->slideFrameNumber, &QSlider::sliderReleased, this, &BisectWindow::updateFrameNumText); + connect(ui->slidePercentage, &QSlider::sliderReleased, this, &BisectWindow::updatePercentText); + connect(ui->editFrameNumber, &QLineEdit::editingFinished, this, &BisectWindow::updateFrameNumSlider); + connect(ui->editPercentage, &QLineEdit::editingFinished, this, &BisectWindow::updatePercentSlider); +} + +BisectWindow::~BisectWindow() +{ + delete ui; +} + +void BisectWindow::showEvent(QShowEvent* event) +{ + QDialog::showEvent(event); + refreshIDList(); + refreshFrameNumbers(); + updateFrameNumText(); + updatePercentText(); +} + +void BisectWindow::refreshIDList() +{ + int id; + for (int i = 0; i < modelFrames->count(); i++) + { + id = modelFrames->at(i).ID; + if (!foundID.contains(id)) + { + foundID.append(id); + } + } + + std::sort(foundID.begin(), foundID.end()); + + foreach (int id, foundID) { + ui->cbIDLower->addItem(Utility::formatNumber(id)); + ui->cbIDUpper->addItem(Utility::formatNumber(id)); + } +} + +void BisectWindow::refreshFrameNumbers() +{ + ui->labelMainListNum->setText(QString::number(modelFrames->count())); + ui->labelSplitNum->setText(QString::number(splitFrames.count())); + ui->slideFrameNumber->setMaximum(modelFrames->count()); +} + +void BisectWindow::updatedFrames(int numFrames) +{ + if (numFrames == -1) //all frames deleted + { + refreshFrameNumbers(); + } + else if (numFrames == -2) //all new set of frames. Reset + { + refreshFrameNumbers(); + refreshIDList(); + } + else //just got some new frames. See if they are relevant. + { + + } +} + +void BisectWindow::handleCalculateButton() +{ + splitFrames.clear(); + bool saveLower = ui->rbLowerSection->isChecked(); + int targetFrameNum; + if (ui->rbFrameNumber->isChecked() || ui->rbPercentage->isChecked()) + { + if (ui->rbFrameNumber->isChecked()) targetFrameNum = ui->slideFrameNumber->value(); + else targetFrameNum = modelFrames->count() * ui->slidePercentage->value() / 10000; + if (saveLower) + { + for (int i = 0; i < targetFrameNum; i++) splitFrames.append(modelFrames->at(i)); + } + else + { + for (int i = targetFrameNum; i < modelFrames->count(); i++) splitFrames.append(modelFrames->at(i)); + } + } + else if (ui->rbIDRange->isChecked()) + { + int lowerID = Utility::ParseStringToNum2(ui->cbIDLower->currentText()); + int 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)); + } + } + refreshFrameNumbers(); +} + +void BisectWindow::handleReplaceButton() +{ + +} + +void BisectWindow::handleSaveButton() +{ + QMessageBox msg; + QString filename; + if (FrameFileIO::saveFrameFile(filename, &splitFrames)) + { + msg.setText(tr("Successfully saved file")); + } + else + { + msg.setText(tr("Error while attempting to save.")); + } + msg.exec(); +} + +void BisectWindow::updateFrameNumSlider() +{ + ui->slideFrameNumber->setValue(ui->editFrameNumber->text().toInt()); +} + +void BisectWindow::updatePercentSlider() +{ + ui->slidePercentage->setValue(ui->editPercentage->text().toFloat() * 100); +} + +void BisectWindow::updateFrameNumText() +{ + ui->editFrameNumber->setText(QString::number(ui->slideFrameNumber->value())); +} + +void BisectWindow::updatePercentText() +{ + ui->editPercentage->setText(QString::number(ui->slidePercentage->value() / 100.0f)); +} diff --git a/bisectwindow.h b/bisectwindow.h new file mode 100644 index 0000000..77f3ebc --- /dev/null +++ b/bisectwindow.h @@ -0,0 +1,46 @@ +#ifndef BISECTWINDOW_H +#define BISECTWINDOW_H + +#include +#include "can_structs.h" + +namespace Ui { +class BisectWindow; +} + +class BisectWindow : public QDialog +{ + Q_OBJECT + +public: + explicit BisectWindow(const QVector *frames, QWidget *parent = 0); + ~BisectWindow(); + void showEvent(QShowEvent*); + +signals: + void sendCANFrame(const CANFrame *, int); + void sendFrameBatch(const QList *); + +private slots: + void updatedFrames(int numFrames); + void handleSaveButton(); + void handleReplaceButton(); + void handleCalculateButton(); + void updateFrameNumSlider(); + void updatePercentSlider(); + void updateFrameNumText(); + void updatePercentText(); + +private: + Ui::BisectWindow *ui; + const QVector *modelFrames; + QVector splitFrames; + QList foundID; + + void refreshIDList(); + void refreshFrameNumbers(); +}; + +#endif // BISECTWINDOW_H + + diff --git a/mainwindow.cpp b/mainwindow.cpp index a407d5d..9498a0c 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -81,6 +81,7 @@ MainWindow::MainWindow(QWidget *parent) : motorctrlConfigWindow = NULL; isoWindow = NULL; snifferWindow = NULL; + bisectWindow = NULL; dbcHandler = new DBCHandler; bDirty = false; inhibitFilterUpdate = false; @@ -126,6 +127,7 @@ MainWindow::MainWindow(QWidget *parent) : connect(ui->actionISO_TP_Decoder, &QAction::triggered, this, &MainWindow::showISOInterpreterWindow); connect(ui->actionSniffer, &QAction::triggered, this, &MainWindow::showSnifferWindow); connect(ui->actionMotorControlConfig, &QAction::triggered, this, &MainWindow::showMCConfigWindow); + connect(ui->actionCapture_Bisector, &QAction::triggered, this, &MainWindow::showBisectWindow); connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames); @@ -274,6 +276,13 @@ MainWindow::~MainWindow() snifferWindow = NULL; } + if (bisectWindow) + { + bisectWindow->close(); + delete bisectWindow; + bisectWindow = NULL; + } + delete model; delete elapsedTime; delete dbcHandler; @@ -854,6 +863,14 @@ void MainWindow::showSnifferWindow() snifferWindow->show(); } +void MainWindow::showBisectWindow() +{ + if (!bisectWindow) + { + bisectWindow = new BisectWindow(model->getListReference()); + } + bisectWindow->show(); +} void MainWindow::showFrameSenderWindow() { diff --git a/mainwindow.h b/mainwindow.h index 5061563..97f4a07 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -11,6 +11,7 @@ #include "re/graphingwindow.h" #include "re/frameinfowindow.h" #include "frameplaybackwindow.h" +#include "bisectwindow.h" #include "re/flowviewwindow.h" #include "framesenderwindow.h" #include "re/filecomparatorwindow.h" @@ -71,6 +72,7 @@ private slots: void showUDSScanWindow(); void showISOInterpreterWindow(); void showSnifferWindow(); + void showBisectWindow(); void exitApp(); void handleSaveDecoded(); void connectionFailed(); @@ -143,6 +145,7 @@ private: ISOTP_InterpreterWindow *isoWindow; SnifferWindow* snifferWindow; MotorControllerConfigWindow *motorctrlConfigWindow; + BisectWindow* bisectWindow; //various private storage QLabel lbStatusConnected; diff --git a/ui/bisectwindow.ui b/ui/bisectwindow.ui new file mode 100644 index 0000000..439386b --- /dev/null +++ b/ui/bisectwindow.ui @@ -0,0 +1,223 @@ + + + BisectWindow + + + + 0 + 0 + 692 + 319 + + + + Bisector Window + + + + + + Splitting Strategy: + + + Qt::AlignCenter + + + + + + + + ID Range + + + + + + + + + + TO + + + Qt::AlignCenter + + + + + + + + + + + + + + Frame Number + + + true + + + + + + + Qt::Horizontal + + + + + + + + + + + + + + Percentage + + + + + + + 1 + + + 10000 + + + 10 + + + 100 + + + Qt::Horizontal + + + + + + + + + + + + + + + Save Which Side: + + + Qt::AlignCenter + + + + + + Lower Section + + + true + + + + + + + Upper Section + + + + + + + + + + + + + 12 + + + + Number of Frames in Main List: + + + + + + + + 14 + + + + 0 + + + + + + + + 12 + + + + Saved Frames after split: + + + + + + + + 14 + + + + 0 + + + + + + + + + + + Calculate Split + + + + + + + Save split frames to a new file + + + + + + + Replace main list with split frames + + + + + + + + + + diff --git a/ui/mainwindow.ui b/ui/mainwindow.ui index b5124e1..a0c47ee 100644 --- a/ui/mainwindow.ui +++ b/ui/mainwindow.ui @@ -215,6 +215,7 @@ + @@ -413,6 +414,11 @@ MotorControlConfig + + + Capture Bisector + + From 0f3f9e0fad44d2978d5e3daccd972dbd289d842d Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Sun, 18 Dec 2016 21:40:56 -0500 Subject: [PATCH 78/86] Unified time base now so both GVRET and Socketcan devices yield timestamps in microseconds since the program started or clear was pressed, fixed frames per second display, fixed timestamps for sent frames --- connections/canconmanager.cpp | 13 +++++++++ connections/canconmanager.h | 4 +++ connections/gvretserial.cpp | 52 +++++++++++++++++++++++------------ connections/gvretserial.h | 8 +++--- connections/socketcan.cpp | 4 ++- connections/socketcan.h | 1 + mainwindow.cpp | 7 +++-- 7 files changed, 63 insertions(+), 26 deletions(-) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 4092f86..008ee03 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -1,3 +1,5 @@ +#include + #include "canconmanager.h" @@ -18,8 +20,14 @@ CANConManager::CANConManager(QObject *parent): QObject(parent) mTimer.setInterval(250); /*tick 4 times a second */ mTimer.setSingleShot(false); mTimer.start(); + + resetTimeBasis(); } +void CANConManager::resetTimeBasis() +{ + mTimestampBasis = QDateTime::currentMSecsSinceEpoch() * 1000; +} CANConManager::~CANConManager() { @@ -70,6 +78,10 @@ void CANConManager::refreshCanList() } } +uint64_t CANConManager::getTimeBasis() +{ + return mTimestampBasis; +} QList& CANConManager::getConnections() { @@ -139,6 +151,7 @@ bool CANConManager::sendFrame(const CANFrame& pFrame) { workingFrame.bus -= busBase; workingFrame.isReceived = false; + workingFrame.timestamp = ((QDateTime::currentMSecsSinceEpoch() * 1000) - mTimestampBasis); txFrame = conn->getQueue().get(); *txFrame = workingFrame; conn->getQueue().queue(); diff --git a/connections/canconmanager.h b/connections/canconmanager.h index d9c7e40..dc94431 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -20,6 +20,9 @@ public: CANConnection* getByName(const QString& pName) const; + uint64_t getTimeBasis(); + void resetTimeBasis(); + int getNumBuses(); /** @@ -46,6 +49,7 @@ private: static CANConManager* mInstance; QList mConns; QTimer mTimer; + uint64_t mTimestampBasis; }; #endif // CANCONNECTIONMODEL_H diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index c76a5ee..90a79a1 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -18,7 +18,8 @@ GVRetSerial::GVRetSerial(QString portName) : gotValidated = true; isAutoRestart = false; - txTimestampBasis = QDateTime::currentMSecsSinceEpoch(); + timeBasis = 0; + lastSystemTimeBasis = 0; readSettings(); } @@ -147,18 +148,10 @@ bool GVRetSerial::piSendFrame(const CANFrame& frame) int c; int ID; CANFrame tempFrame = frame; - tempFrame.isReceived = false; - tempFrame.timestamp = ((QDateTime::currentMSecsSinceEpoch() - txTimestampBasis) * 1000); + tempFrame.isReceived = false; //qDebug() << "Sending out frame with id " << frame->ID; - //show our sent frames in the list too. This happens even if we're not connected. - /* model lives in UI thread, we need to call invokeMethod */ - //QMetaObject::invokeMethod(model, "addFrame", - // Qt::QueuedConnection, - // Q_ARG(CANFrame, tempFrame), - // Q_ARG(bool, false)); - framesRapid++; if (serial == NULL) return false; @@ -240,7 +233,7 @@ void GVRetSerial::connectDevice() output.append((char)0xF1); //another command to the GVRET output.append((char)0x07); //request device information - output.append((char)0xF1); + /*output.append((char)0xF1); output.append((char)0x08); //setting singlewire mode if (settings.value("Main/SingleWireMode", false).toBool()) { @@ -249,7 +242,7 @@ void GVRetSerial::connectDevice() else { output.append((char)0xFF); //signal we don't want single wire mode - } + }*/ output.append((char)0xF1); //yet another command output.append((char)0x09); //comm validation command @@ -293,7 +286,8 @@ void GVRetSerial::disconnectDevice() { void GVRetSerial::connectionTimeout() { //one second after trying to connect are we actually connected? - if (CANCon::NOT_CONNECTED==getStatus()) //no? + //if (CANCon::NOT_CONNECTED==getStatus()) //no? + if (!gotValidated) { //then emit the the failure signal and see if anyone cares qDebug() << "Failed to connect to GVRET at that com port"; @@ -307,10 +301,11 @@ void GVRetSerial::readSerialData() { QByteArray data = serial->readAll(); unsigned char c; - //qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); + qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); for (int i = 0; i < data.length(); i++) { c = data.at(i); + //qDebug() << c << " " << QString::number(c, 16) << " " << QString(c); procRXChar(c); } } @@ -376,6 +371,8 @@ void GVRetSerial::procRXChar(unsigned char c) break; case 3: buildFrame.timestamp |= (uint)c << 24; + + buildFrame.timestamp += timeBasis; break; case 4: buildFrame.ID = c; @@ -425,7 +422,7 @@ void GVRetSerial::procRXChar(unsigned char c) qDebug() << "can't get a frame, ERROR"; //take the time the frame came in and try to resync the time base. - if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame.timestamp / 1000); + //if (continuousTimeSync) txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - (buildFrame.timestamp / 1000); } } break; @@ -447,7 +444,9 @@ void GVRetSerial::procRXChar(unsigned char c) case 3: buildTimeBasis += ((uint32_t)c << 24); qDebug() << "GVRET firmware reports timestamp of " << buildTimeBasis; - txTimestampBasis = QDateTime::currentMSecsSinceEpoch() - ((uint64_t)buildTimeBasis / (uint64_t)1000ull); + + rebuildLocalTimeBasis(); + continuousTimeSync = false; rx_state = IDLE; break; @@ -576,11 +575,28 @@ void GVRetSerial::procRXChar(unsigned char c) } } +void GVRetSerial::rebuildLocalTimeBasis() +{ + uint64_t currTime = QDateTime::currentMSecsSinceEpoch() * 1000; + + /* + 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. + currTime stores the "system" timestamp when the GVRET timestamp was retrieved. + */ + lastSystemTimeBasis = CANConManager::getInstance()->getTimeBasis(); + int64_t systemDelta = currTime - lastSystemTimeBasis; + int32_t localDelta = buildTimeBasis - systemDelta; + timeBasis = localDelta; +} void GVRetSerial::handleTick() { + if (lastSystemTimeBasis != CANConManager::getInstance()->getTimeBasis()) rebuildLocalTimeBasis(); //qDebug() << "Tick!"; - +/* if( CANCon::CONNECTED == getStatus() ) { if (!gotValidated && doValidation) @@ -600,7 +616,7 @@ void GVRetSerial::handleTick() } } } - +*/ if (doValidation && serial && serial->isOpen()) sendCommValidation(); } diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 4038a01..915af16 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -10,10 +10,9 @@ #include /*************/ - #include "canframemodel.h" #include "canconnection.h" - +#include "canconmanager.h" namespace SERIALSTATE { @@ -65,12 +64,12 @@ private: void readSettings(); void procRXChar(unsigned char); void sendCommValidation(); + void rebuildLocalTimeBasis(); protected: QTimer mTimer; QThread mThread; - bool doValidation; bool gotValidated; bool isAutoRestart; @@ -85,8 +84,9 @@ protected: bool can0ListenOnly, can1ListenOnly; int deviceBuildNum; int deviceSingleWireMode; - uint64_t txTimestampBasis; uint32_t buildTimeBasis; + int32_t timeBasis; + uint64_t lastSystemTimeBasis; }; #endif // GVRETSERIAL_H diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index b49e1fe..771f686 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -155,6 +155,8 @@ void SocketCan::framesReceived() /* test */ bool sndNotif = false; + uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis(); + /* sanity checks */ if(!mDev_p) return; @@ -185,7 +187,7 @@ void SocketCan::framesReceived() frame_p->extended = false; frame_p->ID = recFrame.frameId(); frame_p->isReceived = true; - frame_p->timestamp = recFrame.timeStamp().seconds()*1000000 + recFrame.timeStamp().microSeconds(); + frame_p->timestamp = (recFrame.timeStamp().seconds()*1000000 + recFrame.timeStamp().microSeconds()) - timeBasis; /* enqueue frame */ getQueue().queue(); diff --git a/connections/socketcan.h b/connections/socketcan.h index c303236..debd091 100644 --- a/connections/socketcan.h +++ b/connections/socketcan.h @@ -8,6 +8,7 @@ #include "canframemodel.h" #include "canconnection.h" +#include "canconmanager.h" class SocketCan : public CANConnection diff --git a/mainwindow.cpp b/mainwindow.cpp index 9498a0c..0d73526 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -477,8 +477,8 @@ void MainWindow::filterClearAll() void MainWindow::tickGUIUpdate() { rxFrames = model->sendBulkRefresh(); - if(rxFrames>0) - { + //if(rxFrames>0) + //{ int elapsed = elapsedTime->elapsed(); if(elapsed) { framesPerSec = rxFrames * 1000 / elapsed; @@ -499,7 +499,7 @@ void MainWindow::tickGUIUpdate() if (model->needsFilterRefresh()) updateFilterList(); rxFrames = 0; - } + //} } void MainWindow::gotFrames(int framesSinceLastUpdate) @@ -533,6 +533,7 @@ void MainWindow::clearFrames() { ui->canFramesView->scrollToTop(); model->clearFrames(); + CANConManager::getInstance()->resetTimeBasis(); ui->lbNumFrames->setText(QString::number(model->rowCount())); bDirty = false; loadedFileName = ""; From cdfb7661a1bf25a52d530568bbd8aa12b746f63c Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Mon, 19 Dec 2016 20:46:59 -0500 Subject: [PATCH 79/86] Bug fixes in connection code, some commented out debugging statements used only for specific debugging --- connections/canconmanager.cpp | 7 ++++++- connections/gvretserial.cpp | 5 +++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 008ee03..4dc857d 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -103,6 +103,8 @@ CANConnection* CANConManager::getByName(const QString& pName) const void CANConManager::refreshConnection(CANConnection* pConn_p) { + if (pConn_p->getQueue().peek() == NULL) return; + CANFrame* frame_p = NULL; QVector frames; @@ -117,8 +119,11 @@ void CANConManager::refreshConnection(CANConnection* pConn_p) else break; } + //qDebug() << "Bus fixup number: " << busBase; + while( (frame_p = pConn_p->getQueue().peek() ) ) { frame_p->bus += busBase; + //qDebug() << "Rx of frame from bus: " << frame_p->bus; frames.append(*frame_p); pConn_p->getQueue().dequeue(); } @@ -147,7 +152,7 @@ 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 <= busBase + conn->getNumBuses()) + if (pFrame.bus < busBase + conn->getNumBuses()) { workingFrame.bus -= busBase; workingFrame.isReceived = false; diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index 90a79a1..b6940f0 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -150,7 +150,7 @@ bool GVRetSerial::piSendFrame(const CANFrame& frame) CANFrame tempFrame = frame; tempFrame.isReceived = false; - //qDebug() << "Sending out frame with id " << frame->ID; + //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; framesRapid++; @@ -301,7 +301,7 @@ void GVRetSerial::readSerialData() { QByteArray data = serial->readAll(); unsigned char c; - qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); + //qDebug() << (tr("Got data from serial. Len = %0").arg(data.length())); for (int i = 0; i < data.length(); i++) { c = data.at(i); @@ -413,6 +413,7 @@ void GVRetSerial::procRXChar(unsigned char c) /* get frame from queue */ CANFrame* frame_p = getQueue().get(); if(frame_p) { + //qDebug() << "GVRET got frame on bus " << frame_p->bus; /* copy frame */ *frame_p = buildFrame; /* enqueue frame */ From 4d4eabad7a09e45c8d234a50dd03e9d0ed1657e6 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Mon, 19 Dec 2016 21:34:22 -0500 Subject: [PATCH 80/86] Correction for GVRET time sync. Seems to be proper now (hopefully) --- connections/gvretserial.cpp | 10 ++++++---- connections/gvretserial.h | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index b6940f0..af60a1e 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -20,6 +20,7 @@ GVRetSerial::GVRetSerial(QString portName) : timeBasis = 0; lastSystemTimeBasis = 0; + timeAtGVRETSync = 0; readSettings(); } @@ -445,6 +446,7 @@ void GVRetSerial::procRXChar(unsigned char c) case 3: buildTimeBasis += ((uint32_t)c << 24); qDebug() << "GVRET firmware reports timestamp of " << buildTimeBasis; + timeAtGVRETSync = QDateTime::currentMSecsSinceEpoch() * 1000; rebuildLocalTimeBasis(); @@ -578,19 +580,19 @@ void GVRetSerial::procRXChar(unsigned char c) void GVRetSerial::rebuildLocalTimeBasis() { - uint64_t currTime = QDateTime::currentMSecsSinceEpoch() * 1000; + 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. - currTime stores the "system" timestamp when the GVRET timestamp was retrieved. + timeAtGVRETSync stores the "system" timestamp when the GVRET timestamp was retrieved. */ lastSystemTimeBasis = CANConManager::getInstance()->getTimeBasis(); - int64_t systemDelta = currTime - lastSystemTimeBasis; + int64_t systemDelta = timeAtGVRETSync - lastSystemTimeBasis; int32_t localDelta = buildTimeBasis - systemDelta; - timeBasis = localDelta; + timeBasis = -localDelta; } void GVRetSerial::handleTick() diff --git a/connections/gvretserial.h b/connections/gvretserial.h index 915af16..b4bfa4c 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -87,6 +87,7 @@ protected: uint32_t buildTimeBasis; int32_t timeBasis; uint64_t lastSystemTimeBasis; + uint64_t timeAtGVRETSync; }; #endif // GVRETSERIAL_H From 9cceb4404d31c84aa80bfe2adf2f99603732ec22 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Tue, 20 Dec 2016 20:33:11 -0500 Subject: [PATCH 81/86] Remove some older junk code, add ability for main screen to show the number of connected buses --- connections/canconmanager.cpp | 3 +- connections/canconmanager.h | 1 + connections/canconnectionmodel.cpp | 8 +--- connections/connectionwindow.cpp | 3 +- mainwindow.cpp | 68 ++++-------------------------- mainwindow.h | 4 +- 6 files changed, 17 insertions(+), 70 deletions(-) diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 4dc857d..a0a061d 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -40,6 +40,7 @@ void CANConManager::add(CANConnection* pConn_p) { connect(pConn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); mConns.append(pConn_p); + emit connectionStatusUpdated(getNumBuses()); } @@ -47,6 +48,7 @@ void CANConManager::remove(CANConnection* pConn_p) { disconnect(pConn_p, 0, this, 0); mConns.removeOne(pConn_p); + emit connectionStatusUpdated(getNumBuses()); } //Get total number of buses currently registered with the program @@ -169,7 +171,6 @@ bool CANConManager::sendFrame(const CANFrame& pFrame) bool CANConManager::sendFrames(const QList& pFrames) { - qDebug() << "CANConManager sendFrames #" << pFrames.count(); foreach(const CANFrame& frame, pFrames) { if(!sendFrame(frame)) diff --git a/connections/canconmanager.h b/connections/canconmanager.h index dc94431..5abfae9 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -38,6 +38,7 @@ public: signals: void framesReceived(CANConnection* pConn_p, QVector& pFrames); + void connectionStatusUpdated(int conns); private slots: void refreshCanList(); diff --git a/connections/canconnectionmodel.cpp b/connections/canconnectionmodel.cpp index b7216aa..726c334 100644 --- a/connections/canconnectionmodel.cpp +++ b/connections/canconnectionmodel.cpp @@ -135,10 +135,8 @@ void CANConnectionModel::add(CANConnection* pConn_p) { CANConManager* manager = CANConManager::getInstance(); - connect(pConn_p, SIGNAL(notify()), manager, SLOT(refreshCanList())); - beginResetModel(); - manager->getConnections().append(pConn_p); + manager->add(pConn_p); endResetModel(); } @@ -147,10 +145,8 @@ void CANConnectionModel::remove(CANConnection* pConn_p) { CANConManager* manager = CANConManager::getInstance(); - disconnect(pConn_p, 0, manager, 0); - beginResetModel(); - manager->getConnections().removeOne(pConn_p); + manager->remove(pConn_p); endResetModel(); } diff --git a/connections/connectionwindow.cpp b/connections/connectionwindow.cpp index e8e1477..df71109 100644 --- a/connections/connectionwindow.cpp +++ b/connections/connectionwindow.cpp @@ -2,6 +2,7 @@ #include #include "connectionwindow.h" +#include "mainwindow.h" #include "ui_connectionwindow.h" #include "connections/canconfactory.h" #include "connections/canconmanager.h" @@ -38,7 +39,7 @@ ConnectionWindow::ConnectionWindow(QWidget *parent) : ui->cbSpeed->addItem(tr("250000")); ui->cbSpeed->addItem(tr("500000")); ui->cbSpeed->addItem(tr("1000000")); - ui->cbSpeed->addItem(tr("33333")); + ui->cbSpeed->addItem(tr("33333")); /* load connection configuration */ loadConnections(); diff --git a/mainwindow.cpp b/mainwindow.cpp index 0d73526..69af4e3 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -131,7 +131,7 @@ MainWindow::MainWindow(QWidget *parent) : connect(CANConManager::getInstance(), &CANConManager::framesReceived, model, &CANFrameModel::addFrames); - lbStatusConnected.setText(tr("Not connected")); + lbStatusConnected.setText(tr("Connected to 0 buses")); updateFileStatus(); lbStatusDatabase.setText(tr("No DBC database loaded")); ui->statusBar->addWidget(&lbStatusConnected); @@ -163,9 +163,13 @@ MainWindow::MainWindow(QWidget *parent) : qDebug() << "normal row height = " << normalRowHeight; model->clearFrames(); + //connect(CANConManager::getInstance(), CANConManager::connectionStatusUpdated, this, MainWindow::connectionStatusUpdated); + connect(CANConManager::getInstance(), SIGNAL(connectionStatusUpdated(int)), this, SLOT(connectionStatusUpdated(int))); + //Automatically create the connection window so it can be updated even if we never opened it. connectionWindow = new ConnectionWindow(); - connect(this, SIGNAL(suspendCapturing(bool)), connectionWindow, SLOT(setSuspendAll(bool))); + connect(this, SIGNAL(suspendCapturing(bool)), connectionWindow, SLOT(setSuspendAll(bool))); + } MainWindow::~MainWindow() @@ -720,41 +724,9 @@ void MainWindow::toggleCapture() emit suspendCapturing(!allowCapture); } -void MainWindow::connectionSucceeded(int baud0, int baud1) -{ - lbStatusConnected.setText(tr("Connected to GVRET")); - //finally, find the baud rate in the list of rates or - //add it to the bottom if needed (that'll be weird though... -/* - int idx = ui->cbSpeed1->findText(QString::number(baud0)); - if (idx > -1) ui->cbSpeed1->setCurrentIndex(idx); - else - { - ui->cbSpeed1->addItem(QString::number(baud0)); - ui->cbSpeed1->setCurrentIndex(ui->cbSpeed1->count() - 1); - } - - idx = ui->cbSpeed2->findText(QString::number(baud1)); - if (idx > -1) ui->cbSpeed2->setCurrentIndex(idx); - else - { - ui->cbSpeed2->addItem(QString::number(baud1)); - ui->cbSpeed2->setCurrentIndex(ui->cbSpeed2->count() - 1); - } - */ - if (connectionWindow) connectionWindow->setSpeed(baud0); - //ui->btnConnect->setEnabled(false); - ui->actionConnect->setText(tr("Disconnect")); - isConnected = true; -} - -void MainWindow::connectionFailed() -{ - lbStatusConnected.setText(tr("Failed to connect!")); - - QMessageBox msgBox; - msgBox.setText("Connection to the GVRET firmware failed.\nYou might have an old version of GVRET\nor may have chosen the wrong serial port."); - msgBox.exec(); +void MainWindow::connectionStatusUpdated(int conns) +{ + lbStatusConnected.setText(tr("Connected to ") + QString::number(conns) + tr(" buses")); } void MainWindow::updateFileStatus() @@ -783,28 +755,6 @@ void MainWindow::updateFileStatus() lbStatusFilename.setText(output); } -void MainWindow::gotDeviceInfo(int build, int swCAN) -{ - QString str = tr("Connected to GVRET ") + QString::number(build); - if (swCAN == 1) str += "(SW)"; - lbStatusConnected.setText(str); - - if (build < CURRENT_GVRET_VER) - { - QMessageBox msgBox; - msgBox.setText("It appears that you are not running\nan up-to-date version of GVRET\n\nYour version: " - + QString::number(build) +"\nCurrent Version: " + QString::number(CURRENT_GVRET_VER) - + "\n\nPlease upgrade your firmware version.\nOtherwise, you may experience difficulties."); - msgBox.exec(); - } - - if (connectionWindow) - { - if (swCAN == 1) connectionWindow->setSWMode(true); - else connectionWindow->setSWMode(false); - } -} - void MainWindow::showSettingsDialog() { if (!settingsDialog) diff --git a/mainwindow.h b/mainwindow.h index 97f4a07..2ad48bc 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -75,9 +75,7 @@ private slots: void showBisectWindow(); void exitApp(); void handleSaveDecoded(); - void connectionFailed(); - void gotDeviceInfo(int, int); - void connectionSucceeded(int, int); + void connectionStatusUpdated(int conns); void gridClicked(QModelIndex); void gridDoubleClicked(QModelIndex); void interpretToggled(bool); From 96523cc082c61704bef8e126e4439f28e7d89e1f Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Wed, 21 Dec 2016 20:19:23 -0500 Subject: [PATCH 82/86] Disable controls that don't do anything for socketcan --- connections/connectionwindow.cpp | 18 +++++++++++++++--- connections/socketcan.cpp | 3 +++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/connections/connectionwindow.cpp b/connections/connectionwindow.cpp index df71109..782385a 100644 --- a/connections/connectionwindow.cpp +++ b/connections/connectionwindow.cpp @@ -257,6 +257,7 @@ void ConnectionWindow::selectSerial() { /* set combobox page visible */ ui->stPort->setCurrentWidget(ui->cbPage); + ui->cbSpeed->setEnabled(true); ui->cbPort->clear(); ports = QSerialPortInfo::availablePorts(); @@ -269,6 +270,7 @@ void ConnectionWindow::selectKvaser() { /* set combobox page visible */ ui->stPort->setCurrentWidget(ui->cbPage); + ui->cbSpeed->setEnabled(false); } void ConnectionWindow::selectSocketCan() @@ -298,11 +300,21 @@ void ConnectionWindow::setPortName(CANCon::type pType, QString pPortName) switch(pType) { case CANCon::GVRET_SERIAL: - ui->rbGVRET->setChecked(true); break; + ui->rbGVRET->setChecked(true); + ui->cbSpeed->setEnabled(true); + ui->ckListenOnly->setEnabled(true); + ui->ckSingleWire->setEnabled(true); + break; case CANCon::KVASER: - ui->rbKvaser->setChecked(true); break; + ui->rbKvaser->setChecked(true); + break; case CANCon::SOCKETCAN: - ui->rbSocketCAN->setChecked(true); break; + ui->rbSocketCAN->setChecked(true); + //you can't configure any of the below three with socketcan so dim them out + ui->cbSpeed->setEnabled(false); + ui->ckListenOnly->setEnabled(false); + ui->ckSingleWire->setEnabled(false); + break; default: {} } diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 771f686..fd6efc3 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -92,6 +92,9 @@ void SocketCan::piSetBusSettings(int pBusIdx, CANBus bus) mDev->setConfigurationParameter(item.first, item.second); }*/ + //You cannot set the speed of a socketcan interface, it has to be set with console commands. + //mDev_p->setConfigurationParameter(QCanBusDevice::BitRateKey, bus.speed); + /* connect device */ if (!mDev_p->connectDevice()) { disconnectDevice(); From beea680106a0f1e8c9520fdd95cef7c70c36f420 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 29 Dec 2016 19:13:51 -0500 Subject: [PATCH 83/86] Changed the way the filter system works in the CAN connection objects - now used only for sending frames immediately to relevant objects. Tested to work in firmware updater. Currently broken elsewhere. Also switched main frame update interval from 4 times per second to 8 to make things smoother. --- can_structs.h | 1 - connections/canconmanager.cpp | 69 +++++++++++++++++++++++++++- connections/canconmanager.h | 20 ++++++++- connections/canconnection.cpp | 84 ++++++++++++++++++++--------------- connections/canconnection.h | 43 ++++++++---------- connections/gvretserial.cpp | 1 + connections/socketcan.cpp | 12 ++--- firmwareuploaderwindow.cpp | 11 ++++- firmwareuploaderwindow.h | 3 +- mainwindow.cpp | 2 - scriptcontainer.cpp | 13 +++--- 11 files changed, 172 insertions(+), 87 deletions(-) diff --git a/can_structs.h b/can_structs.h index d9fa1c5..3b6f222 100644 --- a/can_structs.h +++ b/can_structs.h @@ -20,7 +20,6 @@ struct CANFlt { quint32 id; quint32 mask; - bool notify; }; struct J1939ID diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index a0a061d..487c750 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -17,7 +17,7 @@ CANConManager* CANConManager::getInstance() CANConManager::CANConManager(QObject *parent): QObject(parent) { connect(&mTimer, SIGNAL(timeout()), this, SLOT(refreshCanList())); - mTimer.setInterval(250); /*tick 4 times a second */ + mTimer.setInterval(125); /*tick 8 times a second */ mTimer.setSingleShot(false); mTimer.start(); @@ -38,7 +38,8 @@ CANConManager::~CANConManager() void CANConManager::add(CANConnection* pConn_p) { - connect(pConn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); + //connect(pConn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); + connect(pConn_p, SIGNAL(targettedFrameReceived(CANFrame)), this, SLOT(gotTargettedFrame(CANFrame))); mConns.append(pConn_p); emit connectionStatusUpdated(getNumBuses()); } @@ -179,3 +180,67 @@ bool CANConManager::sendFrames(const QList& pFrames) return true; } + +//For each device associated with buses go through and see if that device has a bus +//that the filter should apply to. If so forward the data on but fudge +//the bus numbers if bus wasn't -1 so that they're local to the device +bool CANConManager::addTargettedFrame(int pBusId, const CANFlt &target) +{ + int tempBusVal; + int busBase = 0; + + foreach (CANConnection* conn, mConns) + { + if (pBusId == -1) conn->addTargettedFrame(pBusId, target); + else + { + tempBusVal = pBusId >> busBase; + tempBusVal &= ((1 << conn->getNumBuses()) - 1); + if (tempBusVal) { + qDebug() << "Forwarding targetted frame setting to a connection object"; + conn->addTargettedFrame(tempBusVal, target); + } + } + busBase += conn->getNumBuses(); + } +} + +bool CANConManager::removeTargettedFrame(int pBusId, const CANFlt &target) +{ + int tempBusVal; + int busBase = 0; + + foreach (CANConnection* conn, mConns) + { + if (pBusId == -1) conn->removeTargettedFrame(pBusId, target); + else + { + tempBusVal = pBusId >> busBase; + tempBusVal &= ((1 << conn->getNumBuses()) - 1); + if (tempBusVal) conn->removeTargettedFrame(tempBusVal, target); + } + busBase += conn->getNumBuses(); + } +} + +/* + * A connected CANConnection object has passed us a frame that one or more + * other objects are interested in. Fix up the bus number to be a system global bus + * number instead of connection local bus number then send it off again. +*/ +void CANConManager::gotTargettedFrame(CANFrame frame) +{ + int busBase = 0; + + foreach (CANConnection* conn, mConns) + { + if (conn != sender()) busBase += conn->getNumBuses(); + else break; + } + + qDebug() << "Targetted frame, offset was " << busBase << " id was " << frame.ID; + + frame.bus += busBase; + + emit targettedFrameReceived(frame); +} diff --git a/connections/canconmanager.h b/connections/canconmanager.h index 5abfae9..9467f8a 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -36,12 +36,30 @@ public: //just the multi-frame version of above function. bool sendFrames(const QList& pFrames); + /** + * @brief Add a new filter for the targetted frames. If a frame matches it will immediately be sent via the targettedFrameReceived signal + * @param pBusId - Which bus to bond to. -1 for any, otherwise a bitfield of buses (but 0 = first bus, etc) + * @param target - The filter to use for selected targetted frames + * @return true if filter was able to be added, false otherwise. + */ + bool addTargettedFrame(int pBusId, const CANFlt &target); + + /** + * @brief Try to find a matching filter in the list and remove it, no longer targetting those frames + * @param pBusId - Which bus to bond to. Doesn't have to match the call to addTargettedFrame exactly. You could disconnect just one bus for instance. + * @param target - The filter that was set + * @return true if filter was found and deleted, false otherwise. + */ + bool removeTargettedFrame(int pBusId, const CANFlt &target); + signals: void framesReceived(CANConnection* pConn_p, QVector& pFrames); + void targettedFrameReceived(CANFrame frame); void connectionStatusUpdated(int conns); private slots: - void refreshCanList(); + void refreshCanList(); + void gotTargettedFrame(CANFrame frame); private: explicit CANConManager(QObject *parent = 0); diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 778890f..9f29e39 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -5,8 +5,7 @@ struct BusData { CANBus mBus; bool mConfigured; - QVector mFilters; - bool mFilterOut; + QVector mTargettedFrames; }; @@ -38,7 +37,6 @@ CANConnection::CANConnection(QString pPort, mBusData_p = new BusData[mNumBuses]; for(int i=0 ; i& pFilters, bool pFilterOut) +bool CANConnection::addTargettedFrame(int pBusId, const CANFlt &target) { /* make sure we execute in mThread context */ if( mThread_p && (mThread_p != QThread::currentThread()) ) { bool ret; - QMetaObject::invokeMethod(this, "setFilters", + QMetaObject::invokeMethod(this, "addTargettedFrame", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, ret), Q_ARG(int , pBusId), - Q_ARG(const QVector&, pFilters), - Q_ARG(bool , pFilterOut)); + Q_ARG(const CANFlt&, target)); return ret; } /* sanity checks */ - if(pBusId<0 || pBusId>=getNumBuses()) + if(pBusId < -1 || pBusId >= (1 << getNumBuses())) return false; - /* copy filters */ - mBusData_p[pBusId].mFilters = pFilters; - mBusData_p[pBusId].mFilterOut = pFilterOut; - - /* set hardware filtering if available */ - if(pFilterOut) - piSetFilters(pBusId, pFilters); + for (int i = 0; i < getNumBuses(); i++) + { + if (pBusId == -1 || pBusId && (1 << i)) { + qDebug() << "Connection is registering a new targetted frame filter"; + mBusData_p[i].mTargettedFrames.append(target); + } + } return true; } - -bool CANConnection::discard(int pBusId, quint32 pId, bool& pNotify) +bool CANConnection::removeTargettedFrame(int pBusId, const CANFlt &target) { - if(pBusId<0 || pBusId>=getNumBuses()) - return true; - - foreach (const CANFlt& filter, mBusData_p[pBusId].mFilters) - { - if( (filter.id & filter.mask) == (pId & filter.mask) ) - { - if(filter.notify) - pNotify = true; - return false; - } + /* make sure we execute in mThread context */ + if( mThread_p && (mThread_p != QThread::currentThread()) ) { + bool ret; + QMetaObject::invokeMethod(this, "addTargettedFrame", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(bool, ret), + Q_ARG(int , pBusId), + Q_ARG(const CANFlt&, target)); + return ret; } - return mBusData_p[pBusId].mFilterOut; + + /* sanity checks */ + if(pBusId < -1 || pBusId >= (1 << getNumBuses())) + return false; + + for (int i = 0; i < getNumBuses(); i++) + { + //if (pBusId == -1 || (pBusId && (1 << i))) + //mBusData_p[i].mTargettedFrames.removeOne(target); + } + + return true; } +void CANConnection::checkTargettedFrame(CANFrame &frame) +{ + int maskedID; + foreach (const CANFlt filt, mBusData_p[frame.bus].mTargettedFrames) + { + maskedID = frame.ID & filt.mask; + if (maskedID == filt.id) { + qDebug() << "In connection object I got a targetted frame. Forwarding it."; + emit targettedFrameReceived(frame); + return; //only match once then stop. + } + } +} bool CANConnection::piSendFrames(const QList& pFrames) { @@ -316,11 +334,3 @@ bool CANConnection::piSendFrames(const QList& pFrames) return true; } - - -/* default implementation of piSetFilters */ -void CANConnection::piSetFilters(int pBusId, const QVector& pFilters) -{ - Q_UNUSED(pBusId); - Q_UNUSED(pFilters); -} diff --git a/connections/canconnection.h b/connections/canconnection.h index b0c8f51..8633a2a 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -81,9 +81,9 @@ signals: void busStatus(int, int, int); /** - * @brief event sent when a frame matching a filter set with notification hs been received + * @brief event sent when a frame matching a filter is received */ - void notify(); + void targettedFrameReceived(CANFrame frame); /** * @brief event emitted when the CANCon::status of the connection changes (connected->not_connected or the other way round) @@ -149,15 +149,26 @@ public slots: bool sendFrames(const QList& pFrames); /** - * @brief sets a filter list. Filters can be used to send a signal or filter out messages - * @param pFilters: a vector of can filters - * @param pFilterOut: if set to true, can frames not matching a filter are discarded - * @return true if filters have been set, false if busid is invalid + * @brief Add a new filter for the targetted frames. If a frame matches it will immediately be sent via the targettedFrameReceived signal + * @param pBusId - Which bus to bond to. -1 for any, otherwise a bitfield of buses (but 0 = first bus, etc) + * @param target - The filter to use for selected targetted frames + * @return true if filter was able to be added, false otherwise. */ - bool setFilters(int pBusId, const QVector& pFilters, bool pFilterOut); + bool addTargettedFrame(int pBusId, const CANFlt &target); + + /** + * @brief Try to find a matching filter in the list and remove it, no longer targetting those frames + * @param pBusId - Which bus to bond to. Doesn't have to match the call to addTargettedFrame exactly. You could disconnect just one bus for instance. + * @param target - The filter that was set + * @return true if filter was found and deleted, false otherwise. + */ + bool removeTargettedFrame(int pBusId, const CANFlt &target); protected: + //determine if the passed frame is part of a filter or not. + void checkTargettedFrame(CANFrame &frame); + /** * @brief setStatus * @param pStatus: the status to set @@ -206,16 +217,6 @@ protected: */ void setCapSuspended(bool pIsSuspended); - /** - * @brief used to check if a message shall be discarded. The function also update pNotify if a notification is expected for that message - * @param pBusId: the bus id on which the frame has been received - * @param pId: the id of the message to filter - * @param pNotify: set to true if a notification is expected, else pNotify is not set - * @return true if message shall be discarded - */ - bool discard(int pBusId, quint32 pId, bool& pNotify); - - protected: /**************************************************************/ @@ -269,14 +270,6 @@ protected: */ virtual bool piSendFrames(const QList&); - /** - * @brief sets a hardware filter list - * @param pBusId: the bus id on which filters have to be set - * @param pFilters: a vector of can filters, the notification flag of CANFilter is ignored - * @note implementing this function is optional - */ - virtual void piSetFilters(int pBusId, const QVector& pFilters); - private: LFQueue mQueue; const int mNumBuses; diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index af60a1e..d669118 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -417,6 +417,7 @@ void GVRetSerial::procRXChar(unsigned char c) //qDebug() << "GVRET got frame on bus " << frame_p->bus; /* copy frame */ *frame_p = buildFrame; + checkTargettedFrame(buildFrame); /* enqueue frame */ getQueue().queue(); } diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index fd6efc3..2250fc0 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -155,9 +155,6 @@ void SocketCan::framesWritten(qint64 count) void SocketCan::framesReceived() { - /* test */ - bool sndNotif = false; - uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis(); /* sanity checks */ @@ -179,8 +176,7 @@ void SocketCan::framesReceived() /* check frame */ if( !recFrame.payload().isEmpty() && - recFrame.payload().length()<=8 && - !discard(0, recFrame.frameId(), sndNotif) ) + recFrame.payload().length()<=8 ) { CANFrame* frame_p = getQueue().get(); if(frame_p) { @@ -192,6 +188,8 @@ void SocketCan::framesReceived() frame_p->isReceived = true; frame_p->timestamp = (recFrame.timeStamp().seconds()*1000000 + recFrame.timeStamp().microSeconds()) - timeBasis; + checkTargettedFrame(*frame_p); + /* enqueue frame */ getQueue().queue(); } @@ -201,10 +199,6 @@ void SocketCan::framesReceived() #endif } } - - if(sndNotif) { - emit notify(); - } } diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index e6cef48..8d12f14 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -27,10 +27,17 @@ FirmwareUploaderWindow::FirmwareUploaderWindow(const QVector *frames, timer = new QTimer(); timer->setInterval(100); //100ms without a reply will cause us to attempt a resend + CANFlt firmwareFilter; + firmwareFilter.id = 0x100; + firmwareFilter.mask = 0x7F0; + CANConManager::getInstance()->addTargettedFrame(-1, firmwareFilter); + //MainWindow::getReference()->setTargettedID(baseAddress + 0x10); + connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int))); connect(ui->btnLoadFile, SIGNAL(clicked(bool)), this, SLOT(handleLoadFile())); connect(ui->btnStartStop, SIGNAL(clicked(bool)), this, SLOT(handleStartStopTransfer())); connect(timer, SIGNAL(timeout()), this, SLOT(timerElapsed())); + connect(CANConManager::getInstance(), SIGNAL(targettedFrameReceived(CANFrame)), this, SLOT(gotTargettedFrame(CANFrame))); } FirmwareUploaderWindow::~FirmwareUploaderWindow() @@ -66,9 +73,9 @@ void FirmwareUploaderWindow::updatedFrames(int numFrames) } } -void FirmwareUploaderWindow::gotTargettedFrame(int frameLoc) +void FirmwareUploaderWindow::gotTargettedFrame(CANFrame frame) { - const CANFrame &frame = modelFrames->at(frameLoc); + qDebug() << "FUW: Got targetted frame with id " << frame.ID; if (frame.ID == (baseAddress + 0x10)) { qDebug() << "Start firmware reply"; if ((frame.data[0] == 0xAD) && (frame.data[1] == 0xDE)) diff --git a/firmwareuploaderwindow.h b/firmwareuploaderwindow.h index 22221b9..ec07906 100644 --- a/firmwareuploaderwindow.h +++ b/firmwareuploaderwindow.h @@ -4,6 +4,7 @@ #include #include #include "can_structs.h" +#include "connections/canconmanager.h" #include "utility.h" namespace Ui { @@ -22,7 +23,7 @@ signals: void sendCANFrame(const CANFrame *); public slots: - void gotTargettedFrame(int frameLoc); + void gotTargettedFrame(CANFrame frame); private slots: void handleLoadFile(); diff --git a/mainwindow.cpp b/mainwindow.cpp index 69af4e3..7d12ef2 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -852,8 +852,6 @@ void MainWindow::showFirmwareUploaderWindow() if (!firmwareUploaderWindow) { firmwareUploaderWindow = new FirmwareUploaderWindow(model->getListReference()); - //connect(firmwareUploaderWindow, SIGNAL(sendCANFrame(const CANFrame*)), connectionWindow, SLOT(sendFrame(const CANFrame*))); - //connect(worker, SIGNAL(gotTargettedFrame(int)), firmwareUploaderWindow, SLOT(gotTargettedFrame(int))); } firmwareUploaderWindow->show(); } diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 5c4bfa4..c605bb2 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -71,18 +71,17 @@ void ScriptContainer::setFilter(QJSValue id, QJSValue mask, QJSValue bus) CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); if(conn_p) { + CANFlt canFlt; for(int i=0 ; igetNumBuses() ; i++) { - QVector fltrs; foreach(const CANFilter& flt, filters) { if(flt.bus==i) { - fltrs.append({flt.ID, flt.mask, true}); + canFlt.id = idVal; + canFlt.mask = maskVal; + conn_p->addTargettedFrame(busVal, canFlt); } } - - if(fltrs.size()) - conn_p->setFilters(i, fltrs, false); } } } @@ -108,8 +107,8 @@ void ScriptContainer::clearFilters() CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); if(conn_p) { - for(int i=0 ; igetNumBuses() ; i++) - conn_p->setFilters(i, QVector(), false); + //for(int i=0 ; igetNumBuses() ; i++) + //conn_p->setFilters(i, QVector(), false); } } From 7222870b1e4f30edf62c852acf6648daffc5fccb Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Thu, 29 Dec 2016 20:50:02 -0500 Subject: [PATCH 84/86] Many little fixes to clean up warnings and bugs. --- bisectwindow.cpp | 4 ++-- can_structs.h | 6 +++--- canframemodel.cpp | 8 ++++---- canframemodel.h | 4 ++-- connections/canconmanager.cpp | 4 +++- connections/canconnection.cpp | 4 ++-- connections/gvretserial.cpp | 6 ++---- connections/gvretserial.h | 2 +- connections/socketcan.cpp | 1 + dbc/dbchandler.cpp | 12 +++++++----- dbc/dbchandler.h | 4 ++-- dbc/dbcloadsavewindow.cpp | 1 + firmwareuploaderwindow.cpp | 7 +++---- framefileio.cpp | 6 ++++-- frameplaybackwindow.cpp | 2 +- framesenderwindow.cpp | 11 +++++------ mainwindow.cpp | 4 ++++ re/discretestatewindow.cpp | 4 +++- re/filecomparatorwindow.cpp | 2 +- re/flowviewwindow.cpp | 6 +++--- re/frameinfowindow.cpp | 4 ++-- re/fuzzingwindow.cpp | 3 +-- re/graphingwindow.cpp | 5 ++++- re/isotp_handler.cpp | 4 ++-- re/newgraphdialog.cpp | 1 - re/rangestatewindow.cpp | 6 +++--- re/udsscanwindow.cpp | 4 ++-- scriptcontainer.cpp | 3 +-- scriptingwindow.cpp | 1 - 29 files changed, 69 insertions(+), 60 deletions(-) diff --git a/bisectwindow.cpp b/bisectwindow.cpp index a404c14..bbf9324 100644 --- a/bisectwindow.cpp +++ b/bisectwindow.cpp @@ -103,8 +103,8 @@ void BisectWindow::handleCalculateButton() } else if (ui->rbIDRange->isChecked()) { - int lowerID = Utility::ParseStringToNum2(ui->cbIDLower->currentText()); - int upperID = Utility::ParseStringToNum2(ui->cbIDUpper->currentText()); + uint32_t lowerID = Utility::ParseStringToNum2(ui->cbIDLower->currentText()); + 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)); diff --git a/can_structs.h b/can_structs.h index 3b6f222..aaba0b2 100644 --- a/can_structs.h +++ b/can_structs.h @@ -7,8 +7,8 @@ struct CANFrame { public: - int ID; - int bus; + uint32_t ID; + uint32_t bus; bool extended; bool isReceived; //did we receive this or send it? uint32_t len; @@ -38,7 +38,7 @@ public: struct ISOTP_MESSAGE { public: - int ID; + uint32_t ID; int bus; bool extended; bool isReceived; diff --git a/canframemodel.cpp b/canframemodel.cpp index 6263bf9..5e9c816 100644 --- a/canframemodel.cpp +++ b/canframemodel.cpp @@ -131,7 +131,7 @@ void CANFrameModel::setOverwriteMode(bool mode) endResetModel(); } -void CANFrameModel::setFilterState(int ID, bool state) +void CANFrameModel::setFilterState(unsigned int ID, bool state) { if (!filters.contains(ID)) return; filters[ID] = state; @@ -263,8 +263,8 @@ QVariant CANFrameModel::data(const QModelIndex &index, int role) const return QVariant(); } } - else - return QVariant(); + + return QVariant(); } QVariant CANFrameModel::headerData(int section, Qt::Orientation orientation, @@ -480,7 +480,7 @@ void CANFrameModel::insertFrames(const QVector &newFrames) if (needFilterRefresh) emit updatedFiltersList(); } -int CANFrameModel::getIndexFromTimeID(int ID, double timestamp) +int CANFrameModel::getIndexFromTimeID(unsigned int ID, double timestamp) { int bestIndex = -1; uint64_t intTimeStamp = timestamp * 1000000l; diff --git a/canframemodel.h b/canframemodel.h index a26e7f3..5099e7c 100644 --- a/canframemodel.h +++ b/canframemodel.h @@ -33,7 +33,7 @@ public: void setInterpetMode(bool); void setOverwriteMode(bool); void setHexMode(bool); - void setFilterState(int ID, bool state); + void setFilterState(unsigned int ID, bool state); void setAllFilters(bool state); void setSecondsMode(bool); void loadFilterFile(QString filename); @@ -42,7 +42,7 @@ public: void recalcOverwrite(); bool needsFilterRefresh(); void insertFrames(const QVector &newFrames); - int getIndexFromTimeID(int ID, double timestamp); + int getIndexFromTimeID(unsigned int ID, double timestamp); const QVector *getListReference() const; //thou shalt not modify these frames externally! const QVector *getFilteredListReference() const; //Thus saith the Lord, NO. const QMap *getFiltersReference() const; //this neither diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 487c750..9bdf220 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -155,7 +155,7 @@ 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 < busBase + conn->getNumBuses()) + if (pFrame.bus < (uint32_t)(busBase + conn->getNumBuses())) { workingFrame.bus -= busBase; workingFrame.isReceived = false; @@ -203,6 +203,7 @@ bool CANConManager::addTargettedFrame(int pBusId, const CANFlt &target) } busBase += conn->getNumBuses(); } + return true; } bool CANConManager::removeTargettedFrame(int pBusId, const CANFlt &target) @@ -221,6 +222,7 @@ bool CANConManager::removeTargettedFrame(int pBusId, const CANFlt &target) } busBase += conn->getNumBuses(); } + return true; } /* diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 9f29e39..b9b5f5b 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -275,7 +275,7 @@ bool CANConnection::addTargettedFrame(int pBusId, const CANFlt &target) for (int i = 0; i < getNumBuses(); i++) { - if (pBusId == -1 || pBusId && (1 << i)) { + if ( (pBusId == -1) || (pBusId && (1 << i)) ) { qDebug() << "Connection is registering a new targetted frame filter"; mBusData_p[i].mTargettedFrames.append(target); } @@ -312,7 +312,7 @@ bool CANConnection::removeTargettedFrame(int pBusId, const CANFlt &target) void CANConnection::checkTargettedFrame(CANFrame &frame) { - int maskedID; + unsigned int maskedID; foreach (const CANFlt filt, mBusData_p[frame.bus].mTargettedFrames) { maskedID = frame.ID & filt.mask; diff --git a/connections/gvretserial.cpp b/connections/gvretserial.cpp index d669118..fbe1ba9 100644 --- a/connections/gvretserial.cpp +++ b/connections/gvretserial.cpp @@ -146,10 +146,8 @@ void GVRetSerial::piSetBusSettings(int pBusIdx, CANBus bus) bool GVRetSerial::piSendFrame(const CANFrame& frame) { QByteArray buffer; - int c; + unsigned int c; int ID; - CANFrame tempFrame = frame; - tempFrame.isReceived = false; //qDebug() << "Sending out GVRET frame with id " << frame.ID << " on bus " << frame.bus; @@ -386,7 +384,7 @@ void GVRetSerial::procRXChar(unsigned char c) break; case 7: buildFrame.ID |= c << 24; - if ((buildFrame.ID & 1 << 31) == 1 << 31) + if ((buildFrame.ID & 1 << 31) == 1u << 31) { buildFrame.ID &= 0x7FFFFFFF; buildFrame.extended = true; diff --git a/connections/gvretserial.h b/connections/gvretserial.h index b4bfa4c..5180b27 100644 --- a/connections/gvretserial.h +++ b/connections/gvretserial.h @@ -77,7 +77,7 @@ protected: QSerialPort *serial; int framesRapid; STATE rx_state; - int rx_step; + uint32_t rx_step; CANFrame buildFrame; int can0Baud, can1Baud; bool can0Enabled, can1Enabled; diff --git a/connections/socketcan.cpp b/connections/socketcan.cpp index 2250fc0..7402a48 100644 --- a/connections/socketcan.cpp +++ b/connections/socketcan.cpp @@ -150,6 +150,7 @@ void SocketCan::errorReceived(QCanBusDevice::CanBusError error) const void SocketCan::framesWritten(qint64 count) { + Q_UNUSED(count); //qDebug() << "Number of frames written:" << count; } diff --git a/dbc/dbchandler.cpp b/dbc/dbchandler.cpp index 2142ee3..0cb5124 100644 --- a/dbc/dbchandler.cpp +++ b/dbc/dbchandler.cpp @@ -37,6 +37,7 @@ bool DBCSignalHandler::addSignal(DBC_SIGNAL &sig) bool DBCSignalHandler::removeSignal(DBC_SIGNAL *sig) { + Q_UNUSED(sig); //if (sigs.removeAll(*sig) > 0) return true; return false; } @@ -75,7 +76,7 @@ int DBCSignalHandler::getCount() return sigs.count(); } -DBC_MESSAGE* DBCMessageHandler::findMsgByID(int id) +DBC_MESSAGE* DBCMessageHandler::findMsgByID(uint32_t id) { if (messages.count() == 0) return NULL; for (int i = 0; i < messages.count(); i++) @@ -117,6 +118,7 @@ bool DBCMessageHandler::addMessage(DBC_MESSAGE &msg) bool DBCMessageHandler::removeMessage(DBC_MESSAGE *msg) { + Q_UNUSED(msg); //if (messages.removeAll(*msg) > 0) return true; return false; } @@ -130,7 +132,7 @@ bool DBCMessageHandler::removeMessageByIndex(int idx) return true; } -bool DBCMessageHandler::removeMessage(int ID) +bool DBCMessageHandler::removeMessage(uint32_t ID) { bool foundSome = false; if (messages.count() == 0) return false; @@ -302,7 +304,7 @@ void DBCFile::loadFile(QString fileName) { int offset = 0; bool isMultiplexor = false; - bool isMultiplexed = false; + //bool isMultiplexed = false; DBC_SIGNAL sig; sig.multiplexValue = 0; @@ -326,7 +328,7 @@ void DBCFile::loadFile(QString fileName) if (match.hasMatch()) { qDebug() << "Multiplexed signal"; - isMultiplexed = true; + //isMultiplexed = true; sig.isMultiplexed = true; sig.multiplexValue = match.captured(2).toInt(); offset = 1; @@ -805,7 +807,7 @@ DBC_MESSAGE* DBCHandler::findMessage(const CANFrame &frame) { for(int i = 0; i < loadedFiles.count(); i++) { - if (loadedFiles[i].getAssocBus() == -1 || frame.bus == loadedFiles[i].getAssocBus()) + if (loadedFiles[i].getAssocBus() == -1 || frame.bus == (unsigned int)loadedFiles[i].getAssocBus()) { DBC_MESSAGE* msg = loadedFiles[i].messageHandler->findMsgByID(frame.ID); if (msg != NULL) return msg; diff --git a/dbc/dbchandler.h b/dbc/dbchandler.h index 80376da..5f74ee8 100644 --- a/dbc/dbchandler.h +++ b/dbc/dbchandler.h @@ -32,13 +32,13 @@ class DBCMessageHandler: public QObject { Q_OBJECT public: - DBC_MESSAGE *findMsgByID(int id); + DBC_MESSAGE *findMsgByID(uint32_t id); DBC_MESSAGE *findMsgByIdx(int idx); DBC_MESSAGE *findMsgByName(QString name); bool addMessage(DBC_MESSAGE &msg); bool removeMessage(DBC_MESSAGE *msg); bool removeMessageByIndex(int idx); - bool removeMessage(int ID); + bool removeMessage(uint32_t ID); bool removeMessage(QString name); void removeAllMessages(); int getCount(); diff --git a/dbc/dbcloadsavewindow.cpp b/dbc/dbcloadsavewindow.cpp index 0ef704d..a37f813 100644 --- a/dbc/dbcloadsavewindow.cpp +++ b/dbc/dbcloadsavewindow.cpp @@ -114,6 +114,7 @@ void DBCLoadSaveWindow::cellChanged(int row, int col) void DBCLoadSaveWindow::cellDoubleClicked(int row, int col) { + Q_UNUSED(col) editorWindow->setFileIdx(row); editorWindow->show(); } diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index 8d12f14..aaec100 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -54,7 +54,7 @@ void FirmwareUploaderWindow::updateProgress() void FirmwareUploaderWindow::updatedFrames(int numFrames) { - CANFrame thisFrame; + //CANFrame thisFrame; if (numFrames == -1) //all frames deleted. { } @@ -76,7 +76,7 @@ void FirmwareUploaderWindow::updatedFrames(int numFrames) void FirmwareUploaderWindow::gotTargettedFrame(CANFrame frame) { qDebug() << "FUW: Got targetted frame with id " << frame.ID; - if (frame.ID == (baseAddress + 0x10)) { + if (frame.ID == (uint32_t)(baseAddress + 0x10)) { qDebug() << "Start firmware reply"; if ((frame.data[0] == 0xAD) && (frame.data[1] == 0xDE)) { @@ -97,7 +97,7 @@ void FirmwareUploaderWindow::gotTargettedFrame(CANFrame frame) } } - if (frame.ID == (baseAddress + 0x20)) { + if (frame.ID == (uint32_t)(baseAddress + 0x20)) { qDebug() << "Firmware reception success reply"; int seq = frame.data[0] + (256 * frame.data[1]); if (seq == currentSendingPosition) @@ -201,7 +201,6 @@ void FirmwareUploaderWindow::handleLoadFile() { QString filename; QFileDialog dialog; - bool result = false; QStringList filters; filters.append(QString(tr("Raw firmware binary (*.bin)"))); diff --git a/framefileio.cpp b/framefileio.cpp index b7e37e6..9e7defb 100644 --- a/framefileio.cpp +++ b/framefileio.cpp @@ -246,6 +246,8 @@ bool FrameFileIO::loadVehicleSpyFile(QString filename, QVector *frames bool FrameFileIO::saveVehicleSpyFile(QString filename, const QVector *frames) { + Q_UNUSED(filename); + Q_UNUSED(frames); return true; } @@ -440,7 +442,7 @@ bool FrameFileIO::loadPCANFile(QString filename, QVector* frames) thisFrame.bus = 0; thisFrame.extended = false; QList tokens = line.mid(41, thisFrame.len * 3).split(' '); - for (int d = 0; d < thisFrame.len; d++) + for (unsigned int d = 0; d < thisFrame.len; d++) { if (tokens[d] != "") { @@ -580,7 +582,7 @@ bool FrameFileIO::saveNativeCSVFile(QString filename, const QVector* f outFile->write(QString::number(frames->at(c).len).toUtf8()); outFile->putChar(44); - for (int temp = 0; temp < 8; temp++) + for (unsigned 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()); diff --git a/frameplaybackwindow.cpp b/frameplaybackwindow.cpp index f2f631d..4145803 100644 --- a/frameplaybackwindow.cpp +++ b/frameplaybackwindow.cpp @@ -594,7 +594,7 @@ void FramePlaybackWindow::updatePosition(bool forward) thisFrame->bus = whichBusSend; sendingBuffer.append(*thisFrame); } - else if (whichBusSend = ui->comboCANBus->count() - 2) //all + else if (whichBusSend == (ui->comboCANBus->count() - 2)) //all { for (int c = 0; c < ui->comboCANBus->count() - 2; c++) { diff --git a/framesenderwindow.cpp b/framesenderwindow.cpp index 77b3490..e91d12b 100644 --- a/framesenderwindow.cpp +++ b/framesenderwindow.cpp @@ -140,9 +140,9 @@ 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 && thisTrigger->ID == frame->ID) + if (thisTrigger->ID > 0 && (uint32_t)thisTrigger->ID == frame->ID) { - if (thisTrigger->bus == frame->bus || thisTrigger->bus == -1) + if ((uint32_t)thisTrigger->bus == frame->bus || thisTrigger->bus == -1) { if (thisTrigger->currCount < thisTrigger->maxCount) { @@ -458,7 +458,7 @@ CANFrame* FrameSenderWindow::lookupFrame(int ID, int bus) { if (!frameCache.contains(ID)) return NULL; - if (bus == -1 || frameCache[ID].bus == bus) return &frameCache[ID]; + if (bus == -1 || frameCache[ID].bus == (unsigned int)bus) return &frameCache[ID]; return NULL; } @@ -472,7 +472,7 @@ void FrameSenderWindow::processModifierText(int line) { qDebug() << "processModifierText"; QString modString; - bool firstOp = true; + //bool firstOp = true; bool abort = false; QString token; ModifierOp thisOp; @@ -496,7 +496,6 @@ void FrameSenderWindow::processModifierText(int line) { Modifier thisMod; thisMod.destByte = 0; - firstOp = true; QString leftSide = Utility::grabAlphaNumeric(mods[i]); if (leftSide.startsWith("D") && leftSide.length() == 2) @@ -702,7 +701,7 @@ void FrameSenderWindow::updateGridRow(int idx) QTableWidgetItem *item = ui->tableSender->item(gridLine, 7); if (item == NULL) item = new QTableWidgetItem(); item->setText(QString::number(temp->count)); - for (int i = 0; i < temp->len; i++) + for (unsigned int i = 0; i < temp->len; i++) { dataString.append(Utility::formatNumber(temp->data[i])); dataString.append(" "); diff --git a/mainwindow.cpp b/mainwindow.cpp index 7d12ef2..3c00e91 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -381,6 +381,10 @@ void MainWindow::writeSettings() void MainWindow::updateConnectionSettings(QString connectionType, QString port, int speed0, int speed1) { + Q_UNUSED(connectionType); + Q_UNUSED(port); + Q_UNUSED(speed0); + Q_UNUSED(speed1); //connType = connectionType; //portName = port; diff --git a/re/discretestatewindow.cpp b/re/discretestatewindow.cpp index 473402e..f6f46be 100644 --- a/re/discretestatewindow.cpp +++ b/re/discretestatewindow.cpp @@ -267,6 +267,8 @@ void DiscreteStateWindow::handleTick() { case DWStates::IDLE: break; + case DWStates::DONE: + break; case DWStates::COUNTDOWN_SIGNAL: ticksUntilStateChange--; if (ticksUntilStateChange == 0) @@ -334,7 +336,7 @@ void DiscreteStateWindow::calculateResults() frameCache.clear(); for (int i = 0; i < modelFrames->count(); i++) { - if (modelFrames->at(i).ID == it.key()) frameCache.append(modelFrames->at(i)); + if (modelFrames->at(i).ID == (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 c7aeea2..9ab25f4 100644 --- a/re/filecomparatorwindow.cpp +++ b/re/filecomparatorwindow.cpp @@ -154,7 +154,7 @@ void FileComparatorWindow::calculateDetails() CANFrame frame = referenceFrames.at(x); if (referenceIDs.contains(frame.ID)) //if we saw this ID before then add to the QList in there { - for (int y = 0; y < frame.len; y++) + for (unsigned int y = 0; y < frame.len; y++) { referenceIDs[frame.ID].values[y][frame.data[y]]++; tmp = frame.data[y]; diff --git a/re/flowviewwindow.cpp b/re/flowviewwindow.cpp index f443d49..37c2c55 100644 --- a/re/flowviewwindow.cpp +++ b/re/flowviewwindow.cpp @@ -371,7 +371,7 @@ void FlowViewWindow::updatedFrames(int numFrames) else //just got some new frames. See if they are relevant. { if (numFrames > modelFrames->count()) return; - int refID; + unsigned int refID; if (frameCache.count() > 0) refID = frameCache[0].ID; else refID = 0; bool needRefresh = false; @@ -510,7 +510,7 @@ void FlowViewWindow::updateFrameLabel() void FlowViewWindow::changeID(QString newID) { //parse the ID and then load up the frame cache with just messages with that ID. - int id = Utility::ParseStringToNum(newID); + uint32_t id = (uint32_t)Utility::ParseStringToNum(newID); frameCache.clear(); if (modelFrames->count() == 0) return; @@ -531,7 +531,7 @@ void FlowViewWindow::changeID(QString newID) if (frameCache.count() == 0) return; removeAllGraphs(); - for (int c = 0; c < frameCache.at(0).len; c++) + for (uint32_t c = 0; c < frameCache.at(0).len; c++) { createGraph(c); } diff --git a/re/frameinfowindow.cpp b/re/frameinfowindow.cpp index 33c5aa5..4ba4433 100644 --- a/re/frameinfowindow.cpp +++ b/re/frameinfowindow.cpp @@ -84,7 +84,7 @@ void FrameInfoWindow::updatedFrames(int numFrames) else //just got some new frames. See if they are relevant. { if (numFrames > modelFrames->count()) return; - int currID = 0; + unsigned int currID = 0; if (ui->listFrameID->currentItem()) currID = ui->listFrameID->currentItem()->text().toInt(NULL, 16); bool foundID = false; @@ -140,7 +140,7 @@ void FrameInfoWindow::updateDetailsWindow(QString newID) for (int i = 0; i < modelFrames->count(); i++) { CANFrame thisFrame = modelFrames->at(i); - if (thisFrame.ID == targettedID) frameCache.append(thisFrame); + if (thisFrame.ID == (unsigned int)targettedID) frameCache.append(thisFrame); } ui->treeDetails->clear(); diff --git a/re/fuzzingwindow.cpp b/re/fuzzingwindow.cpp index 0ae427f..d2b62a3 100644 --- a/re/fuzzingwindow.cpp +++ b/re/fuzzingwindow.cpp @@ -50,7 +50,6 @@ FuzzingWindow::~FuzzingWindow() void FuzzingWindow::updatedFrames(int numFrames) { - CANFrame thisFrame; int id; if (numFrames == -1) //all frames deleted. Kill the display { @@ -257,7 +256,7 @@ void FuzzingWindow::calcNextBitPattern() for (int bit = 0; bit < 8; bit++) { thisBit = bitGrid[byt * 8 + bit]; - if (thisBit == 1 && (byt * 8 + bit) == bitAccum) + if ( (thisBit == 1) && (unsigned int)(byt * 8 + bit) == bitAccum) { currentBytes[byt] |= (1 << bit); } diff --git a/re/graphingwindow.cpp b/re/graphingwindow.cpp index 88a2ddf..a401eac 100644 --- a/re/graphingwindow.cpp +++ b/re/graphingwindow.cpp @@ -178,6 +178,7 @@ void GraphingWindow::plottableDoubleClick(QCPAbstractPlottable* plottable, QMous void GraphingWindow::gotCenterTimeID(int32_t ID, double timestamp) { + Q_UNUSED(ID) //its problematic to try to highlight a graph since we get the ID //and timestamp not the signal in question so there is no real way //to know which graph. But, if that changes here is a stub @@ -195,8 +196,8 @@ void GraphingWindow::gotCenterTimeID(int32_t ID, double timestamp) void GraphingWindow::titleDoubleClick(QMouseEvent* event, QCPPlotTitle* title) { Q_UNUSED(event) + Q_UNUSED(title) // Set the plot title by double clicking on it - bool ok; /* QString newTitle = QInputDialog::getText(this, "SavvyCAN Graphing", "New plot title:", QLineEdit::Normal, title->text(), &ok); @@ -354,6 +355,8 @@ bool GraphingWindow::eventFilter(QObject *obj, QEvent *event) // standard event processing return QObject::eventFilter(obj, event); } + + return false; } void GraphingWindow::resetView() diff --git a/re/isotp_handler.cpp b/re/isotp_handler.cpp index 0fdac38..f679213 100644 --- a/re/isotp_handler.cpp +++ b/re/isotp_handler.cpp @@ -151,7 +151,7 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) int frameType; int frameLen; int ln; - int offset; + //int offset; ISOTP_MESSAGE msg; ISOTP_MESSAGE *pMsg; @@ -230,7 +230,7 @@ void ISOTP_HANDLER::processFrame(const CANFrame &frame) } if (!pMsg) return; ln = pMsg->len - pMsg->data.count(); - offset = pMsg->data.count(); + //offset = pMsg->data.count(); if (useExtendedAddressing) { if (ln > 6) ln = 6; diff --git a/re/newgraphdialog.cpp b/re/newgraphdialog.cpp index 79da03e..e2d6092 100644 --- a/re/newgraphdialog.cpp +++ b/re/newgraphdialog.cpp @@ -145,7 +145,6 @@ void NewGraphDialog::loadSignals(int idx) void NewGraphDialog::bitfieldClicked(int x,int y) { int bit = (y * 8 + (7-x)); - int res; qDebug() << "Clicked bit: " << bit; startBit = bit; diff --git a/re/rangestatewindow.cpp b/re/rangestatewindow.cpp index 4171fc1..76d03e3 100644 --- a/re/rangestatewindow.cpp +++ b/re/rangestatewindow.cpp @@ -171,7 +171,7 @@ void RangeStateWindow::refreshFilterList() void RangeStateWindow::recalcButton() { QHash::iterator iter; - int id; + uint32_t id; ui->listCandidates->clear(); foundSignals.clear(); @@ -376,7 +376,7 @@ void RangeStateWindow::createGraph(QVector values) else ymin *= 0.8; ymax = maxval; - if (ymax < 0) ymax * 0.8; + if (ymax < 0) ymax *= 0.8; else ymax *= 1.2; if (fabs(ymin) < 0.01) ymin -= (ymax / 60.0); @@ -401,7 +401,7 @@ void RangeStateWindow::clickedSignalList(int idx) { if (idx == -1) return; //just in case... - int id, startBit, bitLength; + uint32_t id, startBit, bitLength; bool isSigned = false, isBigEndian = false; int64_t valu; diff --git a/re/udsscanwindow.cpp b/re/udsscanwindow.cpp index 174a65c..9f36c36 100644 --- a/re/udsscanwindow.cpp +++ b/re/udsscanwindow.cpp @@ -139,7 +139,7 @@ void UDSScanWindow::rapidFrames(int numFrames) { CANFrame thisFrame; QString result; - int id; + uint32_t id; int offset = ui->spinReplyOffset->value(); CANFrame sentFrame; bool gotReply = false; @@ -157,7 +157,7 @@ void UDSScanWindow::rapidFrames(int numFrames) thisFrame = modelFrames->at(i); id = thisFrame.ID; - if ((id == (sentFrame.ID + offset)) || ui->cbAllowAdaptiveOffset->isChecked()) + if ((id == (uint32_t)(sentFrame.ID + offset)) || ui->cbAllowAdaptiveOffset->isChecked()) { int temp = thisFrame.data[0] >> 4; if (temp == 0) //single frame reply (maybe) diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index c605bb2..21a1ca5 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -127,8 +127,7 @@ void ScriptContainer::sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSV frame.data[i] = (uint8_t)data.property(i).toInt(); } - frame.bus = bus.toInt(); - if (frame.bus < 0) frame.bus = 0; + frame.bus = (uint32_t)bus.toInt(); if (frame.bus > 1) frame.bus = 1; if (frame.ID > 0x7FF) frame.extended = true; diff --git a/scriptingwindow.cpp b/scriptingwindow.cpp index 58115dd..be10137 100644 --- a/scriptingwindow.cpp +++ b/scriptingwindow.cpp @@ -87,7 +87,6 @@ void ScriptingWindow::loadNewScript() { QString filename; QFileDialog dialog; - bool result = false; ScriptContainer *container; QStringList filters; From 2758fa8a0915fb3f857b757d34c091b3fb7a1fb8 Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Fri, 30 Dec 2016 14:24:17 -0500 Subject: [PATCH 85/86] Removed a few more warnings, switched the way CAN callbacks work. --- SavvyCAN.pro | 1 - can_structs.h | 12 +++++++- connections/canconmanager.cpp | 38 ++++++++---------------- connections/canconmanager.h | 16 ++++++---- connections/canconnection.cpp | 55 +++++++++++++++++++++++++---------- connections/canconnection.h | 19 +++++++++--- firmwareuploaderwindow.cpp | 7 ++--- framefileio.cpp | 6 ++-- re/flowviewwindow.cpp | 4 +-- scriptcontainer.cpp | 4 +-- 10 files changed, 96 insertions(+), 66 deletions(-) diff --git a/SavvyCAN.pro b/SavvyCAN.pro index f293ad7..784936a 100644 --- a/SavvyCAN.pro +++ b/SavvyCAN.pro @@ -107,7 +107,6 @@ HEADERS += mainwindow.h \ connections/connectionwindow.h \ re/graphingwindow.h \ re/newgraphdialog.h \ - ui/bisectwindow.h \ bisectwindow.h FORMS += ui/candatagrid.ui \ diff --git a/can_structs.h b/can_structs.h index aaba0b2..40428b5 100644 --- a/can_structs.h +++ b/can_structs.h @@ -1,6 +1,7 @@ #ifndef CAN_STRUCTS_H #define CAN_STRUCTS_H +#include #include #include @@ -16,10 +17,19 @@ public: uint64_t timestamp; }; -struct CANFlt +class CANFlt { +public: quint32 id; quint32 mask; + QObject * observer; //used to target the specific object that setup this filter + + bool operator ==(const CANFlt &b) const + { + if ( (id == b.id) && (mask == b.mask) && (observer == b.observer) ) return true; + + return false; + } }; struct J1939ID diff --git a/connections/canconmanager.cpp b/connections/canconmanager.cpp index 9bdf220..5cc5a1f 100644 --- a/connections/canconmanager.cpp +++ b/connections/canconmanager.cpp @@ -37,9 +37,7 @@ CANConManager::~CANConManager() void CANConManager::add(CANConnection* pConn_p) -{ - //connect(pConn_p, SIGNAL(notify()), this, SLOT(refreshCanList())); - connect(pConn_p, SIGNAL(targettedFrameReceived(CANFrame)), this, SLOT(gotTargettedFrame(CANFrame))); +{ mConns.append(pConn_p); emit connectionStatusUpdated(getNumBuses()); } @@ -47,7 +45,7 @@ void CANConManager::add(CANConnection* pConn_p) void CANConManager::remove(CANConnection* pConn_p) { - disconnect(pConn_p, 0, this, 0); + //disconnect(pConn_p, 0, this, 0); mConns.removeOne(pConn_p); emit connectionStatusUpdated(getNumBuses()); } @@ -184,21 +182,21 @@ bool CANConManager::sendFrames(const QList& pFrames) //For each device associated with buses go through and see if that device has a bus //that the filter should apply to. If so forward the data on but fudge //the bus numbers if bus wasn't -1 so that they're local to the device -bool CANConManager::addTargettedFrame(int pBusId, const CANFlt &target) +bool CANConManager::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver) { int tempBusVal; - int busBase = 0; + int busBase = 0; foreach (CANConnection* conn, mConns) { - if (pBusId == -1) conn->addTargettedFrame(pBusId, target); + if (pBusId == -1) conn->addTargettedFrame(pBusId, ID, mask, receiver); else { tempBusVal = pBusId >> busBase; tempBusVal &= ((1 << conn->getNumBuses()) - 1); if (tempBusVal) { qDebug() << "Forwarding targetted frame setting to a connection object"; - conn->addTargettedFrame(tempBusVal, target); + conn->addTargettedFrame(tempBusVal, ID, mask, receiver); } } busBase += conn->getNumBuses(); @@ -206,43 +204,31 @@ bool CANConManager::addTargettedFrame(int pBusId, const CANFlt &target) return true; } -bool CANConManager::removeTargettedFrame(int pBusId, const CANFlt &target) +bool CANConManager::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver) { int tempBusVal; int busBase = 0; foreach (CANConnection* conn, mConns) { - if (pBusId == -1) conn->removeTargettedFrame(pBusId, target); + if (pBusId == -1) conn->removeTargettedFrame(pBusId, ID, mask, receiver); else { tempBusVal = pBusId >> busBase; tempBusVal &= ((1 << conn->getNumBuses()) - 1); - if (tempBusVal) conn->removeTargettedFrame(tempBusVal, target); + if (tempBusVal) conn->removeTargettedFrame(tempBusVal, ID, mask, receiver); } busBase += conn->getNumBuses(); } return true; } -/* - * A connected CANConnection object has passed us a frame that one or more - * other objects are interested in. Fix up the bus number to be a system global bus - * number instead of connection local bus number then send it off again. -*/ -void CANConManager::gotTargettedFrame(CANFrame frame) +bool CANConManager::removeAllTargettedFrames(QObject *receiver) { - int busBase = 0; - foreach (CANConnection* conn, mConns) { - if (conn != sender()) busBase += conn->getNumBuses(); - else break; + conn->removeAllTargettedFrames(receiver); } - qDebug() << "Targetted frame, offset was " << busBase << " id was " << frame.ID; - - frame.bus += busBase; - - emit targettedFrameReceived(frame); + return true; } diff --git a/connections/canconmanager.h b/connections/canconmanager.h index 9467f8a..dc85686 100644 --- a/connections/canconmanager.h +++ b/connections/canconmanager.h @@ -39,27 +39,31 @@ public: /** * @brief Add a new filter for the targetted frames. If a frame matches it will immediately be sent via the targettedFrameReceived signal * @param pBusId - Which bus to bond to. -1 for any, otherwise a bitfield of buses (but 0 = first bus, etc) - * @param target - The filter to use for selected targetted frames + * @param ID - 11 or 29 bit ID to match against + * @param mask - 11 or 29 bit mask used for filter + * @param receiver - Pointer to a QObject that wants to receive notification when filter is matched * @return true if filter was able to be added, false otherwise. */ - bool addTargettedFrame(int pBusId, const CANFlt &target); + bool addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver); /** * @brief Try to find a matching filter in the list and remove it, no longer targetting those frames * @param pBusId - Which bus to bond to. Doesn't have to match the call to addTargettedFrame exactly. You could disconnect just one bus for instance. - * @param target - The filter that was set + * @param ID - 11 or 29 bit ID to match against + * @param mask - 11 or 29 bit mask used for filter + * @param receiver - Pointer to a QObject that wants to receive notification when filter is matched * @return true if filter was found and deleted, false otherwise. */ - bool removeTargettedFrame(int pBusId, const CANFlt &target); + bool removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver); + + bool removeAllTargettedFrames(QObject *receiver); signals: void framesReceived(CANConnection* pConn_p, QVector& pFrames); - void targettedFrameReceived(CANFrame frame); void connectionStatusUpdated(int conns); private slots: void refreshCanList(); - void gotTargettedFrame(CANFrame frame); private: explicit CANConManager(QObject *parent = 0); diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index b9b5f5b..663817c 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -256,19 +256,21 @@ void CANConnection::setCapSuspended(bool pIsSuspended) { mIsCapSuspended = pIsSuspended; } -bool CANConnection::addTargettedFrame(int pBusId, const CANFlt &target) +bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver) { - /* make sure we execute in mThread context */ +/* if( mThread_p && (mThread_p != QThread::currentThread()) ) { bool ret; QMetaObject::invokeMethod(this, "addTargettedFrame", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, ret), - Q_ARG(int , pBusId), - Q_ARG(const CANFlt&, target)); + Q_ARG(int, pBusId), + Q_ARG(uint32_t , ID), + Q_ARG(uint32_t , mask), + Q_ARG(QObject *, receiver)); return ret; } - +*/ /* sanity checks */ if(pBusId < -1 || pBusId >= (1 << getNumBuses())) return false; @@ -277,6 +279,10 @@ bool CANConnection::addTargettedFrame(int pBusId, const CANFlt &target) { if ( (pBusId == -1) || (pBusId && (1 << i)) ) { qDebug() << "Connection is registering a new targetted frame filter"; + CANFlt target; + target.id = ID; + target.mask = mask; + target.observer = receiver; mBusData_p[i].mTargettedFrames.append(target); } } @@ -284,27 +290,47 @@ bool CANConnection::addTargettedFrame(int pBusId, const CANFlt &target) return true; } -bool CANConnection::removeTargettedFrame(int pBusId, const CANFlt &target) +bool CANConnection::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver) { - /* make sure we execute in mThread context */ +/* if( mThread_p && (mThread_p != QThread::currentThread()) ) { bool ret; - QMetaObject::invokeMethod(this, "addTargettedFrame", + QMetaObject::invokeMethod(this, "removeTargettedFrame", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, ret), - Q_ARG(int , pBusId), - Q_ARG(const CANFlt&, target)); + Q_ARG(int, pBusId), + Q_ARG(uint32_t , ID), + Q_ARG(uint32_t , mask), + Q_ARG(QObject *, receiver)); return ret; } - +*/ /* sanity checks */ if(pBusId < -1 || pBusId >= (1 << getNumBuses())) return false; for (int i = 0; i < getNumBuses(); i++) { - //if (pBusId == -1 || (pBusId && (1 << i))) - //mBusData_p[i].mTargettedFrames.removeOne(target); + if (pBusId == -1 || (pBusId && (1 << i))) + { + CANFlt target; + target.id = ID; + target.mask = mask; + target.observer = receiver; + mBusData_p[i].mTargettedFrames.removeAll(target); + } + } + + return true; +} + +bool CANConnection::removeAllTargettedFrames(QObject *receiver) +{ + for (int i = 0; i < getNumBuses(); i++) { + foreach (const CANFlt filt, mBusData_p[i].mTargettedFrames) + { + if (filt.observer == receiver) mBusData_p[i].mTargettedFrames.removeOne(filt); + } } return true; @@ -318,8 +344,7 @@ void CANConnection::checkTargettedFrame(CANFrame &frame) maskedID = frame.ID & filt.mask; if (maskedID == filt.id) { qDebug() << "In connection object I got a targetted frame. Forwarding it."; - emit targettedFrameReceived(frame); - return; //only match once then stop. + QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame)); } } } diff --git a/connections/canconnection.h b/connections/canconnection.h index 8633a2a..c6471e2 100644 --- a/connections/canconnection.h +++ b/connections/canconnection.h @@ -151,18 +151,29 @@ public slots: /** * @brief Add a new filter for the targetted frames. If a frame matches it will immediately be sent via the targettedFrameReceived signal * @param pBusId - Which bus to bond to. -1 for any, otherwise a bitfield of buses (but 0 = first bus, etc) - * @param target - The filter to use for selected targetted frames + * @param ID - 11 or 29 bit ID to match against + * @param mask - 11 or 29 bit mask used for filter + * @param receiver - Pointer to a QObject that wants to receive notification when filter is matched * @return true if filter was able to be added, false otherwise. */ - bool addTargettedFrame(int pBusId, const CANFlt &target); + bool addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver); /** * @brief Try to find a matching filter in the list and remove it, no longer targetting those frames * @param pBusId - Which bus to bond to. Doesn't have to match the call to addTargettedFrame exactly. You could disconnect just one bus for instance. - * @param target - The filter that was set + * @param ID - 11 or 29 bit ID to match against + * @param mask - 11 or 29 bit mask used for filter + * @param receiver - Pointer to a QObject that wants to receive notification when filter is matched * @return true if filter was found and deleted, false otherwise. */ - bool removeTargettedFrame(int pBusId, const CANFlt &target); + bool removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver); + + /** + * @brief Removes all registered filters for the passed receiver + * @param receiver - Pointer to a QObject that registered one or more filters + * @return true if filter(s) was/were found and deleted, false otherwise. + */ + bool removeAllTargettedFrames(QObject *receiver); protected: diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index aaec100..3aa788e 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -27,22 +27,19 @@ FirmwareUploaderWindow::FirmwareUploaderWindow(const QVector *frames, timer = new QTimer(); timer->setInterval(100); //100ms without a reply will cause us to attempt a resend - CANFlt firmwareFilter; - firmwareFilter.id = 0x100; - firmwareFilter.mask = 0x7F0; - CANConManager::getInstance()->addTargettedFrame(-1, firmwareFilter); + CANConManager::getInstance()->addTargettedFrame(-1, 0x100, 0x7F0, this); //MainWindow::getReference()->setTargettedID(baseAddress + 0x10); connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int))); connect(ui->btnLoadFile, SIGNAL(clicked(bool)), this, SLOT(handleLoadFile())); connect(ui->btnStartStop, SIGNAL(clicked(bool)), this, SLOT(handleStartStopTransfer())); connect(timer, SIGNAL(timeout()), this, SLOT(timerElapsed())); - connect(CANConManager::getInstance(), SIGNAL(targettedFrameReceived(CANFrame)), this, SLOT(gotTargettedFrame(CANFrame))); } FirmwareUploaderWindow::~FirmwareUploaderWindow() { timer->stop(); + CANConManager::getInstance()->removeAllTargettedFrames(this); delete timer; delete ui; } diff --git a/framefileio.cpp b/framefileio.cpp index 9e7defb..380b30b 100644 --- a/framefileio.cpp +++ b/framefileio.cpp @@ -1051,8 +1051,8 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame ms = (thisFrame.timestamp / 1000); data[0] = (((ms / 1000) % 60) << 2) + ((ms % 1000) >> 8); data[1] = (char)(ms & 0xFF); - data[2] = 0xFF; - data[3] = 0xFF; + data[2] = (char)0xFF; + data[3] = (char)0xFF; for (int l = 0; l < 8; l++) data[4 + l] = 0; outFile->write(data); @@ -1064,7 +1064,7 @@ bool FrameFileIO::saveCANDOFile(QString filename, const QVector* frame qApp->processEvents(); lineCounter = 0; } - for (int j = 0; j < 8; j++) data[4 + j] = 0xFF; + for (int j = 0; j < 8; j++) data[4 + j] = (char)0xFF; thisFrame = frames->at(c); if (!thisFrame.extended) diff --git a/re/flowviewwindow.cpp b/re/flowviewwindow.cpp index 37c2c55..a46aa58 100644 --- a/re/flowviewwindow.cpp +++ b/re/flowviewwindow.cpp @@ -382,7 +382,7 @@ void FlowViewWindow::updatedFrames(int numFrames) if (!foundID.contains(thisFrame.ID)) { foundID.append(thisFrame.ID); - QListWidgetItem* item = new QListWidgetItem(Utility::formatNumber(thisFrame.ID), ui->listFrameID); + /*QListWidgetItem* item =*/ new QListWidgetItem(Utility::formatNumber(thisFrame.ID), ui->listFrameID); } if (thisFrame.ID == refID) @@ -495,7 +495,7 @@ void FlowViewWindow::refreshIDList() if (!foundID.contains(id)) { foundID.append(id); - QListWidgetItem* item = new QListWidgetItem(Utility::formatNumber(id), ui->listFrameID); + /*QListWidgetItem* item = */ new QListWidgetItem(Utility::formatNumber(id), ui->listFrameID); } } //default is to sort in ascending order diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 21a1ca5..3d326ce 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -77,9 +77,7 @@ void ScriptContainer::setFilter(QJSValue id, QJSValue mask, QJSValue bus) foreach(const CANFilter& flt, filters) { if(flt.bus==i) { - canFlt.id = idVal; - canFlt.mask = maskVal; - conn_p->addTargettedFrame(busVal, canFlt); + conn_p->addTargettedFrame(busVal, idVal, maskVal, this); } } } From b18c30724ea3dff9a364f1e78570c8e03636bccd Mon Sep 17 00:00:00 2001 From: Collin Kidder Date: Mon, 2 Jan 2017 17:25:02 -0500 Subject: [PATCH 86/86] A bit better debugging messages, fix up filtering for firmware updater --- connections/canconnection.cpp | 4 +++- firmwareuploaderwindow.cpp | 10 ++++------ scriptcontainer.cpp | 3 +-- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/connections/canconnection.cpp b/connections/canconnection.cpp index 663817c..41b6329 100644 --- a/connections/canconnection.cpp +++ b/connections/canconnection.cpp @@ -278,7 +278,7 @@ bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QO for (int i = 0; i < getNumBuses(); i++) { if ( (pBusId == -1) || (pBusId && (1 << i)) ) { - qDebug() << "Connection is registering a new targetted frame filter"; + qDebug() << "Connection is registering a new targetted frame filter, local bus " << i; CANFlt target; target.id = ID; target.mask = mask; @@ -339,8 +339,10 @@ bool CANConnection::removeAllTargettedFrames(QObject *receiver) void CANConnection::checkTargettedFrame(CANFrame &frame) { unsigned int maskedID; + qDebug() << "Got frame with ID " << frame.ID << " on bus " << frame.bus; foreach (const CANFlt filt, mBusData_p[frame.bus].mTargettedFrames) { + qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask; maskedID = frame.ID & filt.mask; if (maskedID == filt.id) { qDebug() << "In connection object I got a targetted frame. Forwarding it."; diff --git a/firmwareuploaderwindow.cpp b/firmwareuploaderwindow.cpp index 3aa788e..19ae9e4 100644 --- a/firmwareuploaderwindow.cpp +++ b/firmwareuploaderwindow.cpp @@ -25,10 +25,7 @@ FirmwareUploaderWindow::FirmwareUploaderWindow(const QVector *frames, updateProgress(); timer = new QTimer(); - timer->setInterval(100); //100ms without a reply will cause us to attempt a resend - - CANConManager::getInstance()->addTargettedFrame(-1, 0x100, 0x7F0, this); - //MainWindow::getReference()->setTargettedID(baseAddress + 0x10); + timer->setInterval(100); //100ms without a reply will cause us to attempt a resend connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int))); connect(ui->btnLoadFile, SIGNAL(clicked(bool)), this, SLOT(handleLoadFile())); @@ -170,7 +167,8 @@ void FirmwareUploaderWindow::handleStartStopTransfer() bus = ui->spinBus->value(); baseAddress = Utility::ParseStringToNum(ui->txtBaseAddr->text()); qDebug() << "Base address: " + QString::number(baseAddress); - //MainWindow::getReference()->setTargettedID(baseAddress + 0x10); + 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; @@ -190,7 +188,7 @@ void FirmwareUploaderWindow::handleStartStopTransfer() else //stop anything in process { ui->btnStartStop->setText("Start Upload"); - //MainWindow::getReference()->setTargettedID(-1); + CANConManager::getInstance()->removeAllTargettedFrames(this); } } diff --git a/scriptcontainer.cpp b/scriptcontainer.cpp index 3d326ce..66e120c 100644 --- a/scriptcontainer.cpp +++ b/scriptcontainer.cpp @@ -105,8 +105,7 @@ void ScriptContainer::clearFilters() CANConnection* conn_p = CANConManager::getInstance()->getByName(mConName); if(conn_p) { - //for(int i=0 ; igetNumBuses() ; i++) - //conn_p->setFilters(i, QVector(), false); + conn_p->removeAllTargettedFrames(this); } }