From 610a8015da5175d91ca6e61175760e8028c464ba Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 5 Apr 2020 14:12:56 +0200 Subject: [PATCH] moved BaseConn to shared-libraries --- ScStwApp.pro | 3 +- ScStwSrc/ScStwApp.pro | 8 +- ScStwSrc/headers/appsettings.h | 6 +- ScStwSrc/headers/baseconn.h | 153 --------- ScStwSrc/headers/climbingrace.h | 6 +- ScStwSrc/headers/sqlprofilemodel.h | 29 -- ScStwSrc/headers/sqlstoragemodel.h | 26 -- ScStwSrc/sources/appsettings.cpp | 6 +- ScStwSrc/sources/baseconn.cpp | 462 --------------------------- ScStwSrc/sources/climbingrace.cpp | 62 ++-- ScStwSrc/sources/main.cpp | 1 - ScStwSrc/sources/sqlprofilemodel.cpp | 96 ------ ScStwSrc/sources/sqlstoragemodel.cpp | 43 --- 13 files changed, 44 insertions(+), 857 deletions(-) delete mode 100644 ScStwSrc/headers/baseconn.h delete mode 100644 ScStwSrc/headers/sqlprofilemodel.h delete mode 100644 ScStwSrc/headers/sqlstoragemodel.h delete mode 100644 ScStwSrc/sources/baseconn.cpp delete mode 100644 ScStwSrc/sources/sqlprofilemodel.cpp delete mode 100644 ScStwSrc/sources/sqlstoragemodel.cpp diff --git a/ScStwApp.pro b/ScStwApp.pro index 6955561..cc58038 100644 --- a/ScStwApp.pro +++ b/ScStwApp.pro @@ -2,7 +2,8 @@ TEMPLATE = subdirs CONFIG += ordered SUBDIRS += \ - shared-libraries/ScStwClient \ + ScStwLibraries \ ScStwApp ScStwApp.file = ScStwSrc/ScStwApp.pro +ScStwLibraries.file = shared-libraries/ScStwLibraries/ScStwLibraries.pro diff --git a/ScStwSrc/ScStwApp.pro b/ScStwSrc/ScStwApp.pro index 15ddd3e..7521ca5 100644 --- a/ScStwSrc/ScStwApp.pro +++ b/ScStwSrc/ScStwApp.pro @@ -21,23 +21,17 @@ DEFINES += QT_DEPRECATED_WARNINGS TARGET = speedclimbing_stw # include submodules -include($$PWD/../shared-libraries/ScStwClient/ScStwClient.pri) +include($$PWD/../shared-libraries/ScStwLibraries/ScStwLibraries.pri) SOURCES += \ sources/main.cpp \ - sources/sqlstoragemodel.cpp \ - sources/sqlprofilemodel.cpp \ sources/appsettings.cpp \ - sources/baseconn.cpp \ sources/speedtimer.cpp \ sources/climbingrace.cpp \ sources/apptheme.cpp HEADERS += \ - headers/sqlstoragemodel.h \ - headers/sqlprofilemodel.h \ headers/appsettings.h \ - headers/baseconn.h \ headers/speedtimer.h \ headers/climbingrace.h \ headers/apptheme.h diff --git a/ScStwSrc/headers/appsettings.h b/ScStwSrc/headers/appsettings.h index 8e315ae..1cb6de4 100644 --- a/ScStwSrc/headers/appsettings.h +++ b/ScStwSrc/headers/appsettings.h @@ -12,9 +12,9 @@ public: explicit AppSettings(QObject *parent = nullptr); ~AppSettings(); - Q_INVOKABLE QString loadSetting(const QString &key); - Q_INVOKABLE void writeSetting(const QString &key, const QVariant &variant); - Q_INVOKABLE void setDefaultSetting(const QString &key, const QVariant &defaultVariant); + Q_INVOKABLE QString loadSetting(QString key); + Q_INVOKABLE void writeSetting(QString key, QVariant variant); + Q_INVOKABLE void setDefaultSetting(QString key, QVariant defaultVariant); QSettings *settingsManager; diff --git a/ScStwSrc/headers/baseconn.h b/ScStwSrc/headers/baseconn.h deleted file mode 100644 index 5639bce..0000000 --- a/ScStwSrc/headers/baseconn.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef BASECONN_H -#define BASECONN_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "headers/appsettings.h" -#include "headers/speedtimer.h" - -class BaseConn : public QObject -{ - Q_OBJECT - -public: - explicit BaseConn(QObject *parent = nullptr); - - // values for the socket connection - int connection_progress; - QString ip; - ushort port = 3563; - int errors; - int errors_until_disconnect = 4; - - QVariant connections; - - QString latestReadReply; - - //---general status values---// - - // some meta data of the base - QString firmwareVersion; - bool firmwareUpToDate; - double timeOffset; - - - // the current state - QString state; - // can be: - // - 'disconnected' - // - 'connecting' - // - 'connected' - - -private: - QDateTime *date; - //to get the current time - - QTcpSocket *socket; - //socket for communication with the extention - - QTimer *timeoutTimer; - - QString readBuffer; - - int nextConnectionId; - - struct waitingRequest { - int id; - QEventLoop * loop; - QJsonObject reply; - }; - - QList waitingRequests; - -signals: - void stateChanged(); - //is emitted, when the connection state changes - - void progressChanged(); - //is emmited during the connection process when the progress changes - - void gotUnexpectedReply(QString reply); - - void gotUpdate(QVariant data); - - void connectionsChanged(); - - void connectionSlotReleased(); - - void nextRemoteActionChanged(); - - void nextRemoteActionDelayProgChanged(); - - void gotError(QString error); - - void propertiesChanged(); - -public slots: - - void connectToHost(); - //function to connect to the base station - - void connectionTimeout(); - - bool init(); - void deInit(); - - void closeConnection(); - - void gotError(QAbstractSocket::SocketError err); - - // --- socket communication handling --- - - QVariantMap sendCommand(int header, QJsonValue data = "", bool useTerminationKeys = true, int timeout = 3000); - - // --- updater functions --- - - bool updateTime(); - bool updateFirmware(); - bool isFirmwareUpToDate(); - - // --- helper functions --- - - int writeRemoteSetting(QString key, QString value); - - bool refreshConnections(); - - void setConnections(QVariantList connections); - - - // functions for the qml adapter - QString getIP() const; - void setIP(const QString &ipAdress); - - QString getState() const; - void setState(QString newState); - - int getProgress() const; - - QVariant getConnections(); - -private slots: - void readyRead(); - - void processSocketMessage(QString message); - - void socketReplyRecieved(QString reply); - - void socketStateChanged(QAbstractSocket::SocketState socketState); -}; -extern BaseConn * pGlobalBaseConn; - -#endif // BASECONN_H diff --git a/ScStwSrc/headers/climbingrace.h b/ScStwSrc/headers/climbingrace.h index ada6797..cc0366a 100644 --- a/ScStwSrc/headers/climbingrace.h +++ b/ScStwSrc/headers/climbingrace.h @@ -5,7 +5,9 @@ #include #include #include -#include "headers/baseconn.h" + +#include + #include "headers/appsettings.h" #include "headers/speedtimer.h" @@ -35,7 +37,7 @@ public: private: AppSettings * appSettings; - BaseConn * baseConn; + ScStwClient * scStwClient; QMediaPlayer * player; diff --git a/ScStwSrc/headers/sqlprofilemodel.h b/ScStwSrc/headers/sqlprofilemodel.h deleted file mode 100644 index 253b7ef..0000000 --- a/ScStwSrc/headers/sqlprofilemodel.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef SQLPROFILEMODEL_H -#define SQLPROFILEMODEL_H - -#include -#include -#include -#include -#include -#include -#include - -class SqlProfileModel : public QSqlTableModel -{ - Q_OBJECT -public: - explicit SqlProfileModel(QObject *parent = nullptr); - - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - QHash roleNames() const Q_DECL_OVERRIDE; - - - Q_INVOKABLE bool append(QString name); - Q_INVOKABLE void remove(int row); -signals: - -public slots: -}; - -#endif // SQLPROFILEMODEL_H diff --git a/ScStwSrc/headers/sqlstoragemodel.h b/ScStwSrc/headers/sqlstoragemodel.h deleted file mode 100644 index 51289f3..0000000 --- a/ScStwSrc/headers/sqlstoragemodel.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef SQLSTORAGEMODEL_H -#define SQLSTORAGEMODEL_H - -#include -#include -#include -#include -#include -#include -#include - -class SqlStorageModel : public QSqlTableModel -{ - Q_OBJECT - -public: - explicit SqlStorageModel(QObject *parent = nullptr); - - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - QHash roleNames() const Q_DECL_OVERRIDE; -signals: - -public slots: -}; - -#endif // SQLSTORAGEMODEL_H diff --git a/ScStwSrc/sources/appsettings.cpp b/ScStwSrc/sources/appsettings.cpp index 9bff130..1ea1ffb 100644 --- a/ScStwSrc/sources/appsettings.cpp +++ b/ScStwSrc/sources/appsettings.cpp @@ -38,7 +38,7 @@ AppSettings::AppSettings(QObject* parent) pGlobalAppSettings = this; } -QString AppSettings::loadSetting(const QString &key) +QString AppSettings::loadSetting(QString key) { this->settingsManager->beginGroup("AppSettings"); QString value = this->settingsManager->value(key , false).toString(); @@ -46,14 +46,14 @@ QString AppSettings::loadSetting(const QString &key) return(value); } -void AppSettings::writeSetting(const QString &key, const QVariant &variant) +void AppSettings::writeSetting(QString key, QVariant variant) { this->settingsManager->beginGroup("AppSettings"); this->settingsManager->setValue(key , variant); this->settingsManager->endGroup(); } -void AppSettings::setDefaultSetting(const QString &key, const QVariant &defaultVariant) +void AppSettings::setDefaultSetting(QString key, QVariant defaultVariant) { QString value = this->loadSetting(key); if(value == "false"){ diff --git a/ScStwSrc/sources/baseconn.cpp b/ScStwSrc/sources/baseconn.cpp deleted file mode 100644 index a151209..0000000 --- a/ScStwSrc/sources/baseconn.cpp +++ /dev/null @@ -1,462 +0,0 @@ -#include "headers/baseconn.h" - -BaseConn * pGlobalBaseConn = nullptr; - -BaseConn::BaseConn(QObject *parent) : QObject(parent) -{ - pGlobalBaseConn = this; - - socket = new QTcpSocket(this); - - this->timeoutTimer = new QTimer(this); - this->timeoutTimer->setSingleShot(true); - - this->state = "disconnected"; - - connect(this->socket, SIGNAL(error(QAbstractSocket::SocketError)), - this, SLOT(gotError(QAbstractSocket::SocketError))); - - connect(this->socket, &QAbstractSocket::stateChanged, this, &BaseConn::socketStateChanged); - - this->nextConnectionId = 1; - this->connections = QVariantList({}); -} - -void BaseConn::connectToHost() { - qDebug() << "connecting"; - setState("connecting"); - this->connection_progress = 0; - - connect(this->timeoutTimer, SIGNAL(timeout()), this, SLOT(connectionTimeout())); - - //connect - this->socket->connectToHost(this->ip, this->port); - - timeoutTimer->start(3000); -} - -void BaseConn::connectionTimeout() { - this->socket->abort(); - disconnect(this->timeoutTimer, SIGNAL(timeout()), this, SLOT(connectionTimeout())); -} - -bool BaseConn::init() { - disconnect(this->timeoutTimer, SIGNAL(timeout()), this, SLOT(connectionTimeout())); - this->timeoutTimer->stop(); - - connect(this->socket, &QTcpSocket::readyRead, this, &BaseConn::readyRead); - this->connection_progress = 50; - - this->setState("connected"); - - // init remote session - QJsonArray updateSubs = {"onRaceStateChanged", "onTimersChanged", "onExtensionConnectionsChanged", "onNextStartActionChanged"}; - QJsonObject sessionParams = {{"updateSubs", updateSubs}, {"init", true}, {"usingTerminationKeys", true}}; - - QVariantMap initResponse = this->sendCommand(1, sessionParams, false); - - if(initResponse["status"] != 200) { - return false; - } - - this->firmwareVersion = initResponse["data"].toMap()["version"].toString(); - this->timeOffset = initResponse["data"].toMap()["time"].toDouble() - this->date->currentMSecsSinceEpoch(); - this->firmwareUpToDate = this->isFirmwareUpToDate(); - - emit this->propertiesChanged(); - - qDebug() << "[INFO][BaseStation] Init done! firmware: version: " << this->firmwareVersion << " up-to-date: " << this->firmwareUpToDate << " time offset: " << this->timeOffset; - - return true; -} - -void BaseConn::deInit() { - this->connections.clear(); - emit this->connectionsChanged(); - this->setState("disconnected"); -} - -void BaseConn::closeConnection() -{ - this->connections = QVariantList({}); - emit this->connectionsChanged(); - - qDebug() << "closing connection"; - switch (socket->state()) - { - case 0: - socket->disconnectFromHost(); - break; - case 2: - socket->abort(); - break; - default: - socket->abort(); - } - - setState("disconnected"); -} - -void BaseConn::gotError(QAbstractSocket::SocketError err) -{ - //qDebug() << "got error"; - QString strError = "unknown"; - switch (err) - { - case 0: - strError = "Connection was refused"; - break; - case 1: - strError = "Remote host closed the connection"; - this->closeConnection(); - break; - case 2: - strError = "Host address was not found"; - break; - case 5: - strError = "Connection timed out"; - break; - default: - strError = "Unknown error"; - } - - emit gotError(strError); - qDebug() << "got socket error: " << strError; -} - -// ------------------------------------- -// --- socket communication handling --- -// ------------------------------------- - -void BaseConn::socketStateChanged(QAbstractSocket::SocketState socketState) { - switch (socketState) { - case QAbstractSocket::UnconnectedState: - { - this->deInit(); - break; - } - case QAbstractSocket::ConnectedState: - { - if(!this->init()) { - this->closeConnection(); - } - - break; - } - default: - { - //qDebug() << "+ --- UNKNOWN SOCKET STATE: " << socketState; - break; - } - } -} - -QVariantMap BaseConn::sendCommand(int header, QJsonValue data, bool useTerminationKeys, int timeout) { - if(this->state != "connected"){ - return {{"status", 910}, {"data", "not connected"}}; - } - - // generate id and witing requests entry - int thisId = nextConnectionId; - //qDebug() << "sending command: " << header << " with data: " << data << " and id: " << thisId; - nextConnectionId ++; - - QEventLoop *loop = new QEventLoop(this); - QTimer *timer = new QTimer(this); - QJsonObject reply; - - this->waitingRequests.append({thisId, loop, reply}); - - QJsonObject requestObj; - requestObj.insert("id", thisId); - requestObj.insert("header", header); - requestObj.insert("data", data); - - QString jsonRequest = QJsonDocument(requestObj).toJson(); - - timer->setSingleShot(true); - // quit the loop when the timer times out - loop->connect(timer, SIGNAL(timeout()), loop, SLOT(quit())); - // quit the loop when the connection was established - // loop.connect(this, &BaseConn::gotReply, &loop, &QEventLoop::quit); - // start the timer before starting to connect - timer->start(timeout); - - //write data - if(useTerminationKeys) { - socket->write("" + jsonRequest.toLatin1() + ""); - } - else { - socket->write(jsonRequest.toLatin1()); - } - - //wait for an answer to finish (programm gets stuck in here) - loop->exec(); - - bool replyFound = false; - - // find reply and delete the request from waiting list - for(int i = 0; iwaitingRequests.length(); i++){ - if(this->waitingRequests[i].id == thisId){ - // request was found - replyFound = true; - // delete event loop - if(this->waitingRequests[i].loop != nullptr) { - delete this->waitingRequests[i].loop; - } - // store reply - reply = this->waitingRequests[i].reply; - // remove reply from waiting list - this->waitingRequests.removeAt(i); - } - } - - if(!replyFound) { - // some internal error occured - return {{"status", 900}, {"data", ""}}; - } - - if(timer->remainingTime() == -1){ - //the time has been triggered -> timeout - return {{"status", 911}, {"data", ""}}; - } - - delete timer; - return {{"status", reply.value("header").toInt()}, {"data", reply.value("data").toVariant()}}; - -} - -void BaseConn::readyRead() { - - //qDebug() << "ready to ready " << socket->bytesAvailable() << " bytes" ; - QString reply = socket->readAll(); - - //qWarning() << "socket read: " << reply; - - processSocketMessage(reply); -} - -void BaseConn::processSocketMessage(QString message) { - QString startKey = ""; - QString endKey = ""; - - //qWarning() << "... processing message now ... : " << message; - - if(message == ""){ - return; - } - - if((message.startsWith(startKey) && message.endsWith(endKey)) && (message.count(startKey) == 1 && message.count(endKey) == 1)){ - // non-split message ( e.g.: 123456789 - } - else if(!message.contains(endKey) && (!this->readBuffer.isEmpty() || message.startsWith(startKey))){ - // begin of a split message ( e.g.: 123 ) - // or middle of a split message ( e.g.: 456 ) - //qWarning() << "this is a begin or middle of split a message"; - this->readBuffer += message; - return; - } - else if(!message.contains(startKey) && message.endsWith(endKey)) { - // end of a split message ( e.g.: 789 ) - - if(!this->readBuffer.isEmpty()){ - message = readBuffer + message; - readBuffer.clear(); - } - } - else if((message.count(startKey) > 1 || message.count(endKey) > 1) || (message.contains(endKey) && !message.endsWith(endKey) && message.contains(startKey) && !message.startsWith(startKey))) { - // multiple messages in one packet ( e.g.: 123456789987654321 ) - // or multiple message fragments in one message ( e.g.: 56789987654321 or 5678998765 ) - //qDebug() << "detected multiple messages"; - - int startOfSecondMessage = message.lastIndexOf(startKey); - // process first part of message - QString firstMessage = message.left(startOfSecondMessage); - this->processSocketMessage(firstMessage); - // process second part of message - QString secondMessage = message.right(message.length() - startOfSecondMessage); - this->processSocketMessage(secondMessage); - - return; - } - else { - // invalid message - return; - } - - //qWarning() << "... done processing, message: " << message; - this->socketReplyRecieved(message); -} - -void BaseConn::socketReplyRecieved(QString reply) { - reply.replace("", ""); - reply.replace("", ""); - - int id = 0; - - QJsonDocument jsonReply = QJsonDocument::fromJson(reply.toUtf8()); - QJsonObject replyObj = jsonReply.object(); - - if(!replyObj.isEmpty()){ - id = replyObj.value("id").toInt(); - - if(id == -1) { - // this message is an update!! - emit this->gotUpdate(replyObj.toVariantMap()); - return; - } - - // this message is the reply to a command! - for(int i = 0; i < this->waitingRequests.length(); i++){ - if(this->waitingRequests[i].id == id){ - this->waitingRequests[i].reply = replyObj; - if(this->waitingRequests[i].loop != nullptr){ - this->waitingRequests[i].loop->quit(); - } - return; - } - } - } - - latestReadReply = reply; - emit gotUnexpectedReply(reply); -} - -// ------------------------- -// --- updater functions --- -// ------------------------- - -bool BaseConn::updateTime() { - if(abs(this->timeOffset) < 10000) { - // the time is already up-to-date - return true; - } - - QVariantMap ret = this->sendCommand(5001, this->date->currentSecsSinceEpoch()); - qDebug() << ret; - - return ret["status"].toInt() == 200; -} - -bool BaseConn::updateFirmware() { - QString file = ":/ScStwBasestation.sb64"; - QFile f(file); - if (!f.open(QFile::ReadOnly)) return false; - QString fileContents = f.readAll(); - - if(this->firmwareUpToDate) { - return true; - } - - QVariantMap ret = this->sendCommand(5000, fileContents, true, 15000); - - return ret["status"].toInt() == 200; -} - -bool BaseConn::isFirmwareUpToDate() { - QString file = ":/ScStwBasestation.sb64"; - QFile f(file); - if (!f.open(QFile::ReadOnly)) return false; - QString fileContents = f.readAll(); - - QString newFirmwareVersion = fileContents.split("")[1].split("")[0]; - int newFirmwareVersionMajor = newFirmwareVersion.split(".")[0].toInt(); - int newFirmwareVersionMinor = newFirmwareVersion.split(".")[1].toInt(); - int newFirmwareVersionPatch = newFirmwareVersion.split(".")[2].toInt(); - - qDebug() << "App firmware version is: " << newFirmwareVersion; - - QString currentFirmwareVersion = this->firmwareVersion; - int currentFirmwareVersionMajor = currentFirmwareVersion.split(".")[0].toInt(); - int currentFirmwareVersionMinor = currentFirmwareVersion.split(".")[1].toInt(); - int currentFirmwareVersionPatch = currentFirmwareVersion.split(".")[2].toInt(); - - return newFirmwareVersionMajor < currentFirmwareVersionMajor || newFirmwareVersionMinor < currentFirmwareVersionMinor || newFirmwareVersionPatch <= currentFirmwareVersionPatch; -} - -// ------------------------ -// --- helper functions --- -// ------------------------ - -int BaseConn::writeRemoteSetting(QString key, QString value) { - QJsonArray requestData; - requestData.append(key); - requestData.append(value); - return this->sendCommand(3000, requestData)["status"].toInt(); -} - -void BaseConn::setIP(const QString &ipAdress){ - this->ip = ipAdress; -} - -QString BaseConn::getIP() const -{ - return(this->ip); -} - -QString BaseConn::getState() const -{ - return(this->state); -} - -void BaseConn::setState(QString newState){ - if(this->state != newState) { - qDebug() << "+--- BaseConn state changed: " << newState; - this->state = newState; - emit stateChanged(); - if(this->state == "disconnected") { - this->deInit(); - } - } -} - -int BaseConn::getProgress() const -{ - return(connection_progress); -} - -bool BaseConn::refreshConnections() { - QVariantMap reply = this->sendCommand(2006); - - if(reply["status"] != 200){ - //handle Error!! - if(reply["status"] == 910){ - this->connections = QVariantList({}); - return true; - } - qDebug() << "+ --- error refreshing connections: " << reply["status"]; - return false; - } - - QVariantList tmpConnections = reply["data"].toList(); - - if(this->connections != reply["data"].toList()){ - this->connections = reply["data"].toList(); - emit this->connectionsChanged(); - } - - return true; - -} - -QVariant BaseConn::getConnections() { - return(connections); - /* - "id": "id of the extention (int)", - "type": "type of the extention (can be: 'STARTPAD', 'TOPPAD')", - "name": "name of the extention", - "ip": "ip-adress of he extention (string)", - "state": "state of the extention (can be: 'disconnected', 'connecting', 'connected')" - */ - //QVariantMap conn = {{"id",0}, {"type","STARTPAD"}, {"name", "startpad1"}, {"ip", "192.168.4.11"}, {"state", "connected"}}; - //QVariantMap conn1 = {{"id",0}, {"type","TOPPAD"}, {"name", "buzzer1"}, {"ip", "192.168.4.10"}, {"state", "connected"}}; - //QVariantList conns = {conn, conn1}; - //return conns; -} - -void BaseConn::setConnections(QVariantList connections) { - if(this->connections != connections){ - this->connections = connections; - emit this->connectionsChanged(); - } -} diff --git a/ScStwSrc/sources/climbingrace.cpp b/ScStwSrc/sources/climbingrace.cpp index f8773b3..0b326f0 100644 --- a/ScStwSrc/sources/climbingrace.cpp +++ b/ScStwSrc/sources/climbingrace.cpp @@ -16,14 +16,14 @@ ClimbingRace::ClimbingRace(QObject *parent) : QObject(parent) this->mode = LOCAL; this->appSettings = new AppSettings(this); - this->baseConn = new BaseConn(this); + this->scStwClient = new ScStwClient(this); - this->baseConn->setIP(pGlobalAppSettings->loadSetting("baseStationIpAdress")); - connect(this->baseConn, &BaseConn::stateChanged, this, &ClimbingRace::baseStationStateChanged); - connect(this->baseConn, &BaseConn::stateChanged, this, &ClimbingRace::refreshMode); - connect(this->baseConn, &BaseConn::connectionsChanged, this, &ClimbingRace::baseStationConnectionsChanged); - connect(this->baseConn, &BaseConn::gotUpdate, this, &ClimbingRace::handleBaseStationUpdate); - connect(this->baseConn, &BaseConn::propertiesChanged, this, &ClimbingRace::baseStationPropertiesChanged); + this->scStwClient->setIP(pGlobalAppSettings->loadSetting("baseStationIpAdress")); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ClimbingRace::baseStationStateChanged); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ClimbingRace::refreshMode); + connect(this->scStwClient, &ScStwClient::connectionsChanged, this, &ClimbingRace::baseStationConnectionsChanged); + connect(this->scStwClient, &ScStwClient::gotUpdate, this, &ClimbingRace::handleBaseStationUpdate); + connect(this->scStwClient, &ScStwClient::propertiesChanged, this, &ClimbingRace::baseStationPropertiesChanged); this->speedTimers.append( new SpeedTimer(this) ); @@ -69,7 +69,7 @@ int ClimbingRace::startRace() { } case REMOTE: { - QVariantMap reply = this->baseConn->sendCommand(1000); + QVariantMap reply = this->scStwClient->sendCommand(1000); if(reply["status"] != 200){ //handle Error!! @@ -123,7 +123,7 @@ int ClimbingRace::stopRace(int type) { } case REMOTE: { - QVariantMap reply = this->baseConn->sendCommand(1001); + QVariantMap reply = this->scStwClient->sendCommand(1001); if(reply["status"] != 200){ returnCode = reply["status"].toInt(); @@ -164,7 +164,7 @@ int ClimbingRace::resetRace() { case REMOTE: { - QVariantMap reply = this->baseConn->sendCommand(1002); + QVariantMap reply = this->scStwClient->sendCommand(1002); if(reply["status"] != 200){ //handle Error!! @@ -212,7 +212,7 @@ void ClimbingRace::handleBaseStationUpdate(QVariant data) { case 9002: { // the extension connections have changed - this->baseConn->setConnections(data.toMap()["data"].toList()); + this->scStwClient->setConnections(data.toMap()["data"].toList()); break; } case 9003: @@ -372,7 +372,7 @@ void ClimbingRace::setState(raceState newState) { void ClimbingRace::refreshMode() { raceMode newMode; - if(this->baseConn->state == "connected"){ + if(this->scStwClient->getState() == "connected"){ newMode = REMOTE; } else { @@ -400,7 +400,7 @@ void ClimbingRace::refreshMode() { // reset base conn // clear extensions - this->baseConn->connections.clear(); + this->scStwClient->connections.clear(); } this->mode = newMode; @@ -471,7 +471,7 @@ void ClimbingRace::refreshTimerText() { } bool ClimbingRace::pairConnectedUsbExtensions() { - QVariantMap ret = this->baseConn->sendCommand(5002, "", 10000); + QVariantMap ret = this->scStwClient->sendCommand(5002, "", 10000); qDebug() << ret; return ret["status"] == 200; } @@ -479,7 +479,7 @@ bool ClimbingRace::pairConnectedUsbExtensions() { // - athlete management - QVariant ClimbingRace::getAthletes() { - QVariantMap reply = this->baseConn->sendCommand(4003); + QVariantMap reply = this->scStwClient->sendCommand(4003); if(reply["status"] != 200){ //handle Error!! @@ -498,7 +498,7 @@ bool ClimbingRace::createAthlete(QString userName, QString fullName) { QVariant requestData = QVariantMap({{"fullName", fullName}, {"userName", userName}}); - QVariantMap reply = this->baseConn->sendCommand(4001, requestData.toJsonValue()); + QVariantMap reply = this->scStwClient->sendCommand(4001, requestData.toJsonValue()); if(reply["status"] != 200){ //handle Error!! @@ -513,7 +513,7 @@ bool ClimbingRace::deleteAthlete( QString userName ){ QVariant requestData = QVariantMap({{"userName", userName}}); - QVariantMap reply = this->baseConn->sendCommand(4002, requestData.toJsonValue()); + QVariantMap reply = this->scStwClient->sendCommand(4002, requestData.toJsonValue()); if(reply["status"] != 200){ //handle Error!! @@ -529,7 +529,7 @@ bool ClimbingRace::selectAthlete( QString userName, int timerId ){ QVariant requestData = QVariantMap({{"userName", userName}, {"timerId", timerId}}); - QVariantMap reply = this->baseConn->sendCommand(4000, requestData.toJsonValue()); + QVariantMap reply = this->scStwClient->sendCommand(4000, requestData.toJsonValue()); if(reply["status"] != 200){ //handle Error!! @@ -542,7 +542,7 @@ bool ClimbingRace::selectAthlete( QString userName, int timerId ){ } QVariant ClimbingRace::getResults( QString userName ){ - QVariantMap reply = this->baseConn->sendCommand(4004, userName); + QVariantMap reply = this->scStwClient->sendCommand(4004, userName); if(reply["status"] != 200){ //handle Error!! @@ -585,7 +585,7 @@ void ClimbingRace::writeSetting(QString key, QVariant value) { this->refreshMode(); if(this->mode == REMOTE && ( this->remoteSettings.contains(key) || this->remoteOnlySettings.contains(key) ) ){ - this->baseConn->writeRemoteSetting(key, value.toString()); + this->scStwClient->writeRemoteSetting(key, value.toString()); } else if(!this->remoteOnlySettings.contains(key)){ this->appSettings->writeSetting(key, value); @@ -596,7 +596,7 @@ QString ClimbingRace::readSetting(QString key) { this->refreshMode(); if(this->mode == REMOTE && ( this->remoteSettings.contains(key) || this->remoteOnlySettings.contains(key) )){ - QVariantMap reply = this->baseConn->sendCommand(3001, key); + QVariantMap reply = this->scStwClient->sendCommand(3001, key); if(reply["status"] != 200){ return "false"; } @@ -612,37 +612,37 @@ QString ClimbingRace::readSetting(QString key) { void ClimbingRace::connectBaseStation() { this->reloadBaseStationIpAdress(); - this->baseConn->connectToHost(); + this->scStwClient->connectToHost(); } void ClimbingRace::disconnectBaseStation() { - this->baseConn->closeConnection(); + this->scStwClient->closeConnection(); } QString ClimbingRace::getBaseStationState() { - return this->baseConn->getState(); + return this->scStwClient->getState(); } QVariant ClimbingRace::getBaseStationConnections() { - return baseConn->getConnections(); + return scStwClient->getConnections(); } QVariantMap ClimbingRace::getBaseStationProperties() { - QVariantMap firmware = {{"version", this->baseConn->firmwareVersion}, {"upToDate", this->baseConn->firmwareUpToDate}}; - return {{"firmware", firmware}, {"timeOffset", this->baseConn->timeOffset}}; + QVariantMap firmware = {{"version", this->scStwClient->firmwareVersion}, {"upToDate", this->scStwClient->firmwareUpToDate}}; + return {{"firmware", firmware}, {"timeOffset", this->scStwClient->timeOffset}}; } bool ClimbingRace::updateBasestationFirmware() { - return this->baseConn->updateFirmware(); + return this->scStwClient->updateFirmware(); } bool ClimbingRace::updateBasestationTime() { - return this->baseConn->updateTime(); + return this->scStwClient->updateTime(); } bool ClimbingRace::reloadBaseStationIpAdress() { - if(this->baseConn->state == "disconnected"){ - this->baseConn->setIP(pGlobalAppSettings->loadSetting("baseStationIpAdress")); + if(this->scStwClient->getState() == "disconnected"){ + this->scStwClient->setIP(pGlobalAppSettings->loadSetting("baseStationIpAdress")); return true; } return false; diff --git a/ScStwSrc/sources/main.cpp b/ScStwSrc/sources/main.cpp index 9244717..30d1f21 100644 --- a/ScStwSrc/sources/main.cpp +++ b/ScStwSrc/sources/main.cpp @@ -51,7 +51,6 @@ #include "headers/sqlstoragemodel.h" #include "headers/sqlprofilemodel.h" #include "headers/appsettings.h" -#include "headers/baseconn.h" #include "headers/speedtimer.h" #include "headers/climbingrace.h" #include "headers/apptheme.h" diff --git a/ScStwSrc/sources/sqlprofilemodel.cpp b/ScStwSrc/sources/sqlprofilemodel.cpp deleted file mode 100644 index 1bd98d6..0000000 --- a/ScStwSrc/sources/sqlprofilemodel.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - Speed Climbing Stopwatch - Simple Stopwatch for Climbers - Copyright (C) 2018 Itsblue Development - Dorian Zeder - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, version 3 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -#include "headers/sqlprofilemodel.h" - -static void createTable() -{ - if (QSqlDatabase::database().tables().contains(QStringLiteral("Contacts"))) { - // The table already exists; we don't need to do anything. - return; - } - - QSqlQuery query; - - //creat eth etable to store the profiles - if (!query.exec( - "CREATE TABLE IF NOT EXISTS `profiles` ( " - " `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE," - " `name` TEXT NOT NULL " - " );")) { - qFatal("Failed to query database: %s", qPrintable(query.lastError().text())); - } - - //create the table to store the times - if (!query.exec( - "CREATE TABLE IF NOT EXISTS `times` (" - " `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE," - " `profileid` INTEGER NOT NULL," - " `time` INTEGER NOT NULL, " - " `timestamp` INTEGER NOT NULL" - " );")) { - qFatal("Failed to query database: %s", qPrintable(query.lastError().text())); - } -} - -SqlProfileModel::SqlProfileModel(QObject *parent) : QSqlTableModel(parent) -{ - qDebug("ProfileModel constructor"); - createTable(); - setTable("profiles"); - setEditStrategy(QSqlTableModel::OnManualSubmit); - select(); -} - -QVariant SqlProfileModel::data(const QModelIndex &index, int role) const -{ - if (role < Qt::UserRole) - return QSqlTableModel::data(index, role); - - const QSqlRecord sqlRecord = record(index.row()); - return sqlRecord.value(role - Qt::UserRole); -} - -QHash SqlProfileModel::roleNames() const -{ - QHash names; - names[Qt::UserRole + 0] = "id"; - names[Qt::UserRole + 1] = "name"; - - return names; -} - -bool SqlProfileModel::append(QString name) -{ - qDebug() << name; - QSqlRecord newRecord = record(); - newRecord.setValue("name", name); - - if (!insertRecord(rowCount(), newRecord)) { - qWarning() << "Failed to add profile:" << lastError().text(); - return(false); - } - - submitAll(); - return(true); -} - -void SqlProfileModel::remove(int row) -{ - removeRows(row, 1); - submitAll(); -} diff --git a/ScStwSrc/sources/sqlstoragemodel.cpp b/ScStwSrc/sources/sqlstoragemodel.cpp deleted file mode 100644 index d5906c8..0000000 --- a/ScStwSrc/sources/sqlstoragemodel.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - Speed Climbing Stopwatch - Simple Stopwatch for Climbers - Copyright (C) 2018 Itsblue Development - Dorian Zeder - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, version 3 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -#include "headers/sqlstoragemodel.h" - -SqlStorageModel::SqlStorageModel(QObject *parent) : QSqlTableModel(parent) -{ - qDebug("ProfileModel constructor"); - setTable("times"); - select(); -} - -QVariant SqlStorageModel::data(const QModelIndex &index, int role) const -{ - if (role < Qt::UserRole) - return QSqlTableModel::data(index, role); - - const QSqlRecord sqlRecord = record(index.row()); - return sqlRecord.value(role - Qt::UserRole); -} - -QHash SqlStorageModel::roleNames() const -{ - QHash names; - names[Qt::UserRole + 0] = "id"; - names[Qt::UserRole + 1] = "name"; - - return names; -}