From b0dc543a29dbf005a38f218293700b15fbe4b58d Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 6 Jul 2020 14:21:39 +0200 Subject: [PATCH 01/76] added ScStwSettings class (addressed issue #11 ) --- ScStwLibraries/ScStwLibraries.pri | 2 + ScStwLibraries/headers/ScStw.hpp | 62 +------------------- ScStwLibraries/headers/scstwlibraries.h | 1 + ScStwLibraries/headers/scstwsettings.h | 66 +++++++++++++++++++++ ScStwLibraries/sources/ScStw.cpp | 32 ----------- ScStwLibraries/sources/scstwsettings.cpp | 73 ++++++++++++++++++++++++ 6 files changed, 145 insertions(+), 91 deletions(-) create mode 100644 ScStwLibraries/headers/scstwsettings.h create mode 100644 ScStwLibraries/sources/scstwsettings.cpp diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index e34d9f9..8a72ff1 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -14,6 +14,7 @@ INCLUDEPATH += $$PWD/headers $$PWD SOURCES += \ $$PWD/sources/ScStw.cpp \ + $$PWD/sources/scstwsettings.cpp \ $$PWD/sources/scstwsoundplayer.cpp \ $$PWD/sources/scstwlibraries.cpp \ $$PWD/sources/scstwrace.cpp \ @@ -24,6 +25,7 @@ HEADERS += \ $$PWD/headers/ScStwLibraries_global.h \ $$PWD/headers/scstwlibraries.h \ $$PWD/headers/scstwrace.h \ + $$PWD/headers/scstwsettings.h \ $$PWD/headers/scstwsoundplayer.h \ $$PWD/headers/scstwtimer.h diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 263c951..cb2229a 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -79,24 +79,6 @@ public: }; Q_ENUM(SignalKey) - /*! - * \brief The BaseStationSetting enum contains all settings of the base station that can be changed by a client - * - * \see ScStw::baseStationSettingFromInt() - * \see ScStw::baseStationSettingToString() - * \see ScStw::baseStationSettingFromString() - * \see ScStw::baseStationSettings - */ - enum BaseStationSetting { - InvalidSetting = -1, - ReadySoundEnableSetting, - ReadySoundDelaySetting, - AtYourMarksSoundEnableSetting, - AtYourMarksSoundDelaySetting, - SoundVolumeSetting - }; - Q_ENUM(BaseStationSetting) - /*! * \brief The SocketCommand enum contains all commands the base station can handle * @@ -107,9 +89,9 @@ public: InitializeSessionCommand = 1, - StartTimersCommand = 1000, - StopTimersCommand = 1001, - ResetTimersCommand = 1002, + StartRaceCommand = 1000, + StopRaceCommand = 1001, + ResetRaceCommand = 1002, GetRaceStateCommand = 2000, GetNextStartActionCommand = 2005, @@ -171,44 +153,6 @@ public: */ static const char* SOCKET_MESSAGE_END_KEY; - /*! - * \brief baseStationSettings contains a string with reference to all BaseStationSetting values - * - * \see ScStw::BaseStationSetting - * \see ScStw::baseStationSettingToString() - * \see ScStw::baseStationSettingFromString() - */ - static const QMap baseStationSettings; - - /*! - * \brief Function to convert an int to a BaseStationSetting - * \param i the int to convert - * \return a BaseStationSetting - * - * \see ScStw::BaseStationSetting - */ - static BaseStationSetting baseStationSettingfromInt(int i); - - /*! - * \brief Function to convert a QString to a BaseStationSetting - * \param s the string to convert - * \return a BaseStationSetting - * - * \see ScStw::BaseStationSetting - * \see ScStw::baseStationSettingToString() - */ - static BaseStationSetting baseStationSettingFromString(QString s); - - /*! - * \brief Function to convert BaseStationSetting to a QString - * \param s the BaseStationSetting to convert - * \return a QString - * - * \see ScStw::BaseStationSetting - * \see ScStw::baseStationSettingFromString() - */ - Q_INVOKABLE static QString baseStationSettingToString(BaseStationSetting s); - /*! * \brief Function to convert an int to a SignalKey * \param i the int to convert diff --git a/ScStwLibraries/headers/scstwlibraries.h b/ScStwLibraries/headers/scstwlibraries.h index f6b1857..1321860 100644 --- a/ScStwLibraries/headers/scstwlibraries.h +++ b/ScStwLibraries/headers/scstwlibraries.h @@ -25,6 +25,7 @@ #endif #include "scstwtimer.h" #include "scstwrace.h" +#include "scstwsettings.h" #ifdef ScStwLibraries_ClientLibs #include "scstwremotemonitorrace.h" #include "scstwclient.h" diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h new file mode 100644 index 0000000..8c1c655 --- /dev/null +++ b/ScStwLibraries/headers/scstwsettings.h @@ -0,0 +1,66 @@ +#ifndef SCSTWSETTINGS_H +#define SCSTWSETTINGS_H + +#include +#include +#include +#include +#include +#include +#include +#include + +class ScStwSettings : public QObject +{ + Q_OBJECT +public: + explicit ScStwSettings(QObject *parent = nullptr); + + /*! + * \brief The BaseStationSetting enum contains all settings of the base station that can be changed by a client + * + * \see ScStw::baseStationSettingFromInt() + * \see ScStw::baseStationSettingToString() + * \see ScStw::baseStationSettingFromString() + * \see ScStw::baseStationSettings + */ + enum BaseStationSetting { + InvalidSetting = -1, + ReadySoundEnableSetting, + ReadySoundDelaySetting, + AtYourMarksSoundEnableSetting, + AtYourMarksSoundDelaySetting, + SoundVolumeSetting + }; + + Q_ENUM(BaseStationSetting) + + QVariant readSetting(BaseStationSetting key); + bool writeSetting(BaseStationSetting key, QVariant value); + void setDefaultSetting(BaseStationSetting key, QVariant defaultVariant); + + static BaseStationSetting keyFromInt(int i) { + QMetaEnum enumeration = QMetaEnum::fromType(); + return static_cast(enumeration.keyToValue(enumeration.valueToKey(i))); + } + +protected: + QVariant readSetting(QString key); + bool writeSetting(QString key, QVariant value, int keyInt,int keyLevel = -1); + void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); + +private: + QFile * settingsFile; + QVariantMap settingsCache; + + bool loadSettingsFromFile(); + +private slots: + bool writeSettingsToFile(); + +signals: + void settingChanged(int key, int keyLevel); + +}; + +#endif // SCSTWSETTINGS_H diff --git a/ScStwLibraries/sources/ScStw.cpp b/ScStwLibraries/sources/ScStw.cpp index f01abb2..2cc19f0 100644 --- a/ScStwLibraries/sources/ScStw.cpp +++ b/ScStwLibraries/sources/ScStw.cpp @@ -21,38 +21,6 @@ const char *ScStw::SOCKET_MESSAGE_START_KEY = ""; const char *ScStw::SOCKET_MESSAGE_END_KEY = ""; -const QMap ScStw::baseStationSettings = { - {"ReadySoundEnable", ScStw::ReadySoundEnableSetting}, - {"ReadySoundDelay", ScStw::ReadySoundDelaySetting}, - {"AtYourMarksSoundEnable", ScStw::AtYourMarksSoundEnableSetting}, - {"AtYourMarksSoundDelay", ScStw::AtYourMarksSoundDelaySetting}, - {"SoundVolume", ScStw::SoundVolumeSetting} -}; - -ScStw::BaseStationSetting ScStw::baseStationSettingFromString(QString s) { - if(!ScStw::baseStationSettings.contains(s)) - return ScStw::InvalidSetting; - - return ScStw::baseStationSettings[s]; -} - -QString ScStw::baseStationSettingToString(ScStw::BaseStationSetting s) { - for(QString key: ScStw::baseStationSettings.keys()) { - if(ScStw::baseStationSettings[key] == s) - return key; - } - return "Invalid"; -} - -ScStw::BaseStationSetting ScStw::baseStationSettingfromInt(int i) { - bool ok; - BaseStationSetting s = ScStw::toEnumValue(i, &ok); - if(!ok) - return InvalidSetting; - else - return s; -} - ScStw::SignalKey ScStw::signalKeyFromInt(int i) { bool ok; ScStw::SignalKey k = ScStw::toEnumValue(i, &ok); diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp new file mode 100644 index 0000000..5e33941 --- /dev/null +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -0,0 +1,73 @@ +#include "../headers/scstwsettings.h" + +ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) +{ + QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/settings.json"; + this->settingsFile = new QFile(path); + if(!this->settingsFile->open(QFile::ReadWrite)) + qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path)); + + if(!this->loadSettingsFromFile() && this->settingsFile->size() != 0) + qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path)); + + connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); +} + +QVariant ScStwSettings::readSetting(BaseStationSetting key) { + return this->readSetting(QMetaEnum::fromType().valueToKey(int(key))); +} + +bool ScStwSettings::writeSetting(BaseStationSetting key, QVariant value) { + return this->writeSetting(QMetaEnum::fromType().valueToKey(int(key)), value, int(key), 0); +} + +void ScStwSettings::setDefaultSetting(BaseStationSetting key, QVariant defaultVariant) { + this->setDefaultSetting(QMetaEnum::fromType().valueToKey(int(key)), defaultVariant, int(key), 0); +} + +QVariant ScStwSettings::readSetting(QString key) { + return this->settingsCache[key]; +} + +bool ScStwSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { + if(!this->settingsCache.contains(key)) + this->settingsCache.insert(key, value); + else if (this->settingsCache[key] == value) + return true; + else + this->settingsCache[key] = value; + + emit this->settingChanged(keyInt, keyLevel); + + return true; +} + +void ScStwSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { + if(!this->settingsCache.contains(key)) + this->writeSetting(key, defaultVariant, keyInt, keyLevel); +} + +/* + * File handling + */ + +bool ScStwSettings::writeSettingsToFile() { + QJsonDocument doc = QJsonDocument::fromVariant(this->settingsCache); + + // overwrite file + this->settingsFile->reset(); + this->settingsFile->write(doc.toJson(QJsonDocument::Indented)); + this->settingsFile->flush(); + + return true; +} + +bool ScStwSettings::loadSettingsFromFile() { + QJsonDocument doc = QJsonDocument::fromJson(this->settingsFile->readAll()); + + if(doc.toVariant().type() != QVariant::Map) + return false; + + this->settingsCache = doc.toVariant().toMap(); + return true; +} From 3d18b72eaf7fc8993ff60f1e087fa0c30516f4b5 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 6 Jul 2020 15:03:43 +0200 Subject: [PATCH 02/76] migrated to new settings --- ScStwLibraries/headers/client/scstwclient.h | 5 +++-- ScStwLibraries/sources/client/scstwclient.cpp | 4 ++-- ScStwLibraries/sources/scstwlibraries.cpp | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwclient.h b/ScStwLibraries/headers/client/scstwclient.h index 60c3684..df9c5f8 100644 --- a/ScStwLibraries/headers/client/scstwclient.h +++ b/ScStwLibraries/headers/client/scstwclient.h @@ -33,6 +33,7 @@ #include #include "ScStw.hpp" +#include "scstwsettings.h" /*! * This class is used to connect and talk to the ScStw basestation. @@ -139,14 +140,14 @@ public slots: * \param value the value to write to * \return the status code returned by the command */ - ScStw::StatusCode writeRemoteSetting(ScStw::BaseStationSetting key, QString value); + ScStw::StatusCode writeRemoteSetting(ScStwSettings::BaseStationSetting key, QString value); /*! * \brief Function to read a setting on the base station * \param key the key to read from * \return the value of the key or "false" if the key is not found or an error occured */ - QString readRemoteSetting(ScStw::BaseStationSetting key); + QString readRemoteSetting(ScStwSettings::BaseStationSetting key); /*! Getter fuctions */ diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index e6eaaf8..795ce4a 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -392,14 +392,14 @@ void ScStwClient::handleSignal(QVariantMap data) { // --- helper functions --- // ------------------------ -ScStw::StatusCode ScStwClient::writeRemoteSetting(ScStw::BaseStationSetting key, QString value) { +ScStw::StatusCode ScStwClient::writeRemoteSetting(ScStwSettings::BaseStationSetting key, QString value) { QJsonArray requestData; requestData.append(key); requestData.append(value); return ScStw::StatusCode(this->sendCommand(3000, requestData)["status"].toInt()); } -QString ScStwClient::readRemoteSetting(ScStw::BaseStationSetting key) { +QString ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key) { QVariantMap reply = this->sendCommand(3001, key); if(reply["status"] != 200){ return "false"; diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 14068d2..af0228d 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -26,7 +26,7 @@ ScStwLibraries::ScStwLibraries(QObject *parent) : QObject(parent) void ScStwLibraries::init() { #ifdef ScStwLibraries_QML qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStw"); - qRegisterMetaType("ScStw::BaseStationSetting"); + qRegisterMetaType("ScStw::BaseStationSetting"); qRegisterMetaType("ScStw::SocketCommand"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRace"); From 6c1ce8e65407452ce82f412fdd26d1367bf3ea38 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 10 Jul 2020 15:20:13 +0200 Subject: [PATCH 03/76] completed new settings structure and added class to manage remote settings --- ScStwLibraries/ScStwLibraries.pri | 2 + ScStwLibraries/headers/ScStw.hpp | 3 +- ScStwLibraries/headers/client/scstwclient.h | 4 +- .../headers/client/scstwremotesettings.h | 35 ++++++++++++ ScStwLibraries/headers/scstwsettings.h | 19 ++++--- ScStwLibraries/sources/client/scstwclient.cpp | 10 ++-- .../sources/client/scstwremotesettings.cpp | 53 +++++++++++++++++++ ScStwLibraries/sources/scstwlibraries.cpp | 3 +- ScStwLibraries/sources/scstwsettings.cpp | 17 ++++-- 9 files changed, 125 insertions(+), 21 deletions(-) create mode 100644 ScStwLibraries/headers/client/scstwremotesettings.h create mode 100644 ScStwLibraries/sources/client/scstwremotesettings.cpp diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index fbec086..a168177 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -19,6 +19,7 @@ INCLUDEPATH += $$PWD/headers $$PWD SOURCES += \ $$PWD/sources/ScStw.cpp \ + $$PWD/sources/client/scstwremotesettings.cpp \ $$PWD/sources/scstwsettings.cpp \ $$PWD/sources/scstwsoundplayer.cpp \ $$PWD/sources/scstwlibraries.cpp \ @@ -28,6 +29,7 @@ SOURCES += \ HEADERS += \ $$PWD/headers/ScStw.hpp \ $$PWD/headers/ScStwLibraries_global.h \ + $$PWD/headers/client/scstwremotesettings.h \ $$PWD/headers/scstwlibraries.h \ $$PWD/headers/scstwrace.h \ $$PWD/headers/scstwsettings.h \ diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 497cfc0..11e5a4c 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -61,7 +61,8 @@ public: RaceStateChanged = 9000, TimersChanged = 9001, ExtensionsChanged = 9002, - NextStartActionChanged = 9003 /*, ProfilesChanged*/ + NextStartActionChanged = 9003, /*, ProfilesChanged*/ + SettingChanged = 9004 }; Q_ENUM(SignalKey) diff --git a/ScStwLibraries/headers/client/scstwclient.h b/ScStwLibraries/headers/client/scstwclient.h index df9c5f8..d3a3946 100644 --- a/ScStwLibraries/headers/client/scstwclient.h +++ b/ScStwLibraries/headers/client/scstwclient.h @@ -140,14 +140,14 @@ public slots: * \param value the value to write to * \return the status code returned by the command */ - ScStw::StatusCode writeRemoteSetting(ScStwSettings::BaseStationSetting key, QString value); + ScStw::StatusCode writeRemoteSetting(ScStwSettings::BaseStationSetting key, QVariant value); /*! * \brief Function to read a setting on the base station * \param key the key to read from * \return the value of the key or "false" if the key is not found or an error occured */ - QString readRemoteSetting(ScStwSettings::BaseStationSetting key); + QVariant readRemoteSetting(ScStwSettings::BaseStationSetting key); /*! Getter fuctions */ diff --git a/ScStwLibraries/headers/client/scstwremotesettings.h b/ScStwLibraries/headers/client/scstwremotesettings.h new file mode 100644 index 0000000..7f02d6e --- /dev/null +++ b/ScStwLibraries/headers/client/scstwremotesettings.h @@ -0,0 +1,35 @@ +#ifndef SCSTWREMOTESETTINGS_H +#define SCSTWREMOTESETTINGS_H + +#include +#include "scstwsettings.h" +#include "scstwclient.h" +#include + +class ScStwRemoteSettings : public ScStwSettings +{ + Q_OBJECT +public: + ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent = nullptr); + + enum SettingsMode { + LOCAL, + REMOTE + }; + +protected: + QVariant readSetting(QString key, int keyInt, int keyLevel); + bool writeSetting(QString key, QVariant value, int keyInt,int keyLevel = -1); + void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); + +private: + ScStwClient * scStwClient; + + SettingsMode getMode(); + +private slots: + void handleClientStateChange(); + void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); +}; + +#endif // SCSTWREMOTESETTINGS_H diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index 8c1c655..7fca825 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -9,6 +9,7 @@ #include #include #include +#include class ScStwSettings : public QObject { @@ -32,12 +33,16 @@ public: AtYourMarksSoundDelaySetting, SoundVolumeSetting }; - Q_ENUM(BaseStationSetting) - QVariant readSetting(BaseStationSetting key); - bool writeSetting(BaseStationSetting key, QVariant value); - void setDefaultSetting(BaseStationSetting key, QVariant defaultVariant); + enum KeyLevelEnum { + KeyLevel = 0 + }; + Q_ENUM(KeyLevelEnum) + + Q_INVOKABLE QVariant readSetting(BaseStationSetting key); + Q_INVOKABLE bool writeSetting(BaseStationSetting key, QVariant value); + Q_INVOKABLE void setDefaultSetting(BaseStationSetting key, QVariant defaultVariant); static BaseStationSetting keyFromInt(int i) { QMetaEnum enumeration = QMetaEnum::fromType(); @@ -45,9 +50,9 @@ public: } protected: - QVariant readSetting(QString key); - bool writeSetting(QString key, QVariant value, int keyInt,int keyLevel = -1); - void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); + virtual QVariant readSetting(QString key, int keyInt = -1, int keyLevel = -1); + virtual bool writeSetting(QString key, QVariant value, int keyInt = -1,int keyLevel = -1); + virtual void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); private: QFile * settingsFile; diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index 795ce4a..9e7d93c 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -392,15 +392,15 @@ void ScStwClient::handleSignal(QVariantMap data) { // --- helper functions --- // ------------------------ -ScStw::StatusCode ScStwClient::writeRemoteSetting(ScStwSettings::BaseStationSetting key, QString value) { +ScStw::StatusCode ScStwClient::writeRemoteSetting(ScStwSettings::BaseStationSetting key, QVariant value) { QJsonArray requestData; - requestData.append(key); - requestData.append(value); + requestData.append(int(key)); + requestData.append(QJsonValue::fromVariant(value)); return ScStw::StatusCode(this->sendCommand(3000, requestData)["status"].toInt()); } -QString ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key) { - QVariantMap reply = this->sendCommand(3001, key); +QVariant ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key) { + QVariantMap reply = this->sendCommand(3001, int(key)); if(reply["status"] != 200){ return "false"; } diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp new file mode 100644 index 0000000..8879dea --- /dev/null +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -0,0 +1,53 @@ +#include "../../headers/client/scstwremotesettings.h" + +ScStwRemoteSettings::ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent) : ScStwSettings(parent) +{ + this->scStwClient = scStwClient; + + connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteSettings::handleBaseStationSignal); +} + +ScStwRemoteSettings::SettingsMode ScStwRemoteSettings::getMode() { + if(this->scStwClient->getState() == ScStwClient::CONNECTED) + return ScStwRemoteSettings::REMOTE; + else + return ScStwRemoteSettings::LOCAL; +} + +QVariant ScStwRemoteSettings::readSetting(QString key, int keyInt, int keyLevel) { + if(this->getMode() == LOCAL || keyLevel > 0) + return ScStwSettings::readSetting(key, keyInt, keyLevel); + + return this->scStwClient->readRemoteSetting(ScStwSettings::BaseStationSetting(keyInt)); +} + +bool ScStwRemoteSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { + if(this->getMode() == LOCAL || keyLevel > 0) + return ScStwSettings::writeSetting(key, value, keyInt, keyLevel); + + this->scStwClient->writeRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), value); + emit this->settingChanged(keyInt, keyLevel); + + return true; +} + +void ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { + if(this->getMode() == LOCAL || keyLevel > 0) + return ScStwSettings::setDefaultSetting(key, defaultVariant, keyInt, keyLevel); + + return; +} + +void ScStwRemoteSettings::handleClientStateChange() { + if(this->scStwClient->getState() == ScStwClient::DISCONNECTED) + emit this->settingChanged(-1, 0); +} + +void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { + switch (key) { + case ScStw::SettingChanged: + emit this->settingChanged(data.toMap()["key"].toInt(), 0); + default: + break; +} +} diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index af0228d..4470c31 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -26,7 +26,7 @@ ScStwLibraries::ScStwLibraries(QObject *parent) : QObject(parent) void ScStwLibraries::init() { #ifdef ScStwLibraries_QML qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStw"); - qRegisterMetaType("ScStw::BaseStationSetting"); + qRegisterMetaType("ScStwSettings::BaseStationSetting"); qRegisterMetaType("ScStw::SocketCommand"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRace"); @@ -34,6 +34,7 @@ void ScStwLibraries::init() { #ifdef ScStwLibraries_ClientLibs qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwClient"); + qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSettings"); #endif #endif } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 5e33941..47a779e 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -2,10 +2,15 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) { - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/settings.json"; - this->settingsFile = new QFile(path); + QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + QDir dir(path); + this->settingsFile = new QFile(path+ "/settings.json"); + if(!this->settingsFile->exists()) + if(!dir.mkpath(path)) + qFatal("[FATAL] Couldn't create settings dir %s", qPrintable(path)); + if(!this->settingsFile->open(QFile::ReadWrite)) - qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path)); + qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path + "/settings.json")); if(!this->loadSettingsFromFile() && this->settingsFile->size() != 0) qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path)); @@ -14,7 +19,7 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) } QVariant ScStwSettings::readSetting(BaseStationSetting key) { - return this->readSetting(QMetaEnum::fromType().valueToKey(int(key))); + return this->readSetting(QMetaEnum::fromType().valueToKey(int(key)), int(key), 0); } bool ScStwSettings::writeSetting(BaseStationSetting key, QVariant value) { @@ -25,7 +30,9 @@ void ScStwSettings::setDefaultSetting(BaseStationSetting key, QVariant defaultVa this->setDefaultSetting(QMetaEnum::fromType().valueToKey(int(key)), defaultVariant, int(key), 0); } -QVariant ScStwSettings::readSetting(QString key) { +QVariant ScStwSettings::readSetting(QString key, int keyInt, int keyLevel) { + Q_UNUSED(keyInt) + Q_UNUSED(keyLevel) return this->settingsCache[key]; } From 2cffaf6a91b7ff6cefebda95dfc6d58f355f30ce Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 11:15:06 +0200 Subject: [PATCH 04/76] - creating settings path automatically now - changed includes --- ScStwLibraries/ScStwLibraries.pri | 4 ++-- ScStwLibraries/sources/scstwsettings.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index a168177..2c886fb 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -19,7 +19,6 @@ INCLUDEPATH += $$PWD/headers $$PWD SOURCES += \ $$PWD/sources/ScStw.cpp \ - $$PWD/sources/client/scstwremotesettings.cpp \ $$PWD/sources/scstwsettings.cpp \ $$PWD/sources/scstwsoundplayer.cpp \ $$PWD/sources/scstwlibraries.cpp \ @@ -29,7 +28,6 @@ SOURCES += \ HEADERS += \ $$PWD/headers/ScStw.hpp \ $$PWD/headers/ScStwLibraries_global.h \ - $$PWD/headers/client/scstwremotesettings.h \ $$PWD/headers/scstwlibraries.h \ $$PWD/headers/scstwrace.h \ $$PWD/headers/scstwsettings.h \ @@ -39,10 +37,12 @@ HEADERS += \ ScStwLibraries_ClientLibs { SOURCES += \ $$PWD/sources/client/scstwclient.cpp \ + $$PWD/sources/client/scstwremotesettings.cpp \ $$PWD/sources/client/scstwremotemonitorrace.cpp HEADERS += \ $$PWD/headers/client/scstwclient.h \ + $$PWD/headers/client/scstwremotesettings.h \ $$PWD/headers/client/scstwremotemonitorrace.h INCLUDEPATH += $$PWD/headers/client diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 47a779e..3be7226 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -4,7 +4,7 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) { QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir dir(path); - this->settingsFile = new QFile(path+ "/settings.json"); + this->settingsFile = new QFile(path + "/settings.json"); if(!this->settingsFile->exists()) if(!dir.mkpath(path)) qFatal("[FATAL] Couldn't create settings dir %s", qPrintable(path)); @@ -13,7 +13,7 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path + "/settings.json")); if(!this->loadSettingsFromFile() && this->settingsFile->size() != 0) - qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path)); + qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path + "/settings.json")); connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); } From c44cd117a88e35da0594e2483aa109638a147c78 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 11:16:09 +0200 Subject: [PATCH 05/76] add stuff --- ScStwLibraries/ScStwLibraries.pri | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index a168177..b8311f4 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -38,10 +38,12 @@ HEADERS += \ ScStwLibraries_ClientLibs { SOURCES += \ + $$PWD/sources/client/scstwqmlsetting.cpp \ $$PWD/sources/client/scstwclient.cpp \ $$PWD/sources/client/scstwremotemonitorrace.cpp HEADERS += \ + $$PWD/headers/client/scstwqmlsetting.h \ $$PWD/headers/client/scstwclient.h \ $$PWD/headers/client/scstwremotemonitorrace.h From e853e246ab74417ee2921aad9ad2a4e82df9542d Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 11:17:20 +0200 Subject: [PATCH 06/76] - add new class - change how signal subscriptions are handled in client --- ScStwLibraries/headers/client/scstwclient.h | 9 ++++++++- .../headers/client/scstwqmlsetting.h | 16 ++++++++++++++++ ScStwLibraries/sources/client/scstwclient.cpp | 19 +++++++++++++++---- .../sources/client/scstwqmlsetting.cpp | 6 ++++++ .../sources/client/scstwremotemonitorrace.cpp | 4 ++++ .../sources/client/scstwremotesettings.cpp | 8 +++++--- 6 files changed, 54 insertions(+), 8 deletions(-) create mode 100644 ScStwLibraries/headers/client/scstwqmlsetting.h create mode 100644 ScStwLibraries/sources/client/scstwqmlsetting.cpp diff --git a/ScStwLibraries/headers/client/scstwclient.h b/ScStwLibraries/headers/client/scstwclient.h index d3a3946..99e8dc3 100644 --- a/ScStwLibraries/headers/client/scstwclient.h +++ b/ScStwLibraries/headers/client/scstwclient.h @@ -60,7 +60,10 @@ public: * * \brief ScStwClient */ - explicit ScStwClient(QObject *parent = nullptr); + explicit ScStwClient( + QObject *parent = nullptr, + QList signalSubscriptions = {ScStw::ExtensionsChanged} + ); enum State {DISCONNECTED, CONNECTING, INITIALISING, CONNECTED}; Q_ENUM(State); @@ -76,6 +79,8 @@ private: QVariantList extensions; + QList signalSubscriptions; + //---general status values---// // some meta data of the base station @@ -200,6 +205,8 @@ public slots: */ void setIP(QString ipAdress); + void addSignalSubscription(ScStw::SignalKey key); + private slots: /*! * \brief called when timeout timer times out diff --git a/ScStwLibraries/headers/client/scstwqmlsetting.h b/ScStwLibraries/headers/client/scstwqmlsetting.h new file mode 100644 index 0000000..85e0809 --- /dev/null +++ b/ScStwLibraries/headers/client/scstwqmlsetting.h @@ -0,0 +1,16 @@ +#ifndef SCSTWQMLSETTING_H +#define SCSTWQMLSETTING_H + +#include + +class ScStwQmlSetting : public QObject +{ + Q_OBJECT +public: + explicit ScStwQmlSetting(QObject *parent = nullptr); + +signals: + +}; + +#endif // SCSTWQMLSETTING_H diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index 9e7d93c..0aebd03 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -20,11 +20,12 @@ ScStwClient * pGlobalScStwClient = nullptr; -ScStwClient::ScStwClient(QObject * parent) : QObject(parent) +ScStwClient::ScStwClient(QObject * parent, QList signalSubscriptions) : QObject(parent) { this->state = DISCONNECTED; this->nextConnectionId = 1; this->extensions = QVariantList({}); + this->signalSubscriptions = signalSubscriptions; this->socket = new QTcpSocket(this); @@ -72,9 +73,13 @@ bool ScStwClient::init() { this->setState(INITIALISING); this->timeoutTimer->stop(); + QJsonArray signalSubs; + foreach (ScStw::SignalKey key, this->signalSubscriptions) { + signalSubs.append(key); + } + // init remote session - QJsonArray updateSubs = {ScStw::RaceStateChanged, ScStw::TimersChanged, ScStw::ExtensionsChanged, ScStw::NextStartActionChanged}; - QJsonObject sessionParams = {{"updateSubs", updateSubs}, {"init", true}, {"usingTerminationKeys", true}}; + QJsonObject sessionParams = {{"signalSubscriptions", signalSubs}, {"init", true}, {"usingTerminationKeys", true}}; QVariantMap initResponse = this->sendCommand(1, sessionParams, 3000, false); @@ -368,7 +373,7 @@ void ScStwClient::handleSignal(QVariantMap data) { ScStw::SignalKey signalKey = ScStw::signalKeyFromInt(data["header"].toInt()); - //qDebug() << "got signal: " << signalKey << " with data: " << data["data"]; + qDebug() << "got signal: " << signalKey << " with data: " << data["data"]; switch (signalKey) { case ScStw::ExtensionsChanged: @@ -452,3 +457,9 @@ void ScStwClient::setExtensions(QVariantList extensions) { emit this->extensionsChanged(); } } + + +void ScStwClient::addSignalSubscription(ScStw::SignalKey key) { + if(!this->signalSubscriptions.contains(key)) + this->signalSubscriptions.append(key); +} diff --git a/ScStwLibraries/sources/client/scstwqmlsetting.cpp b/ScStwLibraries/sources/client/scstwqmlsetting.cpp new file mode 100644 index 0000000..86321c3 --- /dev/null +++ b/ScStwLibraries/sources/client/scstwqmlsetting.cpp @@ -0,0 +1,6 @@ +#include "../../headers/client/scstwqmlsetting.h" + +ScStwQmlSetting::ScStwQmlSetting(QObject *parent) : QObject(parent) +{ + +} diff --git a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp index 553598f..b286927 100644 --- a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp +++ b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp @@ -22,6 +22,10 @@ ScStwRemoteMonitorRace::ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObje { this->scStwClient = monitorClient; + this->scStwClient->addSignalSubscription(ScStw::RaceStateChanged); + this->scStwClient->addSignalSubscription(ScStw::TimersChanged); + this->scStwClient->addSignalSubscription(ScStw::NextStartActionChanged); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteMonitorRace::handleClientStateChanged); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteMonitorRace::handleBaseStationSignal); } diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index 8879dea..f653ebd 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -3,6 +3,7 @@ ScStwRemoteSettings::ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent) : ScStwSettings(parent) { this->scStwClient = scStwClient; + this->scStwClient->addSignalSubscription(ScStw::SettingChanged); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteSettings::handleBaseStationSignal); } @@ -25,10 +26,11 @@ bool ScStwRemoteSettings::writeSetting(QString key, QVariant value, int keyInt, if(this->getMode() == LOCAL || keyLevel > 0) return ScStwSettings::writeSetting(key, value, keyInt, keyLevel); - this->scStwClient->writeRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), value); - emit this->settingChanged(keyInt, keyLevel); + qDebug() << "changing setting"; + ScStw::StatusCode res = this->scStwClient->writeRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), value); + qDebug() << "changed setting " << res; - return true; + return res == ScStw::Success; } void ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { From ad3f8318c709653863058fc234469bd0ff006042 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 11:51:42 +0200 Subject: [PATCH 07/76] created class "ScStwSetting" which can be used as a handler for settings --- ScStwLibraries/ScStwLibraries.pri | 8 +-- .../headers/client/scstwqmlsetting.h | 16 ------ ScStwLibraries/headers/client/scstwsetting.h | 47 ++++++++++++++++ ScStwLibraries/headers/scstwlibraries.h | 1 + ScStwLibraries/headers/scstwsettings.h | 2 + .../sources/client/scstwqmlsetting.cpp | 6 -- .../sources/client/scstwsetting.cpp | 55 +++++++++++++++++++ ScStwLibraries/sources/scstwlibraries.cpp | 1 + ScStwLibraries/sources/scstwsettings.cpp | 14 +++++ 9 files changed, 124 insertions(+), 26 deletions(-) delete mode 100644 ScStwLibraries/headers/client/scstwqmlsetting.h create mode 100644 ScStwLibraries/headers/client/scstwsetting.h delete mode 100644 ScStwLibraries/sources/client/scstwqmlsetting.cpp create mode 100644 ScStwLibraries/sources/client/scstwsetting.cpp diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index 0d1a693..781de65 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -36,16 +36,16 @@ HEADERS += \ ScStwLibraries_ClientLibs { SOURCES += \ - $$PWD/sources/client/scstwqmlsetting.cpp \ $$PWD/sources/client/scstwclient.cpp \ $$PWD/sources/client/scstwremotesettings.cpp \ - $$PWD/sources/client/scstwremotemonitorrace.cpp + $$PWD/sources/client/scstwremotemonitorrace.cpp \ + $$PWD/sources/client/scstwsetting.cpp HEADERS += \ - $$PWD/headers/client/scstwqmlsetting.h \ $$PWD/headers/client/scstwclient.h \ $$PWD/headers/client/scstwremotesettings.h \ - $$PWD/headers/client/scstwremotemonitorrace.h + $$PWD/headers/client/scstwremotemonitorrace.h \ + $$PWD/headers/client/scstwsetting.h INCLUDEPATH += $$PWD/headers/client } diff --git a/ScStwLibraries/headers/client/scstwqmlsetting.h b/ScStwLibraries/headers/client/scstwqmlsetting.h deleted file mode 100644 index 85e0809..0000000 --- a/ScStwLibraries/headers/client/scstwqmlsetting.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef SCSTWQMLSETTING_H -#define SCSTWQMLSETTING_H - -#include - -class ScStwQmlSetting : public QObject -{ - Q_OBJECT -public: - explicit ScStwQmlSetting(QObject *parent = nullptr); - -signals: - -}; - -#endif // SCSTWQMLSETTING_H diff --git a/ScStwLibraries/headers/client/scstwsetting.h b/ScStwLibraries/headers/client/scstwsetting.h new file mode 100644 index 0000000..42f857c --- /dev/null +++ b/ScStwLibraries/headers/client/scstwsetting.h @@ -0,0 +1,47 @@ +#ifndef SCSTWQMLSETTING_H +#define SCSTWQMLSETTING_H + +#include +#include + +class ScStwSetting : public QObject +{ + Q_OBJECT + Q_PROPERTY(ScStwSettings* scStwSettings READ getScStwSettings WRITE setScStwSettings NOTIFY scStwSettingsChanged) + Q_PROPERTY(int key READ getKey WRITE setKey NOTIFY keyChanged) + Q_PROPERTY(int keyLevel READ getKeyLevel WRITE setKeyLevel NOTIFY keyLevelChanged) + Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged) +public: + explicit ScStwSetting(QObject *parent = nullptr); + +private: + ScStwSettings* scStwSettings; + int key; + int keyLevel; + QVariant valueCache; + +public slots: + ScStwSettings* getScStwSettings(); + void setScStwSettings(ScStwSettings* scStwSettings); + + int getKey(); + void setKey(int key); + + int getKeyLevel(); + void setKeyLevel(int keyLevel); + + QVariant getValue(); + void setValue(QVariant value); + +private slots: + void handleSettingChange(int key, int keyLevel); + +signals: + void scStwSettingsChanged(); + void keyChanged(); + void keyLevelChanged(); + void valueChanged(); + +}; + +#endif // SCSTWQMLSETTING_H diff --git a/ScStwLibraries/headers/scstwlibraries.h b/ScStwLibraries/headers/scstwlibraries.h index 846f314..76ffb39 100644 --- a/ScStwLibraries/headers/scstwlibraries.h +++ b/ScStwLibraries/headers/scstwlibraries.h @@ -32,6 +32,7 @@ #include "scstwtimer.h" #include "scstwrace.h" #include "scstwsettings.h" +#include "scstwsetting.h" #ifdef ScStwLibraries_ClientLibs #include "scstwremotemonitorrace.h" #include "scstwclient.h" diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index 7fca825..eb859e8 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -41,7 +41,9 @@ public: Q_ENUM(KeyLevelEnum) Q_INVOKABLE QVariant readSetting(BaseStationSetting key); + Q_INVOKABLE virtual QVariant readSetting(int key, int level); Q_INVOKABLE bool writeSetting(BaseStationSetting key, QVariant value); + Q_INVOKABLE virtual bool writeSetting(int key, QVariant value, int level); Q_INVOKABLE void setDefaultSetting(BaseStationSetting key, QVariant defaultVariant); static BaseStationSetting keyFromInt(int i) { diff --git a/ScStwLibraries/sources/client/scstwqmlsetting.cpp b/ScStwLibraries/sources/client/scstwqmlsetting.cpp deleted file mode 100644 index 86321c3..0000000 --- a/ScStwLibraries/sources/client/scstwqmlsetting.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "../../headers/client/scstwqmlsetting.h" - -ScStwQmlSetting::ScStwQmlSetting(QObject *parent) : QObject(parent) -{ - -} diff --git a/ScStwLibraries/sources/client/scstwsetting.cpp b/ScStwLibraries/sources/client/scstwsetting.cpp new file mode 100644 index 0000000..df0f845 --- /dev/null +++ b/ScStwLibraries/sources/client/scstwsetting.cpp @@ -0,0 +1,55 @@ +#include "scstwsetting.h" + +ScStwSetting::ScStwSetting(QObject *parent) : QObject(parent) +{ + +} + +ScStwSettings* ScStwSetting::getScStwSettings(){ + return this->scStwSettings; +} +void ScStwSetting::setScStwSettings(ScStwSettings* scStwSettings) { + if(this->scStwSettings != scStwSettings && scStwSettings != nullptr) { + this->scStwSettings = scStwSettings; + connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSetting::handleSettingChange); + emit this->scStwSettingsChanged(); + } +} + +int ScStwSetting::getKey() { + return this->key; +} +void ScStwSetting::setKey(int key) { + if(this->key != key) { + this->key = key; + this->handleSettingChange(this->key, this->keyLevel); + emit this->keyChanged(); + } +} + +int ScStwSetting::getKeyLevel() { + return this->keyLevel; +} +void ScStwSetting::setKeyLevel(int keyLevel) { + if(this->keyLevel != keyLevel) { + this->keyLevel = keyLevel; + this->handleSettingChange(this->key, this->keyLevel); + emit this->keyLevelChanged(); + } +} + +QVariant ScStwSetting::getValue() { + return this->valueCache; +} +void ScStwSetting::setValue(QVariant value) { + if(value != this->valueCache && this->scStwSettings != nullptr) { + this->scStwSettings->writeSetting(this->key, value, this->keyLevel); + } +} + +void ScStwSetting::handleSettingChange(int key, int keyLevel) { + if(keyLevel == this->keyLevel && key == this->key) { + this->valueCache = this->scStwSettings->readSetting(key, keyLevel); + emit this->valueChanged(); + } +} diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 4470c31..701367c 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -35,6 +35,7 @@ void ScStwLibraries::init() { #ifdef ScStwLibraries_ClientLibs qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwClient"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSettings"); + qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSetting"); #endif #endif } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 3be7226..7da1ac8 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -22,10 +22,24 @@ QVariant ScStwSettings::readSetting(BaseStationSetting key) { return this->readSetting(QMetaEnum::fromType().valueToKey(int(key)), int(key), 0); } +QVariant ScStwSettings::readSetting(int key, int keyLevel) { + if(keyLevel == ScStwSettings::KeyLevel) + return this->readSetting(ScStwSettings::BaseStationSetting(key)); + else + return QVariant(); +} + bool ScStwSettings::writeSetting(BaseStationSetting key, QVariant value) { return this->writeSetting(QMetaEnum::fromType().valueToKey(int(key)), value, int(key), 0); } +bool ScStwSettings::writeSetting(int key, QVariant value, int keyLevel) { + if(keyLevel == ScStwSettings::KeyLevel) + return this->writeSetting(ScStwSettings::BaseStationSetting(key), value); + else + return false; +} + void ScStwSettings::setDefaultSetting(BaseStationSetting key, QVariant defaultVariant) { this->setDefaultSetting(QMetaEnum::fromType().valueToKey(int(key)), defaultVariant, int(key), 0); } From 152887b1e39855b323c2c86d8d95c33ff802dac1 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 14:00:31 +0200 Subject: [PATCH 08/76] changes to setting changed signal --- ScStwLibraries/headers/client/scstwsetting.h | 2 +- ScStwLibraries/headers/scstwsettings.h | 2 +- ScStwLibraries/sources/client/scstwremotesettings.cpp | 4 ++-- ScStwLibraries/sources/client/scstwsetting.cpp | 9 ++++----- ScStwLibraries/sources/scstwsettings.cpp | 2 +- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwsetting.h b/ScStwLibraries/headers/client/scstwsetting.h index 42f857c..7c95674 100644 --- a/ScStwLibraries/headers/client/scstwsetting.h +++ b/ScStwLibraries/headers/client/scstwsetting.h @@ -34,7 +34,7 @@ public slots: void setValue(QVariant value); private slots: - void handleSettingChange(int key, int keyLevel); + void handleSettingChange(int key, int keyLevel, QVariant value); signals: void scStwSettingsChanged(); diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index eb859e8..a91d5c5 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -66,7 +66,7 @@ private slots: bool writeSettingsToFile(); signals: - void settingChanged(int key, int keyLevel); + void settingChanged(int key, int keyLevel, QVariant value); }; diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index f653ebd..4def371 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -42,13 +42,13 @@ void ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant void ScStwRemoteSettings::handleClientStateChange() { if(this->scStwClient->getState() == ScStwClient::DISCONNECTED) - emit this->settingChanged(-1, 0); + emit this->settingChanged(-1, 0, QVariant()); } void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { switch (key) { case ScStw::SettingChanged: - emit this->settingChanged(data.toMap()["key"].toInt(), 0); + emit this->settingChanged(data.toMap()["key"].toInt(), 0, data.toMap()["value"]); default: break; } diff --git a/ScStwLibraries/sources/client/scstwsetting.cpp b/ScStwLibraries/sources/client/scstwsetting.cpp index df0f845..4f6e6e2 100644 --- a/ScStwLibraries/sources/client/scstwsetting.cpp +++ b/ScStwLibraries/sources/client/scstwsetting.cpp @@ -2,7 +2,6 @@ ScStwSetting::ScStwSetting(QObject *parent) : QObject(parent) { - } ScStwSettings* ScStwSetting::getScStwSettings(){ @@ -22,7 +21,7 @@ int ScStwSetting::getKey() { void ScStwSetting::setKey(int key) { if(this->key != key) { this->key = key; - this->handleSettingChange(this->key, this->keyLevel); + this->handleSettingChange(this->key, this->keyLevel, this->scStwSettings->readSetting(this->key, this->keyLevel)); emit this->keyChanged(); } } @@ -33,7 +32,7 @@ int ScStwSetting::getKeyLevel() { void ScStwSetting::setKeyLevel(int keyLevel) { if(this->keyLevel != keyLevel) { this->keyLevel = keyLevel; - this->handleSettingChange(this->key, this->keyLevel); + this->handleSettingChange(this->key, this->keyLevel, this->scStwSettings->readSetting(this->key, this->keyLevel)); emit this->keyLevelChanged(); } } @@ -47,9 +46,9 @@ void ScStwSetting::setValue(QVariant value) { } } -void ScStwSetting::handleSettingChange(int key, int keyLevel) { +void ScStwSetting::handleSettingChange(int key, int keyLevel, QVariant value) { if(keyLevel == this->keyLevel && key == this->key) { - this->valueCache = this->scStwSettings->readSetting(key, keyLevel); + this->valueCache = value; emit this->valueChanged(); } } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 7da1ac8..909ac0c 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -58,7 +58,7 @@ bool ScStwSettings::writeSetting(QString key, QVariant value, int keyInt, int ke else this->settingsCache[key] = value; - emit this->settingChanged(keyInt, keyLevel); + emit this->settingChanged(keyInt, keyLevel, value); return true; } From f336e953eb86f1a47f6376a6e94c30f82982e606 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 20:30:04 +0200 Subject: [PATCH 09/76] some fixes, settings are now working correctly --- ScStwLibraries/ScStwLibraries.pri | 12 ++--- .../headers/client/scstwremotesettings.h | 2 +- ScStwLibraries/headers/client/scstwsetting.h | 47 ---------------- ScStwLibraries/headers/scstwsetting.h | 37 +++++++++++++ ScStwLibraries/headers/scstwsettings.h | 47 +++++++++++++--- ScStwLibraries/sources/client/scstwclient.cpp | 6 +-- .../sources/client/scstwremotesettings.cpp | 14 +++-- .../sources/client/scstwsetting.cpp | 54 ------------------- ScStwLibraries/sources/scstwlibraries.cpp | 2 +- ScStwLibraries/sources/scstwsetting.cpp | 31 +++++++++++ ScStwLibraries/sources/scstwsettings.cpp | 50 +++++++++++++---- 11 files changed, 165 insertions(+), 137 deletions(-) delete mode 100644 ScStwLibraries/headers/client/scstwsetting.h create mode 100644 ScStwLibraries/headers/scstwsetting.h delete mode 100644 ScStwLibraries/sources/client/scstwsetting.cpp create mode 100644 ScStwLibraries/sources/scstwsetting.cpp diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index 781de65..903b9bc 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -23,7 +23,8 @@ SOURCES += \ $$PWD/sources/scstwsoundplayer.cpp \ $$PWD/sources/scstwlibraries.cpp \ $$PWD/sources/scstwrace.cpp \ - $$PWD/sources/scstwtimer.cpp + $$PWD/sources/scstwtimer.cpp \ + $$PWD/sources/scstwsetting.cpp HEADERS += \ $$PWD/headers/ScStw.hpp \ @@ -32,20 +33,19 @@ HEADERS += \ $$PWD/headers/scstwrace.h \ $$PWD/headers/scstwsettings.h \ $$PWD/headers/scstwsoundplayer.h \ - $$PWD/headers/scstwtimer.h + $$PWD/headers/scstwtimer.h \ + $$PWD/headers/scstwsetting.h ScStwLibraries_ClientLibs { SOURCES += \ $$PWD/sources/client/scstwclient.cpp \ $$PWD/sources/client/scstwremotesettings.cpp \ - $$PWD/sources/client/scstwremotemonitorrace.cpp \ - $$PWD/sources/client/scstwsetting.cpp + $$PWD/sources/client/scstwremotemonitorrace.cpp HEADERS += \ $$PWD/headers/client/scstwclient.h \ $$PWD/headers/client/scstwremotesettings.h \ - $$PWD/headers/client/scstwremotemonitorrace.h \ - $$PWD/headers/client/scstwsetting.h + $$PWD/headers/client/scstwremotemonitorrace.h INCLUDEPATH += $$PWD/headers/client } diff --git a/ScStwLibraries/headers/client/scstwremotesettings.h b/ScStwLibraries/headers/client/scstwremotesettings.h index 7f02d6e..9defc47 100644 --- a/ScStwLibraries/headers/client/scstwremotesettings.h +++ b/ScStwLibraries/headers/client/scstwremotesettings.h @@ -20,7 +20,7 @@ public: protected: QVariant readSetting(QString key, int keyInt, int keyLevel); bool writeSetting(QString key, QVariant value, int keyInt,int keyLevel = -1); - void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); + bool setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); private: ScStwClient * scStwClient; diff --git a/ScStwLibraries/headers/client/scstwsetting.h b/ScStwLibraries/headers/client/scstwsetting.h deleted file mode 100644 index 7c95674..0000000 --- a/ScStwLibraries/headers/client/scstwsetting.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef SCSTWQMLSETTING_H -#define SCSTWQMLSETTING_H - -#include -#include - -class ScStwSetting : public QObject -{ - Q_OBJECT - Q_PROPERTY(ScStwSettings* scStwSettings READ getScStwSettings WRITE setScStwSettings NOTIFY scStwSettingsChanged) - Q_PROPERTY(int key READ getKey WRITE setKey NOTIFY keyChanged) - Q_PROPERTY(int keyLevel READ getKeyLevel WRITE setKeyLevel NOTIFY keyLevelChanged) - Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged) -public: - explicit ScStwSetting(QObject *parent = nullptr); - -private: - ScStwSettings* scStwSettings; - int key; - int keyLevel; - QVariant valueCache; - -public slots: - ScStwSettings* getScStwSettings(); - void setScStwSettings(ScStwSettings* scStwSettings); - - int getKey(); - void setKey(int key); - - int getKeyLevel(); - void setKeyLevel(int keyLevel); - - QVariant getValue(); - void setValue(QVariant value); - -private slots: - void handleSettingChange(int key, int keyLevel, QVariant value); - -signals: - void scStwSettingsChanged(); - void keyChanged(); - void keyLevelChanged(); - void valueChanged(); - -}; - -#endif // SCSTWQMLSETTING_H diff --git a/ScStwLibraries/headers/scstwsetting.h b/ScStwLibraries/headers/scstwsetting.h new file mode 100644 index 0000000..e9a3dac --- /dev/null +++ b/ScStwLibraries/headers/scstwsetting.h @@ -0,0 +1,37 @@ +#ifndef SCSTWQMLSETTING_H +#define SCSTWQMLSETTING_H + +#include +#include + +class ScStwSetting : public QObject +{ + Q_OBJECT + Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged) + +protected: + explicit ScStwSetting(QObject *parent = nullptr); + + int key; + int keyLevel; + bool hasToReload; + + virtual bool writeSetting(int, int, QVariant) = 0; + virtual QVariant readSetting(int, int) = 0; + +private: + QVariant valueCache; + +public slots: + QVariant getValue(); + void setValue(QVariant value); + +protected slots: + void handleSettingChange(int key, int keyLevel, QVariant value); + +signals: + void valueChanged(); + +}; + +#endif // SCSTWQMLSETTING_H diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index a91d5c5..ac5a7fa 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -10,6 +10,7 @@ #include #include #include +#include class ScStwSettings : public QObject { @@ -17,6 +18,8 @@ class ScStwSettings : public QObject public: explicit ScStwSettings(QObject *parent = nullptr); + typedef QString(*keyToStringConverter)(int); + /*! * \brief The BaseStationSetting enum contains all settings of the base station that can be changed by a client * @@ -40,21 +43,29 @@ public: }; Q_ENUM(KeyLevelEnum) - Q_INVOKABLE QVariant readSetting(BaseStationSetting key); - Q_INVOKABLE virtual QVariant readSetting(int key, int level); - Q_INVOKABLE bool writeSetting(BaseStationSetting key, QVariant value); - Q_INVOKABLE virtual bool writeSetting(int key, QVariant value, int level); - Q_INVOKABLE void setDefaultSetting(BaseStationSetting key, QVariant defaultVariant); + virtual QVariant readSetting(BaseStationSetting key); + Q_INVOKABLE virtual QVariant readSetting(int key, int keyLevel); + virtual bool writeSetting(BaseStationSetting key, QVariant value); + Q_INVOKABLE virtual bool writeSetting(int key, int keyLevel, QVariant value); + virtual bool setDefaultSetting(BaseStationSetting key, QVariant defaultValue); + Q_INVOKABLE virtual bool setDefaultSetting(int key, int keyLevel, QVariant defaultValue); + + Q_INVOKABLE ScStwSetting * getSetting(int key, int keyLevel); static BaseStationSetting keyFromInt(int i) { QMetaEnum enumeration = QMetaEnum::fromType(); return static_cast(enumeration.keyToValue(enumeration.valueToKey(i))); } + static QString keyToString(int key) { + return QMetaEnum::fromType().valueToKey(key); + } + protected: virtual QVariant readSetting(QString key, int keyInt = -1, int keyLevel = -1); virtual bool writeSetting(QString key, QVariant value, int keyInt = -1,int keyLevel = -1); - virtual void setDefaultSetting(QString key, QVariant defaultVariant, int keyInt,int keyLevel = -1); + virtual bool setDefaultSetting(QString key, QVariant defaultValue, int keyInt,int keyLevel = -1); + bool registerKeyLevelHandler(int keyLevel, keyToStringConverter); private: QFile * settingsFile; @@ -62,6 +73,30 @@ private: bool loadSettingsFromFile(); + class ScStwSettingInternal: public ScStwSetting { + public: + ScStwSettingInternal(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent):ScStwSetting(parent) { + this->scStwSettings = scStwSettings; + connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSettingInternal::handleSettingChange); + this->key = key; + this->keyLevel = keyLevel; + this->handleSettingChange(-1, 0, QVariant()); + } + protected: + ScStwSettings *scStwSettings; + + bool writeSetting(int key, int keyLevel, QVariant value) { + return this->scStwSettings->writeSetting(key, keyLevel, value); + } + + QVariant readSetting(int key, int keyLevel) { + return this->scStwSettings->readSetting(key, keyLevel); + } + }; + + QMap keyToStringConverters; + QMap> internalSettingHandlers; + private slots: bool writeSettingsToFile(); diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index 0aebd03..2fed168 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -91,7 +91,7 @@ bool ScStwClient::init() { this->apiVersion = initResponse["data"].toMap()["apiVersion"].toString(); qDebug() << "[INFO][CLIENT] base station api version is: " << this->apiVersion; int compareResult = ScStw::firmwareCompare(this->API_VERSION, this->apiVersion); - qDebug() << "compare result is: " << compareResult; + //qDebug() << "compare result is: " << compareResult; if( compareResult == -3 ){ // the client version is out of date!! this->closeConnection(); @@ -373,7 +373,7 @@ void ScStwClient::handleSignal(QVariantMap data) { ScStw::SignalKey signalKey = ScStw::signalKeyFromInt(data["header"].toInt()); - qDebug() << "got signal: " << signalKey << " with data: " << data["data"]; + //qDebug() << "got signal: " << signalKey << " with data: " << data["data"]; switch (signalKey) { case ScStw::ExtensionsChanged: @@ -409,7 +409,7 @@ QVariant ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key) { if(reply["status"] != 200){ return "false"; } - return reply["data"].toString(); + return reply["data"]; } void ScStwClient::setIP(QString newIp){ diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index 4def371..bd8bcae 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -16,28 +16,26 @@ ScStwRemoteSettings::SettingsMode ScStwRemoteSettings::getMode() { } QVariant ScStwRemoteSettings::readSetting(QString key, int keyInt, int keyLevel) { - if(this->getMode() == LOCAL || keyLevel > 0) + if(this->getMode() == LOCAL || keyLevel > ScStwSettings::KeyLevel) return ScStwSettings::readSetting(key, keyInt, keyLevel); return this->scStwClient->readRemoteSetting(ScStwSettings::BaseStationSetting(keyInt)); } bool ScStwRemoteSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { - if(this->getMode() == LOCAL || keyLevel > 0) + if(this->getMode() == LOCAL || keyLevel > ScStwSettings::KeyLevel) return ScStwSettings::writeSetting(key, value, keyInt, keyLevel); - qDebug() << "changing setting"; ScStw::StatusCode res = this->scStwClient->writeRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), value); - qDebug() << "changed setting " << res; return res == ScStw::Success; } -void ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { - if(this->getMode() == LOCAL || keyLevel > 0) +bool ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { + if(this->getMode() == LOCAL || keyLevel > ScStwSettings::KeyLevel) return ScStwSettings::setDefaultSetting(key, defaultVariant, keyInt, keyLevel); - return; + return false; } void ScStwRemoteSettings::handleClientStateChange() { @@ -48,7 +46,7 @@ void ScStwRemoteSettings::handleClientStateChange() { void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { switch (key) { case ScStw::SettingChanged: - emit this->settingChanged(data.toMap()["key"].toInt(), 0, data.toMap()["value"]); + emit this->settingChanged(data.toMap()["key"].toInt(), ScStwSettings::KeyLevel, data.toMap()["value"]); default: break; } diff --git a/ScStwLibraries/sources/client/scstwsetting.cpp b/ScStwLibraries/sources/client/scstwsetting.cpp deleted file mode 100644 index 4f6e6e2..0000000 --- a/ScStwLibraries/sources/client/scstwsetting.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "scstwsetting.h" - -ScStwSetting::ScStwSetting(QObject *parent) : QObject(parent) -{ -} - -ScStwSettings* ScStwSetting::getScStwSettings(){ - return this->scStwSettings; -} -void ScStwSetting::setScStwSettings(ScStwSettings* scStwSettings) { - if(this->scStwSettings != scStwSettings && scStwSettings != nullptr) { - this->scStwSettings = scStwSettings; - connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSetting::handleSettingChange); - emit this->scStwSettingsChanged(); - } -} - -int ScStwSetting::getKey() { - return this->key; -} -void ScStwSetting::setKey(int key) { - if(this->key != key) { - this->key = key; - this->handleSettingChange(this->key, this->keyLevel, this->scStwSettings->readSetting(this->key, this->keyLevel)); - emit this->keyChanged(); - } -} - -int ScStwSetting::getKeyLevel() { - return this->keyLevel; -} -void ScStwSetting::setKeyLevel(int keyLevel) { - if(this->keyLevel != keyLevel) { - this->keyLevel = keyLevel; - this->handleSettingChange(this->key, this->keyLevel, this->scStwSettings->readSetting(this->key, this->keyLevel)); - emit this->keyLevelChanged(); - } -} - -QVariant ScStwSetting::getValue() { - return this->valueCache; -} -void ScStwSetting::setValue(QVariant value) { - if(value != this->valueCache && this->scStwSettings != nullptr) { - this->scStwSettings->writeSetting(this->key, value, this->keyLevel); - } -} - -void ScStwSetting::handleSettingChange(int key, int keyLevel, QVariant value) { - if(keyLevel == this->keyLevel && key == this->key) { - this->valueCache = value; - emit this->valueChanged(); - } -} diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 701367c..2c1c0fb 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -35,7 +35,7 @@ void ScStwLibraries::init() { #ifdef ScStwLibraries_ClientLibs qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwClient"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSettings"); - qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSetting"); + qmlRegisterUncreatableType("de.itsblue.ScStw", 2, 0, "ScStwSetting", "The ScStwSetting is manage by a ScStwSettings instance and therefore not creatable"); #endif #endif } diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp new file mode 100644 index 0000000..006ff38 --- /dev/null +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -0,0 +1,31 @@ +#include "scstwsetting.h" +#include + +ScStwSetting::ScStwSetting(QObject *parent) : QObject(parent) +{ +} + +QVariant ScStwSetting::getValue() { + if(this->hasToReload) { + this->valueCache = this->readSetting(this->key, this->keyLevel); + this->hasToReload = false; + } + return this->valueCache; +} +void ScStwSetting::setValue(QVariant value) { + if(value != this->valueCache) { + this->writeSetting(this->key, this->keyLevel, value); + } +} + +void ScStwSetting::handleSettingChange(int key, int keyLevel, QVariant value) { + if(keyLevel == this->keyLevel && key == this->key) { + this->valueCache = value; + qDebug() << "value changed!!! key: " << key << " new value " << value; + emit this->valueChanged(); + } + else if(key == -1 && this->key != -1 && this->keyLevel != -1 && this->keyLevel == keyLevel) { + this->hasToReload = true; + emit this->valueChanged(); + } +} diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 909ac0c..2a7cb7e 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -16,32 +16,41 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path + "/settings.json")); connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); + + this->registerKeyLevelHandler(ScStwSettings::KeyLevel, &ScStwSettings::keyToString); } QVariant ScStwSettings::readSetting(BaseStationSetting key) { - return this->readSetting(QMetaEnum::fromType().valueToKey(int(key)), int(key), 0); + return this->readSetting(key, 0); } QVariant ScStwSettings::readSetting(int key, int keyLevel) { - if(keyLevel == ScStwSettings::KeyLevel) - return this->readSetting(ScStwSettings::BaseStationSetting(key)); + if(this->keyToStringConverters.contains(keyLevel)) + return this->readSetting(this->keyToStringConverters[keyLevel](key), key, keyLevel); else return QVariant(); } bool ScStwSettings::writeSetting(BaseStationSetting key, QVariant value) { - return this->writeSetting(QMetaEnum::fromType().valueToKey(int(key)), value, int(key), 0); + return this->writeSetting(key, 0, value); } -bool ScStwSettings::writeSetting(int key, QVariant value, int keyLevel) { - if(keyLevel == ScStwSettings::KeyLevel) - return this->writeSetting(ScStwSettings::BaseStationSetting(key), value); +bool ScStwSettings::writeSetting(int key, int keyLevel, QVariant value) { + if(this->keyToStringConverters.contains(keyLevel)) + return this->writeSetting(this->keyToStringConverters[keyLevel](key), value, key, keyLevel); else return false; } -void ScStwSettings::setDefaultSetting(BaseStationSetting key, QVariant defaultVariant) { - this->setDefaultSetting(QMetaEnum::fromType().valueToKey(int(key)), defaultVariant, int(key), 0); +bool ScStwSettings::setDefaultSetting(BaseStationSetting key, QVariant defaultValue) { + return this->setDefaultSetting(key, 0, defaultValue); +} + +bool ScStwSettings::setDefaultSetting(int key, int keyLevel, QVariant defaultValue) { + if(this->keyToStringConverters.contains(keyLevel)) + return this->setDefaultSetting(this->keyToStringConverters[keyLevel](key), defaultValue, key, keyLevel); + else + return false; } QVariant ScStwSettings::readSetting(QString key, int keyInt, int keyLevel) { @@ -63,9 +72,28 @@ bool ScStwSettings::writeSetting(QString key, QVariant value, int keyInt, int ke return true; } -void ScStwSettings::setDefaultSetting(QString key, QVariant defaultVariant, int keyInt, int keyLevel) { +bool ScStwSettings::setDefaultSetting(QString key, QVariant defaultValue, int keyInt, int keyLevel) { if(!this->settingsCache.contains(key)) - this->writeSetting(key, defaultVariant, keyInt, keyLevel); + return this->writeSetting(key, defaultValue, keyInt, keyLevel); + return true; +} + +ScStwSetting * ScStwSettings::getSetting(int key, int keyLevel) { + if(!this->internalSettingHandlers.contains(keyLevel)) + this->internalSettingHandlers.insert(keyLevel, {}); + + if(!this->internalSettingHandlers[keyLevel].contains(key)) + this->internalSettingHandlers[keyLevel].insert(key, new ScStwSettingInternal(key, keyLevel, this, this)); + + return this->internalSettingHandlers[keyLevel][key]; +} + +bool ScStwSettings::registerKeyLevelHandler(int keyLevel, keyToStringConverter converterFunction) { + if(this->keyToStringConverters.contains(keyLevel)) + return false; + + this->keyToStringConverters.insert(keyLevel, converterFunction); + return true; } /* From c2fa3cefc2f5393fea8700e77d1720113bd0b1fb Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 11 Jul 2020 21:03:58 +0200 Subject: [PATCH 10/76] some license additions --- .../headers/client/scstwremotesettings.h | 18 ++++++++++++++++++ ScStwLibraries/headers/scstwlibraries.h | 2 +- ScStwLibraries/headers/scstwsetting.h | 18 ++++++++++++++++++ ScStwLibraries/headers/scstwsettings.h | 18 ++++++++++++++++++ .../sources/client/scstwremotesettings.cpp | 18 ++++++++++++++++++ ScStwLibraries/sources/scstwsetting.cpp | 18 ++++++++++++++++++ ScStwLibraries/sources/scstwsettings.cpp | 18 ++++++++++++++++++ 7 files changed, 109 insertions(+), 1 deletion(-) diff --git a/ScStwLibraries/headers/client/scstwremotesettings.h b/ScStwLibraries/headers/client/scstwremotesettings.h index 9defc47..af3beb9 100644 --- a/ScStwLibraries/headers/client/scstwremotesettings.h +++ b/ScStwLibraries/headers/client/scstwremotesettings.h @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #ifndef SCSTWREMOTESETTINGS_H #define SCSTWREMOTESETTINGS_H diff --git a/ScStwLibraries/headers/scstwlibraries.h b/ScStwLibraries/headers/scstwlibraries.h index 76ffb39..e7c495e 100644 --- a/ScStwLibraries/headers/scstwlibraries.h +++ b/ScStwLibraries/headers/scstwlibraries.h @@ -32,8 +32,8 @@ #include "scstwtimer.h" #include "scstwrace.h" #include "scstwsettings.h" -#include "scstwsetting.h" #ifdef ScStwLibraries_ClientLibs +#include "scstwsetting.h" #include "scstwremotemonitorrace.h" #include "scstwclient.h" #endif diff --git a/ScStwLibraries/headers/scstwsetting.h b/ScStwLibraries/headers/scstwsetting.h index e9a3dac..72818b7 100644 --- a/ScStwLibraries/headers/scstwsetting.h +++ b/ScStwLibraries/headers/scstwsetting.h @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #ifndef SCSTWQMLSETTING_H #define SCSTWQMLSETTING_H diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index ac5a7fa..71787a3 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #ifndef SCSTWSETTINGS_H #define SCSTWSETTINGS_H diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index bd8bcae..5fb46f7 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #include "../../headers/client/scstwremotesettings.h" ScStwRemoteSettings::ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent) : ScStwSettings(parent) diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp index 006ff38..1c10f53 100644 --- a/ScStwLibraries/sources/scstwsetting.cpp +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #include "scstwsetting.h" #include diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 2a7cb7e..45844a0 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -1,3 +1,21 @@ +/**************************************************************************** + ** ScStw Libraries + ** Copyright (C) 2020 Itsblue development + ** + ** This program is free software: you can redistribute it and/or modify + ** it under the terms of the GNU General Public License as published by + ** the Free Software Foundation, either version 3 of the License, or + ** (at your option) any later version. + ** + ** 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 General Public License for more details. + ** + ** You should have received a copy of the GNU General Public License + ** along with this program. If not, see . + ****************************************************************************/ + #include "../headers/scstwsettings.h" ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) From 8aa41a3456dad24a4145b8de39f2a62d071484df Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 18 Jul 2020 18:48:00 +0200 Subject: [PATCH 11/76] removed Qt-Secret and added qt-openssl-encryption to replace it --- .gitmodules | 3 + Qt-Secret/GMP/.gitignore | 1 - Qt-Secret/GMP/GMP.pri | 24 - Qt-Secret/GMP/GMP.pro | 38 - Qt-Secret/GMP/LICENSE | 21 - Qt-Secret/GMP/bigint.cpp | 618 ---- Qt-Secret/GMP/bigint.h | 206 -- Qt-Secret/GMP/mini-gmp.c | 4415 --------------------------- Qt-Secret/GMP/mini-gmp.h | 303 -- Qt-Secret/GMP/minigmp_global.h | 21 - Qt-Secret/LICENSE | 165 - Qt-Secret/Qt-RSA/qrsaencryption.cpp | 403 --- Qt-Secret/Qt-RSA/qrsaencryption.h | 116 - Qt-Secret/Qt-Secret.pri | 24 - Qt-Secret/Qt-Secret.pro | 36 - Qt-Secret/qtsecret_global.h | 12 - qt-openssl-encryption | 1 + 17 files changed, 4 insertions(+), 6403 deletions(-) create mode 100644 .gitmodules delete mode 100644 Qt-Secret/GMP/.gitignore delete mode 100644 Qt-Secret/GMP/GMP.pri delete mode 100644 Qt-Secret/GMP/GMP.pro delete mode 100644 Qt-Secret/GMP/LICENSE delete mode 100644 Qt-Secret/GMP/bigint.cpp delete mode 100644 Qt-Secret/GMP/bigint.h delete mode 100644 Qt-Secret/GMP/mini-gmp.c delete mode 100644 Qt-Secret/GMP/mini-gmp.h delete mode 100644 Qt-Secret/GMP/minigmp_global.h delete mode 100644 Qt-Secret/LICENSE delete mode 100644 Qt-Secret/Qt-RSA/qrsaencryption.cpp delete mode 100644 Qt-Secret/Qt-RSA/qrsaencryption.h delete mode 100644 Qt-Secret/Qt-Secret.pri delete mode 100644 Qt-Secret/Qt-Secret.pro delete mode 100644 Qt-Secret/qtsecret_global.h create mode 160000 qt-openssl-encryption diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..fbd8ce1 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "qt-openssl-encryption"] + path = qt-openssl-encryption + url = ssh://git@git.itsblue.de:2222/itsblue-development/qt-openssl-encryption.git diff --git a/Qt-Secret/GMP/.gitignore b/Qt-Secret/GMP/.gitignore deleted file mode 100644 index 84c048a..0000000 --- a/Qt-Secret/GMP/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build/ diff --git a/Qt-Secret/GMP/GMP.pri b/Qt-Secret/GMP/GMP.pri deleted file mode 100644 index 73112bb..0000000 --- a/Qt-Secret/GMP/GMP.pri +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (C) 2018-2019 QuasarApp. -# Distributed under the lgplv3 software license, see the accompanying -# Everyone is permitted to copy and distribute verbatim copies -# of this license document, but changing it is not allowed. -# - -!isEmpty(Qt_GMP_LIB):error("GMP.pri already included") -Qt_GMP_LIB = 1 - -DEFINES += MINIGMP_LIBRARY -DEFINES += QT_DEPRECATED_WARNINGS - -HEADERS += \ - $$PWD/bigint.h \ - $$PWD/mini-gmp.h \ - $$PWD/minigmp_global.h - -SOURCES += \ - $$PWD/bigint.cpp \ - $$PWD/mini-gmp.c - - -INCLUDEPATH += $$PWD diff --git a/Qt-Secret/GMP/GMP.pro b/Qt-Secret/GMP/GMP.pro deleted file mode 100644 index 12cb6d2..0000000 --- a/Qt-Secret/GMP/GMP.pro +++ /dev/null @@ -1,38 +0,0 @@ -# -# Copyright (C) 2018-2019 QuasarApp. -# Distributed under the lgplv3 software license, see the accompanying -# Everyone is permitted to copy and distribute verbatim copies -# of this license document, but changing it is not allowed. -# - - -QT -= core gui - -TARGET = MiniGMP -TEMPLATE = lib - -DEFINES += MINIGMP_LIBRARY -DEFINES += QT_DEPRECATED_WARNINGS - -TARGET = QtBigInt - -CONFIG += static -VERSION = 6.1.2 - -CONFIG(release, debug|release): { - DESTDIR="$$PWD/build/release" -} else { - DESTDIR="$$PWD/build/debug" -} - -DISTFILES += \ - README \ - -HEADERS += \ - bigint.h \ - mini-gmp.h \ - minigmp_global.h - -SOURCES += \ - bigint.cpp \ - mini-gmp.c diff --git a/Qt-Secret/GMP/LICENSE b/Qt-Secret/GMP/LICENSE deleted file mode 100644 index 450ca25..0000000 --- a/Qt-Secret/GMP/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 QuasarApp - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Qt-Secret/GMP/bigint.cpp b/Qt-Secret/GMP/bigint.cpp deleted file mode 100644 index 4287886..0000000 --- a/Qt-Secret/GMP/bigint.cpp +++ /dev/null @@ -1,618 +0,0 @@ -//# -//# Copyright (C) 2018-2019 QuasarApp. -//# Distributed under the lgplv3 software license, see the accompanying -//# Everyone is permitted to copy and distribute verbatim copies -//# of this license document, but changing it is not allowed. -//# - -#include "bigint.h" -#include -#include -#include - -// constructors -BigInt::BigInt() { - mpz_init(data); -} - -BigInt::BigInt(const BigInt &val, int bitCount) { - if (bitCount > 0) { - mpz_init2(data, static_cast(bitCount)); - } else { - mpz_init(data); - } - - mpz_set(data, val.data); - -} - -BigInt::BigInt(const std::string &str, int base): - BigInt() { - mpz_set_str(data, str.c_str(), base); -} - -BigInt::BigInt(intMpz val): - BigInt() { - mpz_set_si(data, val); -} - -BigInt::BigInt(char item, unsigned int size, int base = 2): - BigInt(std::string(size, item),base) { -} - -std::string BigInt::getString(int base) const { - char *str = mpz_get_str(nullptr, base, data); - return str; -} - -BigInt::~BigInt() { - mpz_clear(data); -} - -BigInt &BigInt::powm(const BigInt &pow, const BigInt &mod) { - mpz_powm(data, data, pow.data, mod.data); - return *this; -} - -BigInt BigInt::powm(BigInt val, const BigInt &pow, const BigInt &mod) { - return val.powm(pow, mod); -} - -BigInt &BigInt::pow(uIntMpz pow) { - mpz_pow_ui(data, data, pow); - return *this; -} - -int BigInt::sizeBits() const { - return sizeBytes() * 8; -} - -int BigInt::sizeBytes() const { - return static_cast(mpz_size(data) * sizeof ((*data->_mp_d))); -} - -int BigInt::longBits() const { - return static_cast(getString(2).size()); -} - -int BigInt::longBytes() const { - return static_cast(std::ceil(static_cast(longBits()) / 8)); -} - -#define GMP_ABS(x) ((x) >= 0 ? (x) : -(x)) -int BigInt::sizeType() const { - return static_cast(static_cast(GMP_ABS( data->_mp_alloc)) * - sizeof ((*data->_mp_d))); - -} - -bool BigInt::isPrime(bool absalut) const { - return (mpz_probab_prime_p(data, 50) - (absalut? 1: 0)) > 0; -} - -BigInt& BigInt::gcd(const BigInt &a, const BigInt &b) { - mpz_gcd(data, a.data, b.data); - return *this; - -} - -void BigInt::fromHex(const std::string &hex) { - mpz_set_str(data, hex.c_str(), 16); -} - -BigInt BigInt::bigPow10(unsigned short pow) { - return "1" + std::string(pow, '0'); -} - -BigInt &BigInt::toNegative() { - mpz_neg(data, data); - return *this; -} - -BigInt &BigInt::operator =(const BigInt &val) { - mpz_set(data, val.data); - return *this; -} - -BigInt &BigInt::operator =(const std::string &imput) { - mpz_set_str(data, imput.c_str(), 10); - return *this; -} - -BigInt &BigInt::operator =(intMpz val) { - mpz_set_si(data, val); - return *this; -} - -// add operators - -BigInt operator +(BigInt left, intMpz right) { - if (right >= 0) { - mpz_add_ui(left.data, left.data, static_cast(right)); - return left; - } - - return left -= std::abs(right); -} - -BigInt operator +(intMpz left, BigInt right) { - return right += left; -} - -BigInt operator +(BigInt left, const BigInt &right) { - mpz_add(left.data, left.data, right.data); - return left; -} - -BigInt operator +(BigInt left, const std::string &right) { - return left += BigInt(right); -} - -BigInt operator +(const std::string &left, const BigInt &right) { - return BigInt(left) + right; -} - -BigInt& operator +=(BigInt &left, intMpz right) { - if (right >= 0) { - mpz_add_ui(left.data, left.data, static_cast(right)); - return left; - } - return left -= std::abs(right); -} - -BigInt& operator +=(BigInt &left, const BigInt &right) { - mpz_add(left.data, left.data, right.data); - return left; -} - -BigInt& operator +=(BigInt &left, const std::string &right) { - return left += BigInt(right); -} - -// sub operators - -BigInt operator -(BigInt left, const BigInt &right) { - mpz_sub(left.data, left.data, right.data); - return left; -} - -BigInt operator -(BigInt left, intMpz right) { - if (right >= 0) { - mpz_sub_ui(left.data, left.data, static_cast(right)); - return left; - } - return left += std::abs(right); -} - -BigInt operator -(intMpz left, BigInt right) { - if (left >= 0) { - mpz_ui_sub(right.data, static_cast(left), right.data); - return right; - } - return right += std::abs(left); -} - -BigInt operator-(BigInt val) { - mpz_neg(val.data, val.data); - return val; -} - -BigInt operator -(BigInt left, const std::string &right) { - return left -= BigInt(right); -} - -BigInt operator -(const std::string & left, const BigInt &right) { - return BigInt(left) - right; -} - -BigInt& operator -=(BigInt &left, const BigInt &right) { - mpz_sub(left.data, left.data, right.data); - return left; -} - -BigInt& operator -=(BigInt &left, const std::string &right) { - return left -= BigInt(right); -} - -BigInt& operator -=(BigInt &left, intMpz right) { - if (right >= 0) { - mpz_sub_ui(left.data, left.data, static_cast(right)); - return left; - } - return left += std::abs(right); -} - -// div operators - -BigInt operator /(BigInt left, const BigInt &right) { - mpz_tdiv_q(left.data, left.data, right.data); - return left; -} - -BigInt operator /(BigInt left, intMpz right) { - mpz_tdiv_q_ui(left.data, left.data, static_cast(std::abs(right))); - - if (right >= 0) { - return left; - } - return -left; -} - -BigInt operator /(BigInt left, const std::string &right) { - return left /= BigInt(right); -} - -BigInt operator /(intMpz left, BigInt right) { - return BigInt(left) / right; -} - -BigInt operator /(const std::string & left, const BigInt &right) { - return BigInt(left) / right; -} - -BigInt& operator /=(BigInt &left, const BigInt &right) { - mpz_tdiv_q(left.data, left.data, right.data); - return left; -} - -BigInt& operator /=(BigInt &left, const std::string &right) { - return left /= BigInt(right); -} - -BigInt& operator /=(BigInt &left, intMpz right) { - mpz_tdiv_q_ui(left.data, left.data, static_cast(std::abs(right))); - - if (right >= 0) { - return left; - } - return left.toNegative(); -} - -// mul operators -BigInt operator *(BigInt left, const BigInt &right) { - mpz_mul(left.data, left.data, right.data); - return left; -} - -BigInt operator *(BigInt left, intMpz right) { - mpz_mul_ui(left.data, left.data, static_cast(std::abs(right))); - - if (right >= 0) { - return left; - } - return -left; -} - -BigInt operator *(intMpz left, BigInt right) { - return right *= left; -} - -BigInt operator *(const std::string & left, BigInt right) { - return right *= BigInt(left); -} - -BigInt operator *(BigInt left, const std::string &right) { - return left *= BigInt(right); -} - -BigInt& operator *=(BigInt &left, const BigInt &right) { - mpz_mul(left.data, left.data, right.data); - return left; -} - -BigInt& operator *=(BigInt &left, const std::string &right) { - return left *= BigInt(right); -} - -BigInt& operator *=(BigInt &left, intMpz right) { - mpz_mul_ui(left.data, left.data, static_cast(std::abs(right))); - - if (right >= 0) { - return left; - } - return left.toNegative(); -} - -//mod operations -BigInt operator %(BigInt left, const BigInt &right) { - mpz_tdiv_r(left.data, left.data, right.data); - return left; -} - -BigInt operator %(BigInt left, intMpz right) { - mpz_tdiv_r_ui(left.data, left.data, static_cast(std::abs(right))); - return left; -} - -BigInt operator %(intMpz left, BigInt right) { - return BigInt(left) % right; -} - -BigInt operator %(BigInt left, const std::string & right) { - return left %= BigInt(right); -} - -BigInt operator %(const std::string & left, const BigInt &right) { - return BigInt(left) % right; -} - -BigInt& operator %=(BigInt& left, const BigInt &right) { - mpz_tdiv_r(left.data, left.data, right.data); - return left; -} - -BigInt& operator %=(BigInt& left, intMpz right) { - mpz_tdiv_r_ui(left.data, left.data, static_cast(std::abs(right))); - return left; -} - -BigInt& operator %=(BigInt &left, const std::string &right) { - return left %= BigInt(right); -} - -// incriment and dicriment -BigInt &BigInt::operator--() { - *this -= 1; - return *this; -} - -BigInt &BigInt::operator++() { - *this += 1; - return *this; -} - -BigInt BigInt::operator--(int) { - BigInt temp(*this); - --*this; - return temp; -} - -BigInt BigInt::operator++(int) { - BigInt temp(*this); - ++*this; - return temp; -} - -// move operators - -BigInt operator >>(BigInt left, int right) { - if (right >= 0) { - mpn_rshift(left.data->_mp_d, - left.data->_mp_d, - left.data->_mp_size, - static_cast(std::abs(right))); - return left; - } - - return left << right; -} - -BigInt operator <<(BigInt left, int right) { - if (right >= 0) { - mpn_lshift(left.data->_mp_d, - left.data->_mp_d, - left.data->_mp_size, - static_cast(std::abs(right))); - return left; - } - - return left >> right; -} - -BigInt& operator >>=(BigInt &left, int right) { - if (right >= 0) { - mpn_rshift(left.data->_mp_d, - left.data->_mp_d, - left.data->_mp_size, - static_cast(std::abs(right))); - return left; - } - - return left <<= right; -} - -BigInt& operator <<=(BigInt &left, int right) { - if (right >= 0) { - mpn_lshift(left.data->_mp_d, - left.data->_mp_d, - left.data->_mp_size, - static_cast(std::abs(right))); - return left; - } - - return left >>= right; -} - -// other bin operators -BigInt operator ~(BigInt left) { - mpz_com(left.data, left.data); - return left; -} - -BigInt operator |(BigInt left, const BigInt &right) { - mpz_ior(left.data, left.data, right.data); - return left; -} - -BigInt operator |(const BigInt &left, intMpz right) { - return left | BigInt(right); -} - -BigInt& operator |=(BigInt &left, const BigInt &right) { - mpz_ior(left.data, left.data, right.data); - return left; -} - -BigInt& operator |=(BigInt &left, intMpz right) { - return left |= BigInt(right); -} - -BigInt operator &(BigInt left, const BigInt &right) { - mpz_and(left.data, left.data, right.data); - return left; -} - -BigInt operator &(const BigInt &left, intMpz right) { - return left & BigInt(right); -} - - -BigInt& operator &=(BigInt &left, const BigInt &right) { - mpz_and(left.data, left.data, right.data); - return left; -} - -BigInt& operator &=(BigInt &left, intMpz right) { - return left &= BigInt(right); -} - -BigInt operator ^(BigInt left, const BigInt &right) { - mpz_xor(left.data, left.data, right.data); - return left; -} - -BigInt operator ^(const BigInt &left, intMpz right) { - return left ^ BigInt(right); -} - -BigInt& operator ^=(BigInt &left, const BigInt &right) { - mpz_xor(left.data, left.data, right.data); - return left; -} - -BigInt& operator ^=(BigInt &left, intMpz right) { - return left ^= BigInt(right); -} - - -// logic operators - -bool operator!(const BigInt &val) { - return val == 0; -} - -bool operator == (const BigInt& left, const BigInt& right) { - return mpz_cmp(left.data, right.data) == 0; -} - -bool operator == (const BigInt& left, intMpz right) { - return mpz_cmp_si(left.data, right) == 0; -} - -bool operator == (const BigInt &left, const std::string &right) { - return left == BigInt(right); -} - -bool operator == ( intMpz left, const BigInt & right) { - return right == left; -} - -bool operator == ( const std::string & left, const BigInt & right) { - return right == BigInt(left); -} - -bool operator != (const BigInt &left, const BigInt& right) { - return !(left == right); -} - -bool operator != (const BigInt &left, intMpz right) { - return !(left == right); -} - -bool operator != (const BigInt &left, const std::string &right) { - return left != BigInt(right); -} - -bool operator != ( intMpz left, const BigInt & right) { - return right != left; -} - -bool operator != ( const std::string & left, const BigInt & right) { - return right != BigInt(left); -} - -bool operator < ( const BigInt &left, const BigInt& right) { - return mpz_cmp(left.data, right.data) < 0; -} - -bool operator < ( const BigInt &left, intMpz right) { - return mpz_cmp_si(left.data, right) < 0; -} - -bool operator < ( const BigInt &left, const std::string &right) { - return left < BigInt(right); -} - -bool operator < ( intMpz left, const BigInt & right) { - return right > left; -} - -bool operator < ( const std::string & left, const BigInt & right) { - return right > BigInt(left); -} - -bool operator > ( const BigInt &left, const BigInt& right) { - return mpz_cmp(left.data, right.data) > 0; -} - -bool operator > ( const BigInt &left, intMpz right) { - return mpz_cmp_si(left.data, right) > 0; -} - -bool operator > ( const BigInt &left, const std::string &right) { - return left > BigInt(right); -} - -bool operator > ( intMpz left, const BigInt & right) { - return right < left; -} - -bool operator > ( const std::string & left, const BigInt & right) { - return right < BigInt(left); -} - -bool operator <= ( const BigInt &left, const BigInt& right) { - return mpz_cmp(left.data, right.data) <= 0; -} - -bool operator <= ( const BigInt &left, intMpz right) { - return mpz_cmp_si(left.data, right) <= 0; -} - -bool operator <= ( const BigInt &left, const std::string &right) { - return left <= BigInt(right); -} - -bool operator <= ( intMpz left, const BigInt & right) { - return right >= left; -} - -bool operator <= ( const std::string & left, const BigInt & right) { - return right >= BigInt(left); -} - -bool operator >= ( const BigInt &left, const BigInt& right) { - return mpz_cmp(left.data, right.data) >= 0; -} - -bool operator >= ( const BigInt &left, intMpz right) { - return mpz_cmp_si(left.data, right) >= 0; -} - -bool operator >= ( const BigInt &left, const std::string &right) { - return left >= BigInt(right); -} - -bool operator >= ( intMpz left, const BigInt & right) { - return right <= left; -} - -bool operator >= ( const std::string & left, const BigInt & right) { - return right <= BigInt(left); -} - -//// cast operations - -//BigInt::operator bool() const { -// return *this != 0; -//} diff --git a/Qt-Secret/GMP/bigint.h b/Qt-Secret/GMP/bigint.h deleted file mode 100644 index 6a7d3a6..0000000 --- a/Qt-Secret/GMP/bigint.h +++ /dev/null @@ -1,206 +0,0 @@ -//# -//# Copyright (C) 2018-2019 QuasarApp. -//# Distributed under the lgplv3 software license, see the accompanying -//# Everyone is permitted to copy and distribute verbatim copies -//# of this license document, but changing it is not allowed. -//# - - -#ifndef BIGINT_H -#define BIGINT_H -#include "mini-gmp.h" -#include -#include -#include "minigmp_global.h" - -/** - * @brief The BigInt class - c++ minigmp wrapper - */ - -class MINIGMPSHARED_EXPORT BigInt -{ - mpz_t data; -public: - BigInt(); - BigInt(const BigInt& val, int bitCount = -1); - BigInt(const std::string &imput, int base = 10); - BigInt(intMpz val); - BigInt(char item, unsigned int size, int base); - - std::string getString(int base = 10) const; - ~BigInt(); - - BigInt& powm(const BigInt &pow, const BigInt &mod); - static BigInt powm(BigInt val, const BigInt & pow, const BigInt &mod); - - BigInt& pow(uIntMpz pow); - BigInt& log(int base); - /** - * @brief sizeBits - * @return size of bits in memory - */ - int sizeBits() const; - int sizeBytes() const; - - /** - * @brief longBits - * @return current length in Bits of number - */ - int longBits() const; - int longBytes() const; - - int sizeType() const; - bool isPrime(bool absalut = false) const; - BigInt& gcd(const BigInt &a, const BigInt &b); - void fromHex(const std::string& hex); - - /** - * @brief bigPow10 - * @param pow - * @return number 10 ^ pow - */ - static BigInt bigPow10(unsigned short pow); - - BigInt& toNegative(); - - BigInt& operator = (const BigInt& val); - BigInt& operator = (const std::string &imput); - BigInt& operator = (intMpz val); - - friend BigInt operator + ( BigInt left, const BigInt& right); - friend BigInt operator + ( BigInt left, const std::string &right); - friend BigInt operator + ( BigInt left, intMpz right); - - friend BigInt operator + ( intMpz left, BigInt right); - friend BigInt operator + ( const std::string &left, const BigInt &right); - - friend BigInt& operator += ( BigInt &left, intMpz right); - friend BigInt& operator += ( BigInt &left, const BigInt& right); - friend BigInt& operator += ( BigInt &left, const std::string &right); - - friend BigInt operator - ( BigInt left, const BigInt& right); - friend BigInt operator - ( BigInt left, intMpz right); - friend BigInt operator - ( BigInt left, const std::string &right); - - friend BigInt operator - ( intMpz right, BigInt left); - friend BigInt operator - ( const std::string &right, const BigInt &left); - - friend BigInt operator-(BigInt val); - - friend BigInt& operator -= ( BigInt &left, intMpz right); - - friend BigInt& operator -= ( BigInt &left, const BigInt& right); - friend BigInt& operator -= ( BigInt &left, const std::string &right); - - friend BigInt operator / ( BigInt left, const BigInt& right); - friend BigInt operator / ( BigInt left, const std::string &right); - friend BigInt operator / ( BigInt left, intMpz right); - friend BigInt operator / ( intMpz left, BigInt right); - friend BigInt operator / ( const std::string &left, const BigInt &right); - - friend BigInt& operator /= ( BigInt &left, intMpz right); - friend BigInt& operator /= ( BigInt &left, const std::string &right); - friend BigInt& operator /= ( BigInt &left, const BigInt& right); - - friend BigInt operator * ( BigInt left, const BigInt& right); - friend BigInt operator * ( BigInt left, const std::string &right); - friend BigInt operator * ( BigInt left, intMpz right); - - friend BigInt operator * ( intMpz left, BigInt right); - - friend BigInt& operator *= ( BigInt &left, const BigInt& right); - friend BigInt& operator *= ( BigInt &left, intMpz right); - friend BigInt& operator *= ( BigInt &left, const std::string &right); - - friend BigInt operator % ( BigInt left, const BigInt& right); - friend BigInt operator % ( BigInt left, const std::string &right); - friend BigInt operator % ( BigInt left, intMpz right); - - friend BigInt operator % ( intMpz left, BigInt right); - friend BigInt operator % ( const std::string & left, const BigInt &right); - - friend BigInt& operator %= ( BigInt &left, intMpz right); - friend BigInt& operator %= ( BigInt &left, const std::string &right); - - friend BigInt& operator %= ( BigInt &left, const BigInt& right); - - friend BigInt operator << ( BigInt left, int right); - friend BigInt operator >> ( BigInt left, int right); - - friend BigInt& operator <<= ( BigInt &left, int right); - friend BigInt& operator >>= ( BigInt &left, int right); - - friend bool operator == ( const BigInt& left, const BigInt& right); - friend bool operator == ( const BigInt& left, intMpz right); - friend bool operator == ( const BigInt& left, const std::string& right); - friend bool operator == ( const std::string& left, const BigInt& right); - friend bool operator == ( const BigInt& left, const std::string& right); - friend bool operator == ( intMpz left, const std::string& right); - - friend bool operator != ( const BigInt& left, const BigInt& right); - friend bool operator != ( const BigInt& left, intMpz right); - friend bool operator != ( const BigInt& left, const std::string& str); - friend bool operator != ( const std::string& left, const BigInt& right); - friend bool operator != ( const BigInt& left, const std::string& right); - friend bool operator != ( intMpz left, const std::string& right); - - friend bool operator < ( const BigInt& left, const BigInt& right); - friend bool operator < ( const BigInt& left, intMpz right); - friend bool operator < ( const BigInt& left, const std::string& str); - friend bool operator < ( const std::string& left, const BigInt& right); - friend bool operator < ( const BigInt& left, const std::string& right); - friend bool operator < ( intMpz left, const std::string& right); - - friend bool operator > ( const BigInt& left, const BigInt& right); - friend bool operator > ( const BigInt& left, intMpz right); - friend bool operator > ( const BigInt& left, const std::string& str); - friend bool operator > ( const std::string& left, const BigInt& right); - friend bool operator > ( const BigInt& left, const std::string& right); - friend bool operator > ( intMpz left, const std::string& right); - - friend bool operator <= ( const BigInt& left, const BigInt& right); - friend bool operator <= ( const BigInt& left, intMpz right); - friend bool operator <= ( const BigInt& left, const std::string& str); - friend bool operator <= ( const std::string& left, const BigInt& right); - friend bool operator <= ( const BigInt& left, const std::string& right); - friend bool operator <= ( intMpz left, const std::string& right); - - friend bool operator >= ( const BigInt& left, const BigInt& right); - friend bool operator >= ( const BigInt& left, intMpz right); - friend bool operator >= ( const BigInt& left, const std::string& str); - friend bool operator >= ( const std::string& left, const BigInt& right); - friend bool operator >= ( const BigInt& left, const std::string& right); - friend bool operator >= ( intMpz left, const std::string& right); - - friend bool operator!(const BigInt& val); - - BigInt& operator-- (); - BigInt& operator++ (); - - BigInt operator-- (int); - BigInt operator++ (int); - - - friend BigInt operator~ (BigInt val); - - friend BigInt operator| (BigInt left, const BigInt& right); - friend BigInt operator| (const BigInt &left, intMpz right); - - friend BigInt& operator|= (BigInt &left, const BigInt& right); - friend BigInt& operator|= (BigInt &left, intMpz right); - - friend BigInt operator& (BigInt left, const BigInt& right); - friend BigInt operator& (const BigInt &left, intMpz right); - - friend BigInt& operator&= (BigInt &left, const BigInt& right); - friend BigInt& operator&= (BigInt &left, intMpz right); - - friend BigInt operator^ (BigInt left, const BigInt& right); - friend BigInt operator^ (const BigInt &left, intMpz right); - - friend BigInt& operator^= (BigInt &left, const BigInt& right); - friend BigInt& operator^= (BigInt &left, intMpz right); - -}; - -#endif // BIGINT_H diff --git a/Qt-Secret/GMP/mini-gmp.c b/Qt-Secret/GMP/mini-gmp.c deleted file mode 100644 index f9d598b..0000000 --- a/Qt-Secret/GMP/mini-gmp.c +++ /dev/null @@ -1,4415 +0,0 @@ -/* mini-gmp, a minimalistic implementation of a GNU GMP subset. - - Contributed to the GNU project by Niels Möller - -Copyright 1991-1997, 1999-2016 Free Software Foundation, Inc. - -This file is part of the GNU MP Library. - -The GNU MP Library is free software; you can redistribute it and/or modify -it under the terms of either: - - * the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at your - option) any later version. - -or - - * the GNU General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any - later version. - -or both in parallel, as here. - -The GNU MP Library 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 General Public License -for more details. - -You should have received copies of the GNU General Public License and the -GNU Lesser General Public License along with the GNU MP Library. If not, -see https://www.gnu.org/licenses/. */ - -/* NOTE: All functions in this file which are not declared in - mini-gmp.h are internal, and are not intended to be compatible - neither with GMP nor with future versions of mini-gmp. */ - -/* Much of the material copied from GMP files, including: gmp-impl.h, - longlong.h, mpn/generic/add_n.c, mpn/generic/addmul_1.c, - mpn/generic/lshift.c, mpn/generic/mul_1.c, - mpn/generic/mul_basecase.c, mpn/generic/rshift.c, - mpn/generic/sbpi1_div_qr.c, mpn/generic/sub_n.c, - mpn/generic/submul_1.c. */ - -#include -#include -#include -#include -#include -#include - -#include "mini-gmp.h" - - -/* Macros */ -#define GMP_LIMB_BITS (sizeof(mp_limb_t) * CHAR_BIT) - -#define GMP_LIMB_MAX (~ (mp_limb_t) 0) -#define GMP_LIMB_HIGHBIT ((mp_limb_t) 1 << (GMP_LIMB_BITS - 1)) - -#define GMP_HLIMB_BIT ((mp_limb_t) 1 << (GMP_LIMB_BITS / 2)) -#define GMP_LLIMB_MASK (GMP_HLIMB_BIT - 1) - -#define GMP_ULONG_BITS (sizeof(uIntMpz) * CHAR_BIT) -#define GMP_ULONG_HIGHBIT ((uIntMpz) 1 << (GMP_ULONG_BITS - 1)) - -#define GMP_ABS(x) ((x) >= 0 ? (x) : -(x)) -#define GMP_NEG_CAST(T,x) (-((T)((x) + 1) - 1)) - -#define GMP_MIN(a, b) ((a) < (b) ? (a) : (b)) -#define GMP_MAX(a, b) ((a) > (b) ? (a) : (b)) - -#define GMP_CMP(a,b) (((a) > (b)) - ((a) < (b))) - -#define gmp_assert_nocarry(x) do { \ - mp_limb_t __cy = (x); \ - assert (__cy == 0); \ - } while (0) - -#define gmp_clz(count, x) do { \ - mp_limb_t __clz_x = (x); \ - unsigned __clz_c; \ - for (__clz_c = 0; \ - (__clz_x & ((mp_limb_t) 0xff << (GMP_LIMB_BITS - 8))) == 0; \ - __clz_c += 8) \ - __clz_x <<= 8; \ - for (; (__clz_x & GMP_LIMB_HIGHBIT) == 0; __clz_c++) \ - __clz_x <<= 1; \ - (count) = __clz_c; \ - } while (0) - -#define gmp_ctz(count, x) do { \ - mp_limb_t __ctz_x = (x); \ - unsigned __ctz_c = 0; \ - gmp_clz (__ctz_c, __ctz_x & - __ctz_x); \ - (count) = GMP_LIMB_BITS - 1 - __ctz_c; \ - } while (0) - -#define gmp_add_ssaaaa(sh, sl, ah, al, bh, bl) \ - do { \ - mp_limb_t __x; \ - __x = (al) + (bl); \ - (sh) = (ah) + (bh) + (__x < (al)); \ - (sl) = __x; \ - } while (0) - -#define gmp_sub_ddmmss(sh, sl, ah, al, bh, bl) \ - do { \ - mp_limb_t __x; \ - __x = (al) - (bl); \ - (sh) = (ah) - (bh) - ((al) < (bl)); \ - (sl) = __x; \ - } while (0) - -#define gmp_umul_ppmm(w1, w0, u, v) \ - do { \ - mp_limb_t __x0, __x1, __x2, __x3; \ - unsigned __ul, __vl, __uh, __vh; \ - mp_limb_t __u = (u), __v = (v); \ - \ - __ul = __u & GMP_LLIMB_MASK; \ - __uh = __u >> (GMP_LIMB_BITS / 2); \ - __vl = __v & GMP_LLIMB_MASK; \ - __vh = __v >> (GMP_LIMB_BITS / 2); \ - \ - __x0 = (mp_limb_t) __ul * __vl; \ - __x1 = (mp_limb_t) __ul * __vh; \ - __x2 = (mp_limb_t) __uh * __vl; \ - __x3 = (mp_limb_t) __uh * __vh; \ - \ - __x1 += __x0 >> (GMP_LIMB_BITS / 2);/* this can't give carry */ \ - __x1 += __x2; /* but this indeed can */ \ - if (__x1 < __x2) /* did we get it? */ \ - __x3 += GMP_HLIMB_BIT; /* yes, add it in the proper pos. */ \ - \ - (w1) = __x3 + (__x1 >> (GMP_LIMB_BITS / 2)); \ - (w0) = (__x1 << (GMP_LIMB_BITS / 2)) + (__x0 & GMP_LLIMB_MASK); \ - } while (0) - -#define gmp_udiv_qrnnd_preinv(q, r, nh, nl, d, di) \ - do { \ - mp_limb_t _qh, _ql, _r, _mask; \ - gmp_umul_ppmm (_qh, _ql, (nh), (di)); \ - gmp_add_ssaaaa (_qh, _ql, _qh, _ql, (nh) + 1, (nl)); \ - _r = (nl) - _qh * (d); \ - _mask = -(mp_limb_t) (_r > _ql); /* both > and >= are OK */ \ - _qh += _mask; \ - _r += _mask & (d); \ - if (_r >= (d)) \ - { \ - _r -= (d); \ - _qh++; \ - } \ - \ - (r) = _r; \ - (q) = _qh; \ - } while (0) - -#define gmp_udiv_qr_3by2(q, r1, r0, n2, n1, n0, d1, d0, dinv) \ - do { \ - mp_limb_t _q0, _t1, _t0, _mask; \ - gmp_umul_ppmm ((q), _q0, (n2), (dinv)); \ - gmp_add_ssaaaa ((q), _q0, (q), _q0, (n2), (n1)); \ - \ - /* Compute the two most significant limbs of n - q'd */ \ - (r1) = (n1) - (d1) * (q); \ - gmp_sub_ddmmss ((r1), (r0), (r1), (n0), (d1), (d0)); \ - gmp_umul_ppmm (_t1, _t0, (d0), (q)); \ - gmp_sub_ddmmss ((r1), (r0), (r1), (r0), _t1, _t0); \ - (q)++; \ - \ - /* Conditionally adjust q and the remainders */ \ - _mask = - (mp_limb_t) ((r1) >= _q0); \ - (q) += _mask; \ - gmp_add_ssaaaa ((r1), (r0), (r1), (r0), _mask & (d1), _mask & (d0)); \ - if ((r1) >= (d1)) \ - { \ - if ((r1) > (d1) || (r0) >= (d0)) \ - { \ - (q)++; \ - gmp_sub_ddmmss ((r1), (r0), (r1), (r0), (d1), (d0)); \ - } \ - } \ - } while (0) - -/* Swap macros. */ -#define MP_LIMB_T_SWAP(x, y) \ - do { \ - mp_limb_t __mp_limb_t_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mp_limb_t_swap__tmp; \ - } while (0) -#define MP_SIZE_T_SWAP(x, y) \ - do { \ - mp_size_t __mp_size_t_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mp_size_t_swap__tmp; \ - } while (0) -#define MP_BITCNT_T_SWAP(x,y) \ - do { \ - mp_bitcnt_t __mp_bitcnt_t_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mp_bitcnt_t_swap__tmp; \ - } while (0) -#define MP_PTR_SWAP(x, y) \ - do { \ - mp_ptr __mp_ptr_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mp_ptr_swap__tmp; \ - } while (0) -#define MP_SRCPTR_SWAP(x, y) \ - do { \ - mp_srcptr __mp_srcptr_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mp_srcptr_swap__tmp; \ - } while (0) - -#define MPN_PTR_SWAP(xp,xs, yp,ys) \ - do { \ - MP_PTR_SWAP (xp, yp); \ - MP_SIZE_T_SWAP (xs, ys); \ - } while(0) -#define MPN_SRCPTR_SWAP(xp,xs, yp,ys) \ - do { \ - MP_SRCPTR_SWAP (xp, yp); \ - MP_SIZE_T_SWAP (xs, ys); \ - } while(0) - -#define MPZ_PTR_SWAP(x, y) \ - do { \ - mpz_ptr __mpz_ptr_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mpz_ptr_swap__tmp; \ - } while (0) -#define MPZ_SRCPTR_SWAP(x, y) \ - do { \ - mpz_srcptr __mpz_srcptr_swap__tmp = (x); \ - (x) = (y); \ - (y) = __mpz_srcptr_swap__tmp; \ - } while (0) - -const int mp_bits_per_limb = GMP_LIMB_BITS; - - -/* Memory allocation and other helper functions. */ -static void -gmp_die (const char *msg) -{ - fprintf (stderr, "%s\n", msg); - abort(); -} - -static void * -gmp_default_alloc (size_t size) -{ - void *p; - - assert (size > 0); - - p = malloc (size); - if (!p) - gmp_die("gmp_default_alloc: Virtual memory exhausted."); - - return p; -} - -static void * -gmp_default_realloc (void *old, size_t old_size, size_t new_size) -{ - UN_USED(old_size); - - void * p; - - p = realloc (old, new_size); - - if (!p) - gmp_die("gmp_default_realloc: Virtual memory exhausted."); - - return p; -} - -static void -gmp_default_free (void *p, size_t size) -{ - UN_USED(size); - free (p); -} - -static void * (*gmp_allocate_func) (size_t) = gmp_default_alloc; -static void * (*gmp_reallocate_func) (void *, size_t, size_t) = gmp_default_realloc; -static void (*gmp_free_func) (void *, size_t) = gmp_default_free; - -void -mp_get_memory_functions (void *(**alloc_func) (size_t), - void *(**realloc_func) (void *, size_t, size_t), - void (**free_func) (void *, size_t)) -{ - if (alloc_func) - *alloc_func = gmp_allocate_func; - - if (realloc_func) - *realloc_func = gmp_reallocate_func; - - if (free_func) - *free_func = gmp_free_func; -} - -void -mp_set_memory_functions (void *(*alloc_func) (size_t), - void *(*realloc_func) (void *, size_t, size_t), - void (*free_func) (void *, size_t)) -{ - if (!alloc_func) - alloc_func = gmp_default_alloc; - if (!realloc_func) - realloc_func = gmp_default_realloc; - if (!free_func) - free_func = gmp_default_free; - - gmp_allocate_func = alloc_func; - gmp_reallocate_func = realloc_func; - gmp_free_func = free_func; -} - -#define gmp_xalloc(size) ((*gmp_allocate_func)((size))) -#define gmp_free(p) ((*gmp_free_func) ((p), 0)) - -static mp_ptr -gmp_xalloc_limbs (mp_size_t size) -{ - return (mp_ptr) gmp_xalloc (size * sizeof (mp_limb_t)); -} - -static mp_ptr -gmp_xrealloc_limbs (mp_ptr old, mp_size_t size) -{ - assert (size > 0); - return (mp_ptr) (*gmp_reallocate_func) (old, 0, size * sizeof (mp_limb_t)); -} - - -/* MPN interface */ - -void -mpn_copyi (mp_ptr d, mp_srcptr s, mp_size_t n) -{ - mp_size_t i; - for (i = 0; i < n; i++) - d[i] = s[i]; -} - -void -mpn_copyd (mp_ptr d, mp_srcptr s, mp_size_t n) -{ - while (--n >= 0) - d[n] = s[n]; -} - -int -mpn_cmp (mp_srcptr ap, mp_srcptr bp, mp_size_t n) -{ - while (--n >= 0) - { - if (ap[n] != bp[n]) - return ap[n] > bp[n] ? 1 : -1; - } - return 0; -} - -static int -mpn_cmp4 (mp_srcptr ap, mp_size_t an, mp_srcptr bp, mp_size_t bn) -{ - if (an != bn) - return an < bn ? -1 : 1; - else - return mpn_cmp (ap, bp, an); -} - -static mp_size_t -mpn_normalized_size (mp_srcptr xp, mp_size_t n) -{ - while (n > 0 && xp[n-1] == 0) - --n; - return n; -} - -int -mpn_zero_p(mp_srcptr rp, mp_size_t n) -{ - return mpn_normalized_size (rp, n) == 0; -} - -void -mpn_zero (mp_ptr rp, mp_size_t n) -{ - while (--n >= 0) - rp[n] = 0; -} - -mp_limb_t -mpn_add_1 (mp_ptr rp, mp_srcptr ap, mp_size_t n, mp_limb_t b) -{ - mp_size_t i; - - assert (n > 0); - i = 0; - do - { - mp_limb_t r = ap[i] + b; - /* Carry out */ - b = (r < b); - rp[i] = r; - } - while (++i < n); - - return b; -} - -mp_limb_t -mpn_add_n (mp_ptr rp, mp_srcptr ap, mp_srcptr bp, mp_size_t n) -{ - mp_size_t i; - mp_limb_t cy; - - for (i = 0, cy = 0; i < n; i++) - { - mp_limb_t a, b, r; - a = ap[i]; b = bp[i]; - r = a + cy; - cy = (r < cy); - r += b; - cy += (r < b); - rp[i] = r; - } - return cy; -} - -mp_limb_t -mpn_add (mp_ptr rp, mp_srcptr ap, mp_size_t an, mp_srcptr bp, mp_size_t bn) -{ - mp_limb_t cy; - - assert (an >= bn); - - cy = mpn_add_n (rp, ap, bp, bn); - if (an > bn) - cy = mpn_add_1 (rp + bn, ap + bn, an - bn, cy); - return cy; -} - -mp_limb_t -mpn_sub_1 (mp_ptr rp, mp_srcptr ap, mp_size_t n, mp_limb_t b) -{ - mp_size_t i; - - assert (n > 0); - - i = 0; - do - { - mp_limb_t a = ap[i]; - /* Carry out */ - mp_limb_t cy = a < b; - rp[i] = a - b; - b = cy; - } - while (++i < n); - - return b; -} - -mp_limb_t -mpn_sub_n (mp_ptr rp, mp_srcptr ap, mp_srcptr bp, mp_size_t n) -{ - mp_size_t i; - mp_limb_t cy; - - for (i = 0, cy = 0; i < n; i++) - { - mp_limb_t a, b; - a = ap[i]; b = bp[i]; - b += cy; - cy = (b < cy); - cy += (a < b); - rp[i] = a - b; - } - return cy; -} - -mp_limb_t -mpn_sub (mp_ptr rp, mp_srcptr ap, mp_size_t an, mp_srcptr bp, mp_size_t bn) -{ - mp_limb_t cy; - - assert (an >= bn); - - cy = mpn_sub_n (rp, ap, bp, bn); - if (an > bn) - cy = mpn_sub_1 (rp + bn, ap + bn, an - bn, cy); - return cy; -} - -mp_limb_t -mpn_mul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) -{ - mp_limb_t ul, cl, hpl, lpl; - - assert (n >= 1); - - cl = 0; - do - { - ul = *up++; - gmp_umul_ppmm (hpl, lpl, ul, vl); - - lpl += cl; - cl = (lpl < cl) + hpl; - - *rp++ = lpl; - } - while (--n != 0); - - return cl; -} - -mp_limb_t -mpn_addmul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) -{ - mp_limb_t ul, cl, hpl, lpl, rl; - - assert (n >= 1); - - cl = 0; - do - { - ul = *up++; - gmp_umul_ppmm (hpl, lpl, ul, vl); - - lpl += cl; - cl = (lpl < cl) + hpl; - - rl = *rp; - lpl = rl + lpl; - cl += lpl < rl; - *rp++ = lpl; - } - while (--n != 0); - - return cl; -} - -mp_limb_t -mpn_submul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) -{ - mp_limb_t ul, cl, hpl, lpl, rl; - - assert (n >= 1); - - cl = 0; - do - { - ul = *up++; - gmp_umul_ppmm (hpl, lpl, ul, vl); - - lpl += cl; - cl = (lpl < cl) + hpl; - - rl = *rp; - lpl = rl - lpl; - cl += lpl > rl; - *rp++ = lpl; - } - while (--n != 0); - - return cl; -} - -mp_limb_t -mpn_mul (mp_ptr rp, mp_srcptr up, mp_size_t un, mp_srcptr vp, mp_size_t vn) -{ - assert (un >= vn); - assert (vn >= 1); - - /* We first multiply by the low order limb. This result can be - stored, not added, to rp. We also avoid a loop for zeroing this - way. */ - - rp[un] = mpn_mul_1 (rp, up, un, vp[0]); - - /* Now accumulate the product of up[] and the next higher limb from - vp[]. */ - - while (--vn >= 1) - { - rp += 1, vp += 1; - rp[un] = mpn_addmul_1 (rp, up, un, vp[0]); - } - return rp[un]; -} - -void -mpn_mul_n (mp_ptr rp, mp_srcptr ap, mp_srcptr bp, mp_size_t n) -{ - mpn_mul (rp, ap, n, bp, n); -} - -void -mpn_sqr (mp_ptr rp, mp_srcptr ap, mp_size_t n) -{ - mpn_mul (rp, ap, n, ap, n); -} - -mp_limb_t -mpn_lshift (mp_ptr rp, mp_srcptr up, mp_size_t n, unsigned int cnt) -{ - mp_limb_t high_limb, low_limb; - unsigned int tnc; - mp_limb_t retval; - - assert (n >= 1); - assert (cnt >= 1); - assert (cnt < GMP_LIMB_BITS); - - up += n; - rp += n; - - tnc = GMP_LIMB_BITS - cnt; - low_limb = *--up; - retval = low_limb >> tnc; - high_limb = (low_limb << cnt); - - while (--n != 0) - { - low_limb = *--up; - *--rp = high_limb | (low_limb >> tnc); - high_limb = (low_limb << cnt); - } - *--rp = high_limb; - - return retval; -} - -mp_limb_t -mpn_rshift (mp_ptr rp, mp_srcptr up, mp_size_t n, unsigned int cnt) -{ - mp_limb_t high_limb, low_limb; - unsigned int tnc; - mp_limb_t retval; - - assert (n >= 1); - assert (cnt >= 1); - assert (cnt < GMP_LIMB_BITS); - - tnc = GMP_LIMB_BITS - cnt; - high_limb = *up++; - retval = (high_limb << tnc); - low_limb = high_limb >> cnt; - - while (--n != 0) - { - high_limb = *up++; - *rp++ = low_limb | (high_limb << tnc); - low_limb = high_limb >> cnt; - } - *rp = low_limb; - - return retval; -} - -static mp_bitcnt_t -mpn_common_scan (mp_limb_t limb, mp_size_t i, mp_srcptr up, mp_size_t un, - mp_limb_t ux) -{ - unsigned cnt; - - assert (ux == 0 || ux == GMP_LIMB_MAX); - assert (0 <= i && i <= un ); - - while (limb == 0) - { - i++; - if (i == un) - return (ux == 0 ? ~(mp_bitcnt_t) 0 : un * GMP_LIMB_BITS); - limb = ux ^ up[i]; - } - gmp_ctz (cnt, limb); - return (mp_bitcnt_t) i * GMP_LIMB_BITS + cnt; -} - -mp_bitcnt_t -mpn_scan1 (mp_srcptr ptr, mp_bitcnt_t bit) -{ - mp_size_t i; - i = bit / GMP_LIMB_BITS; - - return mpn_common_scan ( ptr[i] & (GMP_LIMB_MAX << (bit % GMP_LIMB_BITS)), - i, ptr, i, 0); -} - -mp_bitcnt_t -mpn_scan0 (mp_srcptr ptr, mp_bitcnt_t bit) -{ - mp_size_t i; - i = bit / GMP_LIMB_BITS; - - return mpn_common_scan (~ptr[i] & (GMP_LIMB_MAX << (bit % GMP_LIMB_BITS)), - i, ptr, i, GMP_LIMB_MAX); -} - -void -mpn_com (mp_ptr rp, mp_srcptr up, mp_size_t n) -{ - while (--n >= 0) - *rp++ = ~ *up++; -} - -mp_limb_t -mpn_neg (mp_ptr rp, mp_srcptr up, mp_size_t n) -{ - while (*up == 0) - { - *rp = 0; - if (!--n) - return 0; - ++up; ++rp; - } - *rp = - *up; - mpn_com (++rp, ++up, --n); - return 1; -} - - -/* MPN division interface. */ - -/* The 3/2 inverse is defined as - - m = floor( (B^3-1) / (B u1 + u0)) - B -*/ -mp_limb_t -mpn_invert_3by2 (mp_limb_t u1, mp_limb_t u0) -{ - mp_limb_t r, p, m, ql; - unsigned ul, uh, qh; - - assert (u1 >= GMP_LIMB_HIGHBIT); - - /* For notation, let b denote the half-limb base, so that B = b^2. - Split u1 = b uh + ul. */ - ul = u1 & GMP_LLIMB_MASK; - uh = u1 >> (GMP_LIMB_BITS / 2); - - /* Approximation of the high half of quotient. Differs from the 2/1 - inverse of the half limb uh, since we have already subtracted - u0. */ - qh = ~u1 / uh; - - /* Adjust to get a half-limb 3/2 inverse, i.e., we want - - qh' = floor( (b^3 - 1) / u) - b = floor ((b^3 - b u - 1) / u - = floor( (b (~u) + b-1) / u), - - and the remainder - - r = b (~u) + b-1 - qh (b uh + ul) - = b (~u - qh uh) + b-1 - qh ul - - Subtraction of qh ul may underflow, which implies adjustments. - But by normalization, 2 u >= B > qh ul, so we need to adjust by - at most 2. - */ - - r = ((~u1 - (mp_limb_t) qh * uh) << (GMP_LIMB_BITS / 2)) | GMP_LLIMB_MASK; - - p = (mp_limb_t) qh * ul; - /* Adjustment steps taken from udiv_qrnnd_c */ - if (r < p) - { - qh--; - r += u1; - if (r >= u1) /* i.e. we didn't get carry when adding to r */ - if (r < p) - { - qh--; - r += u1; - } - } - r -= p; - - /* Low half of the quotient is - - ql = floor ( (b r + b-1) / u1). - - This is a 3/2 division (on half-limbs), for which qh is a - suitable inverse. */ - - p = (r >> (GMP_LIMB_BITS / 2)) * qh + r; - /* Unlike full-limb 3/2, we can add 1 without overflow. For this to - work, it is essential that ql is a full mp_limb_t. */ - ql = (p >> (GMP_LIMB_BITS / 2)) + 1; - - /* By the 3/2 trick, we don't need the high half limb. */ - r = (r << (GMP_LIMB_BITS / 2)) + GMP_LLIMB_MASK - ql * u1; - - if (r >= (p << (GMP_LIMB_BITS / 2))) - { - ql--; - r += u1; - } - m = ((mp_limb_t) qh << (GMP_LIMB_BITS / 2)) + ql; - if (r >= u1) - { - m++; - r -= u1; - } - - /* Now m is the 2/1 invers of u1. If u0 > 0, adjust it to become a - 3/2 inverse. */ - if (u0 > 0) - { - mp_limb_t th, tl; - r = ~r; - r += u0; - if (r < u0) - { - m--; - if (r >= u1) - { - m--; - r -= u1; - } - r -= u1; - } - gmp_umul_ppmm (th, tl, u0, m); - r += th; - if (r < th) - { - m--; - m -= ((r > u1) | ((r == u1) & (tl > u0))); - } - } - - return m; -} - -struct gmp_div_inverse -{ - /* Normalization shift count. */ - unsigned shift; - /* Normalized divisor (d0 unused for mpn_div_qr_1) */ - mp_limb_t d1, d0; - /* Inverse, for 2/1 or 3/2. */ - mp_limb_t di; -}; - -static void -mpn_div_qr_1_invert (struct gmp_div_inverse *inv, mp_limb_t d) -{ - unsigned shift; - - assert (d > 0); - gmp_clz (shift, d); - inv->shift = shift; - inv->d1 = d << shift; - inv->di = mpn_invert_limb (inv->d1); -} - -static void -mpn_div_qr_2_invert (struct gmp_div_inverse *inv, - mp_limb_t d1, mp_limb_t d0) -{ - unsigned shift; - - assert (d1 > 0); - gmp_clz (shift, d1); - inv->shift = shift; - if (shift > 0) - { - d1 = (d1 << shift) | (d0 >> (GMP_LIMB_BITS - shift)); - d0 <<= shift; - } - inv->d1 = d1; - inv->d0 = d0; - inv->di = mpn_invert_3by2 (d1, d0); -} - -static void -mpn_div_qr_invert (struct gmp_div_inverse *inv, - mp_srcptr dp, mp_size_t dn) -{ - assert (dn > 0); - - if (dn == 1) - mpn_div_qr_1_invert (inv, dp[0]); - else if (dn == 2) - mpn_div_qr_2_invert (inv, dp[1], dp[0]); - else - { - unsigned shift; - mp_limb_t d1, d0; - - d1 = dp[dn-1]; - d0 = dp[dn-2]; - assert (d1 > 0); - gmp_clz (shift, d1); - inv->shift = shift; - if (shift > 0) - { - d1 = (d1 << shift) | (d0 >> (GMP_LIMB_BITS - shift)); - d0 = (d0 << shift) | (dp[dn-3] >> (GMP_LIMB_BITS - shift)); - } - inv->d1 = d1; - inv->d0 = d0; - inv->di = mpn_invert_3by2 (d1, d0); - } -} - -/* Not matching current public gmp interface, rather corresponding to - the sbpi1_div_* functions. */ -static mp_limb_t -mpn_div_qr_1_preinv (mp_ptr qp, mp_srcptr np, mp_size_t nn, - const struct gmp_div_inverse *inv) -{ - mp_limb_t d, di; - mp_limb_t r; - mp_ptr tp = NULL; - - if (inv->shift > 0) - { - tp = gmp_xalloc_limbs (nn); - r = mpn_lshift (tp, np, nn, inv->shift); - np = tp; - } - else - r = 0; - - d = inv->d1; - di = inv->di; - while (--nn >= 0) - { - mp_limb_t q; - - gmp_udiv_qrnnd_preinv (q, r, r, np[nn], d, di); - if (qp) - qp[nn] = q; - } - if (inv->shift > 0) - gmp_free (tp); - - return r >> inv->shift; -} - -static mp_limb_t -mpn_div_qr_1 (mp_ptr qp, mp_srcptr np, mp_size_t nn, mp_limb_t d) -{ - assert (d > 0); - - /* Special case for powers of two. */ - if ((d & (d-1)) == 0) - { - mp_limb_t r = np[0] & (d-1); - if (qp) - { - if (d <= 1) - mpn_copyi (qp, np, nn); - else - { - unsigned shift; - gmp_ctz (shift, d); - mpn_rshift (qp, np, nn, shift); - } - } - return r; - } - else - { - struct gmp_div_inverse inv; - mpn_div_qr_1_invert (&inv, d); - return mpn_div_qr_1_preinv (qp, np, nn, &inv); - } -} - -static void -mpn_div_qr_2_preinv (mp_ptr qp, mp_ptr rp, mp_srcptr np, mp_size_t nn, - const struct gmp_div_inverse *inv) -{ - unsigned shift; - mp_size_t i; - mp_limb_t d1, d0, di, r1, r0; - mp_ptr tp; - - assert (nn >= 2); - shift = inv->shift; - d1 = inv->d1; - d0 = inv->d0; - di = inv->di; - - if (shift > 0) - { - tp = gmp_xalloc_limbs (nn); - r1 = mpn_lshift (tp, np, nn, shift); - np = tp; - } - else - r1 = 0; - - r0 = np[nn - 1]; - - i = nn - 2; - do - { - mp_limb_t n0, q; - n0 = np[i]; - gmp_udiv_qr_3by2 (q, r1, r0, r1, r0, n0, d1, d0, di); - - if (qp) - qp[i] = q; - } - while (--i >= 0); - - if (shift > 0) - { - assert ((r0 << (GMP_LIMB_BITS - shift)) == 0); - r0 = (r0 >> shift) | (r1 << (GMP_LIMB_BITS - shift)); - r1 >>= shift; - - gmp_free (tp); - } - - rp[1] = r1; - rp[0] = r0; -} - -#if 0 -static void -mpn_div_qr_2 (mp_ptr qp, mp_ptr rp, mp_srcptr np, mp_size_t nn, - mp_limb_t d1, mp_limb_t d0) -{ - struct gmp_div_inverse inv; - assert (nn >= 2); - - mpn_div_qr_2_invert (&inv, d1, d0); - mpn_div_qr_2_preinv (qp, rp, np, nn, &inv); -} -#endif - -static void -mpn_div_qr_pi1 (mp_ptr qp, - mp_ptr np, mp_size_t nn, mp_limb_t n1, - mp_srcptr dp, mp_size_t dn, - mp_limb_t dinv) -{ - mp_size_t i; - - mp_limb_t d1, d0; - mp_limb_t cy, cy1; - mp_limb_t q; - - assert (dn > 2); - assert (nn >= dn); - - d1 = dp[dn - 1]; - d0 = dp[dn - 2]; - - assert ((d1 & GMP_LIMB_HIGHBIT) != 0); - /* Iteration variable is the index of the q limb. - * - * We divide - * by - */ - - i = nn - dn; - do - { - mp_limb_t n0 = np[dn-1+i]; - - if (n1 == d1 && n0 == d0) - { - q = GMP_LIMB_MAX; - mpn_submul_1 (np+i, dp, dn, q); - n1 = np[dn-1+i]; /* update n1, last loop's value will now be invalid */ - } - else - { - gmp_udiv_qr_3by2 (q, n1, n0, n1, n0, np[dn-2+i], d1, d0, dinv); - - cy = mpn_submul_1 (np + i, dp, dn-2, q); - - cy1 = n0 < cy; - n0 = n0 - cy; - cy = n1 < cy1; - n1 = n1 - cy1; - np[dn-2+i] = n0; - - if (cy != 0) - { - n1 += d1 + mpn_add_n (np + i, np + i, dp, dn - 1); - q--; - } - } - - if (qp) - qp[i] = q; - } - while (--i >= 0); - - np[dn - 1] = n1; -} - -static void -mpn_div_qr_preinv (mp_ptr qp, mp_ptr np, mp_size_t nn, - mp_srcptr dp, mp_size_t dn, - const struct gmp_div_inverse *inv) -{ - assert (dn > 0); - assert (nn >= dn); - - if (dn == 1) - np[0] = mpn_div_qr_1_preinv (qp, np, nn, inv); - else if (dn == 2) - mpn_div_qr_2_preinv (qp, np, np, nn, inv); - else - { - mp_limb_t nh; - unsigned shift; - - assert (inv->d1 == dp[dn-1]); - assert (inv->d0 == dp[dn-2]); - assert ((inv->d1 & GMP_LIMB_HIGHBIT) != 0); - - shift = inv->shift; - if (shift > 0) - nh = mpn_lshift (np, np, nn, shift); - else - nh = 0; - - mpn_div_qr_pi1 (qp, np, nn, nh, dp, dn, inv->di); - - if (shift > 0) - gmp_assert_nocarry (mpn_rshift (np, np, dn, shift)); - } -} - -static void -mpn_div_qr (mp_ptr qp, mp_ptr np, mp_size_t nn, mp_srcptr dp, mp_size_t dn) -{ - struct gmp_div_inverse inv; - mp_ptr tp = NULL; - - assert (dn > 0); - assert (nn >= dn); - - mpn_div_qr_invert (&inv, dp, dn); - if (dn > 2 && inv.shift > 0) - { - tp = gmp_xalloc_limbs (dn); - gmp_assert_nocarry (mpn_lshift (tp, dp, dn, inv.shift)); - dp = tp; - } - mpn_div_qr_preinv (qp, np, nn, dp, dn, &inv); - if (tp) - gmp_free (tp); -} - - -/* MPN base conversion. */ -static unsigned -mpn_base_power_of_two_p (unsigned b) -{ - switch (b) - { - case 2: return 1; - case 4: return 2; - case 8: return 3; - case 16: return 4; - case 32: return 5; - case 64: return 6; - case 128: return 7; - case 256: return 8; - default: return 0; - } -} - -struct mpn_base_info -{ - /* bb is the largest power of the base which fits in one limb, and - exp is the corresponding exponent. */ - unsigned exp; - mp_limb_t bb; -}; - -static void -mpn_get_base_info (struct mpn_base_info *info, mp_limb_t b) -{ - mp_limb_t m; - mp_limb_t p; - unsigned exp; - - m = GMP_LIMB_MAX / b; - for (exp = 1, p = b; p <= m; exp++) - p *= b; - - info->exp = exp; - info->bb = p; -} - -static mp_bitcnt_t -mpn_limb_size_in_base_2 (mp_limb_t u) -{ - unsigned shift; - - assert (u > 0); - gmp_clz (shift, u); - return GMP_LIMB_BITS - shift; -} - -static size_t -mpn_get_str_bits (unsigned char *sp, unsigned bits, mp_srcptr up, mp_size_t un) -{ - unsigned char mask; - size_t sn, j; - mp_size_t i; - unsigned shift; - - sn = ((un - 1) * GMP_LIMB_BITS + mpn_limb_size_in_base_2 (up[un-1]) - + bits - 1) / bits; - - mask = (1U << bits) - 1; - - for (i = 0, j = sn, shift = 0; j-- > 0;) - { - unsigned char digit = up[i] >> shift; - - shift += bits; - - if (shift >= GMP_LIMB_BITS && ++i < un) - { - shift -= GMP_LIMB_BITS; - digit |= up[i] << (bits - shift); - } - sp[j] = digit & mask; - } - return sn; -} - -/* We generate digits from the least significant end, and reverse at - the end. */ -static size_t -mpn_limb_get_str (unsigned char *sp, mp_limb_t w, - const struct gmp_div_inverse *binv) -{ - mp_size_t i; - for (i = 0; w > 0; i++) - { - mp_limb_t h, l, r; - - h = w >> (GMP_LIMB_BITS - binv->shift); - l = w << binv->shift; - - gmp_udiv_qrnnd_preinv (w, r, h, l, binv->d1, binv->di); - assert ( (r << (GMP_LIMB_BITS - binv->shift)) == 0); - r >>= binv->shift; - - sp[i] = r; - } - return i; -} - -static size_t -mpn_get_str_other (unsigned char *sp, - int base, const struct mpn_base_info *info, - mp_ptr up, mp_size_t un) -{ - struct gmp_div_inverse binv; - size_t sn; - size_t i; - - mpn_div_qr_1_invert (&binv, base); - - sn = 0; - - if (un > 1) - { - struct gmp_div_inverse bbinv; - mpn_div_qr_1_invert (&bbinv, info->bb); - - do - { - mp_limb_t w; - size_t done; - w = mpn_div_qr_1_preinv (up, up, un, &bbinv); - un -= (up[un-1] == 0); - done = mpn_limb_get_str (sp + sn, w, &binv); - - for (sn += done; done < info->exp; done++) - sp[sn++] = 0; - } - while (un > 1); - } - sn += mpn_limb_get_str (sp + sn, up[0], &binv); - - /* Reverse order */ - for (i = 0; 2*i + 1 < sn; i++) - { - unsigned char t = sp[i]; - sp[i] = sp[sn - i - 1]; - sp[sn - i - 1] = t; - } - - return sn; -} - -size_t -mpn_get_str (unsigned char *sp, int base, mp_ptr up, mp_size_t un) -{ - unsigned bits; - - assert (un > 0); - assert (up[un-1] > 0); - - bits = mpn_base_power_of_two_p (base); - if (bits) - return mpn_get_str_bits (sp, bits, up, un); - else - { - struct mpn_base_info info; - - mpn_get_base_info (&info, base); - return mpn_get_str_other (sp, base, &info, up, un); - } -} - -static mp_size_t -mpn_set_str_bits (mp_ptr rp, const unsigned char *sp, size_t sn, - unsigned bits) -{ - mp_size_t rn; - size_t j; - unsigned shift; - - for (j = sn, rn = 0, shift = 0; j-- > 0; ) - { - if (shift == 0) - { - rp[rn++] = sp[j]; - shift += bits; - } - else - { - rp[rn-1] |= (mp_limb_t) sp[j] << shift; - shift += bits; - if (shift >= GMP_LIMB_BITS) - { - shift -= GMP_LIMB_BITS; - if (shift > 0) - rp[rn++] = (mp_limb_t) sp[j] >> (bits - shift); - } - } - } - rn = mpn_normalized_size (rp, rn); - return rn; -} - -/* Result is usually normalized, except for all-zero input, in which - case a single zero limb is written at *RP, and 1 is returned. */ -static mp_size_t -mpn_set_str_other (mp_ptr rp, const unsigned char *sp, size_t sn, - mp_limb_t b, const struct mpn_base_info *info) -{ - mp_size_t rn; - mp_limb_t w; - unsigned k; - size_t j; - - assert (sn > 0); - - k = 1 + (sn - 1) % info->exp; - - j = 0; - w = sp[j++]; - while (--k != 0) - w = w * b + sp[j++]; - - rp[0] = w; - - for (rn = 1; j < sn;) - { - mp_limb_t cy; - - w = sp[j++]; - for (k = 1; k < info->exp; k++) - w = w * b + sp[j++]; - - cy = mpn_mul_1 (rp, rp, rn, info->bb); - cy += mpn_add_1 (rp, rp, rn, w); - if (cy > 0) - rp[rn++] = cy; - } - assert (j == sn); - - return rn; -} - -mp_size_t -mpn_set_str (mp_ptr rp, const unsigned char *sp, size_t sn, int base) -{ - unsigned bits; - - if (sn == 0) - return 0; - - bits = mpn_base_power_of_two_p (base); - if (bits) - return mpn_set_str_bits (rp, sp, sn, bits); - else - { - struct mpn_base_info info; - - mpn_get_base_info (&info, base); - return mpn_set_str_other (rp, sp, sn, base, &info); - } -} - - -/* MPZ interface */ -void -mpz_init (mpz_t r) -{ - static const mp_limb_t dummy_limb = 0xc1a0; - - r->_mp_alloc = 0; - r->_mp_size = 0; - r->_mp_d = (mp_ptr) &dummy_limb; -} - -/* The utility of this function is a bit limited, since many functions - assigns the result variable using mpz_swap. */ -void -mpz_init2 (mpz_t r, mp_bitcnt_t bits) -{ - mp_size_t rn; - - bits -= (bits != 0); /* Round down, except if 0 */ - rn = 1 + bits / GMP_LIMB_BITS; - - r->_mp_alloc = rn; - r->_mp_size = 0; - r->_mp_d = gmp_xalloc_limbs (rn); -} - -void -mpz_clear (mpz_t r) -{ - if (r->_mp_alloc) - gmp_free (r->_mp_d); -} - -static mp_ptr -mpz_realloc (mpz_t r, mp_size_t size) -{ - size = GMP_MAX (size, 1); - - if (r->_mp_alloc) - r->_mp_d = gmp_xrealloc_limbs (r->_mp_d, size); - else - r->_mp_d = gmp_xalloc_limbs (size); - r->_mp_alloc = size; - - if (GMP_ABS (r->_mp_size) > size) - r->_mp_size = 0; - - return r->_mp_d; -} - -/* Realloc for an mpz_t WHAT if it has less than NEEDED limbs. */ -#define MPZ_REALLOC(z,n) ((n) > (z)->_mp_alloc \ - ? mpz_realloc(z,n) \ - : (z)->_mp_d) - -/* MPZ assignment and basic conversions. */ -void -mpz_set_si (mpz_t r, intMpz x) -{ - if (x >= 0) - mpz_set_ui (r, x); - else /* (x < 0) */ - { - r->_mp_size = -1; - MPZ_REALLOC (r, 1)[0] = GMP_NEG_CAST (uIntMpz, x); - } -} - -void -mpz_set_ui (mpz_t r, uIntMpz x) -{ - if (x > 0) - { - r->_mp_size = 1; - MPZ_REALLOC (r, 1)[0] = x; - } - else - r->_mp_size = 0; -} - -void -mpz_set (mpz_t r, const mpz_t x) -{ - /* Allow the NOP r == x */ - if (r != x) - { - mp_size_t n; - mp_ptr rp; - - n = GMP_ABS (x->_mp_size); - rp = MPZ_REALLOC (r, n); - - mpn_copyi (rp, x->_mp_d, n); - r->_mp_size = x->_mp_size; - } -} - -void -mpz_init_set_si (mpz_t r, intMpz x) -{ - mpz_init (r); - mpz_set_si (r, x); -} - -void -mpz_init_set_ui (mpz_t r, uIntMpz x) -{ - mpz_init (r); - mpz_set_ui (r, x); -} - -void -mpz_init_set (mpz_t r, const mpz_t x) -{ - mpz_init (r); - mpz_set (r, x); -} - -int -mpz_fits_slong_p (const mpz_t u) -{ - mp_size_t us = u->_mp_size; - - if (us == 1) - return u->_mp_d[0] < GMP_LIMB_HIGHBIT; - else if (us == -1) - return u->_mp_d[0] <= GMP_LIMB_HIGHBIT; - else - return (us == 0); -} - -int -mpz_fits_ulong_p (const mpz_t u) -{ - mp_size_t us = u->_mp_size; - - return (us == (us > 0)); -} - - intMpz -mpz_get_si (const mpz_t u) -{ - if (u->_mp_size < 0) - /* This expression is necessary to properly handle 0x80000000 */ - return -1 - (long) ((u->_mp_d[0] - 1) & ~GMP_LIMB_HIGHBIT); - else - return (long) (mpz_get_ui (u) & ~GMP_LIMB_HIGHBIT); -} - -uIntMpz -mpz_get_ui (const mpz_t u) -{ - return u->_mp_size == 0 ? 0 : u->_mp_d[0]; -} - -size_t -mpz_size (const mpz_t u) -{ - return GMP_ABS (u->_mp_size); -} - -mp_limb_t -mpz_getlimbn (const mpz_t u, mp_size_t n) -{ - if (n >= 0 && n < GMP_ABS (u->_mp_size)) - return u->_mp_d[n]; - else - return 0; -} - -void -mpz_realloc2 (mpz_t x, mp_bitcnt_t n) -{ - mpz_realloc (x, 1 + (n - (n != 0)) / GMP_LIMB_BITS); -} - -mp_srcptr -mpz_limbs_read (mpz_srcptr x) -{ - return x->_mp_d; -} - -mp_ptr -mpz_limbs_modify (mpz_t x, mp_size_t n) -{ - assert (n > 0); - return MPZ_REALLOC (x, n); -} - -mp_ptr -mpz_limbs_write (mpz_t x, mp_size_t n) -{ - return mpz_limbs_modify (x, n); -} - -void -mpz_limbs_finish (mpz_t x, mp_size_t xs) -{ - mp_size_t xn; - xn = mpn_normalized_size (x->_mp_d, GMP_ABS (xs)); - x->_mp_size = xs < 0 ? -xn : xn; -} - -mpz_srcptr -mpz_roinit_n (mpz_t x, mp_srcptr xp, mp_size_t xs) -{ - x->_mp_alloc = 0; - x->_mp_d = (mp_ptr) xp; - mpz_limbs_finish (x, xs); - return x; -} - - -/* Conversions and comparison to double. */ -void -mpz_set_d (mpz_t r, double x) -{ - int sign; - mp_ptr rp; - mp_size_t rn, i; - double B; - double Bi; - mp_limb_t f; - - /* x != x is true when x is a NaN, and x == x * 0.5 is true when x is - zero or infinity. */ - if (x != x || x == x * 0.5) - { - r->_mp_size = 0; - return; - } - - sign = x < 0.0 ; - if (sign) - x = - x; - - if (x < 1.0) - { - r->_mp_size = 0; - return; - } - B = 2.0 * (double) GMP_LIMB_HIGHBIT; - Bi = 1.0 / B; - for (rn = 1; x >= B; rn++) - x *= Bi; - - rp = MPZ_REALLOC (r, rn); - - f = (mp_limb_t) x; - x -= f; - assert (x < 1.0); - i = rn-1; - rp[i] = f; - while (--i >= 0) - { - x = B * x; - f = (mp_limb_t) x; - x -= f; - assert (x < 1.0); - rp[i] = f; - } - - r->_mp_size = sign ? - rn : rn; -} - -void -mpz_init_set_d (mpz_t r, double x) -{ - mpz_init (r); - mpz_set_d (r, x); -} - -double -mpz_get_d (const mpz_t u) -{ - mp_size_t un; - double x; - double B = 2.0 * (double) GMP_LIMB_HIGHBIT; - - un = GMP_ABS (u->_mp_size); - - if (un == 0) - return 0.0; - - x = u->_mp_d[--un]; - while (un > 0) - x = B*x + u->_mp_d[--un]; - - if (u->_mp_size < 0) - x = -x; - - return x; -} - -int -mpz_cmpabs_d (const mpz_t x, double d) -{ - mp_size_t xn; - double B, Bi; - mp_size_t i; - - xn = x->_mp_size; - d = GMP_ABS (d); - - if (xn != 0) - { - xn = GMP_ABS (xn); - - B = 2.0 * (double) GMP_LIMB_HIGHBIT; - Bi = 1.0 / B; - - /* Scale d so it can be compared with the top limb. */ - for (i = 1; i < xn; i++) - d *= Bi; - - if (d >= B) - return -1; - - /* Compare floor(d) to top limb, subtract and cancel when equal. */ - for (i = xn; i-- > 0;) - { - mp_limb_t f, xl; - - f = (mp_limb_t) d; - xl = x->_mp_d[i]; - if (xl > f) - return 1; - else if (xl < f) - return -1; - d = B * (d - f); - } - } - return - (d > 0.0); -} - -int -mpz_cmp_d (const mpz_t x, double d) -{ - if (x->_mp_size < 0) - { - if (d >= 0.0) - return -1; - else - return -mpz_cmpabs_d (x, d); - } - else - { - if (d < 0.0) - return 1; - else - return mpz_cmpabs_d (x, d); - } -} - - -/* MPZ comparisons and the like. */ -int -mpz_sgn (const mpz_t u) -{ - return GMP_CMP (u->_mp_size, 0); -} - -int -mpz_cmp_si (const mpz_t u, intMpz v) -{ - mp_size_t usize = u->_mp_size; - - if (usize < -1) - return -1; - else if (v >= 0) - return mpz_cmp_ui (u, v); - else if (usize >= 0) - return 1; - else /* usize == -1 */ - return GMP_CMP (GMP_NEG_CAST (mp_limb_t, v), u->_mp_d[0]); -} - -int -mpz_cmp_ui (const mpz_t u, uIntMpz v) -{ - mp_size_t usize = u->_mp_size; - - if (usize > 1) - return 1; - else if (usize < 0) - return -1; - else - return GMP_CMP (mpz_get_ui (u), v); -} - -int -mpz_cmp (const mpz_t a, const mpz_t b) -{ - mp_size_t asize = a->_mp_size; - mp_size_t bsize = b->_mp_size; - - if (asize != bsize) - return (asize < bsize) ? -1 : 1; - else if (asize >= 0) - return mpn_cmp (a->_mp_d, b->_mp_d, asize); - else - return mpn_cmp (b->_mp_d, a->_mp_d, -asize); -} - -int -mpz_cmpabs_ui (const mpz_t u, uIntMpz v) -{ - if (GMP_ABS (u->_mp_size) > 1) - return 1; - else - return GMP_CMP (mpz_get_ui (u), v); -} - -int -mpz_cmpabs (const mpz_t u, const mpz_t v) -{ - return mpn_cmp4 (u->_mp_d, GMP_ABS (u->_mp_size), - v->_mp_d, GMP_ABS (v->_mp_size)); -} - -void -mpz_abs (mpz_t r, const mpz_t u) -{ - mpz_set (r, u); - r->_mp_size = GMP_ABS (r->_mp_size); -} - -void -mpz_neg (mpz_t r, const mpz_t u) -{ - mpz_set (r, u); - r->_mp_size = -r->_mp_size; -} - -void -mpz_swap (mpz_t u, mpz_t v) -{ - MP_SIZE_T_SWAP (u->_mp_size, v->_mp_size); - MP_SIZE_T_SWAP (u->_mp_alloc, v->_mp_alloc); - MP_PTR_SWAP (u->_mp_d, v->_mp_d); -} - - -/* MPZ addition and subtraction */ - -/* Adds to the absolute value. Returns new size, but doesn't store it. */ -static mp_size_t -mpz_abs_add_ui (mpz_t r, const mpz_t a, uIntMpz b) -{ - mp_size_t an; - mp_ptr rp; - mp_limb_t cy; - - an = GMP_ABS (a->_mp_size); - if (an == 0) - { - MPZ_REALLOC (r, 1)[0] = b; - return b > 0; - } - - rp = MPZ_REALLOC (r, an + 1); - - cy = mpn_add_1 (rp, a->_mp_d, an, b); - rp[an] = cy; - an += cy; - - return an; -} - -/* Subtract from the absolute value. Returns new size, (or -1 on underflow), - but doesn't store it. */ -static mp_size_t -mpz_abs_sub_ui (mpz_t r, const mpz_t a, uIntMpz b) -{ - mp_size_t an = GMP_ABS (a->_mp_size); - mp_ptr rp; - - if (an == 0) - { - MPZ_REALLOC (r, 1)[0] = b; - return -(b > 0); - } - rp = MPZ_REALLOC (r, an); - if (an == 1 && a->_mp_d[0] < b) - { - rp[0] = b - a->_mp_d[0]; - return -1; - } - else - { - gmp_assert_nocarry (mpn_sub_1 (rp, a->_mp_d, an, b)); - return mpn_normalized_size (rp, an); - } -} - -void -mpz_add_ui (mpz_t r, const mpz_t a, uIntMpz b) -{ - if (a->_mp_size >= 0) - r->_mp_size = mpz_abs_add_ui (r, a, b); - else - r->_mp_size = -mpz_abs_sub_ui (r, a, b); -} - -void -mpz_sub_ui (mpz_t r, const mpz_t a, uIntMpz b) -{ - if (a->_mp_size < 0) - r->_mp_size = -mpz_abs_add_ui (r, a, b); - else - r->_mp_size = mpz_abs_sub_ui (r, a, b); -} - -void -mpz_ui_sub (mpz_t r, uIntMpz a, const mpz_t b) -{ - if (b->_mp_size < 0) - r->_mp_size = mpz_abs_add_ui (r, b, a); - else - r->_mp_size = -mpz_abs_sub_ui (r, b, a); -} - -static mp_size_t -mpz_abs_add (mpz_t r, const mpz_t a, const mpz_t b) -{ - mp_size_t an = GMP_ABS (a->_mp_size); - mp_size_t bn = GMP_ABS (b->_mp_size); - mp_ptr rp; - mp_limb_t cy; - - if (an < bn) - { - MPZ_SRCPTR_SWAP (a, b); - MP_SIZE_T_SWAP (an, bn); - } - - rp = MPZ_REALLOC (r, an + 1); - cy = mpn_add (rp, a->_mp_d, an, b->_mp_d, bn); - - rp[an] = cy; - - return an + cy; -} - -static mp_size_t -mpz_abs_sub (mpz_t r, const mpz_t a, const mpz_t b) -{ - mp_size_t an = GMP_ABS (a->_mp_size); - mp_size_t bn = GMP_ABS (b->_mp_size); - int cmp; - mp_ptr rp; - - cmp = mpn_cmp4 (a->_mp_d, an, b->_mp_d, bn); - if (cmp > 0) - { - rp = MPZ_REALLOC (r, an); - gmp_assert_nocarry (mpn_sub (rp, a->_mp_d, an, b->_mp_d, bn)); - return mpn_normalized_size (rp, an); - } - else if (cmp < 0) - { - rp = MPZ_REALLOC (r, bn); - gmp_assert_nocarry (mpn_sub (rp, b->_mp_d, bn, a->_mp_d, an)); - return -mpn_normalized_size (rp, bn); - } - else - return 0; -} - -void -mpz_add (mpz_t r, const mpz_t a, const mpz_t b) -{ - mp_size_t rn; - - if ( (a->_mp_size ^ b->_mp_size) >= 0) - rn = mpz_abs_add (r, a, b); - else - rn = mpz_abs_sub (r, a, b); - - r->_mp_size = a->_mp_size >= 0 ? rn : - rn; -} - -void -mpz_sub (mpz_t r, const mpz_t a, const mpz_t b) -{ - mp_size_t rn; - - if ( (a->_mp_size ^ b->_mp_size) >= 0) - rn = mpz_abs_sub (r, a, b); - else - rn = mpz_abs_add (r, a, b); - - r->_mp_size = a->_mp_size >= 0 ? rn : - rn; -} - - -/* MPZ multiplication */ -void -mpz_mul_si (mpz_t r, const mpz_t u, intMpz v) -{ - if (v < 0) - { - mpz_mul_ui (r, u, GMP_NEG_CAST (uIntMpz, v)); - mpz_neg (r, r); - } - else - mpz_mul_ui (r, u, (uIntMpz) v); -} - -void -mpz_mul_ui (mpz_t r, const mpz_t u, uIntMpz v) -{ - mp_size_t un, us; - mp_ptr tp; - mp_limb_t cy; - - us = u->_mp_size; - - if (us == 0 || v == 0) - { - r->_mp_size = 0; - return; - } - - un = GMP_ABS (us); - - tp = MPZ_REALLOC (r, un + 1); - cy = mpn_mul_1 (tp, u->_mp_d, un, v); - tp[un] = cy; - - un += (cy > 0); - r->_mp_size = (us < 0) ? - un : un; -} - -void -mpz_mul (mpz_t r, const mpz_t u, const mpz_t v) -{ - int sign; - mp_size_t un, vn, rn; - mpz_t t; - mp_ptr tp; - - un = u->_mp_size; - vn = v->_mp_size; - - if (un == 0 || vn == 0) - { - r->_mp_size = 0; - return; - } - - sign = (un ^ vn) < 0; - - un = GMP_ABS (un); - vn = GMP_ABS (vn); - - mpz_init2 (t, (un + vn) * GMP_LIMB_BITS); - - tp = t->_mp_d; - if (un >= vn) - mpn_mul (tp, u->_mp_d, un, v->_mp_d, vn); - else - mpn_mul (tp, v->_mp_d, vn, u->_mp_d, un); - - rn = un + vn; - rn -= tp[rn-1] == 0; - - t->_mp_size = sign ? - rn : rn; - mpz_swap (r, t); - mpz_clear (t); -} - -void -mpz_mul_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t bits) -{ - mp_size_t un, rn; - mp_size_t limbs; - unsigned shift; - mp_ptr rp; - - un = GMP_ABS (u->_mp_size); - if (un == 0) - { - r->_mp_size = 0; - return; - } - - limbs = bits / GMP_LIMB_BITS; - shift = bits % GMP_LIMB_BITS; - - rn = un + limbs + (shift > 0); - rp = MPZ_REALLOC (r, rn); - if (shift > 0) - { - mp_limb_t cy = mpn_lshift (rp + limbs, u->_mp_d, un, shift); - rp[rn-1] = cy; - rn -= (cy == 0); - } - else - mpn_copyd (rp + limbs, u->_mp_d, un); - - mpn_zero (rp, limbs); - - r->_mp_size = (u->_mp_size < 0) ? - rn : rn; -} - -void -mpz_addmul_ui (mpz_t r, const mpz_t u, uIntMpz v) -{ - mpz_t t; - mpz_init (t); - mpz_mul_ui (t, u, v); - mpz_add (r, r, t); - mpz_clear (t); -} - -void -mpz_submul_ui (mpz_t r, const mpz_t u, uIntMpz v) -{ - mpz_t t; - mpz_init (t); - mpz_mul_ui (t, u, v); - mpz_sub (r, r, t); - mpz_clear (t); -} - -void -mpz_addmul (mpz_t r, const mpz_t u, const mpz_t v) -{ - mpz_t t; - mpz_init (t); - mpz_mul (t, u, v); - mpz_add (r, r, t); - mpz_clear (t); -} - -void -mpz_submul (mpz_t r, const mpz_t u, const mpz_t v) -{ - mpz_t t; - mpz_init (t); - mpz_mul (t, u, v); - mpz_sub (r, r, t); - mpz_clear (t); -} - - -/* MPZ division */ -enum mpz_div_round_mode { GMP_DIV_FLOOR, GMP_DIV_CEIL, GMP_DIV_TRUNC }; - -/* Allows q or r to be zero. Returns 1 iff remainder is non-zero. */ -static int -mpz_div_qr (mpz_t q, mpz_t r, - const mpz_t n, const mpz_t d, enum mpz_div_round_mode mode) -{ - mp_size_t ns, ds, nn, dn, qs; - ns = n->_mp_size; - ds = d->_mp_size; - - if (ds == 0) - gmp_die("mpz_div_qr: Divide by zero."); - - if (ns == 0) - { - if (q) - q->_mp_size = 0; - if (r) - r->_mp_size = 0; - return 0; - } - - nn = GMP_ABS (ns); - dn = GMP_ABS (ds); - - qs = ds ^ ns; - - if (nn < dn) - { - if (mode == GMP_DIV_CEIL && qs >= 0) - { - /* q = 1, r = n - d */ - if (r) - mpz_sub (r, n, d); - if (q) - mpz_set_ui (q, 1); - } - else if (mode == GMP_DIV_FLOOR && qs < 0) - { - /* q = -1, r = n + d */ - if (r) - mpz_add (r, n, d); - if (q) - mpz_set_si (q, -1); - } - else - { - /* q = 0, r = d */ - if (r) - mpz_set (r, n); - if (q) - q->_mp_size = 0; - } - return 1; - } - else - { - mp_ptr np, qp; - mp_size_t qn, rn; - mpz_t tq, tr; - - mpz_init_set (tr, n); - np = tr->_mp_d; - - qn = nn - dn + 1; - - if (q) - { - mpz_init2 (tq, qn * GMP_LIMB_BITS); - qp = tq->_mp_d; - } - else - qp = NULL; - - mpn_div_qr (qp, np, nn, d->_mp_d, dn); - - if (qp) - { - qn -= (qp[qn-1] == 0); - - tq->_mp_size = qs < 0 ? -qn : qn; - } - rn = mpn_normalized_size (np, dn); - tr->_mp_size = ns < 0 ? - rn : rn; - - if (mode == GMP_DIV_FLOOR && qs < 0 && rn != 0) - { - if (q) - mpz_sub_ui (tq, tq, 1); - if (r) - mpz_add (tr, tr, d); - } - else if (mode == GMP_DIV_CEIL && qs >= 0 && rn != 0) - { - if (q) - mpz_add_ui (tq, tq, 1); - if (r) - mpz_sub (tr, tr, d); - } - - if (q) - { - mpz_swap (tq, q); - mpz_clear (tq); - } - if (r) - mpz_swap (tr, r); - - mpz_clear (tr); - - return rn != 0; - } -} - -void -mpz_cdiv_qr (mpz_t q, mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, r, n, d, GMP_DIV_CEIL); -} - -void -mpz_fdiv_qr (mpz_t q, mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, r, n, d, GMP_DIV_FLOOR); -} - -void -mpz_tdiv_qr (mpz_t q, mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, r, n, d, GMP_DIV_TRUNC); -} - -void -mpz_cdiv_q (mpz_t q, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, NULL, n, d, GMP_DIV_CEIL); -} - -void -mpz_fdiv_q (mpz_t q, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, NULL, n, d, GMP_DIV_FLOOR); -} - -void -mpz_tdiv_q (mpz_t q, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (q, NULL, n, d, GMP_DIV_TRUNC); -} - -void -mpz_cdiv_r (mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (NULL, r, n, d, GMP_DIV_CEIL); -} - -void -mpz_fdiv_r (mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (NULL, r, n, d, GMP_DIV_FLOOR); -} - -void -mpz_tdiv_r (mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (NULL, r, n, d, GMP_DIV_TRUNC); -} - -void -mpz_mod (mpz_t r, const mpz_t n, const mpz_t d) -{ - mpz_div_qr (NULL, r, n, d, d->_mp_size >= 0 ? GMP_DIV_FLOOR : GMP_DIV_CEIL); -} - -static void -mpz_div_q_2exp (mpz_t q, const mpz_t u, mp_bitcnt_t bit_index, - enum mpz_div_round_mode mode) -{ - mp_size_t un, qn; - mp_size_t limb_cnt; - mp_ptr qp; - int adjust; - - un = u->_mp_size; - if (un == 0) - { - q->_mp_size = 0; - return; - } - limb_cnt = bit_index / GMP_LIMB_BITS; - qn = GMP_ABS (un) - limb_cnt; - bit_index %= GMP_LIMB_BITS; - - if (mode == ((un > 0) ? GMP_DIV_CEIL : GMP_DIV_FLOOR)) /* un != 0 here. */ - /* Note: Below, the final indexing at limb_cnt is valid because at - that point we have qn > 0. */ - adjust = (qn <= 0 - || !mpn_zero_p (u->_mp_d, limb_cnt) - || (u->_mp_d[limb_cnt] - & (((mp_limb_t) 1 << bit_index) - 1))); - else - adjust = 0; - - if (qn <= 0) - qn = 0; - else - { - qp = MPZ_REALLOC (q, qn); - - if (bit_index != 0) - { - mpn_rshift (qp, u->_mp_d + limb_cnt, qn, bit_index); - qn -= qp[qn - 1] == 0; - } - else - { - mpn_copyi (qp, u->_mp_d + limb_cnt, qn); - } - } - - q->_mp_size = qn; - - if (adjust) - mpz_add_ui (q, q, 1); - if (un < 0) - mpz_neg (q, q); -} - -static void -mpz_div_r_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t bit_index, - enum mpz_div_round_mode mode) -{ - mp_size_t us, un, rn; - mp_ptr rp; - mp_limb_t mask; - - us = u->_mp_size; - if (us == 0 || bit_index == 0) - { - r->_mp_size = 0; - return; - } - rn = (bit_index + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS; - assert (rn > 0); - - rp = MPZ_REALLOC (r, rn); - un = GMP_ABS (us); - - mask = GMP_LIMB_MAX >> (rn * GMP_LIMB_BITS - bit_index); - - if (rn > un) - { - /* Quotient (with truncation) is zero, and remainder is - non-zero */ - if (mode == ((us > 0) ? GMP_DIV_CEIL : GMP_DIV_FLOOR)) /* us != 0 here. */ - { - /* Have to negate and sign extend. */ - mp_size_t i; - - gmp_assert_nocarry (! mpn_neg (rp, u->_mp_d, un)); - for (i = un; i < rn - 1; i++) - rp[i] = GMP_LIMB_MAX; - - rp[rn-1] = mask; - us = -us; - } - else - { - /* Just copy */ - if (r != u) - mpn_copyi (rp, u->_mp_d, un); - - rn = un; - } - } - else - { - if (r != u) - mpn_copyi (rp, u->_mp_d, rn - 1); - - rp[rn-1] = u->_mp_d[rn-1] & mask; - - if (mode == ((us > 0) ? GMP_DIV_CEIL : GMP_DIV_FLOOR)) /* us != 0 here. */ - { - /* If r != 0, compute 2^{bit_count} - r. */ - mpn_neg (rp, rp, rn); - - rp[rn-1] &= mask; - - /* us is not used for anything else, so we can modify it - here to indicate flipped sign. */ - us = -us; - } - } - rn = mpn_normalized_size (rp, rn); - r->_mp_size = us < 0 ? -rn : rn; -} - -void -mpz_cdiv_q_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_q_2exp (r, u, cnt, GMP_DIV_CEIL); -} - -void -mpz_fdiv_q_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_q_2exp (r, u, cnt, GMP_DIV_FLOOR); -} - -void -mpz_tdiv_q_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_q_2exp (r, u, cnt, GMP_DIV_TRUNC); -} - -void -mpz_cdiv_r_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_r_2exp (r, u, cnt, GMP_DIV_CEIL); -} - -void -mpz_fdiv_r_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_r_2exp (r, u, cnt, GMP_DIV_FLOOR); -} - -void -mpz_tdiv_r_2exp (mpz_t r, const mpz_t u, mp_bitcnt_t cnt) -{ - mpz_div_r_2exp (r, u, cnt, GMP_DIV_TRUNC); -} - -void -mpz_divexact (mpz_t q, const mpz_t n, const mpz_t d) -{ - gmp_assert_nocarry (mpz_div_qr (q, NULL, n, d, GMP_DIV_TRUNC)); -} - -int -mpz_divisible_p (const mpz_t n, const mpz_t d) -{ - return mpz_div_qr (NULL, NULL, n, d, GMP_DIV_TRUNC) == 0; -} - -int -mpz_congruent_p (const mpz_t a, const mpz_t b, const mpz_t m) -{ - mpz_t t; - int res; - - /* a == b (mod 0) iff a == b */ - if (mpz_sgn (m) == 0) - return (mpz_cmp (a, b) == 0); - - mpz_init (t); - mpz_sub (t, a, b); - res = mpz_divisible_p (t, m); - mpz_clear (t); - - return res; -} - -static uIntMpz -mpz_div_qr_ui (mpz_t q, mpz_t r, - const mpz_t n, uIntMpz d, enum mpz_div_round_mode mode) -{ - mp_size_t ns, qn; - mp_ptr qp; - mp_limb_t rl; - mp_size_t rs; - - ns = n->_mp_size; - if (ns == 0) - { - if (q) - q->_mp_size = 0; - if (r) - r->_mp_size = 0; - return 0; - } - - qn = GMP_ABS (ns); - if (q) - qp = MPZ_REALLOC (q, qn); - else - qp = NULL; - - rl = mpn_div_qr_1 (qp, n->_mp_d, qn, d); - assert (rl < d); - - rs = rl > 0; - rs = (ns < 0) ? -rs : rs; - - if (rl > 0 && ( (mode == GMP_DIV_FLOOR && ns < 0) - || (mode == GMP_DIV_CEIL && ns >= 0))) - { - if (q) - gmp_assert_nocarry (mpn_add_1 (qp, qp, qn, 1)); - rl = d - rl; - rs = -rs; - } - - if (r) - { - MPZ_REALLOC (r, 1)[0] = rl; - r->_mp_size = rs; - } - if (q) - { - qn -= (qp[qn-1] == 0); - assert (qn == 0 || qp[qn-1] > 0); - - q->_mp_size = (ns < 0) ? - qn : qn; - } - - return rl; -} - -uIntMpz -mpz_cdiv_qr_ui (mpz_t q, mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, r, n, d, GMP_DIV_CEIL); -} - -uIntMpz -mpz_fdiv_qr_ui (mpz_t q, mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, r, n, d, GMP_DIV_FLOOR); -} - -uIntMpz -mpz_tdiv_qr_ui (mpz_t q, mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, r, n, d, GMP_DIV_TRUNC); -} - -uIntMpz -mpz_cdiv_q_ui (mpz_t q, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, NULL, n, d, GMP_DIV_CEIL); -} - -uIntMpz -mpz_fdiv_q_ui (mpz_t q, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, NULL, n, d, GMP_DIV_FLOOR); -} - -uIntMpz -mpz_tdiv_q_ui (mpz_t q, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (q, NULL, n, d, GMP_DIV_TRUNC); -} - -uIntMpz -mpz_cdiv_r_ui (mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, r, n, d, GMP_DIV_CEIL); -} -uIntMpz -mpz_fdiv_r_ui (mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, r, n, d, GMP_DIV_FLOOR); -} -uIntMpz -mpz_tdiv_r_ui (mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, r, n, d, GMP_DIV_TRUNC); -} - -uIntMpz -mpz_cdiv_ui (const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, NULL, n, d, GMP_DIV_CEIL); -} - -uIntMpz -mpz_fdiv_ui (const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, NULL, n, d, GMP_DIV_FLOOR); -} - -uIntMpz -mpz_tdiv_ui (const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, NULL, n, d, GMP_DIV_TRUNC); -} - -uIntMpz -mpz_mod_ui (mpz_t r, const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, r, n, d, GMP_DIV_FLOOR); -} - -void -mpz_divexact_ui (mpz_t q, const mpz_t n, uIntMpz d) -{ - gmp_assert_nocarry (mpz_div_qr_ui (q, NULL, n, d, GMP_DIV_TRUNC)); -} - -int -mpz_divisible_ui_p (const mpz_t n, uIntMpz d) -{ - return mpz_div_qr_ui (NULL, NULL, n, d, GMP_DIV_TRUNC) == 0; -} - - -/* GCD */ -static mp_limb_t -mpn_gcd_11 (mp_limb_t u, mp_limb_t v) -{ - unsigned shift; - - assert ( (u | v) > 0); - - if (u == 0) - return v; - else if (v == 0) - return u; - - gmp_ctz (shift, u | v); - - u >>= shift; - v >>= shift; - - if ( (u & 1) == 0) - MP_LIMB_T_SWAP (u, v); - - while ( (v & 1) == 0) - v >>= 1; - - while (u != v) - { - if (u > v) - { - u -= v; - do - u >>= 1; - while ( (u & 1) == 0); - } - else - { - v -= u; - do - v >>= 1; - while ( (v & 1) == 0); - } - } - return u << shift; -} - -uIntMpz -mpz_gcd_ui (mpz_t g, const mpz_t u, uIntMpz v) -{ - mp_size_t un; - - if (v == 0) - { - if (g) - mpz_abs (g, u); - } - else - { - un = GMP_ABS (u->_mp_size); - if (un != 0) - v = mpn_gcd_11 (mpn_div_qr_1 (NULL, u->_mp_d, un, v), v); - - if (g) - mpz_set_ui (g, v); - } - - return v; -} - -static mp_bitcnt_t -mpz_make_odd (mpz_t r) -{ - mp_bitcnt_t shift; - - assert (r->_mp_size > 0); - /* Count trailing zeros, equivalent to mpn_scan1, because we know that there is a 1 */ - shift = mpn_common_scan (r->_mp_d[0], 0, r->_mp_d, 0, 0); - mpz_tdiv_q_2exp (r, r, shift); - - return shift; -} - -void -mpz_gcd (mpz_t g, const mpz_t u, const mpz_t v) -{ - mpz_t tu, tv; - mp_bitcnt_t uz, vz, gz; - - if (u->_mp_size == 0) - { - mpz_abs (g, v); - return; - } - if (v->_mp_size == 0) - { - mpz_abs (g, u); - return; - } - - mpz_init (tu); - mpz_init (tv); - - mpz_abs (tu, u); - uz = mpz_make_odd (tu); - mpz_abs (tv, v); - vz = mpz_make_odd (tv); - gz = GMP_MIN (uz, vz); - - if (tu->_mp_size < tv->_mp_size) - mpz_swap (tu, tv); - - mpz_tdiv_r (tu, tu, tv); - if (tu->_mp_size == 0) - { - mpz_swap (g, tv); - } - else - for (;;) - { - int c; - - mpz_make_odd (tu); - c = mpz_cmp (tu, tv); - if (c == 0) - { - mpz_swap (g, tu); - break; - } - if (c < 0) - mpz_swap (tu, tv); - - if (tv->_mp_size == 1) - { - mp_limb_t vl = tv->_mp_d[0]; - mp_limb_t ul = mpz_tdiv_ui (tu, vl); - mpz_set_ui (g, mpn_gcd_11 (ul, vl)); - break; - } - mpz_sub (tu, tu, tv); - } - mpz_clear (tu); - mpz_clear (tv); - mpz_mul_2exp (g, g, gz); -} - -void -mpz_gcdext (mpz_t g, mpz_t s, mpz_t t, const mpz_t u, const mpz_t v) -{ - mpz_t tu, tv, s0, s1, t0, t1; - mp_bitcnt_t uz, vz, gz; - mp_bitcnt_t power; - - if (u->_mp_size == 0) - { - /* g = 0 u + sgn(v) v */ - intMpz sign = mpz_sgn (v); - mpz_abs (g, v); - if (s) - mpz_set_ui (s, 0); - if (t) - mpz_set_si (t, sign); - return; - } - - if (v->_mp_size == 0) - { - /* g = sgn(u) u + 0 v */ - intMpz sign = mpz_sgn (u); - mpz_abs (g, u); - if (s) - mpz_set_si (s, sign); - if (t) - mpz_set_ui (t, 0); - return; - } - - mpz_init (tu); - mpz_init (tv); - mpz_init (s0); - mpz_init (s1); - mpz_init (t0); - mpz_init (t1); - - mpz_abs (tu, u); - uz = mpz_make_odd (tu); - mpz_abs (tv, v); - vz = mpz_make_odd (tv); - gz = GMP_MIN (uz, vz); - - uz -= gz; - vz -= gz; - - /* Cofactors corresponding to odd gcd. gz handled later. */ - if (tu->_mp_size < tv->_mp_size) - { - mpz_swap (tu, tv); - MPZ_SRCPTR_SWAP (u, v); - MPZ_PTR_SWAP (s, t); - MP_BITCNT_T_SWAP (uz, vz); - } - - /* Maintain - * - * u = t0 tu + t1 tv - * v = s0 tu + s1 tv - * - * where u and v denote the inputs with common factors of two - * eliminated, and det (s0, t0; s1, t1) = 2^p. Then - * - * 2^p tu = s1 u - t1 v - * 2^p tv = -s0 u + t0 v - */ - - /* After initial division, tu = q tv + tu', we have - * - * u = 2^uz (tu' + q tv) - * v = 2^vz tv - * - * or - * - * t0 = 2^uz, t1 = 2^uz q - * s0 = 0, s1 = 2^vz - */ - - mpz_setbit (t0, uz); - mpz_tdiv_qr (t1, tu, tu, tv); - mpz_mul_2exp (t1, t1, uz); - - mpz_setbit (s1, vz); - power = uz + vz; - - if (tu->_mp_size > 0) - { - mp_bitcnt_t shift; - shift = mpz_make_odd (tu); - mpz_mul_2exp (t0, t0, shift); - mpz_mul_2exp (s0, s0, shift); - power += shift; - - for (;;) - { - int c; - c = mpz_cmp (tu, tv); - if (c == 0) - break; - - if (c < 0) - { - /* tv = tv' + tu - * - * u = t0 tu + t1 (tv' + tu) = (t0 + t1) tu + t1 tv' - * v = s0 tu + s1 (tv' + tu) = (s0 + s1) tu + s1 tv' */ - - mpz_sub (tv, tv, tu); - mpz_add (t0, t0, t1); - mpz_add (s0, s0, s1); - - shift = mpz_make_odd (tv); - mpz_mul_2exp (t1, t1, shift); - mpz_mul_2exp (s1, s1, shift); - } - else - { - mpz_sub (tu, tu, tv); - mpz_add (t1, t0, t1); - mpz_add (s1, s0, s1); - - shift = mpz_make_odd (tu); - mpz_mul_2exp (t0, t0, shift); - mpz_mul_2exp (s0, s0, shift); - } - power += shift; - } - } - - /* Now tv = odd part of gcd, and -s0 and t0 are corresponding - cofactors. */ - - mpz_mul_2exp (tv, tv, gz); - mpz_neg (s0, s0); - - /* 2^p g = s0 u + t0 v. Eliminate one factor of two at a time. To - adjust cofactors, we need u / g and v / g */ - - mpz_divexact (s1, v, tv); - mpz_abs (s1, s1); - mpz_divexact (t1, u, tv); - mpz_abs (t1, t1); - - while (power-- > 0) - { - /* s0 u + t0 v = (s0 - v/g) u - (t0 + u/g) v */ - if (mpz_odd_p (s0) || mpz_odd_p (t0)) - { - mpz_sub (s0, s0, s1); - mpz_add (t0, t0, t1); - } - mpz_divexact_ui (s0, s0, 2); - mpz_divexact_ui (t0, t0, 2); - } - - /* Arrange so that |s| < |u| / 2g */ - mpz_add (s1, s0, s1); - if (mpz_cmpabs (s0, s1) > 0) - { - mpz_swap (s0, s1); - mpz_sub (t0, t0, t1); - } - if (u->_mp_size < 0) - mpz_neg (s0, s0); - if (v->_mp_size < 0) - mpz_neg (t0, t0); - - mpz_swap (g, tv); - if (s) - mpz_swap (s, s0); - if (t) - mpz_swap (t, t0); - - mpz_clear (tu); - mpz_clear (tv); - mpz_clear (s0); - mpz_clear (s1); - mpz_clear (t0); - mpz_clear (t1); -} - -void -mpz_lcm (mpz_t r, const mpz_t u, const mpz_t v) -{ - mpz_t g; - - if (u->_mp_size == 0 || v->_mp_size == 0) - { - r->_mp_size = 0; - return; - } - - mpz_init (g); - - mpz_gcd (g, u, v); - mpz_divexact (g, u, g); - mpz_mul (r, g, v); - - mpz_clear (g); - mpz_abs (r, r); -} - -void -mpz_lcm_ui (mpz_t r, const mpz_t u, uIntMpz v) -{ - if (v == 0 || u->_mp_size == 0) - { - r->_mp_size = 0; - return; - } - - v /= mpz_gcd_ui (NULL, u, v); - mpz_mul_ui (r, u, v); - - mpz_abs (r, r); -} - -int -mpz_invert (mpz_t r, const mpz_t u, const mpz_t m) -{ - mpz_t g, tr; - int invertible; - - if (u->_mp_size == 0 || mpz_cmpabs_ui (m, 1) <= 0) - return 0; - - mpz_init (g); - mpz_init (tr); - - mpz_gcdext (g, tr, NULL, u, m); - invertible = (mpz_cmp_ui (g, 1) == 0); - - if (invertible) - { - if (tr->_mp_size < 0) - { - if (m->_mp_size >= 0) - mpz_add (tr, tr, m); - else - mpz_sub (tr, tr, m); - } - mpz_swap (r, tr); - } - - mpz_clear (g); - mpz_clear (tr); - return invertible; -} - - -/* Higher level operations (sqrt, pow and root) */ - -void -mpz_pow_ui (mpz_t r, const mpz_t b, uIntMpz e) -{ - uIntMpz bit; - mpz_t tr; - mpz_init_set_ui (tr, 1); - - bit = GMP_ULONG_HIGHBIT; - do - { - mpz_mul (tr, tr, tr); - if (e & bit) - mpz_mul (tr, tr, b); - bit >>= 1; - } - while (bit > 0); - - mpz_swap (r, tr); - mpz_clear (tr); -} - -void -mpz_ui_pow_ui (mpz_t r, uIntMpz blimb, uIntMpz e) -{ - mpz_t b; - mpz_pow_ui (r, mpz_roinit_n (b, &blimb, 1), e); -} - -void -mpz_powm (mpz_t r, const mpz_t b, const mpz_t e, const mpz_t m) -{ - mpz_t tr; - mpz_t base; - mp_size_t en, mn; - mp_srcptr mp; - struct gmp_div_inverse minv; - unsigned shift; - mp_ptr tp = NULL; - - en = GMP_ABS (e->_mp_size); - mn = GMP_ABS (m->_mp_size); - if (mn == 0) - gmp_die ("mpz_powm: Zero modulo."); - - if (en == 0) - { - mpz_set_ui (r, 1); - return; - } - - mp = m->_mp_d; - mpn_div_qr_invert (&minv, mp, mn); - shift = minv.shift; - - if (shift > 0) - { - /* To avoid shifts, we do all our reductions, except the final - one, using a *normalized* m. */ - minv.shift = 0; - - tp = gmp_xalloc_limbs (mn); - gmp_assert_nocarry (mpn_lshift (tp, mp, mn, shift)); - mp = tp; - } - - mpz_init (base); - - if (e->_mp_size < 0) - { - if (!mpz_invert (base, b, m)) - gmp_die ("mpz_powm: Negative exponent and non-invertible base."); - } - else - { - mp_size_t bn; - mpz_abs (base, b); - - bn = base->_mp_size; - if (bn >= mn) - { - mpn_div_qr_preinv (NULL, base->_mp_d, base->_mp_size, mp, mn, &minv); - bn = mn; - } - - /* We have reduced the absolute value. Now take care of the - sign. Note that we get zero represented non-canonically as - m. */ - if (b->_mp_size < 0) - { - mp_ptr bp = MPZ_REALLOC (base, mn); - gmp_assert_nocarry (mpn_sub (bp, mp, mn, bp, bn)); - bn = mn; - } - base->_mp_size = mpn_normalized_size (base->_mp_d, bn); - } - mpz_init_set_ui (tr, 1); - - while (--en >= 0) - { - mp_limb_t w = e->_mp_d[en]; - mp_limb_t bit; - - bit = GMP_LIMB_HIGHBIT; - do - { - mpz_mul (tr, tr, tr); - if (w & bit) - mpz_mul (tr, tr, base); - if (tr->_mp_size > mn) - { - mpn_div_qr_preinv (NULL, tr->_mp_d, tr->_mp_size, mp, mn, &minv); - tr->_mp_size = mpn_normalized_size (tr->_mp_d, mn); - } - bit >>= 1; - } - while (bit > 0); - } - - /* Final reduction */ - if (tr->_mp_size >= mn) - { - minv.shift = shift; - mpn_div_qr_preinv (NULL, tr->_mp_d, tr->_mp_size, mp, mn, &minv); - tr->_mp_size = mpn_normalized_size (tr->_mp_d, mn); - } - if (tp) - gmp_free (tp); - - mpz_swap (r, tr); - mpz_clear (tr); - mpz_clear (base); -} - -void -mpz_powm_ui (mpz_t r, const mpz_t b, uIntMpz elimb, const mpz_t m) -{ - mpz_t e; - mpz_powm (r, b, mpz_roinit_n (e, &elimb, 1), m); -} - -/* x=trunc(y^(1/z)), r=y-x^z */ -void -mpz_rootrem (mpz_t x, mpz_t r, const mpz_t y, uIntMpz z) -{ - int sgn; - mpz_t t, u; - - sgn = y->_mp_size < 0; - if ((~z & sgn) != 0) - gmp_die ("mpz_rootrem: Negative argument, with even root."); - if (z == 0) - gmp_die ("mpz_rootrem: Zeroth root."); - - if (mpz_cmpabs_ui (y, 1) <= 0) { - if (x) - mpz_set (x, y); - if (r) - r->_mp_size = 0; - return; - } - - mpz_init (u); - mpz_init (t); - mpz_setbit (t, mpz_sizeinbase (y, 2) / z + 1); - - if (z == 2) /* simplify sqrt loop: z-1 == 1 */ - do { - mpz_swap (u, t); /* u = x */ - mpz_tdiv_q (t, y, u); /* t = y/x */ - mpz_add (t, t, u); /* t = y/x + x */ - mpz_tdiv_q_2exp (t, t, 1); /* x'= (y/x + x)/2 */ - } while (mpz_cmpabs (t, u) < 0); /* |x'| < |x| */ - else /* z != 2 */ { - mpz_t v; - - mpz_init (v); - if (sgn) - mpz_neg (t, t); - - do { - mpz_swap (u, t); /* u = x */ - mpz_pow_ui (t, u, z - 1); /* t = x^(z-1) */ - mpz_tdiv_q (t, y, t); /* t = y/x^(z-1) */ - mpz_mul_ui (v, u, z - 1); /* v = x*(z-1) */ - mpz_add (t, t, v); /* t = y/x^(z-1) + x*(z-1) */ - mpz_tdiv_q_ui (t, t, z); /* x'=(y/x^(z-1) + x*(z-1))/z */ - } while (mpz_cmpabs (t, u) < 0); /* |x'| < |x| */ - - mpz_clear (v); - } - - if (r) { - mpz_pow_ui (t, u, z); - mpz_sub (r, y, t); - } - if (x) - mpz_swap (x, u); - mpz_clear (u); - mpz_clear (t); -} - -int -mpz_root (mpz_t x, const mpz_t y, uIntMpz z) -{ - int res; - mpz_t r; - - mpz_init (r); - mpz_rootrem (x, r, y, z); - res = r->_mp_size == 0; - mpz_clear (r); - - return res; -} - -/* Compute s = floor(sqrt(u)) and r = u - s^2. Allows r == NULL */ -void -mpz_sqrtrem (mpz_t s, mpz_t r, const mpz_t u) -{ - mpz_rootrem (s, r, u, 2); -} - -void -mpz_sqrt (mpz_t s, const mpz_t u) -{ - mpz_rootrem (s, NULL, u, 2); -} - -int -mpz_perfect_square_p (const mpz_t u) -{ - if (u->_mp_size <= 0) - return (u->_mp_size == 0); - else - return mpz_root (NULL, u, 2); -} - -int -mpn_perfect_square_p (mp_srcptr p, mp_size_t n) -{ - mpz_t t; - - assert (n > 0); - assert (p [n-1] != 0); - return mpz_root (NULL, mpz_roinit_n (t, p, n), 2); -} - -mp_size_t -mpn_sqrtrem (mp_ptr sp, mp_ptr rp, mp_srcptr p, mp_size_t n) -{ - mpz_t s, r, u; - mp_size_t res; - - assert (n > 0); - assert (p [n-1] != 0); - - mpz_init (r); - mpz_init (s); - mpz_rootrem (s, r, mpz_roinit_n (u, p, n), 2); - - assert (s->_mp_size == (n+1)/2); - mpn_copyd (sp, s->_mp_d, s->_mp_size); - mpz_clear (s); - res = r->_mp_size; - if (rp) - mpn_copyd (rp, r->_mp_d, res); - mpz_clear (r); - return res; -} - -/* Combinatorics */ - -void -mpz_fac_ui (mpz_t x, uIntMpz n) -{ - mpz_set_ui (x, n + (n == 0)); - while (n > 2) - mpz_mul_ui (x, x, --n); -} - -void -mpz_bin_uiui (mpz_t r, uIntMpz n, uIntMpz k) -{ - mpz_t t; - - mpz_set_ui (r, k <= n); - - if (k > (n >> 1)) - k = (k <= n) ? n - k : 0; - - mpz_init (t); - mpz_fac_ui (t, k); - - for (; k > 0; k--) - mpz_mul_ui (r, r, n--); - - mpz_divexact (r, r, t); - mpz_clear (t); -} - - -/* Primality testing */ -static int -gmp_millerrabin (const mpz_t n, const mpz_t nm1, mpz_t y, - const mpz_t q, mp_bitcnt_t k) -{ - assert (k > 0); - - /* Caller must initialize y to the base. */ - mpz_powm (y, y, q, n); - - if (mpz_cmp_ui (y, 1) == 0 || mpz_cmp (y, nm1) == 0) - return 1; - - while (--k > 0) - { - mpz_powm_ui (y, y, 2, n); - if (mpz_cmp (y, nm1) == 0) - return 1; - /* y == 1 means that the previous y was a non-trivial square root - of 1 (mod n). y == 0 means that n is a power of the base. - In either case, n is not prime. */ - if (mpz_cmp_ui (y, 1) <= 0) - return 0; - } - return 0; -} - -/* This product is 0xc0cfd797, and fits in 32 bits. */ -#define GMP_PRIME_PRODUCT \ - (3UL*5UL*7UL*11UL*13UL*17UL*19UL*23UL*29UL) - -/* Bit (p+1)/2 is set, for each odd prime <= 61 */ -#define GMP_PRIME_MASK 0xc96996dcUL - -int -mpz_probab_prime_p (const mpz_t n, int reps) -{ - mpz_t nm1; - mpz_t q; - mpz_t y; - mp_bitcnt_t k; - int is_prime; - int j; - - /* Note that we use the absolute value of n only, for compatibility - with the real GMP. */ - if (mpz_even_p (n)) - return (mpz_cmpabs_ui (n, 2) == 0) ? 2 : 0; - - /* Above test excludes n == 0 */ - assert (n->_mp_size != 0); - - if (mpz_cmpabs_ui (n, 64) < 0) - return (GMP_PRIME_MASK >> (n->_mp_d[0] >> 1)) & 2; - - if (mpz_gcd_ui (NULL, n, GMP_PRIME_PRODUCT) != 1) - return 0; - - /* All prime factors are >= 31. */ - if (mpz_cmpabs_ui (n, 31*31) < 0) - return 2; - - /* Use Miller-Rabin, with a deterministic sequence of bases, a[j] = - j^2 + j + 41 using Euler's polynomial. We potentially stop early, - if a[j] >= n - 1. Since n >= 31*31, this can happen only if reps > - 30 (a[30] == 971 > 31*31 == 961). */ - - mpz_init (nm1); - mpz_init (q); - mpz_init (y); - - /* Find q and k, where q is odd and n = 1 + 2**k * q. */ - nm1->_mp_size = mpz_abs_sub_ui (nm1, n, 1); - k = mpz_scan1 (nm1, 0); - mpz_tdiv_q_2exp (q, nm1, k); - - for (j = 0, is_prime = 1; is_prime & (j < reps); j++) - { - mpz_set_ui (y, (uIntMpz) j*j+j+41); - if (mpz_cmp (y, nm1) >= 0) - { - /* Don't try any further bases. This "early" break does not affect - the result for any reasonable reps value (<=5000 was tested) */ - assert (j >= 30); - break; - } - is_prime = gmp_millerrabin (n, nm1, y, q, k); - } - mpz_clear (nm1); - mpz_clear (q); - mpz_clear (y); - - return is_prime; -} - - -/* Logical operations and bit manipulation. */ - -/* Numbers are treated as if represented in two's complement (and - infinitely sign extended). For a negative values we get the two's - complement from -x = ~x + 1, where ~ is bitwise complement. - Negation transforms - - xxxx10...0 - - into - - yyyy10...0 - - where yyyy is the bitwise complement of xxxx. So least significant - bits, up to and including the first one bit, are unchanged, and - the more significant bits are all complemented. - - To change a bit from zero to one in a negative number, subtract the - corresponding power of two from the absolute value. This can never - underflow. To change a bit from one to zero, add the corresponding - power of two, and this might overflow. E.g., if x = -001111, the - two's complement is 110001. Clearing the least significant bit, we - get two's complement 110000, and -010000. */ - -int -mpz_tstbit (const mpz_t d, mp_bitcnt_t bit_index) -{ - mp_size_t limb_index; - unsigned shift; - mp_size_t ds; - mp_size_t dn; - mp_limb_t w; - int bit; - - ds = d->_mp_size; - dn = GMP_ABS (ds); - limb_index = bit_index / GMP_LIMB_BITS; - if (limb_index >= dn) - return ds < 0; - - shift = bit_index % GMP_LIMB_BITS; - w = d->_mp_d[limb_index]; - bit = (w >> shift) & 1; - - if (ds < 0) - { - /* d < 0. Check if any of the bits below is set: If so, our bit - must be complemented. */ - if (shift > 0 && (w << (GMP_LIMB_BITS - shift)) > 0) - return bit ^ 1; - while (--limb_index >= 0) - if (d->_mp_d[limb_index] > 0) - return bit ^ 1; - } - return bit; -} - -static void -mpz_abs_add_bit (mpz_t d, mp_bitcnt_t bit_index) -{ - mp_size_t dn, limb_index; - mp_limb_t bit; - mp_ptr dp; - - dn = GMP_ABS (d->_mp_size); - - limb_index = bit_index / GMP_LIMB_BITS; - bit = (mp_limb_t) 1 << (bit_index % GMP_LIMB_BITS); - - if (limb_index >= dn) - { - mp_size_t i; - /* The bit should be set outside of the end of the number. - We have to increase the size of the number. */ - dp = MPZ_REALLOC (d, limb_index + 1); - - dp[limb_index] = bit; - for (i = dn; i < limb_index; i++) - dp[i] = 0; - dn = limb_index + 1; - } - else - { - mp_limb_t cy; - - dp = d->_mp_d; - - cy = mpn_add_1 (dp + limb_index, dp + limb_index, dn - limb_index, bit); - if (cy > 0) - { - dp = MPZ_REALLOC (d, dn + 1); - dp[dn++] = cy; - } - } - - d->_mp_size = (d->_mp_size < 0) ? - dn : dn; -} - -static void -mpz_abs_sub_bit (mpz_t d, mp_bitcnt_t bit_index) -{ - mp_size_t dn, limb_index; - mp_ptr dp; - mp_limb_t bit; - - dn = GMP_ABS (d->_mp_size); - dp = d->_mp_d; - - limb_index = bit_index / GMP_LIMB_BITS; - bit = (mp_limb_t) 1 << (bit_index % GMP_LIMB_BITS); - - assert (limb_index < dn); - - gmp_assert_nocarry (mpn_sub_1 (dp + limb_index, dp + limb_index, - dn - limb_index, bit)); - dn = mpn_normalized_size (dp, dn); - d->_mp_size = (d->_mp_size < 0) ? - dn : dn; -} - -void -mpz_setbit (mpz_t d, mp_bitcnt_t bit_index) -{ - if (!mpz_tstbit (d, bit_index)) - { - if (d->_mp_size >= 0) - mpz_abs_add_bit (d, bit_index); - else - mpz_abs_sub_bit (d, bit_index); - } -} - -void -mpz_clrbit (mpz_t d, mp_bitcnt_t bit_index) -{ - if (mpz_tstbit (d, bit_index)) - { - if (d->_mp_size >= 0) - mpz_abs_sub_bit (d, bit_index); - else - mpz_abs_add_bit (d, bit_index); - } -} - -void -mpz_combit (mpz_t d, mp_bitcnt_t bit_index) -{ - if (mpz_tstbit (d, bit_index) ^ (d->_mp_size < 0)) - mpz_abs_sub_bit (d, bit_index); - else - mpz_abs_add_bit (d, bit_index); -} - -void -mpz_com (mpz_t r, const mpz_t u) -{ - mpz_neg (r, u); - mpz_sub_ui (r, r, 1); -} - -void -mpz_and (mpz_t r, const mpz_t u, const mpz_t v) -{ - mp_size_t un, vn, rn, i; - mp_ptr up, vp, rp; - - mp_limb_t ux, vx, rx; - mp_limb_t uc, vc, rc; - mp_limb_t ul, vl, rl; - - un = GMP_ABS (u->_mp_size); - vn = GMP_ABS (v->_mp_size); - if (un < vn) - { - MPZ_SRCPTR_SWAP (u, v); - MP_SIZE_T_SWAP (un, vn); - } - if (vn == 0) - { - r->_mp_size = 0; - return; - } - - uc = u->_mp_size < 0; - vc = v->_mp_size < 0; - rc = uc & vc; - - ux = -uc; - vx = -vc; - rx = -rc; - - /* If the smaller input is positive, higher limbs don't matter. */ - rn = vx ? un : vn; - - rp = MPZ_REALLOC (r, rn + (mp_size_t) rc); - - up = u->_mp_d; - vp = v->_mp_d; - - i = 0; - do - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - vl = (vp[i] ^ vx) + vc; - vc = vl < vc; - - rl = ( (ul & vl) ^ rx) + rc; - rc = rl < rc; - rp[i] = rl; - } - while (++i < vn); - assert (vc == 0); - - for (; i < rn; i++) - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - rl = ( (ul & vx) ^ rx) + rc; - rc = rl < rc; - rp[i] = rl; - } - if (rc) - rp[rn++] = rc; - else - rn = mpn_normalized_size (rp, rn); - - r->_mp_size = rx ? -rn : rn; -} - -void -mpz_ior (mpz_t r, const mpz_t u, const mpz_t v) -{ - mp_size_t un, vn, rn, i; - mp_ptr up, vp, rp; - - mp_limb_t ux, vx, rx; - mp_limb_t uc, vc, rc; - mp_limb_t ul, vl, rl; - - un = GMP_ABS (u->_mp_size); - vn = GMP_ABS (v->_mp_size); - if (un < vn) - { - MPZ_SRCPTR_SWAP (u, v); - MP_SIZE_T_SWAP (un, vn); - } - if (vn == 0) - { - mpz_set (r, u); - return; - } - - uc = u->_mp_size < 0; - vc = v->_mp_size < 0; - rc = uc | vc; - - ux = -uc; - vx = -vc; - rx = -rc; - - /* If the smaller input is negative, by sign extension higher limbs - don't matter. */ - rn = vx ? vn : un; - - rp = MPZ_REALLOC (r, rn + (mp_size_t) rc); - - up = u->_mp_d; - vp = v->_mp_d; - - i = 0; - do - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - vl = (vp[i] ^ vx) + vc; - vc = vl < vc; - - rl = ( (ul | vl) ^ rx) + rc; - rc = rl < rc; - rp[i] = rl; - } - while (++i < vn); - assert (vc == 0); - - for (; i < rn; i++) - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - rl = ( (ul | vx) ^ rx) + rc; - rc = rl < rc; - rp[i] = rl; - } - if (rc) - rp[rn++] = rc; - else - rn = mpn_normalized_size (rp, rn); - - r->_mp_size = rx ? -rn : rn; -} - -void -mpz_xor (mpz_t r, const mpz_t u, const mpz_t v) -{ - mp_size_t un, vn, i; - mp_ptr up, vp, rp; - - mp_limb_t ux, vx, rx; - mp_limb_t uc, vc, rc; - mp_limb_t ul, vl, rl; - - un = GMP_ABS (u->_mp_size); - vn = GMP_ABS (v->_mp_size); - if (un < vn) - { - MPZ_SRCPTR_SWAP (u, v); - MP_SIZE_T_SWAP (un, vn); - } - if (vn == 0) - { - mpz_set (r, u); - return; - } - - uc = u->_mp_size < 0; - vc = v->_mp_size < 0; - rc = uc ^ vc; - - ux = -uc; - vx = -vc; - rx = -rc; - - rp = MPZ_REALLOC (r, un + (mp_size_t) rc); - - up = u->_mp_d; - vp = v->_mp_d; - - i = 0; - do - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - vl = (vp[i] ^ vx) + vc; - vc = vl < vc; - - rl = (ul ^ vl ^ rx) + rc; - rc = rl < rc; - rp[i] = rl; - } - while (++i < vn); - assert (vc == 0); - - for (; i < un; i++) - { - ul = (up[i] ^ ux) + uc; - uc = ul < uc; - - rl = (ul ^ ux) + rc; - rc = rl < rc; - rp[i] = rl; - } - if (rc) - rp[un++] = rc; - else - un = mpn_normalized_size (rp, un); - - r->_mp_size = rx ? -un : un; -} - -static unsigned -gmp_popcount_limb (mp_limb_t x) -{ - unsigned c; - - /* Do 16 bits at a time, to avoid limb-sized constants. */ - for (c = 0; x > 0; x >>= 16) - { - unsigned w = ((x >> 1) & 0x5555) + (x & 0x5555); - w = ((w >> 2) & 0x3333) + (w & 0x3333); - w = ((w >> 4) & 0x0f0f) + (w & 0x0f0f); - w = (w >> 8) + (w & 0x00ff); - c += w; - } - return c; -} - -mp_bitcnt_t -mpn_popcount (mp_srcptr p, mp_size_t n) -{ - mp_size_t i; - mp_bitcnt_t c; - - for (c = 0, i = 0; i < n; i++) - c += gmp_popcount_limb (p[i]); - - return c; -} - -mp_bitcnt_t -mpz_popcount (const mpz_t u) -{ - mp_size_t un; - - un = u->_mp_size; - - if (un < 0) - return ~(mp_bitcnt_t) 0; - - return mpn_popcount (u->_mp_d, un); -} - -mp_bitcnt_t -mpz_hamdist (const mpz_t u, const mpz_t v) -{ - mp_size_t un, vn, i; - mp_limb_t uc, vc, ul, vl, comp; - mp_srcptr up, vp; - mp_bitcnt_t c; - - un = u->_mp_size; - vn = v->_mp_size; - - if ( (un ^ vn) < 0) - return ~(mp_bitcnt_t) 0; - - comp = - (uc = vc = (un < 0)); - if (uc) - { - assert (vn < 0); - un = -un; - vn = -vn; - } - - up = u->_mp_d; - vp = v->_mp_d; - - if (un < vn) - MPN_SRCPTR_SWAP (up, un, vp, vn); - - for (i = 0, c = 0; i < vn; i++) - { - ul = (up[i] ^ comp) + uc; - uc = ul < uc; - - vl = (vp[i] ^ comp) + vc; - vc = vl < vc; - - c += gmp_popcount_limb (ul ^ vl); - } - assert (vc == 0); - - for (; i < un; i++) - { - ul = (up[i] ^ comp) + uc; - uc = ul < uc; - - c += gmp_popcount_limb (ul ^ comp); - } - - return c; -} - -mp_bitcnt_t -mpz_scan1 (const mpz_t u, mp_bitcnt_t starting_bit) -{ - mp_ptr up; - mp_size_t us, un, i; - mp_limb_t limb, ux; - - us = u->_mp_size; - un = GMP_ABS (us); - i = starting_bit / GMP_LIMB_BITS; - - /* Past the end there's no 1 bits for u>=0, or an immediate 1 bit - for u<0. Notice this test picks up any u==0 too. */ - if (i >= un) - return (us >= 0 ? ~(mp_bitcnt_t) 0 : starting_bit); - - up = u->_mp_d; - ux = 0; - limb = up[i]; - - if (starting_bit != 0) - { - if (us < 0) - { - ux = mpn_zero_p (up, i); - limb = ~ limb + ux; - ux = - (mp_limb_t) (limb >= ux); - } - - /* Mask to 0 all bits before starting_bit, thus ignoring them. */ - limb &= (GMP_LIMB_MAX << (starting_bit % GMP_LIMB_BITS)); - } - - return mpn_common_scan (limb, i, up, un, ux); -} - -mp_bitcnt_t -mpz_scan0 (const mpz_t u, mp_bitcnt_t starting_bit) -{ - mp_ptr up; - mp_size_t us, un, i; - mp_limb_t limb, ux; - - us = u->_mp_size; - ux = - (mp_limb_t) (us >= 0); - un = GMP_ABS (us); - i = starting_bit / GMP_LIMB_BITS; - - /* When past end, there's an immediate 0 bit for u>=0, or no 0 bits for - u<0. Notice this test picks up all cases of u==0 too. */ - if (i >= un) - return (ux ? starting_bit : ~(mp_bitcnt_t) 0); - - up = u->_mp_d; - limb = up[i] ^ ux; - - if (ux == 0) - limb -= mpn_zero_p (up, i); /* limb = ~(~limb + zero_p) */ - - /* Mask all bits before starting_bit, thus ignoring them. */ - limb &= (GMP_LIMB_MAX << (starting_bit % GMP_LIMB_BITS)); - - return mpn_common_scan (limb, i, up, un, ux); -} - - -/* MPZ base conversion. */ - -size_t -mpz_sizeinbase (const mpz_t u, int base) -{ - mp_size_t un; - mp_srcptr up; - mp_ptr tp; - mp_bitcnt_t bits; - struct gmp_div_inverse bi; - size_t ndigits; - - assert (base >= 2); - assert (base <= 36); - - un = GMP_ABS (u->_mp_size); - if (un == 0) - return 1; - - up = u->_mp_d; - - bits = (un - 1) * GMP_LIMB_BITS + mpn_limb_size_in_base_2 (up[un-1]); - switch (base) - { - case 2: - return bits; - case 4: - return (bits + 1) / 2; - case 8: - return (bits + 2) / 3; - case 16: - return (bits + 3) / 4; - case 32: - return (bits + 4) / 5; - /* FIXME: Do something more clever for the common case of base - 10. */ - } - - tp = gmp_xalloc_limbs (un); - mpn_copyi (tp, up, un); - mpn_div_qr_1_invert (&bi, base); - - ndigits = 0; - do - { - ndigits++; - mpn_div_qr_1_preinv (tp, tp, un, &bi); - un -= (tp[un-1] == 0); - } - while (un > 0); - - gmp_free (tp); - return ndigits; -} - -char * -mpz_get_str (char *sp, int base, const mpz_t u) -{ - unsigned bits; - const char *digits; - mp_size_t un; - size_t i, sn; - - if (base >= 0) - { - digits = "0123456789abcdefghijklmnopqrstuvwxyz"; - } - else - { - base = -base; - digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - } - if (base <= 1) - base = 10; - if (base > 36) - return NULL; - - sn = 1 + mpz_sizeinbase (u, base); - if (!sp) - sp = (char *) gmp_xalloc (1 + sn); - - un = GMP_ABS (u->_mp_size); - - if (un == 0) - { - sp[0] = '0'; - sp[1] = '\0'; - return sp; - } - - i = 0; - - if (u->_mp_size < 0) - sp[i++] = '-'; - - bits = mpn_base_power_of_two_p (base); - - if (bits) - /* Not modified in this case. */ - sn = i + mpn_get_str_bits ((unsigned char *) sp + i, bits, u->_mp_d, un); - else - { - struct mpn_base_info info; - mp_ptr tp; - - mpn_get_base_info (&info, base); - tp = gmp_xalloc_limbs (un); - mpn_copyi (tp, u->_mp_d, un); - - sn = i + mpn_get_str_other ((unsigned char *) sp + i, base, &info, tp, un); - gmp_free (tp); - } - - for (; i < sn; i++) - sp[i] = digits[(unsigned char) sp[i]]; - - sp[sn] = '\0'; - return sp; -} - -int -mpz_set_str (mpz_t r, const char *sp, int base) -{ - unsigned bits; - mp_size_t rn, alloc; - mp_ptr rp; - size_t dn; - int sign; - unsigned char *dp; - - assert (base == 0 || (base >= 2 && base <= 36)); - - while (isspace( (unsigned char) *sp)) - sp++; - - sign = (*sp == '-'); - sp += sign; - - if (base == 0) - { - if (sp[0] == '0') - { - if (sp[1] == 'x' || sp[1] == 'X') - { - base = 16; - sp += 2; - } - else if (sp[1] == 'b' || sp[1] == 'B') - { - base = 2; - sp += 2; - } - else - base = 8; - } - else - base = 10; - } - - if (!*sp) - { - r->_mp_size = 0; - return -1; - } - dp = (unsigned char *) gmp_xalloc (strlen (sp)); - - for (dn = 0; *sp; sp++) - { - unsigned digit; - - if (isspace ((unsigned char) *sp)) - continue; - else if (*sp >= '0' && *sp <= '9') - digit = *sp - '0'; - else if (*sp >= 'a' && *sp <= 'z') - digit = *sp - 'a' + 10; - else if (*sp >= 'A' && *sp <= 'Z') - digit = *sp - 'A' + 10; - else - digit = base; /* fail */ - - if (digit >= (unsigned) base) - { - gmp_free (dp); - r->_mp_size = 0; - return -1; - } - - dp[dn++] = digit; - } - - if (!dn) - { - gmp_free (dp); - r->_mp_size = 0; - return -1; - } - bits = mpn_base_power_of_two_p (base); - - if (bits > 0) - { - alloc = (dn * bits + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS; - rp = MPZ_REALLOC (r, alloc); - rn = mpn_set_str_bits (rp, dp, dn, bits); - } - else - { - struct mpn_base_info info; - mpn_get_base_info (&info, base); - alloc = (dn + info.exp - 1) / info.exp; - rp = MPZ_REALLOC (r, alloc); - rn = mpn_set_str_other (rp, dp, dn, base, &info); - /* Normalization, needed for all-zero input. */ - assert (rn > 0); - rn -= rp[rn-1] == 0; - } - assert (rn <= alloc); - gmp_free (dp); - - r->_mp_size = sign ? - rn : rn; - - return 0; -} - -int -mpz_init_set_str (mpz_t r, const char *sp, int base) -{ - mpz_init (r); - return mpz_set_str (r, sp, base); -} - -size_t -mpz_out_str (FILE *stream, int base, const mpz_t x) -{ - char *str; - size_t len; - - str = mpz_get_str (NULL, base, x); - len = strlen (str); - len = fwrite (str, 1, len, stream); - gmp_free (str); - return len; -} - - -static int -gmp_detect_endian (void) -{ - static const int i = 2; - const unsigned char *p = (const unsigned char *) &i; - return 1 - *p; -} - -/* Import and export. Does not support nails. */ -void -mpz_import (mpz_t r, size_t count, int order, size_t size, int endian, - size_t nails, const void *src) -{ - const unsigned char *p; - ptrdiff_t word_step; - mp_ptr rp; - mp_size_t rn; - - /* The current (partial) limb. */ - mp_limb_t limb; - /* The number of bytes already copied to this limb (starting from - the low end). */ - size_t bytes; - /* The index where the limb should be stored, when completed. */ - mp_size_t i; - - if (nails != 0) - gmp_die ("mpz_import: Nails not supported."); - - assert (order == 1 || order == -1); - assert (endian >= -1 && endian <= 1); - - if (endian == 0) - endian = gmp_detect_endian (); - - p = (unsigned char *) src; - - word_step = (order != endian) ? 2 * size : 0; - - /* Process bytes from the least significant end, so point p at the - least significant word. */ - if (order == 1) - { - p += size * (count - 1); - word_step = - word_step; - } - - /* And at least significant byte of that word. */ - if (endian == 1) - p += (size - 1); - - rn = (size * count + sizeof(mp_limb_t) - 1) / sizeof(mp_limb_t); - rp = MPZ_REALLOC (r, rn); - - for (limb = 0, bytes = 0, i = 0; count > 0; count--, p += word_step) - { - size_t j; - for (j = 0; j < size; j++, p -= (ptrdiff_t) endian) - { - limb |= (mp_limb_t) *p << (bytes++ * CHAR_BIT); - if (bytes == sizeof(mp_limb_t)) - { - rp[i++] = limb; - bytes = 0; - limb = 0; - } - } - } - assert (i + (bytes > 0) == rn); - if (limb != 0) - rp[i++] = limb; - else - i = mpn_normalized_size (rp, i); - - r->_mp_size = i; -} - -void * -mpz_export (void *r, size_t *countp, int order, size_t size, int endian, - size_t nails, const mpz_t u) -{ - size_t count; - mp_size_t un; - - if (nails != 0) - gmp_die ("mpz_import: Nails not supported."); - - assert (order == 1 || order == -1); - assert (endian >= -1 && endian <= 1); - assert (size > 0 || u->_mp_size == 0); - - un = u->_mp_size; - count = 0; - if (un != 0) - { - size_t k; - unsigned char *p; - ptrdiff_t word_step; - /* The current (partial) limb. */ - mp_limb_t limb; - /* The number of bytes left to to in this limb. */ - size_t bytes; - /* The index where the limb was read. */ - mp_size_t i; - - un = GMP_ABS (un); - - /* Count bytes in top limb. */ - limb = u->_mp_d[un-1]; - assert (limb != 0); - - k = 0; - do { - k++; limb >>= CHAR_BIT; - } while (limb != 0); - - count = (k + (un-1) * sizeof (mp_limb_t) + size - 1) / size; - - if (!r) - r = gmp_xalloc (count * size); - - if (endian == 0) - endian = gmp_detect_endian (); - - p = (unsigned char *) r; - - word_step = (order != endian) ? 2 * size : 0; - - /* Process bytes from the least significant end, so point p at the - least significant word. */ - if (order == 1) - { - p += size * (count - 1); - word_step = - word_step; - } - - /* And at least significant byte of that word. */ - if (endian == 1) - p += (size - 1); - - for (bytes = 0, i = 0, k = 0; k < count; k++, p += word_step) - { - size_t j; - for (j = 0; j < size; j++, p -= (ptrdiff_t) endian) - { - if (bytes == 0) - { - if (i < un) - limb = u->_mp_d[i++]; - bytes = sizeof (mp_limb_t); - } - *p = limb; - limb >>= CHAR_BIT; - bytes--; - } - } - assert (i == un); - assert (k == count); - } - - if (countp) - *countp = count; - - return r; -} diff --git a/Qt-Secret/GMP/mini-gmp.h b/Qt-Secret/GMP/mini-gmp.h deleted file mode 100644 index 44ef5f5..0000000 --- a/Qt-Secret/GMP/mini-gmp.h +++ /dev/null @@ -1,303 +0,0 @@ -/* mini-gmp, a minimalistic implementation of a GNU GMP subset. - -Copyright 2011-2015 Free Software Foundation, Inc. - -This file is part of the GNU MP Library. - -The GNU MP Library is free software; you can redistribute it and/or modify -it under the terms of either: - - * the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at your - option) any later version. - -or - - * the GNU General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any - later version. - -or both in parallel, as here. - -The GNU MP Library 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 General Public License -for more details. - -You should have received copies of the GNU General Public License and the -GNU Lesser General Public License along with the GNU MP Library. If not, -see https://www.gnu.org/licenses/. */ - -/* About mini-gmp: This is a minimal implementation of a subset of the - GMP interface. It is intended for inclusion into applications which - have modest bignums needs, as a fallback when the real GMP library - is not installed. - - This file defines the public interface. */ - -#ifndef MINI_GMP -#define MINI_GMP - -/* For size_t */ -#include - -#if defined (__cplusplus) -extern "C" { -#endif - -#define UN_USED(X) (void)X - -void mp_set_memory_functions (void *(*) (size_t), - void *(*) (void *, size_t, size_t), - void (*) (void *, size_t)); - -void mp_get_memory_functions (void *(**) (size_t), - void *(**) (void *, size_t, size_t), - void (**) (void *, size_t)); - -typedef unsigned long long uIntMpz; -typedef long long intMpz; - -typedef uIntMpz mp_limb_t; -typedef intMpz mp_size_t; -typedef uIntMpz mp_bitcnt_t; - -typedef mp_limb_t *mp_ptr; -typedef const mp_limb_t *mp_srcptr; - -typedef struct -{ - int _mp_alloc; /* Number of *limbs* allocated and pointed - to by the _mp_d field. */ - int _mp_size; /* abs(_mp_size) is the number of limbs the - last field points to. If _mp_size is - negative this is a negative number. */ - mp_limb_t *_mp_d; /* Pointer to the limbs. */ -} __mpz_struct; - -typedef __mpz_struct mpz_t[1]; - -typedef __mpz_struct *mpz_ptr; -typedef const __mpz_struct *mpz_srcptr; - -extern const int mp_bits_per_limb; - -void mpn_copyi (mp_ptr, mp_srcptr, mp_size_t); -void mpn_copyd (mp_ptr, mp_srcptr, mp_size_t); -void mpn_zero (mp_ptr, mp_size_t); - -int mpn_cmp (mp_srcptr, mp_srcptr, mp_size_t); -int mpn_zero_p (mp_srcptr, mp_size_t); - -mp_limb_t mpn_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); -mp_limb_t mpn_add_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); -mp_limb_t mpn_add (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); - -mp_limb_t mpn_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); -mp_limb_t mpn_sub_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); -mp_limb_t mpn_sub (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); - -mp_limb_t mpn_mul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); -mp_limb_t mpn_addmul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); -mp_limb_t mpn_submul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); - -mp_limb_t mpn_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); -void mpn_mul_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); -void mpn_sqr (mp_ptr, mp_srcptr, mp_size_t); -int mpn_perfect_square_p (mp_srcptr, mp_size_t); -mp_size_t mpn_sqrtrem (mp_ptr, mp_ptr, mp_srcptr, mp_size_t); - -mp_limb_t mpn_lshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); -mp_limb_t mpn_rshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); - -mp_bitcnt_t mpn_scan0 (mp_srcptr, mp_bitcnt_t); -mp_bitcnt_t mpn_scan1 (mp_srcptr, mp_bitcnt_t); - -void mpn_com (mp_ptr, mp_srcptr, mp_size_t); -mp_limb_t mpn_neg (mp_ptr, mp_srcptr, mp_size_t); - -mp_bitcnt_t mpn_popcount (mp_srcptr, mp_size_t); - -mp_limb_t mpn_invert_3by2 (mp_limb_t, mp_limb_t); -#define mpn_invert_limb(x) mpn_invert_3by2 ((x), 0) - -size_t mpn_get_str (unsigned char *, int, mp_ptr, mp_size_t); -mp_size_t mpn_set_str (mp_ptr, const unsigned char *, size_t, int); - -void mpz_init (mpz_t); -void mpz_init2 (mpz_t, mp_bitcnt_t); -void mpz_clear (mpz_t); - -#define mpz_odd_p(z) (((z)->_mp_size != 0) & (int) (z)->_mp_d[0]) -#define mpz_even_p(z) (! mpz_odd_p (z)) - -int mpz_sgn (const mpz_t); -int mpz_cmp_si (const mpz_t, intMpz); -int mpz_cmp_ui (const mpz_t, uIntMpz); -int mpz_cmp (const mpz_t, const mpz_t); -int mpz_cmpabs_ui (const mpz_t, uIntMpz); -int mpz_cmpabs (const mpz_t, const mpz_t); -int mpz_cmp_d (const mpz_t, double); -int mpz_cmpabs_d (const mpz_t, double); - -void mpz_abs (mpz_t, const mpz_t); -void mpz_neg (mpz_t, const mpz_t); -void mpz_swap (mpz_t, mpz_t); - -void mpz_add_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_add (mpz_t, const mpz_t, const mpz_t); -void mpz_sub_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_ui_sub (mpz_t, uIntMpz, const mpz_t); -void mpz_sub (mpz_t, const mpz_t, const mpz_t); - -void mpz_mul_si (mpz_t, const mpz_t, intMpz); -void mpz_mul_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_mul (mpz_t, const mpz_t, const mpz_t); -void mpz_mul_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_addmul_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_addmul (mpz_t, const mpz_t, const mpz_t); -void mpz_submul_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_submul (mpz_t, const mpz_t, const mpz_t); - -void mpz_cdiv_qr (mpz_t, mpz_t, const mpz_t, const mpz_t); -void mpz_fdiv_qr (mpz_t, mpz_t, const mpz_t, const mpz_t); -void mpz_tdiv_qr (mpz_t, mpz_t, const mpz_t, const mpz_t); -void mpz_cdiv_q (mpz_t, const mpz_t, const mpz_t); -void mpz_fdiv_q (mpz_t, const mpz_t, const mpz_t); -void mpz_tdiv_q (mpz_t, const mpz_t, const mpz_t); -void mpz_cdiv_r (mpz_t, const mpz_t, const mpz_t); -void mpz_fdiv_r (mpz_t, const mpz_t, const mpz_t); -void mpz_tdiv_r (mpz_t, const mpz_t, const mpz_t); - -void mpz_cdiv_q_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_fdiv_q_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_tdiv_q_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_cdiv_r_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_fdiv_r_2exp (mpz_t, const mpz_t, mp_bitcnt_t); -void mpz_tdiv_r_2exp (mpz_t, const mpz_t, mp_bitcnt_t); - -void mpz_mod (mpz_t, const mpz_t, const mpz_t); - -void mpz_divexact (mpz_t, const mpz_t, const mpz_t); - -int mpz_divisible_p (const mpz_t, const mpz_t); -int mpz_congruent_p (const mpz_t, const mpz_t, const mpz_t); - -uIntMpz mpz_cdiv_qr_ui (mpz_t, mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_fdiv_qr_ui (mpz_t, mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_tdiv_qr_ui (mpz_t, mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_cdiv_q_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_fdiv_q_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_tdiv_q_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_cdiv_r_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_fdiv_r_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_tdiv_r_ui (mpz_t, const mpz_t, uIntMpz); -uIntMpz mpz_cdiv_ui (const mpz_t, uIntMpz); -uIntMpz mpz_fdiv_ui (const mpz_t, uIntMpz); -uIntMpz mpz_tdiv_ui (const mpz_t, uIntMpz); - -uIntMpz mpz_mod_ui (mpz_t, const mpz_t, uIntMpz); - -void mpz_divexact_ui (mpz_t, const mpz_t, uIntMpz); - -int mpz_divisible_ui_p (const mpz_t, uIntMpz); - -uIntMpz mpz_gcd_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_gcd (mpz_t, const mpz_t, const mpz_t); -void mpz_gcdext (mpz_t, mpz_t, mpz_t, const mpz_t, const mpz_t); -void mpz_lcm_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_lcm (mpz_t, const mpz_t, const mpz_t); -int mpz_invert (mpz_t, const mpz_t, const mpz_t); - -void mpz_sqrtrem (mpz_t, mpz_t, const mpz_t); -void mpz_sqrt (mpz_t, const mpz_t); -int mpz_perfect_square_p (const mpz_t); - -void mpz_pow_ui (mpz_t, const mpz_t, uIntMpz); -void mpz_ui_pow_ui (mpz_t, uIntMpz, uIntMpz); -void mpz_powm (mpz_t, const mpz_t, const mpz_t, const mpz_t); -void mpz_powm_ui (mpz_t, const mpz_t, uIntMpz, const mpz_t); - -void mpz_rootrem (mpz_t, mpz_t, const mpz_t, uIntMpz); -int mpz_root (mpz_t, const mpz_t, uIntMpz); - -void mpz_fac_ui (mpz_t, uIntMpz); -void mpz_bin_uiui (mpz_t, uIntMpz, uIntMpz); - -int mpz_probab_prime_p (const mpz_t, int); - -int mpz_tstbit (const mpz_t, mp_bitcnt_t); -void mpz_setbit (mpz_t, mp_bitcnt_t); -void mpz_clrbit (mpz_t, mp_bitcnt_t); -void mpz_combit (mpz_t, mp_bitcnt_t); - -void mpz_com (mpz_t, const mpz_t); -void mpz_and (mpz_t, const mpz_t, const mpz_t); -void mpz_ior (mpz_t, const mpz_t, const mpz_t); -void mpz_xor (mpz_t, const mpz_t, const mpz_t); - -mp_bitcnt_t mpz_popcount (const mpz_t); -mp_bitcnt_t mpz_hamdist (const mpz_t, const mpz_t); -mp_bitcnt_t mpz_scan0 (const mpz_t, mp_bitcnt_t); -mp_bitcnt_t mpz_scan1 (const mpz_t, mp_bitcnt_t); - -int mpz_fits_slong_p (const mpz_t); -int mpz_fits_ulong_p (const mpz_t); -intMpz mpz_get_si (const mpz_t); -uIntMpz mpz_get_ui (const mpz_t); -double mpz_get_d (const mpz_t); -size_t mpz_size (const mpz_t); -mp_limb_t mpz_getlimbn (const mpz_t, mp_size_t); - -void mpz_realloc2 (mpz_t, mp_bitcnt_t); -mp_srcptr mpz_limbs_read (mpz_srcptr); -mp_ptr mpz_limbs_modify (mpz_t, mp_size_t); -mp_ptr mpz_limbs_write (mpz_t, mp_size_t); -void mpz_limbs_finish (mpz_t, mp_size_t); -mpz_srcptr mpz_roinit_n (mpz_t, mp_srcptr, mp_size_t); - -#define MPZ_ROINIT_N(xp, xs) {{0, (xs),(xp) }} - -void mpz_set_si (mpz_t, intMpz); -void mpz_set_ui (mpz_t, uIntMpz); -void mpz_set (mpz_t, const mpz_t); -void mpz_set_d (mpz_t, double); - -void mpz_init_set_si (mpz_t, intMpz); -void mpz_init_set_ui (mpz_t, uIntMpz); -void mpz_init_set (mpz_t, const mpz_t); -void mpz_init_set_d (mpz_t, double); - -size_t mpz_sizeinbase (const mpz_t, int); -char *mpz_get_str (char *, int, const mpz_t); -int mpz_set_str (mpz_t, const char *, int); -int mpz_init_set_str (mpz_t, const char *, int); - -/* This long list taken from gmp.h. */ -/* For reference, "defined(EOF)" cannot be used here. In g++ 2.95.4, - defines EOF but not FILE. */ -#if defined (FILE) \ - || defined (H_STDIO) \ - || defined (_H_STDIO) /* AIX */ \ - || defined (_STDIO_H) /* glibc, Sun, SCO */ \ - || defined (_STDIO_H_) /* BSD, OSF */ \ - || defined (__STDIO_H) /* Borland */ \ - || defined (__STDIO_H__) /* IRIX */ \ - || defined (_STDIO_INCLUDED) /* HPUX */ \ - || defined (__dj_include_stdio_h_) /* DJGPP */ \ - || defined (_FILE_DEFINED) /* Microsoft */ \ - || defined (__STDIO__) /* Apple MPW MrC */ \ - || defined (_MSL_STDIO_H) /* Metrowerks */ \ - || defined (_STDIO_H_INCLUDED) /* QNX4 */ \ - || defined (_ISO_STDIO_ISO_H) /* Sun C++ */ \ - || defined (__STDIO_LOADED) /* VMS */ -size_t mpz_out_str (FILE *, int, const mpz_t); -#endif - -void mpz_import (mpz_t, size_t, int, size_t, int, size_t, const void *); -void *mpz_export (void *, size_t *, int, size_t, int, size_t, const mpz_t); - -#if defined (__cplusplus) -} -#endif -#endif /* MINI_GMP */ diff --git a/Qt-Secret/GMP/minigmp_global.h b/Qt-Secret/GMP/minigmp_global.h deleted file mode 100644 index 5757875..0000000 --- a/Qt-Secret/GMP/minigmp_global.h +++ /dev/null @@ -1,21 +0,0 @@ -//# -//# Copyright (C) 2018-2019 QuasarApp. -//# Distributed under the lgplv3 software license, see the accompanying -//# Everyone is permitted to copy and distribute verbatim copies -//# of this license document, but changing it is not allowed. -//# - -#ifndef MINIGMP_GLOBAL_H -#define MINIGMP_GLOBAL_H - -#ifdef _WIN32 -# define MINIGMPSHARED_EXPORT __declspec(dllexport) -#endif - -#ifdef linux -# define MINIGMPSHARED_EXPORT __attribute__((visibility("default"))) -#endif - - - -#endif //MINIGMP_GLOBAL_H diff --git a/Qt-Secret/LICENSE b/Qt-Secret/LICENSE deleted file mode 100644 index 65c5ca8..0000000 --- a/Qt-Secret/LICENSE +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/Qt-Secret/Qt-RSA/qrsaencryption.cpp b/Qt-Secret/Qt-RSA/qrsaencryption.cpp deleted file mode 100644 index 01a3344..0000000 --- a/Qt-Secret/Qt-RSA/qrsaencryption.cpp +++ /dev/null @@ -1,403 +0,0 @@ -//# -//# Copyright (C) 2018-2019 QuasarApp. -//# Distributed under the lgplv3 software license, see the accompanying -//# Everyone is permitted to copy and distribute verbatim copies -//# of this license document, but changing it is not allowed. -//# - -#include "qrsaencryption.h" - -#include -#include -#include -#include - -#define KEY_GEN_LIMIT 10 - -const QString SIGN_MARKER = "-SIGN-"; -const int signMarkerLength = SIGN_MARKER.length(); - -QRSAEncryption::INT eulerFunc(const QRSAEncryption::INT &p, const QRSAEncryption::INT &q) { - return (p - 1) * (q - 1); -} - -bool QRSAEncryption::isMutuallyPrime(const INT &a, const INT &b) { - if ( (!(a % 2) && !(b % 2)) - || (!(a % 3) && !(b % 3)) - || (!(a % 5) && !(b % 5)) - || (!(a % 7) && !(b % 7)) - ) return false; - - return INT().gcd(a, b) == 1; -} - -QRSAEncryption::Rsa QRSAEncryption::getBitsSize(const INT &i) const { - int rsaBits = RSA_64; - int intBits = i.sizeBits(); - - while (rsaBits < intBits) { - rsaBits *= 2; - } - - return static_cast(rsaBits); - -} - -QRSAEncryption::Rsa QRSAEncryption::getBitsSize(const QByteArray &key) const { - if (isValidRsaKey(key)) { - return static_cast(key.size() * 4); - } - - return QRSAEncryption::Rsa::Invalid; -} - -QRSAEncryption::INT QRSAEncryption::fromArray(const QByteArray &array) const { - INT res = 0; - res.fromHex(array.toHex().toStdString()); - return res; -} - -QByteArray QRSAEncryption::toArray(const INT &i, short sizeBlok) { - QByteArray res; - res = QByteArray::fromHex(QByteArray::fromStdString(i.getString(16))); - - if (sizeBlok < 0) { - return res; - } - - while (res.size() < sizeBlok) { - res.push_front(char(0)); - } - - return res.left(sizeBlok); -} - -QRSAEncryption::INT QRSAEncryption::randomNumber(bool fullFill) const { - - srand(std::chrono::duration_cast - (std::chrono::system_clock::now().time_since_epoch()).count() - % std::numeric_limits::max()); - - INT res{1}; - - if(fullFill) { - - while(res.longBits() < _rsa) { - res *= (rand() % (std::numeric_limits::max() - 1)) + 1; - } - } else { - - int longDiff = _rsa / (sizeof (int) * 8); - - while (longDiff > 0) { - longDiff--; - res *= (rand() % (std::numeric_limits::max() - 1)) + 1; - } - } - - return res; -} - -QRSAEncryption::INT QRSAEncryption::toPrime(INT n) const { - if (!(n % 2)) { - ++n; - } - - INT LN = n; - INT RN = n; - - while (true) { - - if (LN.isPrime(false)) return LN; - - RN+=2; - - if (RN.isPrime(false)) return RN; - LN-=2; - } -} - -QRSAEncryption::INT QRSAEncryption::randomPrimeNumber(INT no) const { - srand(static_cast(time(nullptr))); - - // max INT - INT max('1', _rsa / 2, 2); - - auto p = toPrime(randomNumber() % max); - while(p == no) p = toPrime(randomNumber() % max); - - return p; -} - -QRSAEncryption::INT QRSAEncryption::extEuclid(INT a, INT b) const { - INT x = 0, y = 1, u = 1, v = 0, gcd = b, m, n, q, r; - while (a != 0) { - q = gcd / a; - r = gcd % a; - m = x - u * q; - n = y - v * q; - gcd = a; - a = r; - x = u; - y = v; - u = m; - v = n; - } - return y; -} - -short QRSAEncryption::getBlockSize(INT i) const { - return static_cast(i.longBytes()) - 1; -} - -QByteArray QRSAEncryption::encodeBlok(const INT &block, const INT &e, const INT &m, short blockSize) { - - return toArray(INT::powm(block, e, m), blockSize); -} - -QByteArray QRSAEncryption::decodeBlok(const INT &block, const INT &d, const INT &m, short blockSize) { - - return toArray(INT::powm(block, d, m), blockSize); -} - -QRSAEncryption::QRSAEncryption(Rsa rsa) { - _rsa = rsa; -} - -bool QRSAEncryption::generatePairKeyS(QByteArray &pubKey, QByteArray &privKey, QRSAEncryption::Rsa rsa) { - qWarning() << "method " << Q_FUNC_INFO << - " will be deleted in newxt version. please use generatePairKey method"; - return generatePairKey(pubKey, privKey, rsa); -} - -QByteArray QRSAEncryption::encodeS(const QByteArray &rawData, const QByteArray &pubKey, QRSAEncryption::Rsa rsa, QRSAEncryption::BlockSize blockSizeMode) { - qWarning() << "method " << Q_FUNC_INFO << - " will be deleted in newxt version. please use encode method"; - return encode(rawData, pubKey, rsa, blockSizeMode); - -} - -QByteArray QRSAEncryption::decodeS(const QByteArray &rawData, const QByteArray &privKey, QRSAEncryption::Rsa rsa, QRSAEncryption::BlockSize blockSizeMode) { - qWarning() << "method " << Q_FUNC_INFO << - " will be deleted in newxt version. please use decode method"; - return decode(rawData, privKey, rsa, blockSizeMode); - -} - -QByteArray QRSAEncryption::signMessageS(QByteArray rawData, const QByteArray &privKey, QRSAEncryption::Rsa rsa) { - qWarning() << "method " << Q_FUNC_INFO << - " will be deleted in newxt version. please use signMessage method"; - return signMessage(rawData, privKey, rsa); - -} - -bool QRSAEncryption::checkSignMessageS(const QByteArray &rawData, const QByteArray &pubKey, QRSAEncryption::Rsa rsa) { - qWarning() << "method " << Q_FUNC_INFO << - " will be deleted in newxt version. please use signMessage method"; - return checkSignMessage(rawData, pubKey, rsa); -} - -unsigned int QRSAEncryption::getKeyBytesSize(QRSAEncryption::Rsa rsa) { - - return rsa / 4; -} - -// --- static methods --- -bool QRSAEncryption::generatePairKey(QByteArray &pubKey, QByteArray &privKey, - QRSAEncryption::Rsa rsa) { - - return QRSAEncryption(rsa).generatePairKey(pubKey, privKey); -} - -QByteArray QRSAEncryption::encode(const QByteArray &rawData, const QByteArray &pubKey, - Rsa rsa, BlockSize blockSizeMode) { - - return QRSAEncryption(rsa).encode(rawData, pubKey, blockSizeMode); -} - -QByteArray QRSAEncryption::decode(const QByteArray &rawData, const QByteArray &privKey, - Rsa rsa, BlockSize blockSizeMode) { - - return QRSAEncryption(rsa).decode(rawData, privKey, blockSizeMode); -} - -QByteArray QRSAEncryption::signMessage(QByteArray rawData, const QByteArray &privKey, Rsa rsa) { - - return QRSAEncryption(rsa).signMessage(rawData, privKey); -} - -bool QRSAEncryption::checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey, Rsa rsa) { - - return QRSAEncryption(rsa).checkSignMessage(rawData, pubKey); -} - -// --- end of static methods --- - -bool QRSAEncryption::generatePairKey(QByteArray &pubKey, QByteArray &privKey) { - - int cnt{0}; - bool keyGenRes{false}; - INT p, q, modul, eilor, e, d; - do { - - pubKey.clear(); - privKey.clear(); - - p = randomPrimeNumber(); - q = randomPrimeNumber(p); - - modul = 0; - while ((modul = p * q) < 0) { - p = toPrime((p - 1) / 2); - } - - eilor = eulerFunc(p, q); - e = randomNumber() % eilor; - - if (!(e % 2)) --e; - - do { - e -= 2; - } while((!isMutuallyPrime(eilor, e))); - - d = extEuclid(eilor , e); - - while(d < 0 ) { - d += eilor; - } - - pubKey.append(toArray(e, _rsa / 8)); - pubKey.append(toArray(modul, _rsa / 8)); - privKey.append(toArray(d, _rsa / 8)); - privKey.append(toArray(modul, _rsa / 8)); - - } while (!(keyGenRes = testKeyPair(pubKey, privKey)) && (++cnt < KEY_GEN_LIMIT)); - - if(cnt >= KEY_GEN_LIMIT) qWarning() << QString("(Warning): Exceeded limit of key generation (%0)!").arg(KEY_GEN_LIMIT); - - return (keyGenRes && cnt < KEY_GEN_LIMIT); -} - -// --- non-static methods --- -QByteArray QRSAEncryption::encode(const QByteArray &rawData, const QByteArray &pubKey, BlockSize blockSizeMode) { - - if (getBitsSize(pubKey) != _rsa) { - return QByteArray(); - } - - int index = 0; - - QByteArray block; - - INT e = fromArray(pubKey.mid(0, pubKey.size() / 2)); - INT m = fromArray(pubKey.mid(pubKey.size() / 2)); - - short blockSizeOut = getBlockSize(m) + 1; // BlockSize::OneByte - short blockSizeIn = 1; // BlockSize::OneByte - - if (blockSizeMode == BlockSize::Auto) { - blockSizeIn = getBlockSize(m); - } - - if (!blockSizeIn) { - qDebug() << "module of key small! size = 1 byte, 2 byte is minimum"; - return QByteArray(); - } - - QByteArray res; - - while ((block = rawData.mid(index, blockSizeIn)).size()) { - - if (index + blockSizeIn > rawData.size() && block.size() && !block[0]) { - qWarning() << "When trying to encrypt data, problems arose, the last block contains non-significant zeros." - " These zeros will be deleted during the decryption process." - " For encode and decode data with non-significant zeros use BlockSize::OneByte"; - } - - res.append(encodeBlok(fromArray(block), e, m, blockSizeOut)); - index += blockSizeIn; - } - - return res; - -} -QByteArray QRSAEncryption::decode(const QByteArray &rawData, const QByteArray &privKey, BlockSize blockSizeMode) { - - if (getBitsSize(privKey) != _rsa) { - return QByteArray(); - } - - int index = 0; - - QByteArray block; - - INT d = fromArray(privKey.mid(0, privKey.size() / 2)); - INT m = fromArray(privKey.mid(privKey.size() / 2)); - - short blockSizeIn = getBlockSize(m) + 1; - - short blockSizeOut = 1; // BlockSize::OneByte - if (blockSizeMode == BlockSize::Auto) { - blockSizeOut = getBlockSize(m); - } - - QByteArray res; - while ((block = rawData.mid(index, blockSizeIn)).size()) { - bool isLastBlock = (index + blockSizeIn) >= rawData.size(); - - res.append(decodeBlok(fromArray(block), d, m, - (isLastBlock && blockSizeMode == BlockSize::Auto)? -1 : blockSizeOut)); - index += blockSizeIn; - } - return res; - -} -QByteArray QRSAEncryption::signMessage(QByteArray rawData, const QByteArray &privKey) { - - QByteArray hash = QCryptographicHash::hash(rawData, HashAlgorithm::Sha256); - - QByteArray signature = encode(hash, privKey, BlockSize::OneByte); - - rawData.append(SIGN_MARKER + signature.toHex() + SIGN_MARKER); - - return rawData; -} -bool QRSAEncryption::checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey) { - - // start position of SIGN_MARKER in rawData - auto signStartPos = rawData.lastIndexOf(SIGN_MARKER, rawData.length() - signMarkerLength - 1); - - // length of signature in rawData - auto signLength = rawData.length() - signStartPos - signMarkerLength * 2; - - // message, that was recieved from channel - QByteArray message = rawData.left(signStartPos); - - // hash, that was decrypt from recieved signature - QByteArray recievedHash = decode(QByteArray::fromHex(rawData.mid(signStartPos + signMarkerLength, signLength)), - pubKey, BlockSize::OneByte); - - // if recievedHash == hashAlgorithm(recived message), then signed message is valid - return recievedHash == QCryptographicHash::hash(message, HashAlgorithm::Sha256); -} - -QRSAEncryption::Rsa QRSAEncryption::getRsa() const { - return _rsa; -} - -bool QRSAEncryption::testKeyPair(const QByteArray &pubKey, const QByteArray &privKey) { - - QByteArray tesVal = "Test message of encrypkey"; - - bool result = tesVal == decode(encode(tesVal, pubKey), privKey); - - if (!result) qWarning() << "(Warning): Testkey Fail, try generate new key pair!"; - - return result; -} - -// --- end of non-static methods --- - -bool QRSAEncryption::isValidRsaKey(const QByteArray &key) { - return key.size() && ((static_cast(key.size()) % getKeyBytesSize(RSA_64)) == 0); -} diff --git a/Qt-Secret/Qt-RSA/qrsaencryption.h b/Qt-Secret/Qt-RSA/qrsaencryption.h deleted file mode 100644 index 6fdffb3..0000000 --- a/Qt-Secret/Qt-RSA/qrsaencryption.h +++ /dev/null @@ -1,116 +0,0 @@ -//# -//# Copyright (C) 2018-2019 QuasarApp. -//# Distributed under the lgplv3 software license, see the accompanying -//# Everyone is permitted to copy and distribute verbatim copies -//# of this license document, but changing it is not allowed. -//# - -#ifndef QRSAENCRYPTION_H -#define QRSAENCRYPTION_H - -#include -#include -#include -#include -#include -#include // to use sha256 -#include "./../qtsecret_global.h" - -#include - - -class Qt_SECRETSHARED_EXPORT QRSAEncryption -{ -public: - typedef BigInt INT; - typedef QCryptographicHash::Algorithm HashAlgorithm; - - enum Rsa { - Invalid = 0, - RSA_64 = 64, - RSA_128 = 128, - RSA_256 = 256, - RSA_512 = 512, - RSA_1024 = 1024, - RSA_2048 = 2048, - RSA_4096 = 4096, - RSA_8192 = 8192, - - }; - - enum BlockSize { - Auto = 0, // fast but not stable. (using by default) - OneByte = 1 // stable but slow. (using for sig and check sig messages) - }; - - - QRSAEncryption(Rsa rsa = Rsa::RSA_256); - -// static methods - - // OLDMETHODS DELETE IN next Version - static bool generatePairKeyS(QByteArray &pubKey, QByteArray &privKey, - QRSAEncryption::Rsa rsa = RSA_256); - static QByteArray encodeS(const QByteArray &rawData, const QByteArray &pubKey, - Rsa rsa = RSA_256, BlockSize blockSizeMode = BlockSize::Auto); - static QByteArray decodeS(const QByteArray &rawData, const QByteArray &privKey, - Rsa rsa = RSA_256, BlockSize blockSizeMode = BlockSize::Auto); - static QByteArray signMessageS(QByteArray rawData, const QByteArray &privKey, - Rsa rsa = RSA_256); - static bool checkSignMessageS(const QByteArray &rawData, const QByteArray &pubKey, - Rsa rsa); - // OLDMETHODS END - - static bool generatePairKey(QByteArray &pubKey, QByteArray &privKey, - QRSAEncryption::Rsa rsa); - static QByteArray encode(const QByteArray &rawData, const QByteArray &pubKey, - Rsa rsa, BlockSize blockSizeMode = BlockSize::Auto); - static QByteArray decode(const QByteArray &rawData, const QByteArray &privKey, - Rsa rsa, BlockSize blockSizeMode = BlockSize::Auto); - static QByteArray signMessage(QByteArray rawData, const QByteArray &privKey, - Rsa rsa); - static bool checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey, - Rsa rsa); - static bool isValidRsaKey(const QByteArray& key); - static unsigned int getKeyBytesSize(QRSAEncryption::Rsa rsa); - -// non-static methods - bool generatePairKey(QByteArray &pubKey, QByteArray &privKey); - - QByteArray encode(const QByteArray &rawData, const QByteArray &pubKey, - BlockSize blockSizeMode = BlockSize::Auto); - - QByteArray decode(const QByteArray &rawData, const QByteArray &privKey, - BlockSize blockSizeMode = BlockSize::Auto); - - QByteArray signMessage(QByteArray rawData, const QByteArray &privKey); - - bool checkSignMessage(const QByteArray &rawData, const QByteArray &pubKey); - - Rsa getRsa() const; - -private: - - Rsa _rsa; - - bool testKeyPair(const QByteArray &pubKey, const QByteArray &privKey); - bool isMutuallyPrime(const INT &a, const INT &b); - Rsa getBitsSize(const INT& i) const; - Rsa getBitsSize(const QByteArray& array) const; - - INT fromArray(const QByteArray& array) const; - QByteArray toArray(const INT &i, short sizeBlok = -1); - INT randomNumber(bool fullFilled = true) const; - INT toPrime(INT) const; - INT randomPrimeNumber(INT no = 0) const; - INT extEuclid(INT a, INT b) const; - - short getBlockSize(INT i) const; - - QByteArray encodeBlok(const INT& block, const INT& e, const INT& m, short blockSize); - QByteArray decodeBlok(const INT& block, const INT& d, const INT& m, short blockSize); - - -}; - -#endif // QRSAENCRYPTION_H diff --git a/Qt-Secret/Qt-Secret.pri b/Qt-Secret/Qt-Secret.pri deleted file mode 100644 index dfa6c3c..0000000 --- a/Qt-Secret/Qt-Secret.pri +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (C) 2018-2019 QuasarApp. -# Distributed under the lgplv3 software license, see the accompanying -# Everyone is permitted to copy and distribute verbatim copies -# of this license document, but changing it is not allowed. -# - -!isEmpty(Qt_SECRET_LIB):error("Qt-Secret.pri already included") -Qt_SECRET_LIB = 1 - -DEFINES += Qt_SECRET_LIBRARY -DEFINES += QT_DEPRECATED_WARNINGS - -HEADERS += \ - $$PWD/qtsecret_global.h \ - $$PWD/Qt-RSA/qrsaencryption.h - -SOURCES += \ - $$PWD/Qt-RSA/qrsaencryption.cpp - - -INCLUDEPATH += $$PWD $$PWD/Qt-RSA - -include($$PWD/GMP/GMP.pri) diff --git a/Qt-Secret/Qt-Secret.pro b/Qt-Secret/Qt-Secret.pro deleted file mode 100644 index f62c07f..0000000 --- a/Qt-Secret/Qt-Secret.pro +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright (C) 2018-2019 QuasarApp. -# Distributed under the lgplv3 software license, see the accompanying -# Everyone is permitted to copy and distribute verbatim copies -# of this license document, but changing it is not allowed. -# - -QT -= gui -CONFIG += c++11 - -TARGET = Qt-Secret -TEMPLATE = lib - -DEFINES += Qt_SECRET_LIBRARY -DEFINES += QT_DEPRECATED_WARNINGS - -#DEPENDS -CONFIG(release, debug|release): { - DESTDIR="$$PWD/build/release" -} else { - DESTDIR="$$PWD/build/debug" -} - -include($$PWD/GMP/GMP.pri) - -VERSION = 1.2.0 - -HEADERS += \ - qtsecret_global.h \ - Qt-RSA/qrsaencryption.h - -SOURCES += \ - Qt-RSA/qrsaencryption.cpp - -target.path = /usr/local/lib -!isEmpty(target.path): INSTALLS += target diff --git a/Qt-Secret/qtsecret_global.h b/Qt-Secret/qtsecret_global.h deleted file mode 100644 index 1893b41..0000000 --- a/Qt-Secret/qtsecret_global.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef QTSECRET_GLOBAL_H -#define QTSECRET_GLOBAL_H - -#include - -#if defined(Qt_SECRET_LIBRARY) -# define Qt_SECRETSHARED_EXPORT Q_DECL_EXPORT -#else -# define Qt_SECRETSHARED_EXPORT Q_DECL_IMPORT -#endif - -#endif // QTSECRET_GLOBAL_H diff --git a/qt-openssl-encryption b/qt-openssl-encryption new file mode 160000 index 0000000..05fbf56 --- /dev/null +++ b/qt-openssl-encryption @@ -0,0 +1 @@ +Subproject commit 05fbf562c3435f3bbff10a68c031ff465e81d337 From 10b2f7b888a59ea5b89cedde0edb962d14eae9cb Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 18 Jul 2020 22:17:24 +0200 Subject: [PATCH 12/76] added classes for dynamic API management --- ScStwLibraries/headers/ScStw.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 11e5a4c..f5dbcb2 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -126,7 +126,8 @@ public: TimeoutError = 911, SettingNotAccessibleError = 901, InternalError = 950, - InternalErrorTimerOperationFailed = 951 + InternalErrorTimerOperationFailed = 951, + ApiVersionNotSupportedError = 952 }; Q_ENUM(ScStw::StatusCode) From 150b33b483547b1e8df49eb9bb5b149da0b29a0e Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 24 Jul 2020 13:05:28 +0200 Subject: [PATCH 13/76] added api version to init --- ScStwLibraries/sources/client/scstwclient.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index 2fed168..e9a4ef9 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -79,7 +79,7 @@ bool ScStwClient::init() { } // init remote session - QJsonObject sessionParams = {{"signalSubscriptions", signalSubs}, {"init", true}, {"usingTerminationKeys", true}}; + QJsonObject sessionParams = {{"apiVersion", this->API_VERSION}, {"signalSubscriptions", signalSubs}, {"init", true}, {"usingTerminationKeys", true}}; QVariantMap initResponse = this->sendCommand(1, sessionParams, 3000, false); From 615ac508d65afa9625b9fe0acae84f781979597a Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 24 Jul 2020 13:07:27 +0200 Subject: [PATCH 14/76] added type security to settings --- ScStwLibraries/headers/scstwsettings.h | 19 ++++++++++++++++++- ScStwLibraries/sources/scstwsettings.cpp | 11 ++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index 71787a3..be0afb6 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -37,6 +37,7 @@ public: explicit ScStwSettings(QObject *parent = nullptr); typedef QString(*keyToStringConverter)(int); + typedef QVariant::Type(*keyToTypeConverter)(int); /*! * \brief The BaseStationSetting enum contains all settings of the base station that can be changed by a client @@ -79,11 +80,26 @@ public: return QMetaEnum::fromType().valueToKey(key); } + static QVariant::Type keyToType(int key) { + QMap types = { + {ReadySoundEnableSetting, QVariant::Bool}, + {ReadySoundDelaySetting, QVariant::Double}, + {AtYourMarksSoundEnableSetting, QVariant::Bool}, + {AtYourMarksSoundDelaySetting, QVariant::Double}, + {SoundVolumeSetting, QVariant::Double} + }; + + if(types.contains(BaseStationSetting(key))) + return types[BaseStationSetting(key)]; + + return QVariant::Invalid; + } + protected: virtual QVariant readSetting(QString key, int keyInt = -1, int keyLevel = -1); virtual bool writeSetting(QString key, QVariant value, int keyInt = -1,int keyLevel = -1); virtual bool setDefaultSetting(QString key, QVariant defaultValue, int keyInt,int keyLevel = -1); - bool registerKeyLevelHandler(int keyLevel, keyToStringConverter); + bool registerKeyLevelConverters(int keyLevel, keyToStringConverter, keyToTypeConverter); private: QFile * settingsFile; @@ -113,6 +129,7 @@ private: }; QMap keyToStringConverters; + QMap keyToTypeConverters; QMap> internalSettingHandlers; private slots: diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 45844a0..81c843c 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -35,7 +35,7 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); - this->registerKeyLevelHandler(ScStwSettings::KeyLevel, &ScStwSettings::keyToString); + this->registerKeyLevelConverters(ScStwSettings::KeyLevel, &ScStwSettings::keyToString, &ScStwSettings::keyToType); } QVariant ScStwSettings::readSetting(BaseStationSetting key) { @@ -78,6 +78,10 @@ QVariant ScStwSettings::readSetting(QString key, int keyInt, int keyLevel) { } bool ScStwSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { + if(!this->keyToTypeConverters.contains(keyInt) || !value.convert(this->keyToTypeConverters[keyLevel](keyInt)) || value.type() == QVariant::Invalid) { + return false; + } + if(!this->settingsCache.contains(key)) this->settingsCache.insert(key, value); else if (this->settingsCache[key] == value) @@ -106,11 +110,12 @@ ScStwSetting * ScStwSettings::getSetting(int key, int keyLevel) { return this->internalSettingHandlers[keyLevel][key]; } -bool ScStwSettings::registerKeyLevelHandler(int keyLevel, keyToStringConverter converterFunction) { +bool ScStwSettings::registerKeyLevelConverters(int keyLevel, keyToStringConverter keyToStringConverterFunction, keyToTypeConverter keyToTypeConverterFunction) { if(this->keyToStringConverters.contains(keyLevel)) return false; - this->keyToStringConverters.insert(keyLevel, converterFunction); + this->keyToStringConverters.insert(keyLevel, keyToStringConverterFunction); + this->keyToTypeConverters.insert(keyLevel, keyToTypeConverterFunction); return true; } From d982bafab14b45e407b30efdaa6c1acdcbe6b781 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Wed, 29 Jul 2020 17:56:32 +0200 Subject: [PATCH 15/76] added function to get list with timer objects --- ScStwLibraries/headers/scstwrace.h | 1 + ScStwLibraries/sources/scstwrace.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 206a457..f4d8718 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -130,6 +130,7 @@ public slots: RaceState getState(); StartAction getNextStartAction(); virtual QVariantList getNextStartActionDetails(); + QList getTimers(); QVariantList getTimerDetailList(); protected slots: diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 5998f13..4c4adb1 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -387,6 +387,10 @@ ScStwRace::StartAction ScStwRace::getNextStartAction() return this->nextStartAction; } +QList ScStwRace::getTimers() { + return this->timers; +} + QVariantList ScStwRace::getTimerDetailList() { QVariantList tmpTimers; From e3cea065580dd1b5855f2860d7d21d545ec59790 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Thu, 30 Jul 2020 12:12:44 +0200 Subject: [PATCH 16/76] fixed non working settings write --- ScStwLibraries/sources/scstwsettings.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 81c843c..fa372ea 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -74,14 +74,21 @@ bool ScStwSettings::setDefaultSetting(int key, int keyLevel, QVariant defaultVal QVariant ScStwSettings::readSetting(QString key, int keyInt, int keyLevel) { Q_UNUSED(keyInt) Q_UNUSED(keyLevel) - return this->settingsCache[key]; + + if(this->settingsCache.contains(key)) + return this->settingsCache[key]; + else + return QVariant(); } bool ScStwSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { - if(!this->keyToTypeConverters.contains(keyInt) || !value.convert(this->keyToTypeConverters[keyLevel](keyInt)) || value.type() == QVariant::Invalid) { + + // check if the value type is valid + if(!this->keyToTypeConverters.contains(keyLevel) || !value.convert(this->keyToTypeConverters[keyLevel](keyInt)) || value.type() == QVariant::Invalid) { return false; } + // write the setting if(!this->settingsCache.contains(key)) this->settingsCache.insert(key, value); else if (this->settingsCache[key] == value) From b90456697755dba61395bd373c594be3d8ac3b93 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 3 Aug 2020 20:02:42 +0200 Subject: [PATCH 17/76] - implemented basic competition mode that comes with a few restrictions. --- ScStwLibraries/headers/ScStw.hpp | 3 ++- ScStwLibraries/headers/scstwsettings.h | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index f5dbcb2..c353675 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -127,7 +127,8 @@ public: SettingNotAccessibleError = 901, InternalError = 950, InternalErrorTimerOperationFailed = 951, - ApiVersionNotSupportedError = 952 + ApiVersionNotSupportedError = 952, + CompetitionModeProhibitsThisError = 953 }; Q_ENUM(ScStw::StatusCode) diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index be0afb6..19026b8 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -53,7 +53,8 @@ public: ReadySoundDelaySetting, AtYourMarksSoundEnableSetting, AtYourMarksSoundDelaySetting, - SoundVolumeSetting + SoundVolumeSetting, + CompetitionModeSetting }; Q_ENUM(BaseStationSetting) @@ -86,7 +87,8 @@ public: {ReadySoundDelaySetting, QVariant::Double}, {AtYourMarksSoundEnableSetting, QVariant::Bool}, {AtYourMarksSoundDelaySetting, QVariant::Double}, - {SoundVolumeSetting, QVariant::Double} + {SoundVolumeSetting, QVariant::Double}, + {CompetitionModeSetting, QVariant::Bool} }; if(types.contains(BaseStationSetting(key))) From ec2d6fb9ef359684fefda4f640f64ce2e7e6c89c Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 9 Aug 2020 11:46:13 +0200 Subject: [PATCH 18/76] made the current theme writable via a property --- ScStwLibraries/headers/styling/scstwappthememanager.h | 2 ++ ScStwLibraries/sources/styling/scstwappthememanager.cpp | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/ScStwLibraries/headers/styling/scstwappthememanager.h b/ScStwLibraries/headers/styling/scstwappthememanager.h index bec5135..04b4ffb 100644 --- a/ScStwLibraries/headers/styling/scstwappthememanager.h +++ b/ScStwLibraries/headers/styling/scstwappthememanager.h @@ -27,6 +27,7 @@ class ScStwAppThemeManager : public QObject { Q_OBJECT Q_PROPERTY(ScStwAppTheme* theme READ getTheme NOTIFY themeChanged) + Q_PROPERTY(QString themeName READ getThemeName WRITE setTheme NOTIFY themeChanged) public: explicit ScStwAppThemeManager(QObject *parent = nullptr); @@ -45,6 +46,7 @@ signals: public slots: ScStwAppTheme* getTheme(); Q_INVOKABLE bool setTheme(QString themeName); + Q_INVOKABLE QString getThemeName(); }; diff --git a/ScStwLibraries/sources/styling/scstwappthememanager.cpp b/ScStwLibraries/sources/styling/scstwappthememanager.cpp index b8d3145..afa31c2 100644 --- a/ScStwLibraries/sources/styling/scstwappthememanager.cpp +++ b/ScStwLibraries/sources/styling/scstwappthememanager.cpp @@ -174,3 +174,7 @@ QString ScStwAppThemeManager::lighter(QString color, double factor) { qcolor.setHsv(h,s,v * factor); return qcolor.name(); } + +QString ScStwAppThemeManager::getThemeName() { + return this->currentTheme->getName(); +} From 41ff6e2bf7f0bff86044900035986c0dfb487e94 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 9 Aug 2020 13:29:37 +0200 Subject: [PATCH 19/76] added ability to prohibit automatic timer disable --- ScStwLibraries/headers/scstwrace.h | 10 ++--- ScStwLibraries/headers/scstwtimer.h | 19 ++++++++- ScStwLibraries/sources/scstwrace.cpp | 61 ++++++++++++++++++++------- ScStwLibraries/sources/scstwtimer.cpp | 13 ++++++ 4 files changed, 82 insertions(+), 21 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index f4d8718..e3ddfb5 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -77,17 +77,16 @@ protected: private: RaceState state; - QList timerEnableQueque; - QTimer *nextActionTimer; QEventLoop *nextActionLoop; // sounds ScStwSoundPlayer * soundPlayer; - // some settings double soundVolume; + bool allowAutomaticTimerDisable; + bool allowAutomaticTimerDisableChanged; /*! * \brief stores the start action settings @@ -125,6 +124,7 @@ public slots: bool writeStartActionSetting(StartAction action, bool enabled, int delay); bool setSoundVolume(double volume); virtual bool addTimer(ScStwTimer *timer); + void setAllowAutomaticTimerDisable(bool allow); // getters RaceState getState(); @@ -138,10 +138,10 @@ protected slots: private slots: void refreshTimerStates(); - void handleTimerEnable(ScStwTimer* timer); + void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); int handleFalseStart(); bool playSoundsAndStartTimers(StartAction thisAction); - + void enableAllTimers(); /** * \brief Function to declare the winner and looser timers after a timer has been stopped diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index e1aac72..6b65a5a 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -127,6 +127,11 @@ protected: */ QString letter; + /*! + * \brief Defines if the timer currently wants to be disabled or not + */ + bool wantsToBeDisabled; + public slots: /*! @@ -294,6 +299,12 @@ public slots: */ bool setLetter(QString newLetter); + /*! + * \brief Function to check if the timer currently wants to be disabled + * \return true or false + */ + bool getWantsToBeDisabled(); + protected slots: /*! @@ -338,6 +349,12 @@ protected slots: */ void setState(TimerState newState); + /*! + * \brief Function to set whether the timer currently wants to be disabled + * \param wantsToBeDisabled true or false + */ + void setWantsToBeDisabled(bool wantsToBeDisabled); + signals: /*! @@ -354,7 +371,7 @@ signals: * \brief Emitted when the timer wants its state to be changed by the external handler * \param timer the timer object */ - void requestEnableChange(ScStwTimer* timer); + void wantsToBeDisabledChanged(ScStwTimer* timer, bool wantsToBeDisabled); }; diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 4c4adb1..12961cb 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -1,4 +1,4 @@ -/**************************************************************************** + /**************************************************************************** ** ScStw Libraries ** Copyright (C) 2020 Itsblue development ** @@ -39,6 +39,7 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) this->writeStartActionSetting(AtYourMarks, false, 0); this->writeStartActionSetting(Ready, false, 0); this->setSoundVolume(1.0); + this->allowAutomaticTimerDisable = false; } // -------------------------- @@ -256,12 +257,18 @@ void ScStwRace::setState(RaceState newState) { emit this->stateChanged(newState); if(this->state == IDLE) { - // if we changed to IDLE -> enable timers - foreach(ScStwTimer* timer, this->timerEnableQueque) { - this->handleTimerEnable(timer); + // if we changed to IDLE -> handle timer enable / disable + if(this->allowAutomaticTimerDisableChanged && !this->allowAutomaticTimerDisable) { + this->enableAllTimers(); + this->allowAutomaticTimerDisableChanged = false; } - this->timerEnableQueque.clear(); + if(this->allowAutomaticTimerDisable) { + foreach(ScStwTimer* timer, this->timers) { + if(timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) + this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); + } + } } } } @@ -299,17 +306,38 @@ void ScStwRace::refreshTimerStates() { * @brief ScStwRace::handleTimerEnable function to enable timers at the right moment to prevent them from bricking the state machine * @param {ScStwExtensionControlledTimer*} timer timer to be enabled */ -void ScStwRace::handleTimerEnable(ScStwTimer* timer) { +void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled) { + if(!this->allowAutomaticTimerDisable) + return; + if(this->state == IDLE) { - if(timer->getState() == ScStwTimer::DISABLED) { - timer->setDisabled(false); - } - else { - timer->setDisabled(true); - } + timer->setDisabled(wantsToBeDisabled); } - else { - this->timerEnableQueque.append(timer); +} + + +void ScStwRace::setAllowAutomaticTimerDisable(bool allow) { + if(this->allowAutomaticTimerDisable == allow) + return; + + qDebug() << "Setting allow automatic timer disable to " << allow; + + this->allowAutomaticTimerDisable = allow; + + if(this->state != IDLE) + this->allowAutomaticTimerDisableChanged = true; + else if(!this->allowAutomaticTimerDisable) + this->enableAllTimers(); +} + +void ScStwRace::enableAllTimers() { + if(this->state != IDLE) + return; + + qDebug() << "ENABLING ALL TIMERS"; + + foreach (ScStwTimer *timer, this->timers) { + timer->setDisabled(false); } } @@ -370,10 +398,13 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { this->timers.append(timer); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::refreshTimerStates); - connect(timer, &ScStwTimer::requestEnableChange, this, &ScStwRace::handleTimerEnable); + connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); + if(!this->allowAutomaticTimerDisable && timer->getState() == ScStwTimer::DISABLED) + timer->setDisabled(false); + return true; } diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 11950e5..1f03590 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -283,3 +283,16 @@ void ScStwTimer::setDisabled(bool disabled) { else this->setState(IDLE); } + +void ScStwTimer::setWantsToBeDisabled(bool wantsToBeDisabled) { + if(this->wantsToBeDisabled == wantsToBeDisabled) + return; + + this->wantsToBeDisabled = wantsToBeDisabled; + + emit this->wantsToBeDisabledChanged(this, wantsToBeDisabled); +} + +bool ScStwTimer::getWantsToBeDisabled() { + return this->wantsToBeDisabled; +} From d210a75d518489c64e9c87d1088c4275849ab960 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 14 Aug 2020 17:02:53 +0200 Subject: [PATCH 20/76] some preperations for start procedure checks (#20) --- ScStwLibraries/headers/scstwrace.h | 1 + ScStwLibraries/headers/scstwtimer.h | 33 +++++++++++++++++++++++---- ScStwLibraries/sources/scstwtimer.cpp | 4 ++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index e3ddfb5..17213b1 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -57,6 +57,7 @@ public: explicit ScStwRace(QObject *parent = nullptr); enum RaceState { IDLE, STARTING, WAITING, RUNNING, STOPPED }; + // will become IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED later Q_ENUM(RaceState) enum StartAction { None = -1, AtYourMarks = 0, Ready = 1, Start = 2 }; diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 6b65a5a..ee82a10 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -82,6 +82,7 @@ public: LOST, /*!< Timer has lost */ FAILED, /*!< A false start occured */ CANCELLED, /*!< Timer was cancelled */ +// INCIDENT, /*!< There was a technical incident */ DISABLED /*!< Timer is disabled */ }; Q_ENUM(TimerState); @@ -90,10 +91,22 @@ public: * \brief The StopReason enum contains all possible reasons for a stop */ enum StopReason { - ManualStop, /*!< Timer was stopped manually */ - CancelStop, /*!< Timer was cancelled */ - FailStop, /*!< A false start occured */ - TopPadStop /*!< Timer was stopped by a physical trigger (eg. a ScStwExtension) */ + ManualStop, /*!< Timer was stopped manually */ + CancelStop, /*!< Timer was cancelled */ + FailStop, /*!< A false start occured */ + TopPadStop, /*!< Timer was stopped by a physical trigger (eg. a ScStwExtension) */ + TechnicalIncidentStop /*!< The timer was stopped due to a technical incident */ + }; + + /*! + * \brief The ReadyStatus enum contains all possible reasons for a timer not to be ready (>0) and the case that it is ready (0) + */ + enum ReadyState { + IsReady = 0, /*!< Timer is ready for start */ + NotInIdleState, /*!< Timer is not in IDLE state */ + IsDisabled, /*!< Timer is disabled */ + NotAllExtensionsConnected, /*!< Not all extension of the timer are conneted */ + NotAllClimbersReady /*!< The startpad of the timer is not triggered */ }; protected: @@ -305,6 +318,12 @@ public slots: */ bool getWantsToBeDisabled(); + /*! + * \brief Function to get the current ready status of a timer + * \return The current ready status + */ + virtual ScStwTimer::ReadyState getReadyState(); + protected slots: /*! @@ -373,6 +392,12 @@ signals: */ void wantsToBeDisabledChanged(ScStwTimer* timer, bool wantsToBeDisabled); + /*! + * \brief Emitted when the ready state of the timer changes + * \param readyState the new ReadyState + */ + void readyStateChanged(ReadyState readyState); + }; #endif // SCSTWTIMER_H diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 1f03590..6a69f52 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -157,6 +157,10 @@ bool ScStwTimer::reset(){ return true; } +ScStwTimer::ReadyState ScStwTimer::getReadyState() { + return this->state == IDLE ? ScStwTimer::IsReady : ScStwTimer::NotInIdleState; +} + // ------------------------ // --- helper functions --- // ------------------------ From c5ac250b4e79ba10b621f1c3dbabd757cdc13334 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 22 Sep 2020 15:44:57 +0200 Subject: [PATCH 21/76] - redesigned the Extension status display in the top left corner - redesigned the Extension overview in the basestation settings (for #19) --- ScStwLibraries/headers/client/scstwclient.h | 8 ++++---- ScStwLibraries/sources/client/scstwclient.cpp | 12 +++++++----- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwclient.h b/ScStwLibraries/headers/client/scstwclient.h index 99e8dc3..e316097 100644 --- a/ScStwLibraries/headers/client/scstwclient.h +++ b/ScStwLibraries/headers/client/scstwclient.h @@ -51,7 +51,7 @@ class ScStwClient : public QObject { Q_OBJECT Q_PROPERTY(State state READ getState NOTIFY stateChanged) - Q_PROPERTY(QVariantList extensions READ getExtensions NOTIFY extensionsChanged) + Q_PROPERTY(QVariantMap extensions READ getExtensions NOTIFY extensionsChanged) Q_PROPERTY(QString ipAddress READ getIP WRITE setIP) public: @@ -77,7 +77,7 @@ private: int errors; const static int ERRORS_UNTIL_DISCONNECT = 4; - QVariantList extensions; + QVariantMap extensions; QList signalSubscriptions; @@ -173,7 +173,7 @@ public slots: * \brief Function to get the extensions and their state from the base station * \return a list with all configured extensions and their state */ - QVariantList getExtensions(); + QVariantMap getExtensions(); /*! * \brief Function to get the time offset of the base station relative to the clients time @@ -287,7 +287,7 @@ private slots: * \see gotSignal() * \param connections the list to set the chache to */ - void setExtensions(QVariantList extensions); + void setExtensions(QVariantMap extensions); /*! * \brief Function to set the local state. diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index e9a4ef9..cf12a27 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -24,7 +24,7 @@ ScStwClient::ScStwClient(QObject * parent, QList signalSubscri { this->state = DISCONNECTED; this->nextConnectionId = 1; - this->extensions = QVariantList({}); + this->extensions = QVariantMap({}); this->signalSubscriptions = signalSubscriptions; this->socket = new QTcpSocket(this); @@ -121,7 +121,7 @@ void ScStwClient::deInit() { if(this->state == DISCONNECTED) return; - this->setExtensions(QVariantList({})); + this->setExtensions(QVariantMap({})); this->setState(DISCONNECTED); } @@ -380,7 +380,7 @@ void ScStwClient::handleSignal(QVariantMap data) { { // the extension connections have changed // -> handle locally - this->setExtensions(data["data"].toList()); + this->setExtensions(data["data"].toMap()); return; break; } @@ -434,7 +434,7 @@ void ScStwClient::setState(ScStwClient::State newState){ } } -QVariantList ScStwClient::getExtensions() { +QVariantMap ScStwClient::getExtensions() { return this->extensions; } @@ -450,7 +450,9 @@ QString ScStwClient::getApiVersion() { return this->apiVersion; } -void ScStwClient::setExtensions(QVariantList extensions) { +void ScStwClient::setExtensions(QVariantMap extensions) { + qDebug() << "[CLIENT][DEBUG] Extensions changed: " << extensions; + if(this->extensions != extensions){ this->extensions = extensions; emit this->gotSignal(ScStw::ExtensionsChanged, this->getExtensions()); From f5acde704b9c14a6b221ecd91f5c9ab9bb8551f7 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 22 Sep 2020 15:53:44 +0200 Subject: [PATCH 22/76] - added ExtensionType and ExtensionState enums - added extensionTypeToString enum --- ScStwLibraries/headers/ScStw.hpp | 28 ++++++++++++++++++++++++++++ ScStwLibraries/sources/ScStw.cpp | 11 +++++++++++ 2 files changed, 39 insertions(+) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index c353675..d977370 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -132,6 +132,25 @@ public: }; Q_ENUM(ScStw::StatusCode) + /*! + * \brief The ExtensionType enum contains all types of extensions + */ + enum ExtensionType { + StartPad, + TopPad + }; + Q_ENUM(ExtensionType); + + + enum ExtensionState { + Disconnected = 0, + Connecting = 1, + Initialising = 2, + Connected = 3 + }; + Q_ENUM(ExtensionState); + + /*! * \brief SOCKET_MESSAGE_START_KEY contains the key, a message is supposed to start with */ @@ -160,6 +179,15 @@ public: */ static SocketCommand socketCommandFromInt(int i); + /*! + * \brief Function to convert an ExtensionType to a string + * \param t the ExtensionType to convert + * \return String + * + * \see ScStwExtensionType + */ + static QString extensionTypeToStrin(ExtensionType t); + /*! * \brief Function to compare to string firmware versions in .. formar * \param a version a diff --git a/ScStwLibraries/sources/ScStw.cpp b/ScStwLibraries/sources/ScStw.cpp index 2cc19f0..dc3cdc3 100644 --- a/ScStwLibraries/sources/ScStw.cpp +++ b/ScStwLibraries/sources/ScStw.cpp @@ -39,6 +39,17 @@ ScStw::SocketCommand ScStw::socketCommandFromInt(int i) { return c; } +QString ScStw::extensionTypeToString(ExtensionType t) { + switch (t) { + case StartPad: + return "StartPad"; + case TopPad: + return "TopPad"; + default: + return "Invalid"; + } +} + int ScStw::firmwareCompare(QString a, QString b) { /* * * \return -3: major of a is lower than b From 02b51e54ee3f90b5e53844d81664ca23fd3622f2 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 22 Sep 2020 16:02:16 +0200 Subject: [PATCH 23/76] fixed a typo --- ScStwLibraries/headers/ScStw.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index d977370..e88eee1 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -186,7 +186,7 @@ public: * * \see ScStwExtensionType */ - static QString extensionTypeToStrin(ExtensionType t); + static QString extensionTypeToString(ExtensionType t); /*! * \brief Function to compare to string firmware versions in .. formar From 172ba0d1a0b023ef029025667ee6b865ea9c3f5c Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 25 Sep 2020 18:24:40 +0200 Subject: [PATCH 24/76] - added ExtensionBatteryState to ScStw and renamed ReadyStates in timer --- ScStwLibraries/headers/ScStw.hpp | 23 +++++++++++++++++++++++ ScStwLibraries/headers/scstwtimer.h | 5 +++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index e88eee1..e7584dd 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -142,6 +142,9 @@ public: Q_ENUM(ExtensionType); + /*! + * \brief The ExtensionState enum contains all possible states of an extension + */ enum ExtensionState { Disconnected = 0, Connecting = 1, @@ -151,6 +154,26 @@ public: Q_ENUM(ExtensionState); + /*! + * \brief The ExtensionBatteryState enum contains all possible battery states of an extension + */ + enum ExtensionBatteryState { + BatteryUnknown = -1, + BatteryFine = 1, + BatteryCritical = 0 + }; + Q_ENUM(ExtensionBatteryState); + + /*! + * \brief The PadState enum contains whether a pad is currently pressed or not + */ + enum PadState { + PadNotPressed = 0, + PadPressed = 1 + }; + Q_ENUM(PadState); + + /*! * \brief SOCKET_MESSAGE_START_KEY contains the key, a message is supposed to start with */ diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index ee82a10..51561fa 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -105,8 +105,9 @@ public: IsReady = 0, /*!< Timer is ready for start */ NotInIdleState, /*!< Timer is not in IDLE state */ IsDisabled, /*!< Timer is disabled */ - NotAllExtensionsConnected, /*!< Not all extension of the timer are conneted */ - NotAllClimbersReady /*!< The startpad of the timer is not triggered */ + ExtensionIsNotConnected, /*!< Not all extension of the timer are conneted */ + ExtensionBatteryNotFine, /*!< The battery level of one or more extension is critical or unknown */ + ClimberIsNotReady /*!< The startpad of the timer is not triggered */ }; protected: From c6af1f89854f97dced9d47a35ba7bc64d1512374 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 29 Sep 2020 12:53:40 +0200 Subject: [PATCH 25/76] added some functionality for start ready detection --- ScStwLibraries/headers/ScStw.hpp | 3 +- ScStwLibraries/headers/scstwrace.h | 8 +- ScStwLibraries/headers/scstwtimer.h | 17 ++- ScStwLibraries/sources/scstwlibraries.cpp | 2 + ScStwLibraries/sources/scstwrace.cpp | 157 +++++++++++++++++----- ScStwLibraries/sources/scstwtimer.cpp | 16 ++- 6 files changed, 166 insertions(+), 37 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index e7584dd..d7666b1 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -128,7 +128,8 @@ public: InternalError = 950, InternalErrorTimerOperationFailed = 951, ApiVersionNotSupportedError = 952, - CompetitionModeProhibitsThisError = 953 + CompetitionModeProhibitsThisError = 953, + TimersNotReadyError = 501 /*!< One or more timer is not ready */ }; Q_ENUM(ScStw::StatusCode) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 17213b1..2feff1b 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -56,8 +56,7 @@ class ScStwRace : public QObject public: explicit ScStwRace(QObject *parent = nullptr); - enum RaceState { IDLE, STARTING, WAITING, RUNNING, STOPPED }; - // will become IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED later + enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED }; Q_ENUM(RaceState) enum StartAction { None = -1, AtYourMarks = 0, Ready = 1, Start = 2 }; @@ -80,6 +79,8 @@ private: QTimer *nextActionTimer; QEventLoop *nextActionLoop; + QTimer *climberReadyWaitTimer; + QEventLoop *climberReadyWaitLoop; // sounds ScStwSoundPlayer * soundPlayer; @@ -141,7 +142,8 @@ private slots: void refreshTimerStates(); void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); int handleFalseStart(); - bool playSoundsAndStartTimers(StartAction thisAction); + bool playSoundsAndStartTimers(); + bool doDelayAndSoundOfStartAction(StartAction action, double *timeOfSoundPlaybackStart = nullptr); void enableAllTimers(); /** diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 51561fa..25e9fda 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -25,6 +25,9 @@ #include #include "ScStw.hpp" +class ScStwRace; +class ScStwRemoteRace; + /*! * \brief The ScStwTimer class is used for advanced time measurement. * @@ -70,6 +73,9 @@ public: */ explicit ScStwTimer(QObject *parent = nullptr, bool directControlEnabled = false, QString letter = "" ); + friend class ScStwRace; + friend class ScStwRemoteRace; + /*! * \brief The TimerState enum contains all state the timer can be in */ @@ -82,7 +88,7 @@ public: LOST, /*!< Timer has lost */ FAILED, /*!< A false start occured */ CANCELLED, /*!< Timer was cancelled */ -// INCIDENT, /*!< There was a technical incident */ + INCIDENT, /*!< There was a technical incident (most likely a disconnected extension) */ DISABLED /*!< Timer is disabled */ }; Q_ENUM(TimerState); @@ -375,6 +381,15 @@ protected slots: */ void setWantsToBeDisabled(bool wantsToBeDisabled); + /*! + * \brief Function to set the timer into INCIDENT state immidieately + * + * The current state of the timer will be ignored! It can only get out of this state by calling ScStwTimer::reset + * + * \see reset + */ + void technicalIncident(); + signals: /*! diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 2c1c0fb..c557e26 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -38,6 +38,8 @@ void ScStwLibraries::init() { qmlRegisterUncreatableType("de.itsblue.ScStw", 2, 0, "ScStwSetting", "The ScStwSetting is manage by a ScStwSettings instance and therefore not creatable"); #endif #endif + + qRegisterMetaType("ScStw::PadState"); } diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 12961cb..74a545a 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -1,4 +1,4 @@ - /**************************************************************************** +/**************************************************************************** ** ScStw Libraries ** Copyright (C) 2020 Itsblue development ** @@ -28,10 +28,12 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) // configure timer that handles the delay between the start commands this->nextActionTimer = new QTimer(this); nextActionTimer->setSingleShot(true); - this->nextActionLoop = new QEventLoop(); + this->nextActionLoop = new QEventLoop(this); this->nextStartAction = None; + this->climberReadyWaitLoop = new QEventLoop(this); connect(this->nextActionTimer, &QTimer::timeout, this->nextActionLoop, &QEventLoop::quit); + connect(this->nextActionTimer, &QTimer::timeout, this->climberReadyWaitLoop, &QEventLoop::quit); connect(this, &ScStwRace::nextStartActionChanged, this, &ScStwRace::nextStartActionDetailsChanged); // write default settings @@ -51,15 +53,45 @@ int ScStwRace::start(bool asyncronous) { return ScStw::CurrentStateNotVaildForOperationError; } - qDebug() << "+ [INFO] starting race"; + qDebug() << "[INFO][RACE] checking timers"; + foreach (ScStwTimer *timer, this->timers) { + if(timer->getState() == ScStwTimer::DISABLED) + continue; - this->setState(STARTING); + if(timer->getReadyState() != ScStwTimer::ClimberIsNotReady) { + + if(this->allowAutomaticTimerDisable) { + timer->setDisabled(true); + continue; + } + + qDebug() << "Timer ready state is: " << timer->getReadyState(); + + timer->technicalIncident(); + + foreach (ScStwTimer *subTimer, this->timers) { + if(timer != subTimer && subTimer->getReadyState() != ScStwTimer::ClimberIsNotReady) + subTimer->technicalIncident(); + else if(timer != subTimer) + subTimer->setState(ScStwTimer::CANCELLED); + } + + this->setState(STOPPED); + + qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; + + return ScStw::TimersNotReadyError; + } + } + + qDebug() << "[INFO][RACE] starting race"; + this->setState(PREPAIRING); if(asyncronous) { - QTimer::singleShot(1, [=](){this->playSoundsAndStartTimers(None);}); + QTimer::singleShot(1, [=](){this->playSoundsAndStartTimers();}); } else - this->playSoundsAndStartTimers(None); + this->playSoundsAndStartTimers(); return ScStw::Success; } @@ -188,34 +220,70 @@ int ScStwRace::handleFalseStart() { return returnCode; } -bool ScStwRace::playSoundsAndStartTimers(StartAction thisAction) { - if(this->state != STARTING) +bool ScStwRace::playSoundsAndStartTimers() { + if(this->state != PREPAIRING) return true; + // The check if all timers are ready has already happened at this point + if(!this->doDelayAndSoundOfStartAction(AtYourMarks)) { + qDebug() << "At marks sound returned false!"; + return false; + } + + qDebug() << "NOW IN WAITING"; + this->setState(WAITING); + + // do climber readiness tests + this->nextStartAction = Ready; + emit this->nextStartActionChanged(); + + // if the automatic ready tone is enabled, wait for the climbers to become ready + if(this->startActionSettings.contains(Ready) && this->startActionSettings[Ready]["Enabled"].toBool()) { + + qDebug() << "[RACE][INFO] Now waiting for climbers"; + + // get delay + int minimumReadyDelay = 1000; + if(this->startActionSettings[Ready]["Delay"].toInt() > 1000 || !this->allowAutomaticTimerDisable) + minimumReadyDelay = this->startActionSettings[Ready]["Delay"].toInt(); + + // wait for climbers to become ready initially + bool allClimbersReady = false; + while (!allClimbersReady) { + allClimbersReady = true; + foreach (ScStwTimer *timer, this->timers) { + if(timer->getReadyState() != ScStwTimer::IsReady) + allClimbersReady = false; + } + + if(!allClimbersReady) + this->climberReadyWaitLoop->exec(); + } + + qDebug() << "[RACE][DEBUG] Initial wait finished"; + + // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly + // the climber ready wait loop will also quit, if the climber steps of the pad + // -> wait for both climbers to stand on the pad for at least one second + do { + this->nextActionTimer->stop(); + this->nextActionTimer->start(minimumReadyDelay); + this->climberReadyWaitLoop->exec(); + } while(this->nextActionTimer->remainingTime() > 0); + + qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; + + // play ready tone + if(!this->soundPlayer->play(Ready, this->soundVolume)) + return false; + } + + // enter starting state + this->setState(STARTING); + + // play start tone double timeOfSoundPlaybackStart; - if(this->startActionSettings.contains(thisAction) && this->startActionSettings[thisAction]["Enabled"].toBool()) { - if(!this->soundPlayer->play(thisAction, this->soundVolume, &timeOfSoundPlaybackStart)) - return false; - if(this->state != STARTING) - return true; - } - - if(thisAction < Start) { - this->nextStartAction = StartAction(thisAction + 1); - qDebug() << "next action is: " << nextStartAction; - - int nextActionDelay = -1; - if(this->startActionSettings.contains(this->nextStartAction) && this->startActionSettings[this->nextStartAction]["Enabled"].toBool()) { - nextActionDelay = this->startActionSettings[this->nextStartAction]["Delay"].toInt(); - } - - // perform next action - this->nextActionTimer->start(nextActionDelay > 0 ? nextActionDelay:1); - if(nextActionDelay > 0) - emit this->nextStartActionChanged(); - this->nextActionLoop->exec(); - return this->playSoundsAndStartTimers(this->nextStartAction); - } + this->doDelayAndSoundOfStartAction(Start, &timeOfSoundPlaybackStart); // perform start @@ -250,6 +318,32 @@ bool ScStwRace::playSoundsAndStartTimers(StartAction thisAction) { } +bool ScStwRace::doDelayAndSoundOfStartAction(ScStwRace::StartAction action, double *timeOfSoundPlaybackStart) { + if(this->startActionSettings.contains(action) && this->startActionSettings[action]["Enabled"].toBool()) { + + this->nextStartAction = action; + emit this->nextStartActionChanged(); + + if(action != Start && this->startActionSettings[action]["Delay"].toInt() > 0) { + // perform the delay before the start + + // get delay + int thisActionDelay = this->startActionSettings[action]["Delay"].toInt(); + + // perform next action + if(thisActionDelay > 0) { + this->nextActionTimer->start(thisActionDelay); + this->nextActionLoop->exec(); + } + } + + if(!this->soundPlayer->play(action, this->soundVolume, timeOfSoundPlaybackStart)) + return false; + } + + return true; +} + void ScStwRace::setState(RaceState newState) { if(newState != this->state) { qDebug() << "[INFO][RACE] state changed: " << newState; @@ -401,6 +495,7 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); + connect(timer, &ScStwTimer::readyStateChanged, this->climberReadyWaitLoop, &QEventLoop::quit); if(!this->allowAutomaticTimerDisable && timer->getState() == ScStwTimer::DISABLED) timer->setDisabled(false); diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 6a69f52..e2b6bff 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -64,6 +64,12 @@ bool ScStwTimer::start(double timeOfStart) { } } +void ScStwTimer::technicalIncident() { + qDebug() << "[INFO][TIMER] Timer got a technical incident"; + + this->setState(INCIDENT); +} + void ScStwTimer::handleClimberStart(double timeOfStart) { this->reactionTime = timeOfStart - this->startTime; qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; @@ -80,7 +86,7 @@ bool ScStwTimer::cancel() { if(!(this->state == IDLE || this->state == STARTING || this->state == RUNNING)) return false; - this->setState(CANCELLED); + this->stop(CancelStop, -1); return true; } @@ -119,6 +125,11 @@ bool ScStwTimer::stop(StopReason reason, double timeOfStop) { this->setState(FAILED); break; } + case CancelStop: { + qDebug() << "[INFO][TIMER] Timer was cancelled"; + this->setState(CANCELLED); + break; + } default: { return false; } @@ -201,6 +212,9 @@ void ScStwTimer::setState(TimerState newState){ if(this->state == DISABLED && newState != IDLE) return; + if(this->state == INCIDENT && newState != IDLE) + return; + if(this->state != newState) { this->state = newState; qDebug() << "+ [INFO][TIMER] timer state changed: " << newState; From 6460714b62b8f7452f112596de01eeef196dcae0 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 29 Sep 2020 15:21:00 +0200 Subject: [PATCH 26/76] - some renaming - added INCIDENT state for race --- ScStwLibraries/headers/ScStw.hpp | 8 +-- ScStwLibraries/headers/scstwrace.h | 3 +- ScStwLibraries/sources/scstwrace.cpp | 82 ++++++++++++++++------------ 3 files changed, 53 insertions(+), 40 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index d7666b1..705b12d 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -147,10 +147,10 @@ public: * \brief The ExtensionState enum contains all possible states of an extension */ enum ExtensionState { - Disconnected = 0, - Connecting = 1, - Initialising = 2, - Connected = 3 + ExtensionDisconnected = 0, + ExtensionConnecting = 1, + ExtensionInitialising = 2, + ExtensionConnected = 3 }; Q_ENUM(ExtensionState); diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 2feff1b..bf0e28d 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -56,7 +56,7 @@ class ScStwRace : public QObject public: explicit ScStwRace(QObject *parent = nullptr); - enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED }; + enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED, INCIDENT }; Q_ENUM(RaceState) enum StartAction { None = -1, AtYourMarks = 0, Ready = 1, Start = 2 }; @@ -79,7 +79,6 @@ private: QTimer *nextActionTimer; QEventLoop *nextActionLoop; - QTimer *climberReadyWaitTimer; QEventLoop *climberReadyWaitLoop; // sounds diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 74a545a..e3af55c 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -58,7 +58,7 @@ int ScStwRace::start(bool asyncronous) { if(timer->getState() == ScStwTimer::DISABLED) continue; - if(timer->getReadyState() != ScStwTimer::ClimberIsNotReady) { + if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { if(this->allowAutomaticTimerDisable) { timer->setDisabled(true); @@ -70,13 +70,13 @@ int ScStwRace::start(bool asyncronous) { timer->technicalIncident(); foreach (ScStwTimer *subTimer, this->timers) { - if(timer != subTimer && subTimer->getReadyState() != ScStwTimer::ClimberIsNotReady) + if(timer != subTimer && (timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine)) subTimer->technicalIncident(); else if(timer != subTimer) subTimer->setState(ScStwTimer::CANCELLED); } - this->setState(STOPPED); + this->setState(INCIDENT); qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; @@ -161,7 +161,7 @@ void ScStwRace::handleTimerStop() { } int ScStwRace::reset() { - if(this->state != STOPPED) { + if(this->state != STOPPED && this->state != INCIDENT) { return ScStw::CurrentStateNotVaildForOperationError; } @@ -183,7 +183,7 @@ int ScStwRace::reset() { } int ScStwRace::cancel() { - if(this->state != STARTING && this->state != RUNNING) + if(this->state != PREPAIRING && this->state != WAITING && this->state != STARTING && this->state != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; qDebug() << "[INFO][RACE] cancelling race"; @@ -191,6 +191,7 @@ int ScStwRace::cancel() { this->soundPlayer->cancel(this->soundVolume); this->nextActionTimer->stop(); this->nextActionLoop->quit(); + this->climberReadyWaitLoop->quit(); this->nextStartAction = None; int returnCode = ScStw::Success; @@ -230,6 +231,10 @@ bool ScStwRace::playSoundsAndStartTimers() { return false; } + // check if the start was cancelled + if(this->state != PREPAIRING) + return false; + qDebug() << "NOW IN WAITING"; this->setState(WAITING); @@ -240,42 +245,51 @@ bool ScStwRace::playSoundsAndStartTimers() { // if the automatic ready tone is enabled, wait for the climbers to become ready if(this->startActionSettings.contains(Ready) && this->startActionSettings[Ready]["Enabled"].toBool()) { - qDebug() << "[RACE][INFO] Now waiting for climbers"; + qDebug() << "[RACE][INFO] Now waiting for climbers"; - // get delay - int minimumReadyDelay = 1000; - if(this->startActionSettings[Ready]["Delay"].toInt() > 1000 || !this->allowAutomaticTimerDisable) - minimumReadyDelay = this->startActionSettings[Ready]["Delay"].toInt(); + // get delay + int minimumReadyDelay = 1000; + if(this->startActionSettings[Ready]["Delay"].toInt() > 1000 || !this->allowAutomaticTimerDisable) + minimumReadyDelay = this->startActionSettings[Ready]["Delay"].toInt(); - // wait for climbers to become ready initially - bool allClimbersReady = false; - while (!allClimbersReady) { - allClimbersReady = true; - foreach (ScStwTimer *timer, this->timers) { - if(timer->getReadyState() != ScStwTimer::IsReady) - allClimbersReady = false; - } - - if(!allClimbersReady) - this->climberReadyWaitLoop->exec(); + // wait for climbers to become ready initially + bool allClimbersReady = false; + while (!allClimbersReady) { + allClimbersReady = true; + foreach (ScStwTimer *timer, this->timers) { + if(timer->getReadyState() != ScStwTimer::IsReady) + allClimbersReady = false; } - qDebug() << "[RACE][DEBUG] Initial wait finished"; - - // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly - // the climber ready wait loop will also quit, if the climber steps of the pad - // -> wait for both climbers to stand on the pad for at least one second - do { - this->nextActionTimer->stop(); - this->nextActionTimer->start(minimumReadyDelay); + if(!allClimbersReady) this->climberReadyWaitLoop->exec(); - } while(this->nextActionTimer->remainingTime() > 0); - qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; - - // play ready tone - if(!this->soundPlayer->play(Ready, this->soundVolume)) + // check if the start was cancelled + if(this->state != WAITING) return false; + } + + qDebug() << "[RACE][DEBUG] Initial wait finished"; + + // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly + // the climber ready wait loop will also quit, if the climber steps of the pad + // -> wait for both climbers to stand on the pad for at least one second + do { + this->nextActionTimer->stop(); + this->nextActionTimer->start(minimumReadyDelay); + this->climberReadyWaitLoop->exec(); + + // check if the start was cancelled + if(this->state != WAITING) + return false; + + } while(this->nextActionTimer->remainingTime() > 0); + + qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; + + // play ready tone + if(!this->soundPlayer->play(Ready, this->soundVolume)) + return false; } // enter starting state From 78b0b883d55aae9c7efeb59aa2fef9eb5cfe0c7d Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Thu, 1 Oct 2020 01:54:39 +0200 Subject: [PATCH 27/76] - began to redo layout - fixed some issues in ScStwRace --- ScStwLibraries/headers/scstwrace.h | 2 + .../sources/client/scstwremotemonitorrace.cpp | 7 +--- ScStwLibraries/sources/scstwrace.cpp | 40 ++++++++++++------- ScStwLibraries/sources/scstwtimer.cpp | 12 +++--- 4 files changed, 35 insertions(+), 26 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index bf0e28d..7f1b061 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -150,6 +150,8 @@ private slots: */ void handleTimerStop(); + bool isStarting(); + signals: void startTimers(); void stopTimers(int type); diff --git a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp index b286927..40767da 100644 --- a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp +++ b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp @@ -71,11 +71,6 @@ int ScStwRemoteMonitorRace::stop() { return 904; } - // type can be: - // 0: stopp - // 1: cancel - // 2: fail (fase start) - qDebug() << "+ --- stopping race"; int returnCode = 900; @@ -95,7 +90,7 @@ int ScStwRemoteMonitorRace::stop() { int ScStwRemoteMonitorRace::reset() { - if(this->getState() != ScStwRace::STOPPED) { + if(this->getState() != ScStwRace::STOPPED && this->getState() != ScStwRace::INCIDENT) { return 904; } diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index e3af55c..22af64d 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -175,9 +175,8 @@ int ScStwRace::reset() { } } - if(returnCode == ScStw::Success){ + if(returnCode == ScStw::Success) this->setState(IDLE); - } return returnCode; } @@ -188,12 +187,6 @@ int ScStwRace::cancel() { qDebug() << "[INFO][RACE] cancelling race"; - this->soundPlayer->cancel(this->soundVolume); - this->nextActionTimer->stop(); - this->nextActionLoop->quit(); - this->climberReadyWaitLoop->quit(); - this->nextStartAction = None; - int returnCode = ScStw::Success; foreach(ScStwTimer *timer, this->timers){ @@ -201,6 +194,17 @@ int ScStwRace::cancel() { returnCode = ScStw::InternalErrorTimerOperationFailed; } + if(returnCode != ScStw::Success) + return returnCode; + + this->setState(STOPPED); + + this->soundPlayer->cancel(this->soundVolume); + this->nextActionTimer->stop(); + this->nextActionLoop->quit(); + this->climberReadyWaitLoop->quit(); + this->nextStartAction = None; + return returnCode; } @@ -227,15 +231,13 @@ bool ScStwRace::playSoundsAndStartTimers() { // The check if all timers are ready has already happened at this point if(!this->doDelayAndSoundOfStartAction(AtYourMarks)) { - qDebug() << "At marks sound returned false!"; return false; } // check if the start was cancelled - if(this->state != PREPAIRING) + if(!this->isStarting()) return false; - qDebug() << "NOW IN WAITING"; this->setState(WAITING); // do climber readiness tests @@ -265,7 +267,7 @@ bool ScStwRace::playSoundsAndStartTimers() { this->climberReadyWaitLoop->exec(); // check if the start was cancelled - if(this->state != WAITING) + if(!this->isStarting()) return false; } @@ -280,7 +282,7 @@ bool ScStwRace::playSoundsAndStartTimers() { this->climberReadyWaitLoop->exec(); // check if the start was cancelled - if(this->state != WAITING) + if(!this->isStarting()) return false; } while(this->nextActionTimer->remainingTime() > 0); @@ -319,7 +321,7 @@ bool ScStwRace::playSoundsAndStartTimers() { } // check if a false start occured - if(this->state != STARTING) + if(!this->isStarting()) return true; nextStartAction = None; @@ -333,6 +335,9 @@ bool ScStwRace::playSoundsAndStartTimers() { } bool ScStwRace::doDelayAndSoundOfStartAction(ScStwRace::StartAction action, double *timeOfSoundPlaybackStart) { + if(!this->isStarting()) + return false; + if(this->startActionSettings.contains(action) && this->startActionSettings[action]["Enabled"].toBool()) { this->nextStartAction = action; @@ -351,6 +356,9 @@ bool ScStwRace::doDelayAndSoundOfStartAction(ScStwRace::StartAction action, doub } } + if(!this->isStarting()) + return false; + if(!this->soundPlayer->play(action, this->soundVolume, timeOfSoundPlaybackStart)) return false; } @@ -547,3 +555,7 @@ QVariantList ScStwRace::getTimerDetailList() { return tmpTimers; } + +bool ScStwRace::isStarting() { + return this->state == PREPAIRING || this->state == WAITING || this->state == STARTING; +} diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index e2b6bff..0756f50 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -86,7 +86,9 @@ bool ScStwTimer::cancel() { if(!(this->state == IDLE || this->state == STARTING || this->state == RUNNING)) return false; - this->stop(CancelStop, -1); + qDebug() << "[INFO][TIMER] Timer was cancelled"; + + this->setState(CANCELLED); return true; } @@ -125,11 +127,6 @@ bool ScStwTimer::stop(StopReason reason, double timeOfStop) { this->setState(FAILED); break; } - case CancelStop: { - qDebug() << "[INFO][TIMER] Timer was cancelled"; - this->setState(CANCELLED); - break; - } default: { return false; } @@ -284,6 +281,9 @@ QString ScStwTimer::getText() { case ScStwTimer::CANCELLED: newText = "cancelled"; break; + case ScStwTimer::INCIDENT: + newText = "Technical incident!"; + break; case ScStwTimer::DISABLED: newText = "---"; break; From 41818ff3083d741a2fc02147410cbdf8e7cf29d4 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 14:16:24 +0200 Subject: [PATCH 28/76] did some adjustments to allow waiting for climbers before start; renamed some stuff --- ScStwLibraries/headers/ScStw.hpp | 8 +- .../headers/client/scstwremotemonitorrace.h | 2 +- ScStwLibraries/headers/scstwrace.h | 46 +-- ScStwLibraries/headers/scstwsoundplayer.h | 6 + ScStwLibraries/sources/scstwrace.cpp | 288 +++++++++++------- 5 files changed, 204 insertions(+), 146 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 705b12d..47f6ba7 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -61,7 +61,7 @@ public: RaceStateChanged = 9000, TimersChanged = 9001, ExtensionsChanged = 9002, - NextStartActionChanged = 9003, /*, ProfilesChanged*/ + CurrentStartDelayChanged = 9003, /*, ProfilesChanged*/ SettingChanged = 9004 }; Q_ENUM(SignalKey) @@ -84,7 +84,7 @@ public: GetNextStartActionCommand = 2005, GetExtensionsCommand = 2006, GetTimersCommand = 2007, - GetNextStartActionDetailsCommand = 2009, + GetCurrentStartDelayCommand = 2009, WriteSettingCommand = 3000, ReadSettingCommand = 3001, @@ -160,8 +160,8 @@ public: */ enum ExtensionBatteryState { BatteryUnknown = -1, - BatteryFine = 1, - BatteryCritical = 0 + BatteryCritical = 0, + BatteryFine = 1 }; Q_ENUM(ExtensionBatteryState); diff --git a/ScStwLibraries/headers/client/scstwremotemonitorrace.h b/ScStwLibraries/headers/client/scstwremotemonitorrace.h index c36db54..281c53e 100644 --- a/ScStwLibraries/headers/client/scstwremotemonitorrace.h +++ b/ScStwLibraries/headers/client/scstwremotemonitorrace.h @@ -42,7 +42,7 @@ public slots: int stop(); int reset(); bool addTimer(ScStwTimer *timer); - QVariantList getNextStartActionDetails(); + QVariantList getCurrentStartDelay(); private slots: void handleClientStateChanged(); diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 7f1b061..3f4cafb 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -51,7 +51,7 @@ class ScStwRace : public QObject Q_OBJECT Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) - Q_PROPERTY(QVariantList nextStartActionDetails READ getNextStartActionDetails NOTIFY nextStartActionDetailsChanged) + Q_PROPERTY(QVariantList currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) public: explicit ScStwRace(QObject *parent = nullptr); @@ -59,42 +59,43 @@ public: enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED, INCIDENT }; Q_ENUM(RaceState) - enum StartAction { None = -1, AtYourMarks = 0, Ready = 1, Start = 2 }; - Q_ENUM(StartAction) - - enum NextStartActionDetailAttributes { - NextStartAction = 0, - NextStartActionTotalDelay = 1, - NextStartActionDelayProgress = 2 + enum CurrentStartDetailAttributes { + CurrentStartStateTotalDelay = 0, + CurrentStartStateDelayProgress = 1 }; - Q_ENUM(NextStartActionDetailAttributes); + Q_ENUM(CurrentStartDetailAttributes); protected: - StartAction nextStartAction; QList timers; void setState(RaceState newState); private: RaceState state; - QTimer *nextActionTimer; - QEventLoop *nextActionLoop; - QEventLoop *climberReadyWaitLoop; + QTimer *startDelayTimer; + QEventLoop *startWaitLoop; // sounds ScStwSoundPlayer * soundPlayer; // some settings double soundVolume; - bool allowAutomaticTimerDisable; - bool allowAutomaticTimerDisableChanged; + bool competitionMode; + bool competitionModeChanged; /*! * \brief stores the start action settings * * \details Stores the settings for the action ScStwRace::AtYourMarks and ScStwRace::Ready. The settings keys are: "Enabled" and "Delay" */ - QMap startActionSettings; + QMap startSoundSettings; + + + enum LoopExitTypes { + LoopAutomaticExit = 0, + LoopManualExit = 2, + LoopCancelExit = 3 + }; public slots: @@ -122,15 +123,14 @@ public slots: virtual int cancel(); // setters - bool writeStartActionSetting(StartAction action, bool enabled, int delay); + bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); bool setSoundVolume(double volume); virtual bool addTimer(ScStwTimer *timer); - void setAllowAutomaticTimerDisable(bool allow); + void setCompetitionMode(bool competitionMode); // getters RaceState getState(); - StartAction getNextStartAction(); - virtual QVariantList getNextStartActionDetails(); + virtual QVariantList getCurrentStartDelay(); QList getTimers(); QVariantList getTimerDetailList(); @@ -142,7 +142,7 @@ private slots: void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); int handleFalseStart(); bool playSoundsAndStartTimers(); - bool doDelayAndSoundOfStartAction(StartAction action, double *timeOfSoundPlaybackStart = nullptr); + bool doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); void enableAllTimers(); /** @@ -151,14 +151,14 @@ private slots: void handleTimerStop(); bool isStarting(); + bool isReadyForNextState(); signals: void startTimers(); void stopTimers(int type); void resetTimers(); void stateChanged(RaceState state); - void nextStartActionChanged(); - void nextStartActionDetailsChanged(); + void currentStartDelayChanged(); void timersChanged(); diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index d158725..561e995 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -41,6 +41,12 @@ public: */ explicit ScStwSoundPlayer(QObject *parent = nullptr); + enum StartSound { + Start, + Ready, + AtYourMarks + }; + private: /*! * \brief A map containing all sound files diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 22af64d..1321918 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -26,22 +26,18 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) this->soundPlayer = new ScStwSoundPlayer(); // configure timer that handles the delay between the start commands - this->nextActionTimer = new QTimer(this); - nextActionTimer->setSingleShot(true); - this->nextActionLoop = new QEventLoop(this); - this->nextStartAction = None; - this->climberReadyWaitLoop = new QEventLoop(this); + this->startDelayTimer = new QTimer(this); + startDelayTimer->setSingleShot(true); + this->startWaitLoop = new QEventLoop(this); - connect(this->nextActionTimer, &QTimer::timeout, this->nextActionLoop, &QEventLoop::quit); - connect(this->nextActionTimer, &QTimer::timeout, this->climberReadyWaitLoop, &QEventLoop::quit); - connect(this, &ScStwRace::nextStartActionChanged, this, &ScStwRace::nextStartActionDetailsChanged); + connect(this->startDelayTimer, &QTimer::timeout, this->startWaitLoop, &QEventLoop::quit); // write default settings - this->startActionSettings.insert(Start, {{"Enabled", true}, {"Delay", 1}}); - this->writeStartActionSetting(AtYourMarks, false, 0); - this->writeStartActionSetting(Ready, false, 0); + this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); + this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); + this->writeStartSoundSetting(ScStwSoundPlayer::Ready, false, 0); this->setSoundVolume(1.0); - this->allowAutomaticTimerDisable = false; + this->competitionMode = false; } // -------------------------- @@ -49,40 +45,22 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) // -------------------------- int ScStwRace::start(bool asyncronous) { - if(this->state != IDLE) { + if(this->state == WAITING) { + if(this->isReadyForNextState()) { + this->startWaitLoop->exit(LoopManualExit); + return ScStw::Success; + } + else { + return ScStw::TimersNotReadyError; + } + } + else if(this->state != IDLE) { return ScStw::CurrentStateNotVaildForOperationError; } qDebug() << "[INFO][RACE] checking timers"; - foreach (ScStwTimer *timer, this->timers) { - if(timer->getState() == ScStwTimer::DISABLED) - continue; - - if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { - - if(this->allowAutomaticTimerDisable) { - timer->setDisabled(true); - continue; - } - - qDebug() << "Timer ready state is: " << timer->getReadyState(); - - timer->technicalIncident(); - - foreach (ScStwTimer *subTimer, this->timers) { - if(timer != subTimer && (timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine)) - subTimer->technicalIncident(); - else if(timer != subTimer) - subTimer->setState(ScStwTimer::CANCELLED); - } - - this->setState(INCIDENT); - - qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; - - return ScStw::TimersNotReadyError; - } - } + if(!this->isReadyForNextState()) + return ScStw::TimersNotReadyError; qDebug() << "[INFO][RACE] starting race"; this->setState(PREPAIRING); @@ -199,11 +177,9 @@ int ScStwRace::cancel() { this->setState(STOPPED); + this->startWaitLoop->exit(LoopCancelExit); this->soundPlayer->cancel(this->soundVolume); - this->nextActionTimer->stop(); - this->nextActionLoop->quit(); - this->climberReadyWaitLoop->quit(); - this->nextStartAction = None; + this->startDelayTimer->stop(); return returnCode; } @@ -230,9 +206,8 @@ bool ScStwRace::playSoundsAndStartTimers() { return true; // The check if all timers are ready has already happened at this point - if(!this->doDelayAndSoundOfStartAction(AtYourMarks)) { + if(!this->doDelayAndSoundOfCurrentStartState()) return false; - } // check if the start was cancelled if(!this->isStarting()) @@ -241,65 +216,84 @@ bool ScStwRace::playSoundsAndStartTimers() { this->setState(WAITING); // do climber readiness tests - this->nextStartAction = Ready; - emit this->nextStartActionChanged(); + + // wait until both climbers are ready // if the automatic ready tone is enabled, wait for the climbers to become ready - if(this->startActionSettings.contains(Ready) && this->startActionSettings[Ready]["Enabled"].toBool()) { + if(this->startSoundSettings.contains(ScStwSoundPlayer::Ready) && this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) { qDebug() << "[RACE][INFO] Now waiting for climbers"; // get delay int minimumReadyDelay = 1000; - if(this->startActionSettings[Ready]["Delay"].toInt() > 1000 || !this->allowAutomaticTimerDisable) - minimumReadyDelay = this->startActionSettings[Ready]["Delay"].toInt(); + if(this->startSoundSettings[ScStwSoundPlayer::Ready]["Delay"].toInt() > 1000) + minimumReadyDelay = this->startSoundSettings[ScStwSoundPlayer::Ready]["Delay"].toInt(); + + this->startDelayTimer->setInterval(minimumReadyDelay); // wait for climbers to become ready initially - bool allClimbersReady = false; - while (!allClimbersReady) { - allClimbersReady = true; - foreach (ScStwTimer *timer, this->timers) { - if(timer->getReadyState() != ScStwTimer::IsReady) - allClimbersReady = false; + bool timerTriggered = true; + do { + + if(!this->isReadyForNextState()) { + this->startDelayTimer->stop(); + timerTriggered = false; + } + else if(this->startDelayTimer->isActive()) { + timerTriggered = true; + } + else { + this->startDelayTimer->stop(); + this->startDelayTimer->start(); } - if(!allClimbersReady) - this->climberReadyWaitLoop->exec(); + emit this->currentStartDelayChanged(); - // check if the start was cancelled - if(!this->isStarting()) + int loopExitCode = this->startWaitLoop->exec(); + + switch (loopExitCode) { + case LoopAutomaticExit: + break; + case LoopManualExit: + // prevent manual stop + timerTriggered = false; + break; + case LoopCancelExit: return false; - } + } + + } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->isReadyForNextState()); qDebug() << "[RACE][DEBUG] Initial wait finished"; // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly // the climber ready wait loop will also quit, if the climber steps of the pad // -> wait for both climbers to stand on the pad for at least one second - do { - this->nextActionTimer->stop(); - this->nextActionTimer->start(minimumReadyDelay); - this->climberReadyWaitLoop->exec(); - - // check if the start was cancelled - if(!this->isStarting()) - return false; - - } while(this->nextActionTimer->remainingTime() > 0); qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; // play ready tone - if(!this->soundPlayer->play(Ready, this->soundVolume)) + if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) return false; } + else { + // wait for climbers and manual start + int loopExitCode; + do { + loopExitCode = this->startWaitLoop->exec(); + + if(loopExitCode == LoopCancelExit) + return false; + + } while(loopExitCode != LoopManualExit || !this->isReadyForNextState()); + } // enter starting state this->setState(STARTING); // play start tone double timeOfSoundPlaybackStart; - this->doDelayAndSoundOfStartAction(Start, &timeOfSoundPlaybackStart); + this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart); // perform start @@ -324,9 +318,6 @@ bool ScStwRace::playSoundsAndStartTimers() { if(!this->isStarting()) return true; - nextStartAction = None; - emit this->nextStartActionChanged(); - this->setState(RUNNING); return true; @@ -334,32 +325,48 @@ bool ScStwRace::playSoundsAndStartTimers() { } -bool ScStwRace::doDelayAndSoundOfStartAction(ScStwRace::StartAction action, double *timeOfSoundPlaybackStart) { - if(!this->isStarting()) +bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart) { + ScStwSoundPlayer::StartSound sound; + + switch (this->state) { + case PREPAIRING: + sound = ScStwSoundPlayer::AtYourMarks; + break; + case WAITING: + sound = ScStwSoundPlayer::Ready; + break; + case STARTING: + sound = ScStwSoundPlayer::Start; + break; + default: return false; + } - if(this->startActionSettings.contains(action) && this->startActionSettings[action]["Enabled"].toBool()) { + if(this->startSoundSettings.contains(sound) && this->startSoundSettings[sound]["Enabled"].toBool()) { - this->nextStartAction = action; - emit this->nextStartActionChanged(); - if(action != Start && this->startActionSettings[action]["Delay"].toInt() > 0) { + if(sound != ScStwSoundPlayer::Start && this->startSoundSettings[sound]["Delay"].toInt() > 0) { // perform the delay before the start // get delay - int thisActionDelay = this->startActionSettings[action]["Delay"].toInt(); + int thisSoundDelay = this->startSoundSettings[sound]["Delay"].toInt(); // perform next action - if(thisActionDelay > 0) { - this->nextActionTimer->start(thisActionDelay); - this->nextActionLoop->exec(); + if(thisSoundDelay > 0) { + this->startDelayTimer->setInterval(thisSoundDelay); + this->startDelayTimer->start(); + + emit this->currentStartDelayChanged(); + + if(this->startWaitLoop->exec() == LoopCancelExit) + return false; } } if(!this->isStarting()) return false; - if(!this->soundPlayer->play(action, this->soundVolume, timeOfSoundPlaybackStart)) + if(!this->soundPlayer->play(sound, this->soundVolume, timeOfSoundPlaybackStart)) return false; } @@ -374,12 +381,12 @@ void ScStwRace::setState(RaceState newState) { if(this->state == IDLE) { // if we changed to IDLE -> handle timer enable / disable - if(this->allowAutomaticTimerDisableChanged && !this->allowAutomaticTimerDisable) { + if(this->competitionModeChanged && this->competitionMode) { this->enableAllTimers(); - this->allowAutomaticTimerDisableChanged = false; + this->competitionModeChanged = false; } - if(this->allowAutomaticTimerDisable) { + if(!this->competitionMode) { foreach(ScStwTimer* timer, this->timers) { if(timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); @@ -418,12 +425,64 @@ void ScStwRace::refreshTimerStates() { // --- helper functions --- // ------------------------ +bool ScStwRace::isReadyForNextState() { + switch (this->state) { + case IDLE: { + foreach (ScStwTimer *timer, this->timers) { + if(timer->getState() == ScStwTimer::DISABLED) + continue; + + if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { + + if(!this->competitionMode) { + timer->setDisabled(true); + continue; + } + + qDebug() << "Timer ready state is: " << timer->getReadyState(); + + timer->technicalIncident(); + + foreach (ScStwTimer *subTimer, this->timers) { + if(timer != subTimer && (timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine)) + subTimer->technicalIncident(); + else if(timer != subTimer) + subTimer->setState(ScStwTimer::CANCELLED); + } + + this->setState(INCIDENT); + + qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; + + return false; + } + } + + break; + case WAITING: { + foreach (ScStwTimer *timer, this->timers) { + if(timer->getReadyState() != ScStwTimer::IsReady) + return false; + } + break; + } + + default: + break;; + } + + } + + return true; + +} + /** * @brief ScStwRace::handleTimerEnable function to enable timers at the right moment to prevent them from bricking the state machine * @param {ScStwExtensionControlledTimer*} timer timer to be enabled */ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled) { - if(!this->allowAutomaticTimerDisable) + if(this->competitionMode) return; if(this->state == IDLE) { @@ -431,18 +490,17 @@ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wants } } - -void ScStwRace::setAllowAutomaticTimerDisable(bool allow) { - if(this->allowAutomaticTimerDisable == allow) +void ScStwRace::setCompetitionMode(bool competitionMode) { + if(this->competitionMode == competitionMode) return; - qDebug() << "Setting allow automatic timer disable to " << allow; + qDebug() << "Setting competition mode to " << competitionMode; - this->allowAutomaticTimerDisable = allow; + this->competitionMode = competitionMode; if(this->state != IDLE) - this->allowAutomaticTimerDisableChanged = true; - else if(!this->allowAutomaticTimerDisable) + this->competitionModeChanged = true; + else if(this->competitionMode) this->enableAllTimers(); } @@ -457,14 +515,14 @@ void ScStwRace::enableAllTimers() { } } -QVariantList ScStwRace::getNextStartActionDetails() { +QVariantList ScStwRace::getCurrentStartDelay() { int nextActionDelay = 0; double nextActionDelayProg = -1; - if(this->nextStartAction == AtYourMarks || this->nextStartAction == Ready) { + if(this->state == PREPAIRING || this->state == WAITING) { // get the total delay and the delay progress of the next action timer - double remaining = this->nextActionTimer->remainingTime(); - nextActionDelay = this->startActionSettings[this->nextStartAction]["Delay"].toInt(); + double remaining = this->startDelayTimer->remainingTime(); + nextActionDelay = this->startDelayTimer->interval();; if(remaining < 0) { remaining = nextActionDelay; } @@ -472,22 +530,21 @@ QVariantList ScStwRace::getNextStartActionDetails() { } return { - this->nextStartAction, nextActionDelay, nextActionDelayProg }; } -bool ScStwRace::writeStartActionSetting(StartAction action, bool enabled, int delay) { - if(action != AtYourMarks && action != Ready) +bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { + if(sound != ScStwSoundPlayer::AtYourMarks && sound != ScStwSoundPlayer::Ready) return false; QVariantMap setting = {{"Enabled", enabled}, {"Delay", delay}}; - if(!this->startActionSettings.contains(action)) - this->startActionSettings.insert(action, setting); + if(!this->startSoundSettings.contains(sound)) + this->startSoundSettings.insert(sound, setting); else - this->startActionSettings[action] = setting; + this->startSoundSettings[sound] = setting; return true; } @@ -517,9 +574,9 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); - connect(timer, &ScStwTimer::readyStateChanged, this->climberReadyWaitLoop, &QEventLoop::quit); + connect(timer, &ScStwTimer::readyStateChanged, this->startWaitLoop, &QEventLoop::quit); - if(!this->allowAutomaticTimerDisable && timer->getState() == ScStwTimer::DISABLED) + if(this->competitionMode && timer->getState() == ScStwTimer::DISABLED) timer->setDisabled(false); return true; @@ -530,11 +587,6 @@ ScStwRace::RaceState ScStwRace::getState() { return this->state; } -ScStwRace::StartAction ScStwRace::getNextStartAction() -{ - return this->nextStartAction; -} - QList ScStwRace::getTimers() { return this->timers; } From d1f132d0b02fb6b4208f89455aae0a934658687b Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 15:20:11 +0200 Subject: [PATCH 29/76] - some bug fixes n race and sound player - added cancelRace command --- ScStwLibraries/headers/ScStw.hpp | 1 + ScStwLibraries/headers/scstwrace.h | 8 +++--- ScStwLibraries/headers/scstwsoundplayer.h | 11 ++++---- ScStwLibraries/sources/scstwrace.cpp | 31 +++++++++++++++------ ScStwLibraries/sources/scstwsoundplayer.cpp | 28 +++++++++---------- 5 files changed, 47 insertions(+), 32 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 47f6ba7..fac3f33 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -79,6 +79,7 @@ public: StartRaceCommand = 1000, StopRaceCommand = 1001, ResetRaceCommand = 1002, + CancelRaceCommand = 1003, GetRaceStateCommand = 2000, GetNextStartActionCommand = 2005, diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 3f4cafb..80906da 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -106,21 +106,21 @@ public slots: * or if if should wait until the start sequence is over and quit after that (false) * \return 200: OK; 904: state not matching */ - int start(bool asyncronous = true); + virtual ScStw::StatusCode start(bool asyncronous = true); /*! * \brief Function to stop the currently running race * * \return 200: OK; 904: state not matching */ - virtual int stop(); + virtual ScStw::StatusCode stop(); /*! * \brief Function to reset a stopped race * \return */ - virtual int reset(); - virtual int cancel(); + virtual ScStw::StatusCode reset(); + virtual ScStw::StatusCode cancel(); // setters bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index 561e995..1e977db 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -42,9 +42,10 @@ public: explicit ScStwSoundPlayer(QObject *parent = nullptr); enum StartSound { - Start, + AtYourMarks, Ready, - AtYourMarks + Start, + FalseStart }; private: @@ -55,7 +56,7 @@ private: * 2: StartSound * 3: FalseStartSound */ - QMap soundFiles; + QMap soundFiles; /*! * \brief The sound effect object @@ -75,7 +76,7 @@ private: /*! * \brief The action that is currently played */ - int currentlyPlayingAction; + StartSound currentlyPlayingSound; /*! * \brief Holds the time the playback started at @@ -91,7 +92,7 @@ public slots: * \param timeOfStop The time the playback actually started (msecs since epoch) * \return true if the playback was successfully started, false otherwise */ - bool play(int action, double volume, double *timeOfStart = nullptr); + bool play(StartSound sound, double volume, double *timeOfStart = nullptr); /*! * \brief Function to wait for the playback to finish diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 1321918..eb65e9e 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -206,6 +206,7 @@ bool ScStwRace::playSoundsAndStartTimers() { return true; // The check if all timers are ready has already happened at this point + qDebug() << "now playing at marks sound"; if(!this->doDelayAndSoundOfCurrentStartState()) return false; @@ -213,6 +214,7 @@ bool ScStwRace::playSoundsAndStartTimers() { if(!this->isStarting()) return false; + qDebug() << "Now in waiting state"; this->setState(WAITING); // do climber readiness tests @@ -220,7 +222,7 @@ bool ScStwRace::playSoundsAndStartTimers() { // wait until both climbers are ready // if the automatic ready tone is enabled, wait for the climbers to become ready - if(this->startSoundSettings.contains(ScStwSoundPlayer::Ready) && this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) { + if(this->competitionMode && this->startSoundSettings.contains(ScStwSoundPlayer::Ready) && this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) { qDebug() << "[RACE][INFO] Now waiting for climbers"; @@ -245,11 +247,15 @@ bool ScStwRace::playSoundsAndStartTimers() { else { this->startDelayTimer->stop(); this->startDelayTimer->start(); + timerTriggered = true; } emit this->currentStartDelayChanged(); + + qDebug() << "entering wait loop..."; int loopExitCode = this->startWaitLoop->exec(); + qDebug() << "wait loop exited with code " << loopExitCode; switch (loopExitCode) { case LoopAutomaticExit: @@ -262,6 +268,8 @@ bool ScStwRace::playSoundsAndStartTimers() { return false; } + qDebug() << "At end of loop: remaining time: " << this->startDelayTimer->remainingTime() << " timer triggered: " << timerTriggered << " ready for next state: " << this->isReadyForNextState(); + } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->isReadyForNextState()); qDebug() << "[RACE][DEBUG] Initial wait finished"; @@ -276,7 +284,7 @@ bool ScStwRace::playSoundsAndStartTimers() { if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) return false; } - else { + else if(this->competitionMode) { // wait for climbers and manual start int loopExitCode; do { @@ -287,11 +295,19 @@ bool ScStwRace::playSoundsAndStartTimers() { } while(loopExitCode != LoopManualExit || !this->isReadyForNextState()); } + else { + qDebug() << "now playing ready sound"; + if(!this->doDelayAndSoundOfCurrentStartState()) + return false; + } + + qDebug() << "now in starting state"; // enter starting state this->setState(STARTING); // play start tone + qDebug() << "now playing start sound"; double timeOfSoundPlaybackStart; this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart); @@ -343,8 +359,6 @@ bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackSt } if(this->startSoundSettings.contains(sound) && this->startSoundSettings[sound]["Enabled"].toBool()) { - - if(sound != ScStwSoundPlayer::Start && this->startSoundSettings[sound]["Delay"].toInt() > 0) { // perform the delay before the start @@ -426,6 +440,10 @@ void ScStwRace::refreshTimerStates() { // ------------------------ bool ScStwRace::isReadyForNextState() { + if(!this->competitionMode) { + return true; + } + switch (this->state) { case IDLE: { foreach (ScStwTimer *timer, this->timers) { @@ -434,11 +452,6 @@ bool ScStwRace::isReadyForNextState() { if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { - if(!this->competitionMode) { - timer->setDisabled(true); - continue; - } - qDebug() << "Timer ready state is: " << timer->getReadyState(); timer->technicalIncident(); diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 0c576a5..79b82d0 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -23,10 +23,10 @@ ScStwSoundPlayer::ScStwSoundPlayer(QObject *parent) : QObject(parent) this->waitLoop = new QEventLoop(this); this->waitTimer = new QTimer(this); - this->soundFiles.insert(0, {{"path","qrc:/sound/AtYourMarksSound.wav"}, {"duration", 1000}}); - this->soundFiles.insert(1, {{"path","qrc:/sound/ReadySound.wav"}, {"duration", 570}}); - this->soundFiles.insert(2, {{"path","qrc:/sound/StartsignalSoundExtended.wav"}, {"duration", 3200}}); - this->soundFiles.insert(3, {{"path","qrc:/sound/FalseStartSound.wav"}, {"duration", 2000}}); + this->soundFiles.insert(AtYourMarks, {{"path","qrc:/sound/AtYourMarksSound.wav"}, {"duration", 1000}}); + this->soundFiles.insert(Ready, {{"path","qrc:/sound/ReadySound.wav"}, {"duration", 570}}); + this->soundFiles.insert(Start, {{"path","qrc:/sound/StartsignalSoundExtended.wav"}, {"duration", 3200}}); + this->soundFiles.insert(FalseStart, {{"path","qrc:/sound/FalseStartSound.wav"}, {"duration", 2000}}); this->soundEffect = new QSoundEffect(this); this->soundEffect->setLoopCount(1); @@ -35,11 +35,11 @@ ScStwSoundPlayer::ScStwSoundPlayer(QObject *parent) : QObject(parent) connect(this->soundEffect, &QSoundEffect::playingChanged, this->waitLoop, &QEventLoop::quit); } -bool ScStwSoundPlayer::play(int action, double volume, double *timeOfStart) { - if(!this->soundFiles.contains(action)) +bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, double *timeOfStart) { + if(!this->soundFiles.contains(sound)) return false; - if(action > 2 || action < 0) + if(sound > Start || sound < AtYourMarks) return false; // stop playback @@ -47,13 +47,13 @@ bool ScStwSoundPlayer::play(int action, double volume, double *timeOfStart) { this->soundEffect->stop(); // update currently playing action - this->currentlyPlayingAction = action; + this->currentlyPlayingSound = sound; // update volume this->soundEffect->setVolume(volume); // load - this->soundEffect->setSource(this->soundFiles[action]["path"].toString()); + this->soundEffect->setSource(this->soundFiles[sound]["path"].toString()); // wait for the effect to load QEventLoop loop; @@ -76,7 +76,7 @@ bool ScStwSoundPlayer::play(int action, double volume, double *timeOfStart) { *timeOfStart = this->playingStartedAt; } - if(action < 2) + if(sound < 2) return this->waitForSoundFinish(); return true; @@ -90,14 +90,14 @@ bool ScStwSoundPlayer::cancel(double volume) { this->soundEffect->stop(); this->waitLoop->quit(); - if(this->currentlyPlayingAction != 2) + if(this->currentlyPlayingSound != 2) return true; // update volume this->soundEffect->setVolume(volume); // load - this->soundEffect->setSource(this->soundFiles[3]["path"].toString()); + this->soundEffect->setSource(this->soundFiles[FalseStart]["path"].toString()); // play this->soundEffect->play(); @@ -114,7 +114,7 @@ bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { // wait until the sound is actually over // the timeOffset is the buffer time before the audio started! - int timeOffset = this->soundFiles[this->currentlyPlayingAction]["duration"].toDouble() - (QDateTime::currentMSecsSinceEpoch() - playingStartedAt); + int timeOffset = this->soundFiles[this->currentlyPlayingSound]["duration"].toDouble() - (QDateTime::currentMSecsSinceEpoch() - playingStartedAt); if(timeOffset > 0) { QTimer timer; @@ -124,7 +124,7 @@ bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { // calculate the point in time where the sound playback actually ended if(timeOfStop != nullptr) { - int latency = this->playingStartedAt + this->soundFiles[this->currentlyPlayingAction]["duration"].toDouble(); + int latency = this->playingStartedAt + this->soundFiles[this->currentlyPlayingSound]["duration"].toDouble(); *timeOfStop = QDateTime::currentMSecsSinceEpoch() - latency; } From 72b03c0e66b791af96f987b17d06327295802325 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 15:23:30 +0200 Subject: [PATCH 30/76] bug fixes --- ScStwLibraries/sources/scstwrace.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index eb65e9e..803e23a 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -44,7 +44,7 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) // --- Main Functionality --- // -------------------------- -int ScStwRace::start(bool asyncronous) { +ScStw::StatusCode ScStwRace::start(bool asyncronous) { if(this->state == WAITING) { if(this->isReadyForNextState()) { this->startWaitLoop->exit(LoopManualExit); @@ -74,7 +74,7 @@ int ScStwRace::start(bool asyncronous) { return ScStw::Success; } -int ScStwRace::stop() { +ScStw::StatusCode ScStwRace::stop() { if(this->state != RUNNING && this->state != STARTING) { return ScStw::CurrentStateNotVaildForOperationError; } @@ -83,7 +83,7 @@ int ScStwRace::stop() { double timeOfStop = QDateTime::currentMSecsSinceEpoch(); - int returnCode = ScStw::Success; + ScStw::StatusCode returnCode = ScStw::Success; foreach(ScStwTimer *speedTimer, this->timers){ if(!speedTimer->stop(timeOfStop) && speedTimer->getState() != ScStwTimer::DISABLED){ @@ -138,14 +138,14 @@ void ScStwRace::handleTimerStop() { } } -int ScStwRace::reset() { +ScStw::StatusCode ScStwRace::reset() { if(this->state != STOPPED && this->state != INCIDENT) { return ScStw::CurrentStateNotVaildForOperationError; } qDebug() << "+ [INFO] resetting race"; - int returnCode = ScStw::Success; + ScStw::StatusCode returnCode = ScStw::Success; foreach(ScStwTimer *speedTimer, this->timers){ if(!speedTimer->reset() && speedTimer->getState() != ScStwTimer::DISABLED) { @@ -159,13 +159,13 @@ int ScStwRace::reset() { return returnCode; } -int ScStwRace::cancel() { +ScStw::StatusCode ScStwRace::cancel() { if(this->state != PREPAIRING && this->state != WAITING && this->state != STARTING && this->state != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; qDebug() << "[INFO][RACE] cancelling race"; - int returnCode = ScStw::Success; + ScStw::StatusCode returnCode = ScStw::Success; foreach(ScStwTimer *timer, this->timers){ if(!timer->cancel() && timer->getState() != ScStwTimer::DISABLED) From a247a6c3054545ec69c4eff14b5134f4c084ec31 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 16:49:24 +0200 Subject: [PATCH 31/76] some fixes --- .../headers/client/scstwremotemonitorrace.h | 13 +- .../sources/client/scstwremotemonitorrace.cpp | 117 +++++++----------- ScStwLibraries/sources/scstwlibraries.cpp | 1 + 3 files changed, 52 insertions(+), 79 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremotemonitorrace.h b/ScStwLibraries/headers/client/scstwremotemonitorrace.h index 281c53e..ef134e7 100644 --- a/ScStwLibraries/headers/client/scstwremotemonitorrace.h +++ b/ScStwLibraries/headers/client/scstwremotemonitorrace.h @@ -30,17 +30,18 @@ public: ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObject *parent = nullptr); protected: - double nextStartActionTotalDelay; - double nextStartActionDelayStartedAt; + double currentStartTotalDelay; + double currentStartDelayStartedAt; + bool currentlyWaitingForClimbers; private: ScStwClient *scStwClient; public slots: - int start(); - int cancel(); - int stop(); - int reset(); + ScStw::StatusCode start(); + ScStw::StatusCode cancel(); + ScStw::StatusCode stop(); + ScStw::StatusCode reset(); bool addTimer(ScStwTimer *timer); QVariantList getCurrentStartDelay(); diff --git a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp index 40767da..210ce9d 100644 --- a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp +++ b/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp @@ -20,11 +20,13 @@ ScStwRemoteMonitorRace::ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObject *parent) : ScStwRace(parent) { + this->currentlyWaitingForClimbers = false; + this->scStwClient = monitorClient; this->scStwClient->addSignalSubscription(ScStw::RaceStateChanged); this->scStwClient->addSignalSubscription(ScStw::TimersChanged); - this->scStwClient->addSignalSubscription(ScStw::NextStartActionChanged); + this->scStwClient->addSignalSubscription(ScStw::CurrentStartDelayChanged); connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteMonitorRace::handleClientStateChanged); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteMonitorRace::handleBaseStationSignal); @@ -34,84 +36,48 @@ ScStwRemoteMonitorRace::ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObje // --- Main Functionality --- // -------------------------- -int ScStwRemoteMonitorRace::start() { - - if(this->getState() != ScStwRace::IDLE) { - return 904; - } +ScStw::StatusCode ScStwRemoteMonitorRace::start() { + if(this->getState() != ScStwRace::IDLE && this->getState() != ScStwRace::WAITING) + return ScStw::CurrentStateNotVaildForOperationError; qDebug() << "+ --- starting race"; - int returnCode = 900; + QVariantMap reply = this->scStwClient->sendCommand(ScStw::StartRaceCommand); - QVariantMap reply = this->scStwClient->sendCommand(1000); - - if(reply["status"] != 200){ - //handle Error!! - returnCode = reply["status"].toInt(); - } - else { - - returnCode = 200; - - } - - - return returnCode; + return ScStw::StatusCode(reply["status"].toInt()); } -int ScStwRemoteMonitorRace::cancel() { - return this->stop(); - -} - -int ScStwRemoteMonitorRace::stop() { - - if(this->getState() != ScStwRace::RUNNING && this->getState() != ScStwRace::STARTING) { - return 904; - } +ScStw::StatusCode ScStwRemoteMonitorRace::cancel() { + if(this->getState() != PREPAIRING && this->getState() != WAITING && this->getState() != STARTING && this->getState() != RUNNING) + return ScStw::CurrentStateNotVaildForOperationError; qDebug() << "+ --- stopping race"; - int returnCode = 900; + QVariantMap reply = this->scStwClient->sendCommand(ScStw::CancelRaceCommand); - QVariantMap reply = this->scStwClient->sendCommand(1001); - - if(reply["status"] != 200){ - returnCode = reply["status"].toInt(); - } - else { - returnCode = 200; - } - - - return returnCode; + return ScStw::StatusCode(reply["status"].toInt()); } -int ScStwRemoteMonitorRace::reset() { +ScStw::StatusCode ScStwRemoteMonitorRace::stop() { + if(this->getState() != ScStwRace::RUNNING && this->getState() != ScStwRace::STARTING) + return ScStw::CurrentStateNotVaildForOperationError; - if(this->getState() != ScStwRace::STOPPED && this->getState() != ScStwRace::INCIDENT) { - return 904; - } + qDebug() << "+ --- stopping race"; + + QVariantMap reply = this->scStwClient->sendCommand(ScStw::StopRaceCommand); + + return ScStw::StatusCode(reply["status"].toInt()); +} + +ScStw::StatusCode ScStwRemoteMonitorRace::reset() { + if(this->getState() != ScStwRace::STOPPED && this->getState() != ScStwRace::INCIDENT) + return ScStw::CurrentStateNotVaildForOperationError; qDebug() << "+ --- resetting race"; - int returnCode = 900; + QVariantMap reply = this->scStwClient->sendCommand(ScStw::ResetRaceCommand); - - QVariantMap reply = this->scStwClient->sendCommand(1002); - - if(reply["status"] != 200){ - //handle Error!! - returnCode = reply["status"].toInt(); - } - else { - returnCode = 200; - } - - - - return returnCode; + return ScStw::StatusCode(reply["status"].toInt()); } @@ -154,14 +120,17 @@ void ScStwRemoteMonitorRace::handleBaseStationSignal(ScStw::SignalKey key, QVari this->refreshRemoteTimers(data.toList()); break; } - case ScStw::NextStartActionChanged: + case ScStw::CurrentStartDelayChanged: { // the next start action has changed - this->nextStartActionTotalDelay = data.toList()[ScStwRace::NextStartActionTotalDelay].toDouble(); - this->nextStartActionDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->nextStartActionTotalDelay * data.toList()[ScStwRace::NextStartActionDelayProgress].toDouble()); - this->nextStartAction = ScStwRace::StartAction( data.toList()[ScStwRace::NextStartAction].toInt() ); + this->currentStartTotalDelay = data.toList()[ScStwRace::CurrentStartStateTotalDelay].toInt(); + this->currentStartDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->currentStartTotalDelay * data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble()); + this->currentlyWaitingForClimbers = data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble() == 0 && this->currentStartTotalDelay == -1; + + emit this->currentStartDelayChanged(); + + qDebug() << "Current start delay changed: total:" << this->currentStartTotalDelay << " progress: " << data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble(); - emit this->nextStartActionChanged(); break; } case ScStw::InvalidSignal: @@ -218,14 +187,17 @@ bool ScStwRemoteMonitorRace::addTimer(ScStwTimer* timer) { return false; } -QVariantList ScStwRemoteMonitorRace::getNextStartActionDetails() { - int nextActionDelay = 0; +QVariantList ScStwRemoteMonitorRace::getCurrentStartDelay() { + int nextActionDelay = -1; double nextActionDelayProg = -1; - if(this->nextStartAction == AtYourMarks || this->nextStartAction == Ready) { + if(this->getState() == WAITING && this->currentlyWaitingForClimbers) { + nextActionDelayProg = 0; + } + else if(this->getState() == PREPAIRING || this->getState() == WAITING) { // get the total delay and the delay progress of the next action timer - double elapsed = QDateTime::currentMSecsSinceEpoch() - this->nextStartActionDelayStartedAt; - nextActionDelay = this->nextStartActionTotalDelay; + double elapsed = QDateTime::currentMSecsSinceEpoch() - this->currentStartDelayStartedAt; + nextActionDelay = this->currentStartTotalDelay; if(elapsed < 0 || elapsed > nextActionDelay) { elapsed = nextActionDelay; } @@ -233,7 +205,6 @@ QVariantList ScStwRemoteMonitorRace::getNextStartActionDetails() { } return { - this->nextStartAction, nextActionDelay, nextActionDelayProg }; diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index c557e26..34b75b7 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -28,6 +28,7 @@ void ScStwLibraries::init() { qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStw"); qRegisterMetaType("ScStwSettings::BaseStationSetting"); qRegisterMetaType("ScStw::SocketCommand"); + qRegisterMetaType("ScStw::StatusCode"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRace"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwTimer"); From 9a81d87451154935a976d65e2b199d6ed22eb917 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 17:05:52 +0200 Subject: [PATCH 32/76] some fixes in race and soundplayer --- ScStwLibraries/headers/scstwsoundplayer.h | 9 ++-- ScStwLibraries/sources/scstwrace.cpp | 51 +++++++++++++-------- ScStwLibraries/sources/scstwsoundplayer.cpp | 4 +- 3 files changed, 39 insertions(+), 25 deletions(-) diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index 1e977db..ac05926 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -42,10 +42,11 @@ public: explicit ScStwSoundPlayer(QObject *parent = nullptr); enum StartSound { - AtYourMarks, - Ready, - Start, - FalseStart + None = -1, + AtYourMarks = 0, + Ready = 1, + Start = 2, + FalseStart = 3 }; private: diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 803e23a..f90f0de 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -58,11 +58,9 @@ ScStw::StatusCode ScStwRace::start(bool asyncronous) { return ScStw::CurrentStateNotVaildForOperationError; } - qDebug() << "[INFO][RACE] checking timers"; if(!this->isReadyForNextState()) return ScStw::TimersNotReadyError; - qDebug() << "[INFO][RACE] starting race"; this->setState(PREPAIRING); if(asyncronous) { @@ -156,6 +154,8 @@ ScStw::StatusCode ScStwRace::reset() { if(returnCode == ScStw::Success) this->setState(IDLE); + this->soundPlayer->cancel(); + return returnCode; } @@ -181,6 +181,8 @@ ScStw::StatusCode ScStwRace::cancel() { this->soundPlayer->cancel(this->soundVolume); this->startDelayTimer->stop(); + emit this->currentStartDelayChanged(); + return returnCode; } @@ -233,7 +235,10 @@ bool ScStwRace::playSoundsAndStartTimers() { this->startDelayTimer->setInterval(minimumReadyDelay); - // wait for climbers to become ready initially + // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly + // the climber ready wait loop will also quit, if the climber steps of the pad + // -> wait for both climbers to stand on the pad for at least one second + bool timerTriggered = true; do { @@ -252,10 +257,7 @@ bool ScStwRace::playSoundsAndStartTimers() { emit this->currentStartDelayChanged(); - - qDebug() << "entering wait loop..."; int loopExitCode = this->startWaitLoop->exec(); - qDebug() << "wait loop exited with code " << loopExitCode; switch (loopExitCode) { case LoopAutomaticExit: @@ -268,21 +270,18 @@ bool ScStwRace::playSoundsAndStartTimers() { return false; } - qDebug() << "At end of loop: remaining time: " << this->startDelayTimer->remainingTime() << " timer triggered: " << timerTriggered << " ready for next state: " << this->isReadyForNextState(); + //qDebug() << "At end of loop: remaining time: " << this->startDelayTimer->remainingTime() << " timer triggered: " << timerTriggered << " ready for next state: " << this->isReadyForNextState(); } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->isReadyForNextState()); - qDebug() << "[RACE][DEBUG] Initial wait finished"; - - // wait for all climbers to be ready for the ReadyActionDelay, but at least one second continuosly - // the climber ready wait loop will also quit, if the climber steps of the pad - // -> wait for both climbers to stand on the pad for at least one second - qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; // play ready tone - if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) + if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) { + qDebug() << "Ready sound redturned false!"; + this->setState(INCIDENT); return false; + } } else if(this->competitionMode) { // wait for climbers and manual start @@ -297,8 +296,10 @@ bool ScStwRace::playSoundsAndStartTimers() { } else { qDebug() << "now playing ready sound"; - if(!this->doDelayAndSoundOfCurrentStartState()) + if(!this->doDelayAndSoundOfCurrentStartState()) { + this->cancel(); return false; + } } qDebug() << "now in starting state"; @@ -309,7 +310,10 @@ bool ScStwRace::playSoundsAndStartTimers() { // play start tone qDebug() << "now playing start sound"; double timeOfSoundPlaybackStart; - this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart); + if(!this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart)) { + this->setState(INCIDENT); + return false; + } // perform start @@ -322,11 +326,13 @@ bool ScStwRace::playSoundsAndStartTimers() { } if(!startOk) { qDebug() << "[ERROR][START] error staring all timers"; + this->setState(INCIDENT); return false; } if(!this->soundPlayer->waitForSoundFinish()) { qDebug() << "[ERROR][START] start sound wait error"; + this->setState(INCIDENT); return false; } @@ -529,17 +535,24 @@ void ScStwRace::enableAllTimers() { } QVariantList ScStwRace::getCurrentStartDelay() { - int nextActionDelay = 0; + int nextActionDelay = -1; double nextActionDelayProg = -1; - if(this->state == PREPAIRING || this->state == WAITING) { + if(this->state == WAITING && !this->isReadyForNextState()) { + // indicate that we are waiting for climbers and the progress shall be zero + nextActionDelayProg = 0; + } + else if(this->state == PREPAIRING || this->state == WAITING) { // get the total delay and the delay progress of the next action timer double remaining = this->startDelayTimer->remainingTime(); - nextActionDelay = this->startDelayTimer->interval();; + nextActionDelay = this->startDelayTimer->interval(); if(remaining < 0) { remaining = nextActionDelay; } nextActionDelayProg = 1 - (remaining / nextActionDelay); + + if(nextActionDelayProg < 0) + nextActionDelayProg = 0; } return { diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 79b82d0..be694c5 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -76,7 +76,7 @@ bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, d *timeOfStart = this->playingStartedAt; } - if(sound < 2) + if(sound < Start) return this->waitForSoundFinish(); return true; @@ -90,7 +90,7 @@ bool ScStwSoundPlayer::cancel(double volume) { this->soundEffect->stop(); this->waitLoop->quit(); - if(this->currentlyPlayingSound != 2) + if(this->currentlyPlayingSound != Start) return true; // update volume From ef8ceff27ef215d94ca2323d2121e95cf2c5e428 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 19:53:07 +0200 Subject: [PATCH 33/76] - some bug fixes - added race details --- ScStwLibraries/headers/ScStw.hpp | 5 ++-- ScStwLibraries/headers/scstwrace.h | 4 +++ ScStwLibraries/sources/scstwrace.cpp | 32 +++++++++++++++++++-- ScStwLibraries/sources/scstwsoundplayer.cpp | 17 ----------- 4 files changed, 37 insertions(+), 21 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index fac3f33..a05be82 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -62,7 +62,8 @@ public: TimersChanged = 9001, ExtensionsChanged = 9002, CurrentStartDelayChanged = 9003, /*, ProfilesChanged*/ - SettingChanged = 9004 + SettingChanged = 9004, + RaceDetailsChanged = 9005 }; Q_ENUM(SignalKey) @@ -82,7 +83,7 @@ public: CancelRaceCommand = 1003, GetRaceStateCommand = 2000, - GetNextStartActionCommand = 2005, + GetRaceDetailsCommand = 2001, GetExtensionsCommand = 2006, GetTimersCommand = 2007, GetCurrentStartDelayCommand = 2009, diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 80906da..779bc86 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -52,6 +52,7 @@ class ScStwRace : public QObject Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) Q_PROPERTY(QVariantList currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) + Q_PROPERTY(QVariantMap details READ getDetails NOTIFY detailsChanged) public: explicit ScStwRace(QObject *parent = nullptr); @@ -133,6 +134,7 @@ public slots: virtual QVariantList getCurrentStartDelay(); QList getTimers(); QVariantList getTimerDetailList(); + QVariantMap getDetails(); protected slots: @@ -152,6 +154,7 @@ private slots: bool isStarting(); bool isReadyForNextState(); + void handleTimerReadyStateChange(ScStwTimer::ReadyState readyState); signals: void startTimers(); @@ -160,6 +163,7 @@ signals: void stateChanged(RaceState state); void currentStartDelayChanged(); void timersChanged(); + void detailsChanged(); }; diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index f90f0de..c9ebb3d 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -32,6 +32,9 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) connect(this->startDelayTimer, &QTimer::timeout, this->startWaitLoop, &QEventLoop::quit); + connect(this, &ScStwRace::currentStartDelayChanged, this, &ScStwRace::detailsChanged); + connect(this, &ScStwRace::timersChanged, this, &ScStwRace::detailsChanged); + // write default settings this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); @@ -198,7 +201,8 @@ int ScStwRace::handleFalseStart() { } this->setState(STOPPED); - this->soundPlayer->cancel(this->soundVolume); + this->soundPlayer->cancel(); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->soundVolume); return returnCode; } @@ -597,10 +601,11 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { this->timers.append(timer); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::refreshTimerStates); - connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); + connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::readyStateChanged, this->startWaitLoop, &QEventLoop::quit); + connect(timer, &ScStwTimer::readyStateChanged, this, &ScStwRace::handleTimerReadyStateChange); if(this->competitionMode && timer->getState() == ScStwTimer::DISABLED) timer->setDisabled(false); @@ -628,12 +633,35 @@ QVariantList ScStwRace::getTimerDetailList() { tmpTimer.insert("reactionTime", timer->getReactionTime()); tmpTimer.insert("text", timer->getText()); tmpTimer.insert("letter", timer->getLetter()); + tmpTimer.insert("readyState", timer->getReadyState()); tmpTimers.append(tmpTimer); } return tmpTimers; } +QVariantMap ScStwRace::getDetails() { + QVariantMap tmpDetails; + + tmpDetails.insert("timers", this->getTimerDetailList()); + tmpDetails.insert("currentStartDelay", this->getCurrentStartDelay()); + tmpDetails.insert("competitionMode", this->competitionMode); + tmpDetails.insert("readySoundEnabled", this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()); + + if(this->state == WAITING) + tmpDetails.insert("isReady", this->isReadyForNextState()); + + return tmpDetails; +} + bool ScStwRace::isStarting() { return this->state == PREPAIRING || this->state == WAITING || this->state == STARTING; } + +void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { + Q_UNUSED(readyState) + + // only continue if the current state is waiting + if(this->state == WAITING) + emit this->timersChanged(); +} diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index be694c5..07de6f0 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -39,9 +39,6 @@ bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, d if(!this->soundFiles.contains(sound)) return false; - if(sound > Start || sound < AtYourMarks) - return false; - // stop playback if(this->soundEffect->isPlaying()) this->soundEffect->stop(); @@ -89,20 +86,6 @@ bool ScStwSoundPlayer::cancel(double volume) { // stop playback this->soundEffect->stop(); this->waitLoop->quit(); - - if(this->currentlyPlayingSound != Start) - return true; - - // update volume - this->soundEffect->setVolume(volume); - - // load - this->soundEffect->setSource(this->soundFiles[FalseStart]["path"].toString()); - - // play - this->soundEffect->play(); - - return true; } bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { From e8d091e345a9027e5586f6564179496633cec7e7 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 19:55:47 +0200 Subject: [PATCH 34/76] some fixes in race and settings --- .../client/{scstwremotemonitorrace.h => scstwremoterace.h} | 0 .../client/{scstwremotemonitorrace.cpp => scstwremoterace.cpp} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename ScStwLibraries/headers/client/{scstwremotemonitorrace.h => scstwremoterace.h} (100%) rename ScStwLibraries/sources/client/{scstwremotemonitorrace.cpp => scstwremoterace.cpp} (100%) diff --git a/ScStwLibraries/headers/client/scstwremotemonitorrace.h b/ScStwLibraries/headers/client/scstwremoterace.h similarity index 100% rename from ScStwLibraries/headers/client/scstwremotemonitorrace.h rename to ScStwLibraries/headers/client/scstwremoterace.h diff --git a/ScStwLibraries/sources/client/scstwremotemonitorrace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp similarity index 100% rename from ScStwLibraries/sources/client/scstwremotemonitorrace.cpp rename to ScStwLibraries/sources/client/scstwremoterace.cpp From 8be3541bb5dcc1ee79f64589b0134cc1d0abdf64 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 2 Oct 2020 19:56:08 +0200 Subject: [PATCH 35/76] some fixes in race and settings --- ScStwLibraries/ScStwLibraries.pri | 10 ++- .../headers/client/scstwremoterace.h | 7 +- .../headers/client/scstwremotetimer.h | 80 +++++++++++++++++++ ScStwLibraries/headers/scstwlibraries.h | 2 +- ScStwLibraries/headers/scstwrace.h | 2 + ScStwLibraries/headers/scstwsetting.h | 10 ++- ScStwLibraries/headers/scstwsettings.h | 23 +----- ScStwLibraries/headers/scstwtimer.h | 60 +------------- .../sources/client/scstwremoterace.cpp | 49 +++++++----- .../sources/client/scstwremotesettings.cpp | 2 + .../sources/client/scstwremotetimer.cpp | 41 ++++++++++ ScStwLibraries/sources/scstwrace.cpp | 2 + ScStwLibraries/sources/scstwsetting.cpp | 16 +++- ScStwLibraries/sources/scstwsettings.cpp | 2 +- ScStwLibraries/sources/scstwtimer.cpp | 45 +---------- 15 files changed, 192 insertions(+), 159 deletions(-) create mode 100644 ScStwLibraries/headers/client/scstwremotetimer.h create mode 100644 ScStwLibraries/sources/client/scstwremotetimer.cpp diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index 903b9bc..28d1ab7 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -39,13 +39,15 @@ HEADERS += \ ScStwLibraries_ClientLibs { SOURCES += \ $$PWD/sources/client/scstwclient.cpp \ - $$PWD/sources/client/scstwremotesettings.cpp \ - $$PWD/sources/client/scstwremotemonitorrace.cpp + $$PWD/sources/client/scstwremoterace.cpp \ + $$PWD/sources/client/scstwremotetimer.cpp \ + $$PWD/sources/client/scstwremotesettings.cpp HEADERS += \ $$PWD/headers/client/scstwclient.h \ - $$PWD/headers/client/scstwremotesettings.h \ - $$PWD/headers/client/scstwremotemonitorrace.h + $$PWD/headers/client/scstwremoterace.h \ + $$PWD/headers/client/scstwremotetimer.h \ + $$PWD/headers/client/scstwremotesettings.h INCLUDEPATH += $$PWD/headers/client } diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index ef134e7..42c68dc 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -22,12 +22,13 @@ #include #include "scstwrace.h" #include "scstwclient.h" +#include "scstwremotetimer.h" -class ScStwRemoteMonitorRace : public ScStwRace +class ScStwRemoteRace : public ScStwRace { Q_OBJECT public: - ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObject *parent = nullptr); + ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent = nullptr); protected: double currentStartTotalDelay; @@ -36,8 +37,10 @@ protected: private: ScStwClient *scStwClient; + QList remoteTimers; public slots: + ScStw::StatusCode start(bool); ScStw::StatusCode start(); ScStw::StatusCode cancel(); ScStw::StatusCode stop(); diff --git a/ScStwLibraries/headers/client/scstwremotetimer.h b/ScStwLibraries/headers/client/scstwremotetimer.h new file mode 100644 index 0000000..71d5992 --- /dev/null +++ b/ScStwLibraries/headers/client/scstwremotetimer.h @@ -0,0 +1,80 @@ +#ifndef SCSTWREMOTETIMER_H +#define SCSTWREMOTETIMER_H + +#include +#include + +class ScStwRemoteTimer : public ScStwTimer +{ + Q_OBJECT +public: + ScStwRemoteTimer(QObject *parent = nullptr); + + friend class ScStwRemoteRace; + +private: + ScStwTimer::ReadyState readyState; + +public slots: + /*! + * \brief Function to get the current ready status of a timer + * \return The current ready status + */ + virtual ScStwTimer::ReadyState getReadyState(); + +protected slots: + /*! + * \brief Function to dircetly change the start time + * + * Only works when directControlEnabled is set to true! + * + * \param startTime the time to change to + * \return false when directControlEnabled is set to false and the startTime was therefore not modified, true otherwise + */ + void setStartTime(double startTime); + + /*! + * \brief Function to dircetly change the stop time + * + * Only works when directControlEnabled is set to true! + * + * \param stopTime the time to change to + * \return false when directControlEnabled is set to false and the stopTime was therefore not modified, true otherwise + */ + void setStopTime(double stopTime); + + /*! + * \brief Function to dircetly change the rection time + * + * Only works when directControlEnabled is set to true! + * + * \param reactionTime the time to change to + * \return false when directControlEnabled is set to false and the reactionTime was therefore not modified, true otherwise + */ + void setReactionTime(double rectionTime); + + /*! + * \brief Function to dircetly change the letter + * + * Only works when directControlEnabled is set to true! + * + * \param newLetter the letter to change to + * \return false when directControlEnabled is set to false and the letter was therefore not modified, true otherwise + */ + void setLetter(QString newLetter); + + void setReadyState(ScStwTimer::ReadyState); + + /*! + * \brief Function to change the state of the timer + * + * Doing this will emit the ScStwTimer::stateChanged() signal (only if the new state differs from the current one) + * + * \param newState The new state + */ + void setState(TimerState newState); + + +}; + +#endif // SCSTWREMOTETIMER_H diff --git a/ScStwLibraries/headers/scstwlibraries.h b/ScStwLibraries/headers/scstwlibraries.h index e7c495e..1965a70 100644 --- a/ScStwLibraries/headers/scstwlibraries.h +++ b/ScStwLibraries/headers/scstwlibraries.h @@ -34,7 +34,7 @@ #include "scstwsettings.h" #ifdef ScStwLibraries_ClientLibs #include "scstwsetting.h" -#include "scstwremotemonitorrace.h" +#include "scstwremoterace.h" #include "scstwclient.h" #endif diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 80906da..e3edea4 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -52,6 +52,7 @@ class ScStwRace : public QObject Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) Q_PROPERTY(QVariantList currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) + Q_PROPERTY(bool isReadyForNextState READ isReadyForNextState NOTIFY isReadyForNextStateChanged) public: explicit ScStwRace(QObject *parent = nullptr); @@ -160,6 +161,7 @@ signals: void stateChanged(RaceState state); void currentStartDelayChanged(); void timersChanged(); + void isReadyForNextStateChanged(); }; diff --git a/ScStwLibraries/headers/scstwsetting.h b/ScStwLibraries/headers/scstwsetting.h index 72818b7..bd57cd7 100644 --- a/ScStwLibraries/headers/scstwsetting.h +++ b/ScStwLibraries/headers/scstwsetting.h @@ -22,23 +22,25 @@ #include #include +class ScStwSettings; + class ScStwSetting : public QObject { Q_OBJECT Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged) protected: - explicit ScStwSetting(QObject *parent = nullptr); + explicit ScStwSetting(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent); + + friend class ScStwSettings; int key; int keyLevel; bool hasToReload; - virtual bool writeSetting(int, int, QVariant) = 0; - virtual QVariant readSetting(int, int) = 0; - private: QVariant valueCache; + ScStwSettings *scStwSettings; public slots: QVariant getValue(); diff --git a/ScStwLibraries/headers/scstwsettings.h b/ScStwLibraries/headers/scstwsettings.h index 19026b8..282a603 100644 --- a/ScStwLibraries/headers/scstwsettings.h +++ b/ScStwLibraries/headers/scstwsettings.h @@ -109,30 +109,9 @@ private: bool loadSettingsFromFile(); - class ScStwSettingInternal: public ScStwSetting { - public: - ScStwSettingInternal(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent):ScStwSetting(parent) { - this->scStwSettings = scStwSettings; - connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSettingInternal::handleSettingChange); - this->key = key; - this->keyLevel = keyLevel; - this->handleSettingChange(-1, 0, QVariant()); - } - protected: - ScStwSettings *scStwSettings; - - bool writeSetting(int key, int keyLevel, QVariant value) { - return this->scStwSettings->writeSetting(key, keyLevel, value); - } - - QVariant readSetting(int key, int keyLevel) { - return this->scStwSettings->readSetting(key, keyLevel); - } - }; - QMap keyToStringConverters; QMap keyToTypeConverters; - QMap> internalSettingHandlers; + QMap> internalSettingHandlers; private slots: bool writeSettingsToFile(); diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 25e9fda..a8a94a0 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -71,10 +71,9 @@ public: * \param directControlEnabled Defines if protected properties (startTimer, stopTime, reactionTime and state) can be directly set from outside. * \param letter the letter of the timer (only first char will be used!) */ - explicit ScStwTimer(QObject *parent = nullptr, bool directControlEnabled = false, QString letter = "" ); + explicit ScStwTimer(QObject *parent = nullptr, QString letter = "" ); friend class ScStwRace; - friend class ScStwRemoteRace; /*! * \brief The TimerState enum contains all state the timer can be in @@ -137,11 +136,6 @@ protected: */ double reactionTime; - /*! - * \brief Defines if protected properties (startTimer, stopTime, reactionTime and state) can be directly set from outside. - */ - bool directControlEnabled; - /*! * \brief The letter (eg. "A" or "B") of the Timer (only one char) */ @@ -267,58 +261,6 @@ public slots: */ void setDisabled(bool disabled); - /*! - * \brief Function to change the state of the timer - * - * Only works when directControlEnabled is set to true! - * Doing this will emit the ScStwTimer::stateChanged() signal (only if the new state differs from the current one) - * - * \param newState The new state - * \param force whether to force the state change (just to distinguish between protected and public function) - * \return false when directControlEnabled or force is set to false and the startTime was therefore not modified, true otherwise - */ - bool setState(TimerState newState, bool force); - - /*! - * \brief Function to dircetly change the start time - * - * Only works when directControlEnabled is set to true! - * - * \param startTime the time to change to - * \return false when directControlEnabled is set to false and the startTime was therefore not modified, true otherwise - */ - bool setStartTime(double startTime); - - /*! - * \brief Function to dircetly change the stop time - * - * Only works when directControlEnabled is set to true! - * - * \param stopTime the time to change to - * \return false when directControlEnabled is set to false and the stopTime was therefore not modified, true otherwise - */ - bool setStopTime(double stopTime); - - /*! - * \brief Function to dircetly change the rection time - * - * Only works when directControlEnabled is set to true! - * - * \param reactionTime the time to change to - * \return false when directControlEnabled is set to false and the reactionTime was therefore not modified, true otherwise - */ - bool setReactionTime(double rectionTime); - - /*! - * \brief Function to dircetly change the letter - * - * Only works when directControlEnabled is set to true! - * - * \param newLetter the letter to change to - * \return false when directControlEnabled is set to false and the letter was therefore not modified, true otherwise - */ - bool setLetter(QString newLetter); - /*! * \brief Function to check if the timer currently wants to be disabled * \return true or false diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 210ce9d..13f94ba 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -16,9 +16,9 @@ ** along with this program. If not, see . ****************************************************************************/ -#include "scstwremotemonitorrace.h" +#include "scstwremoterace.h" -ScStwRemoteMonitorRace::ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObject *parent) : ScStwRace(parent) +ScStwRemoteRace::ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent) : ScStwRace(parent) { this->currentlyWaitingForClimbers = false; @@ -28,15 +28,19 @@ ScStwRemoteMonitorRace::ScStwRemoteMonitorRace(ScStwClient *monitorClient, QObje this->scStwClient->addSignalSubscription(ScStw::TimersChanged); this->scStwClient->addSignalSubscription(ScStw::CurrentStartDelayChanged); - connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteMonitorRace::handleClientStateChanged); - connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteMonitorRace::handleBaseStationSignal); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChanged); + connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteRace::handleBaseStationSignal); } // -------------------------- // --- Main Functionality --- // -------------------------- -ScStw::StatusCode ScStwRemoteMonitorRace::start() { +ScStw::StatusCode ScStwRemoteRace::start(bool) { + return this->start(); +} + +ScStw::StatusCode ScStwRemoteRace::start() { if(this->getState() != ScStwRace::IDLE && this->getState() != ScStwRace::WAITING) return ScStw::CurrentStateNotVaildForOperationError; @@ -47,7 +51,7 @@ ScStw::StatusCode ScStwRemoteMonitorRace::start() { return ScStw::StatusCode(reply["status"].toInt()); } -ScStw::StatusCode ScStwRemoteMonitorRace::cancel() { +ScStw::StatusCode ScStwRemoteRace::cancel() { if(this->getState() != PREPAIRING && this->getState() != WAITING && this->getState() != STARTING && this->getState() != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; @@ -58,7 +62,7 @@ ScStw::StatusCode ScStwRemoteMonitorRace::cancel() { return ScStw::StatusCode(reply["status"].toInt()); } -ScStw::StatusCode ScStwRemoteMonitorRace::stop() { +ScStw::StatusCode ScStwRemoteRace::stop() { if(this->getState() != ScStwRace::RUNNING && this->getState() != ScStwRace::STARTING) return ScStw::CurrentStateNotVaildForOperationError; @@ -69,7 +73,7 @@ ScStw::StatusCode ScStwRemoteMonitorRace::stop() { return ScStw::StatusCode(reply["status"].toInt()); } -ScStw::StatusCode ScStwRemoteMonitorRace::reset() { +ScStw::StatusCode ScStwRemoteRace::reset() { if(this->getState() != ScStwRace::STOPPED && this->getState() != ScStwRace::INCIDENT) return ScStw::CurrentStateNotVaildForOperationError; @@ -85,7 +89,7 @@ ScStw::StatusCode ScStwRemoteMonitorRace::reset() { // --- Base Station sync --- // ------------------------- -void ScStwRemoteMonitorRace::handleClientStateChanged() { +void ScStwRemoteRace::handleClientStateChanged() { // TODO switch (this->scStwClient->getState()) { case ScStwClient::CONNECTED: @@ -105,7 +109,7 @@ void ScStwRemoteMonitorRace::handleClientStateChanged() { * * @param data */ -void ScStwRemoteMonitorRace::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { +void ScStwRemoteRace::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { //qDebug() << "got signal: " << data; switch (key) { case ScStw::RaceStateChanged: @@ -141,7 +145,7 @@ void ScStwRemoteMonitorRace::handleBaseStationSignal(ScStw::SignalKey key, QVari } } -bool ScStwRemoteMonitorRace::refreshRemoteTimers(QVariantList remoteTimers) { +bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { if(remoteTimers.length() != this->timers.length()){ // local timers are out of sync @@ -155,8 +159,9 @@ bool ScStwRemoteMonitorRace::refreshRemoteTimers(QVariantList remoteTimers) { foreach(QVariant remoteTimer, remoteTimers){ // create a local timer for each remote timer - ScStwTimer * timer = new ScStwTimer(this, true); + ScStwRemoteTimer * timer = new ScStwRemoteTimer(this); this->timers.append(timer); + this->remoteTimers.append(timer); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); } @@ -164,30 +169,34 @@ bool ScStwRemoteMonitorRace::refreshRemoteTimers(QVariantList remoteTimers) { foreach(QVariant remoteTimer, remoteTimers){ int currId = remoteTimer.toMap()["id"].toInt(); + ScStwTimer::TimerState newState = ScStwTimer::TimerState(remoteTimer.toMap()["state"].toInt()); + + qDebug() << "refreshing timers: id: " << currId << " state: " << newState << " readyState: " << remoteTimer.toMap()["readyState"].toInt(); + double currentMSecsSinceEpoch = QDateTime::currentMSecsSinceEpoch(); - this->timers[currId]->setStartTime(currentMSecsSinceEpoch - remoteTimer.toMap()["currentTime"].toDouble()); + this->remoteTimers[currId]->setStartTime(currentMSecsSinceEpoch - remoteTimer.toMap()["currentTime"].toDouble()); if(newState >= ScStwTimer::WAITING) - this->timers[currId]->setStopTime(currentMSecsSinceEpoch); + this->remoteTimers[currId]->setStopTime(currentMSecsSinceEpoch); - this->timers[currId]->setReactionTime(remoteTimer.toMap()["reactionTime"].toDouble()); + this->remoteTimers[currId]->setReactionTime(remoteTimer.toMap()["reactionTime"].toDouble()); + this->remoteTimers[currId]->setLetter(remoteTimer.toMap()["letter"].toString()); + this->remoteTimers[currId]->setReadyState(ScStwTimer::ReadyState(remoteTimer.toMap()["readyState"].toInt())); - this->timers[currId]->setState(newState, true); - - this->timers[currId]->setLetter(remoteTimer.toMap()["letter"].toString()); + this->remoteTimers[currId]->setState(newState); } return true; } -bool ScStwRemoteMonitorRace::addTimer(ScStwTimer* timer) { +bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { Q_UNUSED(timer) return false; } -QVariantList ScStwRemoteMonitorRace::getCurrentStartDelay() { +QVariantList ScStwRemoteRace::getCurrentStartDelay() { int nextActionDelay = -1; double nextActionDelayProg = -1; diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index 5fb46f7..4128256 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -59,6 +59,8 @@ bool ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant void ScStwRemoteSettings::handleClientStateChange() { if(this->scStwClient->getState() == ScStwClient::DISCONNECTED) emit this->settingChanged(-1, 0, QVariant()); + else if(this->scStwClient->getState() == ScStwClient::CONNECTED) + emit this->settingChanged(-1, 0, QVariant()); } void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { diff --git a/ScStwLibraries/sources/client/scstwremotetimer.cpp b/ScStwLibraries/sources/client/scstwremotetimer.cpp new file mode 100644 index 0000000..a1c55b2 --- /dev/null +++ b/ScStwLibraries/sources/client/scstwremotetimer.cpp @@ -0,0 +1,41 @@ +#include "../../headers/client/scstwremotetimer.h" + +ScStwRemoteTimer::ScStwRemoteTimer(QObject *parent) : ScStwTimer(parent) +{ + this->readyState = ScStwTimer::getReadyState(); +} + +ScStwTimer::ReadyState ScStwRemoteTimer::getReadyState() { + return this->readyState; +} + +void ScStwRemoteTimer::setStartTime(double startTime) { + this->startTime = startTime; +} + +void ScStwRemoteTimer::setStopTime(double stopTime) { + this->stopTime = stopTime; +} + +void ScStwRemoteTimer::setReactionTime(double reactionTime) { + this->reactionTime = reactionTime; +} + +void ScStwRemoteTimer::setLetter(QString newLetter) { + this->letter = newLetter; +} + +void ScStwRemoteTimer::setReadyState(ScStwTimer::ReadyState readyState) { + if(this->readyState != readyState) { + this->readyState = readyState; + emit this->readyStateChanged(readyState); + } +} + +void ScStwRemoteTimer::setState(TimerState newState){ + if(this->state != newState) { + this->state = newState; + qDebug() << "+ [INFO][REMOTETIMER] timer state changed: " << newState; + emit this->stateChanged(); + } +} diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 803e23a..56d753f 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -589,6 +589,8 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::readyStateChanged, this->startWaitLoop, &QEventLoop::quit); + connect(timer, &ScStwTimer::readyStateChanged, this, &ScStwRace::isReadyForNextStateChanged); + if(this->competitionMode && timer->getState() == ScStwTimer::DISABLED) timer->setDisabled(false); diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp index 1c10f53..2dcc0ee 100644 --- a/ScStwLibraries/sources/scstwsetting.cpp +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -17,22 +17,32 @@ ****************************************************************************/ #include "scstwsetting.h" +#include "scstwsettings.h" #include -ScStwSetting::ScStwSetting(QObject *parent) : QObject(parent) +ScStwSetting::ScStwSetting(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent) : QObject(parent) { + this->scStwSettings = scStwSettings; + connect(this->scStwSettings, &ScStwSettings::settingChanged, this, &ScStwSetting::handleSettingChange); + this->key = key; + this->keyLevel = keyLevel; + this->handleSettingChange(-1, this->keyLevel, QVariant()); } QVariant ScStwSetting::getValue() { if(this->hasToReload) { - this->valueCache = this->readSetting(this->key, this->keyLevel); + this->valueCache = this->scStwSettings->readSetting(this->key, this->keyLevel); this->hasToReload = false; } + + qDebug() << "Setting read: keyLevel: " << this->keyLevel << " key: " << this->key << " value: " << this->valueCache; + return this->valueCache; } + void ScStwSetting::setValue(QVariant value) { if(value != this->valueCache) { - this->writeSetting(this->key, this->keyLevel, value); + this->scStwSettings->writeSetting(this->key, this->keyLevel, value); } } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index fa372ea..260881f 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -112,7 +112,7 @@ ScStwSetting * ScStwSettings::getSetting(int key, int keyLevel) { this->internalSettingHandlers.insert(keyLevel, {}); if(!this->internalSettingHandlers[keyLevel].contains(key)) - this->internalSettingHandlers[keyLevel].insert(key, new ScStwSettingInternal(key, keyLevel, this, this)); + this->internalSettingHandlers[keyLevel].insert(key, new ScStwSetting(key, keyLevel, this, this)); return this->internalSettingHandlers[keyLevel][key]; } diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 0756f50..249bfa8 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -18,10 +18,8 @@ #include "../headers/scstwtimer.h" -ScStwTimer::ScStwTimer(QObject *parent, bool directControlEnabled, QString letter) : QObject(parent) +ScStwTimer::ScStwTimer(QObject *parent, QString letter) : QObject(parent) { - this->directControlEnabled = directControlEnabled; - if(letter.length() > 1) this->letter = letter[0]; else @@ -30,6 +28,7 @@ ScStwTimer::ScStwTimer(QObject *parent, bool directControlEnabled, QString lette this->startTime = 0; this->stopTime = 0; this->reactionTime = 0; + this->wantsToBeDisabled = false; this->state = IDLE; } @@ -173,38 +172,6 @@ ScStwTimer::ReadyState ScStwTimer::getReadyState() { // --- helper functions --- // ------------------------ -bool ScStwTimer::setStartTime(double startTime) { - if(!this->directControlEnabled) - return false; - - this->startTime = startTime; - return true; -} - -bool ScStwTimer::setStopTime(double stopTime) { - if(!this->directControlEnabled) - return false; - - this->stopTime = stopTime; - return true; -} - -bool ScStwTimer::setReactionTime(double reactionTime) { - if(!this->directControlEnabled) - return false; - - this->reactionTime = reactionTime; - return true; -} - -bool ScStwTimer::setState(TimerState newState, bool force) { - if(!this->directControlEnabled || !force) - return false; - - this->setState(newState); - return true; -} - void ScStwTimer::setState(TimerState newState){ if(this->state == DISABLED && newState != IDLE) return; @@ -219,14 +186,6 @@ void ScStwTimer::setState(TimerState newState){ } } -bool ScStwTimer::setLetter(QString newLetter) { - if(!this->directControlEnabled) - return false; - - this->letter = newLetter; - return true; -} - ScStwTimer::TimerState ScStwTimer::getState() { return this->state; } From c9e1f4f8ecfa46b10560c608b303d607819266b3 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 11:10:15 +0200 Subject: [PATCH 36/76] implemented race details --- .../headers/client/scstwremoterace.h | 4 ++ ScStwLibraries/headers/scstwrace.h | 11 +-- ScStwLibraries/headers/scstwsoundplayer.h | 2 +- .../sources/client/scstwremoterace.cpp | 68 +++++++++++-------- ScStwLibraries/sources/scstwrace.cpp | 24 ++++--- ScStwLibraries/sources/scstwsoundplayer.cpp | 4 +- 6 files changed, 67 insertions(+), 46 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 42c68dc..9c89e56 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -23,6 +23,7 @@ #include "scstwrace.h" #include "scstwclient.h" #include "scstwremotetimer.h" +#include "scstwsoundplayer.h" class ScStwRemoteRace : public ScStwRace { @@ -34,6 +35,7 @@ protected: double currentStartTotalDelay; double currentStartDelayStartedAt; bool currentlyWaitingForClimbers; + bool isReadyForNextState; private: ScStwClient *scStwClient; @@ -47,11 +49,13 @@ public slots: ScStw::StatusCode reset(); bool addTimer(ScStwTimer *timer); QVariantList getCurrentStartDelay(); + bool getIsReadyForNextState(); private slots: void handleClientStateChanged(); void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); bool refreshRemoteTimers(QVariantList remoteTimers); + void refreshDetails(QVariantMap details); }; diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 78b5c44..6d9b682 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -26,6 +26,8 @@ #include "scstwtimer.h" #include "scstwsoundplayer.h" +class ScStwRemoteRace; + /*! * \brief The ScStwRace class can be used to measure timings of climbing races with multiple lanes at once. * @@ -52,12 +54,14 @@ class ScStwRace : public QObject Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) Q_PROPERTY(QVariantList currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) - Q_PROPERTY(bool isReadyForNextState READ isReadyForNextState NOTIFY isReadyForNextStateChanged) + Q_PROPERTY(bool isReadyForNextState READ getIsReadyForNextState NOTIFY isReadyForNextStateChanged) Q_PROPERTY(QVariantMap details READ getDetails NOTIFY detailsChanged) public: explicit ScStwRace(QObject *parent = nullptr); + friend class ScStwRemoteRace; + enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED, INCIDENT }; Q_ENUM(RaceState) @@ -154,7 +158,7 @@ private slots: void handleTimerStop(); bool isStarting(); - bool isReadyForNextState(); + virtual bool getIsReadyForNextState(); void handleTimerReadyStateChange(ScStwTimer::ReadyState readyState); signals: @@ -164,11 +168,8 @@ signals: void stateChanged(RaceState state); void currentStartDelayChanged(); void timersChanged(); -<<<<<<< HEAD void isReadyForNextStateChanged(); -======= void detailsChanged(); ->>>>>>> origin/master }; diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index ac05926..82a8436 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -110,7 +110,7 @@ public slots: * \param volume the volume to play the false start sound at * \return true if the playback was successfully stopped, false otherwise */ - bool cancel(double volume = 0); + bool cancel(); private slots: diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 13f94ba..a8f53e2 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -21,12 +21,11 @@ ScStwRemoteRace::ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent) : ScStwRace(parent) { this->currentlyWaitingForClimbers = false; + this->isReadyForNextState = true; this->scStwClient = monitorClient; - this->scStwClient->addSignalSubscription(ScStw::RaceStateChanged); - this->scStwClient->addSignalSubscription(ScStw::TimersChanged); - this->scStwClient->addSignalSubscription(ScStw::CurrentStartDelayChanged); + this->scStwClient->addSignalSubscription(ScStw::RaceDetailsChanged); connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChanged); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteRace::handleBaseStationSignal); @@ -112,39 +111,48 @@ void ScStwRemoteRace::handleClientStateChanged() { void ScStwRemoteRace::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { //qDebug() << "got signal: " << data; switch (key) { - case ScStw::RaceStateChanged: + case ScStw::RaceDetailsChanged: { - // the remote race state has changed - this->setState( ScStwRace::RaceState( data.toInt() ) ); + this->refreshDetails(data.toMap()); break; } - case ScStw::TimersChanged: - { - // the remote timers have changed - this->refreshRemoteTimers(data.toList()); - break; - } - case ScStw::CurrentStartDelayChanged: - { - // the next start action has changed - this->currentStartTotalDelay = data.toList()[ScStwRace::CurrentStartStateTotalDelay].toInt(); - this->currentStartDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->currentStartTotalDelay * data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble()); - this->currentlyWaitingForClimbers = data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble() == 0 && this->currentStartTotalDelay == -1; - - emit this->currentStartDelayChanged(); - - qDebug() << "Current start delay changed: total:" << this->currentStartTotalDelay << " progress: " << data.toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble(); - - break; - } - case ScStw::InvalidSignal: - return; - default: return; } } +void ScStwRemoteRace::refreshDetails(QVariantMap details) { + // the details of the race have changed: + + // state + this->setState(ScStwRace::RaceState(details["state"].toInt())); + + // competition mode + this->competitionMode = details["competitionMode"].toBool(); + + // ready sound enabled + this->writeStartSoundSetting(ScStwSoundPlayer::Ready, details["readySoundEnabled"].toBool(), 0); + + // current start delay + this->currentStartTotalDelay = details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateTotalDelay].toInt(); + this->currentStartDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->currentStartTotalDelay * details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble()); + this->currentlyWaitingForClimbers = details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble() == 0 && this->currentStartTotalDelay == -1; + + emit this->currentStartDelayChanged(); + + // timers + this->refreshRemoteTimers(details["timers"].toList()); + + // isReady + if(this->state == WAITING) { + this->isReadyForNextState = details["isReadyForNextState"].toBool(); + emit this->isReadyForNextStateChanged(); + } + + emit this->detailsChanged(); + +} + bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { if(remoteTimers.length() != this->timers.length()){ @@ -218,3 +226,7 @@ QVariantList ScStwRemoteRace::getCurrentStartDelay() { nextActionDelayProg }; } + +bool ScStwRemoteRace::getIsReadyForNextState() { + return this->isReadyForNextState; +} diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index f5dd736..6f6ae98 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -34,6 +34,7 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) connect(this, &ScStwRace::currentStartDelayChanged, this, &ScStwRace::detailsChanged); connect(this, &ScStwRace::timersChanged, this, &ScStwRace::detailsChanged); + connect(this, &ScStwRace::stateChanged, this, &ScStwRace::detailsChanged); // write default settings this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); @@ -49,7 +50,7 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) ScStw::StatusCode ScStwRace::start(bool asyncronous) { if(this->state == WAITING) { - if(this->isReadyForNextState()) { + if(this->getIsReadyForNextState()) { this->startWaitLoop->exit(LoopManualExit); return ScStw::Success; } @@ -61,7 +62,7 @@ ScStw::StatusCode ScStwRace::start(bool asyncronous) { return ScStw::CurrentStateNotVaildForOperationError; } - if(!this->isReadyForNextState()) + if(!this->getIsReadyForNextState()) return ScStw::TimersNotReadyError; this->setState(PREPAIRING); @@ -181,7 +182,7 @@ ScStw::StatusCode ScStwRace::cancel() { this->setState(STOPPED); this->startWaitLoop->exit(LoopCancelExit); - this->soundPlayer->cancel(this->soundVolume); + this->soundPlayer->cancel(); this->startDelayTimer->stop(); emit this->currentStartDelayChanged(); @@ -246,7 +247,7 @@ bool ScStwRace::playSoundsAndStartTimers() { bool timerTriggered = true; do { - if(!this->isReadyForNextState()) { + if(!this->getIsReadyForNextState()) { this->startDelayTimer->stop(); timerTriggered = false; } @@ -276,7 +277,7 @@ bool ScStwRace::playSoundsAndStartTimers() { //qDebug() << "At end of loop: remaining time: " << this->startDelayTimer->remainingTime() << " timer triggered: " << timerTriggered << " ready for next state: " << this->isReadyForNextState(); - } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->isReadyForNextState()); + } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->getIsReadyForNextState()); qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; @@ -296,7 +297,7 @@ bool ScStwRace::playSoundsAndStartTimers() { if(loopExitCode == LoopCancelExit) return false; - } while(loopExitCode != LoopManualExit || !this->isReadyForNextState()); + } while(loopExitCode != LoopManualExit || !this->getIsReadyForNextState()); } else { qDebug() << "now playing ready sound"; @@ -449,7 +450,7 @@ void ScStwRace::refreshTimerStates() { // --- helper functions --- // ------------------------ -bool ScStwRace::isReadyForNextState() { +bool ScStwRace::getIsReadyForNextState() { if(!this->competitionMode) { return true; } @@ -542,7 +543,7 @@ QVariantList ScStwRace::getCurrentStartDelay() { int nextActionDelay = -1; double nextActionDelayProg = -1; - if(this->state == WAITING && !this->isReadyForNextState()) { + if(this->state == WAITING && !this->getIsReadyForNextState()) { // indicate that we are waiting for climbers and the progress shall be zero nextActionDelayProg = 0; } @@ -645,13 +646,14 @@ QVariantList ScStwRace::getTimerDetailList() { QVariantMap ScStwRace::getDetails() { QVariantMap tmpDetails; - tmpDetails.insert("timers", this->getTimerDetailList()); - tmpDetails.insert("currentStartDelay", this->getCurrentStartDelay()); + tmpDetails.insert("state", this->getState()); tmpDetails.insert("competitionMode", this->competitionMode); tmpDetails.insert("readySoundEnabled", this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()); + tmpDetails.insert("currentStartDelay", this->getCurrentStartDelay()); + tmpDetails.insert("timers", this->getTimerDetailList()); if(this->state == WAITING) - tmpDetails.insert("isReady", this->isReadyForNextState()); + tmpDetails.insert("isReadyForNextState", this->getIsReadyForNextState()); return tmpDetails; } diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 07de6f0..943513b 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -79,13 +79,15 @@ bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, d return true; } -bool ScStwSoundPlayer::cancel(double volume) { +bool ScStwSoundPlayer::cancel() { if(!this->soundEffect->isPlaying() ) return false; // stop playback this->soundEffect->stop(); this->waitLoop->quit(); + + return true; } bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { From da97e671a5ce64420753a9c10fde868eea17e396 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 11:44:56 +0200 Subject: [PATCH 37/76] some fixes and cleanup (made some things more consistent) --- .../headers/client/scstwremoterace.h | 4 +- ScStwLibraries/headers/scstwrace.h | 20 +++-- .../sources/client/scstwremoterace.cpp | 42 +++++----- ScStwLibraries/sources/scstwrace.cpp | 77 ++++++++++++------- 4 files changed, 86 insertions(+), 57 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 9c89e56..2b22cf5 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -34,7 +34,7 @@ public: protected: double currentStartTotalDelay; double currentStartDelayStartedAt; - bool currentlyWaitingForClimbers; + double latestStartDelayProgress; bool isReadyForNextState; private: @@ -48,7 +48,7 @@ public slots: ScStw::StatusCode stop(); ScStw::StatusCode reset(); bool addTimer(ScStwTimer *timer); - QVariantList getCurrentStartDelay(); + QVariantMap getCurrentStartDelay(); bool getIsReadyForNextState(); private slots: diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 6d9b682..4409c9a 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -53,8 +53,10 @@ class ScStwRace : public QObject Q_OBJECT Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) - Q_PROPERTY(QVariantList currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) + Q_PROPERTY(QVariantMap currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) Q_PROPERTY(bool isReadyForNextState READ getIsReadyForNextState NOTIFY isReadyForNextStateChanged) + Q_PROPERTY(bool competitionMode READ getCompetitionMode NOTIFY competitionModeChanged) + Q_PROPERTY(bool readySoundEnabled READ getReadySoundEnabled NOTIFY readySoundEnabledChanged) Q_PROPERTY(QVariantMap details READ getDetails NOTIFY detailsChanged) public: @@ -65,12 +67,6 @@ public: enum RaceState { IDLE, PREPAIRING, WAITING, STARTING, RUNNING, STOPPED, INCIDENT }; Q_ENUM(RaceState) - enum CurrentStartDetailAttributes { - CurrentStartStateTotalDelay = 0, - CurrentStartStateDelayProgress = 1 - }; - Q_ENUM(CurrentStartDetailAttributes); - protected: QList timers; void setState(RaceState newState); @@ -87,7 +83,7 @@ private: // some settings double soundVolume; bool competitionMode; - bool competitionModeChanged; + bool competitionModeChangedRecently; /*! * \brief stores the start action settings @@ -136,14 +132,15 @@ public slots: // getters RaceState getState(); - virtual QVariantList getCurrentStartDelay(); + virtual QVariantMap getCurrentStartDelay(); QList getTimers(); QVariantList getTimerDetailList(); QVariantMap getDetails(); + bool getCompetitionMode(); + bool getReadySoundEnabled(); protected slots: - private slots: void refreshTimerStates(); void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); @@ -170,7 +167,8 @@ signals: void timersChanged(); void isReadyForNextStateChanged(); void detailsChanged(); - + void competitionModeChanged(); + void readySoundEnabledChanged(); }; diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index a8f53e2..a7a5e8f 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -128,15 +128,21 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { this->setState(ScStwRace::RaceState(details["state"].toInt())); // competition mode - this->competitionMode = details["competitionMode"].toBool(); + if(this->competitionMode != details["competitionMode"].toBool()) { + this->competitionMode = details["competitionMode"].toBool(); + emit this->competitionModeChanged(); + } // ready sound enabled - this->writeStartSoundSetting(ScStwSoundPlayer::Ready, details["readySoundEnabled"].toBool(), 0); + if(this->getReadySoundEnabled() != details["readySoundEnabled"].toBool()) { + this->writeStartSoundSetting(ScStwSoundPlayer::Ready, details["readySoundEnabled"].toBool(), 0); + emit this->readySoundEnabledChanged(); + } // current start delay - this->currentStartTotalDelay = details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateTotalDelay].toInt(); - this->currentStartDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->currentStartTotalDelay * details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble()); - this->currentlyWaitingForClimbers = details["currentStartDelay"].toList()[ScStwRace::CurrentStartStateDelayProgress].toDouble() == 0 && this->currentStartTotalDelay == -1; + this->currentStartTotalDelay = details["currentStartDelay"].toMap()["total"].toInt(); + this->latestStartDelayProgress = details["currentStartDelay"].toMap()["progress"].toDouble(); + this->currentStartDelayStartedAt = QDateTime::currentMSecsSinceEpoch() - (this->currentStartTotalDelay * this->latestStartDelayProgress); emit this->currentStartDelayChanged(); @@ -204,27 +210,27 @@ bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { return false; } -QVariantList ScStwRemoteRace::getCurrentStartDelay() { - int nextActionDelay = -1; - double nextActionDelayProg = -1; +QVariantMap ScStwRemoteRace::getCurrentStartDelay() { - if(this->getState() == WAITING && this->currentlyWaitingForClimbers) { - nextActionDelayProg = 0; + QVariantMap currentStartDelay = { + {"total", -1.0}, + {"progress", -1.0} + }; + + if(this->currentStartTotalDelay == -1) { + currentStartDelay["progress"] = this->latestStartDelayProgress; } else if(this->getState() == PREPAIRING || this->getState() == WAITING) { // get the total delay and the delay progress of the next action timer double elapsed = QDateTime::currentMSecsSinceEpoch() - this->currentStartDelayStartedAt; - nextActionDelay = this->currentStartTotalDelay; - if(elapsed < 0 || elapsed > nextActionDelay) { - elapsed = nextActionDelay; + currentStartDelay["total"] = this->currentStartTotalDelay; + if(elapsed < 0 || elapsed > currentStartDelay["total"].toDouble()) { + elapsed = currentStartDelay["total"].toDouble(); } - nextActionDelayProg = elapsed / nextActionDelay; + currentStartDelay["progress"] = elapsed / currentStartDelay["total"].toDouble(); } - return { - nextActionDelay, - nextActionDelayProg - }; + return currentStartDelay; } bool ScStwRemoteRace::getIsReadyForNextState() { diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 6f6ae98..58cbe94 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -406,9 +406,9 @@ void ScStwRace::setState(RaceState newState) { if(this->state == IDLE) { // if we changed to IDLE -> handle timer enable / disable - if(this->competitionModeChanged && this->competitionMode) { + if(this->competitionModeChangedRecently && this->competitionMode) { this->enableAllTimers(); - this->competitionModeChanged = false; + this->competitionModeChangedRecently = false; } if(!this->competitionMode) { @@ -523,7 +523,7 @@ void ScStwRace::setCompetitionMode(bool competitionMode) { this->competitionMode = competitionMode; if(this->state != IDLE) - this->competitionModeChanged = true; + this->competitionModeChangedRecently = true; else if(this->competitionMode) this->enableAllTimers(); } @@ -539,31 +539,48 @@ void ScStwRace::enableAllTimers() { } } -QVariantList ScStwRace::getCurrentStartDelay() { - int nextActionDelay = -1; - double nextActionDelayProg = -1; +QVariantMap ScStwRace::getCurrentStartDelay() { - if(this->state == WAITING && !this->getIsReadyForNextState()) { - // indicate that we are waiting for climbers and the progress shall be zero - nextActionDelayProg = 0; - } - else if(this->state == PREPAIRING || this->state == WAITING) { - // get the total delay and the delay progress of the next action timer - double remaining = this->startDelayTimer->remainingTime(); - nextActionDelay = this->startDelayTimer->interval(); - if(remaining < 0) { - remaining = nextActionDelay; - } - nextActionDelayProg = 1 - (remaining / nextActionDelay); - - if(nextActionDelayProg < 0) - nextActionDelayProg = 0; - } - - return { - nextActionDelay, - nextActionDelayProg + QVariantMap currentStartDelay = { + {"total", -1.0}, + {"progress", -1.0} }; + + switch (this->state) { + + case WAITING: + if(!this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) + return currentStartDelay; + if(!this->getIsReadyForNextState()) + // indicate that we are waiting for climbers and the progress shall be zero + currentStartDelay["progress"] = -1; + return currentStartDelay; + case PREPAIRING: { + if(!this->startSoundSettings[ScStwSoundPlayer::AtYourMarks]["Enabled"].toBool()) + return currentStartDelay; + + break; + } + + default: + return currentStartDelay; + break; + + } + + // get the total delay and the delay progress of the next action timer + double remaining = this->startDelayTimer->remainingTime(); + currentStartDelay["total"] = this->startDelayTimer->interval(); + if(remaining < 0) { + remaining = currentStartDelay["total"].toDouble(); + } + currentStartDelay["progress"] = 1 - (remaining / currentStartDelay["total"].toDouble()); + + if(currentStartDelay["progress"].toDouble() < 0) + currentStartDelay["progress"] = 0; + + + return currentStartDelay; } bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { @@ -669,3 +686,11 @@ void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { if(this->state == WAITING) emit this->timersChanged(); } + +bool ScStwRace::getCompetitionMode() { + return this->competitionMode; +} + +bool ScStwRace::getReadySoundEnabled() { + return this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool(); +} From a3eeb3d43e43c23b63df2b93f76526e6ff28afea Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 12:45:44 +0200 Subject: [PATCH 38/76] fixes ready delay not working --- ScStwLibraries/sources/scstwrace.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 58cbe94..be715c1 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -551,10 +551,11 @@ QVariantMap ScStwRace::getCurrentStartDelay() { case WAITING: if(!this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) return currentStartDelay; - if(!this->getIsReadyForNextState()) + if(!this->getIsReadyForNextState()) { // indicate that we are waiting for climbers and the progress shall be zero - currentStartDelay["progress"] = -1; - return currentStartDelay; + currentStartDelay["progress"] = 0; + return currentStartDelay; + } case PREPAIRING: { if(!this->startSoundSettings[ScStwSoundPlayer::AtYourMarks]["Enabled"].toBool()) return currentStartDelay; From 8c7452147787df6f3cc2758eb2df4d1e40ec1f17 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 13:06:14 +0200 Subject: [PATCH 39/76] - remote race now switches to a local race when the client is not connected automatically - fixed some issues --- .../headers/client/scstwremoterace.h | 18 ++- .../headers/client/scstwremotesettings.h | 3 +- ScStwLibraries/headers/scstwrace.h | 2 +- .../sources/client/scstwremoterace.cpp | 117 +++++++++++++----- ScStwLibraries/sources/scstwtimer.cpp | 7 ++ 5 files changed, 107 insertions(+), 40 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 2b22cf5..505cb4e 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -29,33 +29,43 @@ class ScStwRemoteRace : public ScStwRace { Q_OBJECT public: - ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent = nullptr); + ScStwRemoteRace(ScStwClient *scStwClient, QObject *parent = nullptr); + + enum RaceMode { + LOCAL, + REMOTE + }; protected: double currentStartTotalDelay; double currentStartDelayStartedAt; double latestStartDelayProgress; bool isReadyForNextState; + bool readySoundEnabled; private: ScStwClient *scStwClient; QList remoteTimers; + QList localTimers; public slots: - ScStw::StatusCode start(bool); - ScStw::StatusCode start(); + ScStw::StatusCode start(bool asyncronous = true); ScStw::StatusCode cancel(); ScStw::StatusCode stop(); ScStw::StatusCode reset(); bool addTimer(ScStwTimer *timer); QVariantMap getCurrentStartDelay(); bool getIsReadyForNextState(); + bool getReadySoundEnabled(); private slots: - void handleClientStateChanged(); void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); bool refreshRemoteTimers(QVariantList remoteTimers); + void rebuildRemoteTimers(QVariantList remoteTimers); void refreshDetails(QVariantMap details); + void handleClientStateChange(); + RaceMode getMode(); + bool local(); }; diff --git a/ScStwLibraries/headers/client/scstwremotesettings.h b/ScStwLibraries/headers/client/scstwremotesettings.h index af3beb9..2b6a9f3 100644 --- a/ScStwLibraries/headers/client/scstwremotesettings.h +++ b/ScStwLibraries/headers/client/scstwremotesettings.h @@ -43,11 +43,10 @@ protected: private: ScStwClient * scStwClient; - SettingsMode getMode(); - private slots: void handleClientStateChange(); void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); + SettingsMode getMode(); }; #endif // SCSTWREMOTESETTINGS_H diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 4409c9a..7d6ac3c 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -137,7 +137,7 @@ public slots: QVariantList getTimerDetailList(); QVariantMap getDetails(); bool getCompetitionMode(); - bool getReadySoundEnabled(); + virtual bool getReadySoundEnabled(); protected slots: diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index a7a5e8f..aca8b6e 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -18,16 +18,15 @@ #include "scstwremoterace.h" -ScStwRemoteRace::ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent) : ScStwRace(parent) +ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, QObject *parent) : ScStwRace(parent) { - this->currentlyWaitingForClimbers = false; this->isReadyForNextState = true; - this->scStwClient = monitorClient; + this->scStwClient = scStwClient; this->scStwClient->addSignalSubscription(ScStw::RaceDetailsChanged); - connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChanged); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChange); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteRace::handleBaseStationSignal); } @@ -35,11 +34,10 @@ ScStwRemoteRace::ScStwRemoteRace(ScStwClient *monitorClient, QObject *parent) : // --- Main Functionality --- // -------------------------- -ScStw::StatusCode ScStwRemoteRace::start(bool) { - return this->start(); -} +ScStw::StatusCode ScStwRemoteRace::start(bool asyncronous) { + if(this->local()) + return ScStwRace::start(asyncronous); -ScStw::StatusCode ScStwRemoteRace::start() { if(this->getState() != ScStwRace::IDLE && this->getState() != ScStwRace::WAITING) return ScStw::CurrentStateNotVaildForOperationError; @@ -51,6 +49,9 @@ ScStw::StatusCode ScStwRemoteRace::start() { } ScStw::StatusCode ScStwRemoteRace::cancel() { + if(this->local()) + return ScStwRace::cancel(); + if(this->getState() != PREPAIRING && this->getState() != WAITING && this->getState() != STARTING && this->getState() != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; @@ -62,6 +63,9 @@ ScStw::StatusCode ScStwRemoteRace::cancel() { } ScStw::StatusCode ScStwRemoteRace::stop() { + if(this->local()) + return ScStwRace::stop(); + if(this->getState() != ScStwRace::RUNNING && this->getState() != ScStwRace::STARTING) return ScStw::CurrentStateNotVaildForOperationError; @@ -73,6 +77,9 @@ ScStw::StatusCode ScStwRemoteRace::stop() { } ScStw::StatusCode ScStwRemoteRace::reset() { + if(this->local()) + return ScStwRace::reset(); + if(this->getState() != ScStwRace::STOPPED && this->getState() != ScStwRace::INCIDENT) return ScStw::CurrentStateNotVaildForOperationError; @@ -88,18 +95,41 @@ ScStw::StatusCode ScStwRemoteRace::reset() { // --- Base Station sync --- // ------------------------- -void ScStwRemoteRace::handleClientStateChanged() { - // TODO +void ScStwRemoteRace::handleClientStateChange() { switch (this->scStwClient->getState()) { case ScStwClient::CONNECTED: - break; - default: + this->localTimers.clear(); + this->localTimers = this->timers; this->timers.clear(); + break; + case ScStwClient::DISCONNECTED: + foreach(ScStwRemoteTimer *remoteTimer, this->remoteTimers) + remoteTimer->deleteLater(); + this->remoteTimers.clear(); + + this->timers.clear(); + this->timers = this->localTimers; + this->localTimers.clear(); + emit this->timersChanged(); + this->competitionMode = false; this->setState(IDLE); break; + default: + break; } } +ScStwRemoteRace::RaceMode ScStwRemoteRace::getMode() { + if(this->scStwClient->getState() == ScStwClient::CONNECTED) + return ScStwRemoteRace::REMOTE; + else + return ScStwRemoteRace::LOCAL; +} + +bool ScStwRemoteRace::local() { + return this->getMode() == LOCAL; +} + /** * @brief ScStwAppBackend::handleBaseStationUpdate * @@ -134,8 +164,8 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { } // ready sound enabled - if(this->getReadySoundEnabled() != details["readySoundEnabled"].toBool()) { - this->writeStartSoundSetting(ScStwSoundPlayer::Ready, details["readySoundEnabled"].toBool(), 0); + if(this->readySoundEnabled != details["readySoundEnabled"].toBool()) { + this->readySoundEnabled = details["readySoundEnabled"].toBool(); emit this->readySoundEnabledChanged(); } @@ -159,34 +189,41 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { } +void ScStwRemoteRace::rebuildRemoteTimers(QVariantList remoteTimers) { + // delete all current timers + foreach(ScStwTimer * oldTimer, this->timers){ + oldTimer->deleteLater(); + } + + this->remoteTimers.clear(); + this->timers.clear(); + + foreach(QVariant remoteTimer, remoteTimers){ + // create a local timer for each remote timer + ScStwRemoteTimer * timer = new ScStwRemoteTimer(this); + this->timers.append(timer); + this->remoteTimers.append(timer); + connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); + connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); + } +} + bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { - if(remoteTimers.length() != this->timers.length()){ + if(remoteTimers.length() != this->remoteTimers.length()){ // local timers are out of sync - - // delete all current timers - foreach(ScStwTimer * locTimer, this->timers){ - delete locTimer; - } - - this->timers.clear(); - - foreach(QVariant remoteTimer, remoteTimers){ - // create a local timer for each remote timer - ScStwRemoteTimer * timer = new ScStwRemoteTimer(this); - this->timers.append(timer); - this->remoteTimers.append(timer); - connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); - connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); - } + this->rebuildRemoteTimers(remoteTimers); } foreach(QVariant remoteTimer, remoteTimers){ int currId = remoteTimer.toMap()["id"].toInt(); + if(this->remoteTimers.length() <= currId) + this->rebuildRemoteTimers(remoteTimers); + ScStwTimer::TimerState newState = ScStwTimer::TimerState(remoteTimer.toMap()["state"].toInt()); - qDebug() << "refreshing timers: id: " << currId << " state: " << newState << " readyState: " << remoteTimer.toMap()["readyState"].toInt(); + qDebug() << "refreshing timers: id: " << currId << " state: " << newState << " readyState: " << remoteTimer.toMap()["readyState"].toInt() << " currentTime: " << remoteTimer.toMap()["currentTime"].toDouble(); double currentMSecsSinceEpoch = QDateTime::currentMSecsSinceEpoch(); @@ -206,11 +243,15 @@ bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { } bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { - Q_UNUSED(timer) + if(this->local()) + return ScStwRace::addTimer(timer); + return false; } QVariantMap ScStwRemoteRace::getCurrentStartDelay() { + if(this->local()) + return ScStwRace::getCurrentStartDelay(); QVariantMap currentStartDelay = { {"total", -1.0}, @@ -234,5 +275,15 @@ QVariantMap ScStwRemoteRace::getCurrentStartDelay() { } bool ScStwRemoteRace::getIsReadyForNextState() { + if(this->local()) + return ScStwRace::getIsReadyForNextState(); + return this->isReadyForNextState; } + +bool ScStwRemoteRace::getReadySoundEnabled() { + if(this->local()) + return ScStwRace::getReadySoundEnabled(); + + return this->readySoundEnabled; +} diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 249bfa8..f7f77ba 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -25,6 +25,8 @@ ScStwTimer::ScStwTimer(QObject *parent, QString letter) : QObject(parent) else this->letter = letter; + qDebug() << "Timer created with letter: " << letter; + this->startTime = 0; this->stopTime = 0; this->reactionTime = 0; @@ -86,6 +88,9 @@ bool ScStwTimer::cancel() { return false; qDebug() << "[INFO][TIMER] Timer was cancelled"; + this->reactionTime = 0; + this->startTime = 0; + this->stopTime = 0; this->setState(CANCELLED); return true; @@ -213,6 +218,8 @@ QString ScStwTimer::getLetter() { QString ScStwTimer::getText() { + qDebug() << "getting text: start time: " << this->startTime << " state: " << this->state; + QString newText = ""; int newTime = 0; switch (this->state) { From 46c62ba1873da9120af2cf9ec0b98a7f4cd28c79 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 13:49:56 +0200 Subject: [PATCH 40/76] fixed getCUrrentStartDelay returning crap --- ScStwLibraries/headers/scstwsoundplayer.h | 2 ++ ScStwLibraries/sources/scstwrace.cpp | 8 +++++--- ScStwLibraries/sources/scstwsoundplayer.cpp | 4 ++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index 82a8436..3356a51 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -112,6 +112,8 @@ public slots: */ bool cancel(); + bool isPlaying(); + private slots: signals: diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index be715c1..86a60af 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -556,6 +556,7 @@ QVariantMap ScStwRace::getCurrentStartDelay() { currentStartDelay["progress"] = 0; return currentStartDelay; } + break; case PREPAIRING: { if(!this->startSoundSettings[ScStwSoundPlayer::AtYourMarks]["Enabled"].toBool()) return currentStartDelay; @@ -571,10 +572,11 @@ QVariantMap ScStwRace::getCurrentStartDelay() { // get the total delay and the delay progress of the next action timer double remaining = this->startDelayTimer->remainingTime(); + + if(remaining < 0) + return currentStartDelay; + currentStartDelay["total"] = this->startDelayTimer->interval(); - if(remaining < 0) { - remaining = currentStartDelay["total"].toDouble(); - } currentStartDelay["progress"] = 1 - (remaining / currentStartDelay["total"].toDouble()); if(currentStartDelay["progress"].toDouble() < 0) diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 943513b..e68caee 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -115,3 +115,7 @@ bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { return true; } + +bool ScStwSoundPlayer::isPlaying() { + return this->soundEffect->isPlaying(); +} From a56eae71a7ed95258fd85945f6ff7666a99016ed Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 15:15:49 +0200 Subject: [PATCH 41/76] some more fixes and additions; completed #5 --- .../headers/client/scstwremoterace.h | 5 +- ScStwLibraries/headers/scstwrace.h | 13 +- .../sources/client/scstwremoterace.cpp | 9 +- .../sources/client/scstwremotesettings.cpp | 5 + ScStwLibraries/sources/scstwrace.cpp | 128 ++++++++++++++++-- ScStwLibraries/sources/scstwsetting.cpp | 2 - ScStwLibraries/sources/scstwsettings.cpp | 7 + 7 files changed, 147 insertions(+), 22 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 505cb4e..c5eb83d 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -29,7 +29,7 @@ class ScStwRemoteRace : public ScStwRace { Q_OBJECT public: - ScStwRemoteRace(ScStwClient *scStwClient, QObject *parent = nullptr); + ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settings = nullptr, QObject *parent = nullptr); enum RaceMode { LOCAL, @@ -60,13 +60,14 @@ public slots: private slots: void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); + void handleSettingChange(int keyInt, int keyLevel, QVariant value); + bool refreshRemoteTimers(QVariantList remoteTimers); void rebuildRemoteTimers(QVariantList remoteTimers); void refreshDetails(QVariantMap details); void handleClientStateChange(); RaceMode getMode(); bool local(); - }; #endif // SCSTWREMOTEMONITORRACE_H diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 7d6ac3c..d620eaf 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -25,6 +25,7 @@ #include #include "scstwtimer.h" #include "scstwsoundplayer.h" +#include "scstwsettings.h" class ScStwRemoteRace; @@ -61,6 +62,7 @@ class ScStwRace : public QObject public: explicit ScStwRace(QObject *parent = nullptr); + explicit ScStwRace(ScStwSettings *settings, QObject *parent = nullptr); friend class ScStwRemoteRace; @@ -80,7 +82,8 @@ private: // sounds ScStwSoundPlayer * soundPlayer; - // some settings + // settings + ScStwSettings *settings; double soundVolume; bool competitionMode; bool competitionModeChangedRecently; @@ -128,7 +131,7 @@ public slots: bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); bool setSoundVolume(double volume); virtual bool addTimer(ScStwTimer *timer); - void setCompetitionMode(bool competitionMode); + bool setCompetitionMode(bool competitionMode); // getters RaceState getState(); @@ -148,6 +151,7 @@ private slots: bool playSoundsAndStartTimers(); bool doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); void enableAllTimers(); + void technicalIncident(); /** * \brief Function to declare the winner and looser timers after a timer has been stopped @@ -158,6 +162,11 @@ private slots: virtual bool getIsReadyForNextState(); void handleTimerReadyStateChange(ScStwTimer::ReadyState readyState); + // settings + bool writeStartSoundSettingKey(ScStwSoundPlayer::StartSound sound, QString key, QVariant value); + virtual void handleSettingChange(int keyInt, int keyLevel, QVariant value); + void reloadAllSettings(); + signals: void startTimers(); void stopTimers(int type); diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index aca8b6e..1dd7acc 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -18,7 +18,7 @@ #include "scstwremoterace.h" -ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, QObject *parent) : ScStwRace(parent) +ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settings, QObject *parent) : ScStwRace(settings, parent) { this->isReadyForNextState = true; @@ -90,7 +90,6 @@ ScStw::StatusCode ScStwRemoteRace::reset() { return ScStw::StatusCode(reply["status"].toInt()); } - // ------------------------- // --- Base Station sync --- // ------------------------- @@ -130,6 +129,12 @@ bool ScStwRemoteRace::local() { return this->getMode() == LOCAL; } +void ScStwRemoteRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { + if(this->local()) + return ScStwRace::handleSettingChange(keyInt, keyLevel, value); +} + + /** * @brief ScStwAppBackend::handleBaseStationUpdate * diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index 4128256..aaecf45 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -37,6 +37,8 @@ QVariant ScStwRemoteSettings::readSetting(QString key, int keyInt, int keyLevel) if(this->getMode() == LOCAL || keyLevel > ScStwSettings::KeyLevel) return ScStwSettings::readSetting(key, keyInt, keyLevel); + qDebug() << "Setting read: keyLevel: " << keyLevel << " key: " << key; + return this->scStwClient->readRemoteSetting(ScStwSettings::BaseStationSetting(keyInt)); } @@ -44,6 +46,9 @@ bool ScStwRemoteSettings::writeSetting(QString key, QVariant value, int keyInt, if(this->getMode() == LOCAL || keyLevel > ScStwSettings::KeyLevel) return ScStwSettings::writeSetting(key, value, keyInt, keyLevel); + + qDebug() << "Setting write: keyLevel: " << keyLevel << " key: " << key << " value: " << value; + ScStw::StatusCode res = this->scStwClient->writeRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), value); return res == ScStw::Success; diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 86a60af..04c258f 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -18,7 +18,11 @@ #include "../headers/scstwrace.h" -ScStwRace::ScStwRace(QObject *parent) : QObject(parent) +ScStwRace::ScStwRace(QObject * parent) : ScStwRace(nullptr, parent) +{ +} + +ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) { this->state = IDLE; @@ -36,12 +40,18 @@ ScStwRace::ScStwRace(QObject *parent) : QObject(parent) connect(this, &ScStwRace::timersChanged, this, &ScStwRace::detailsChanged); connect(this, &ScStwRace::stateChanged, this, &ScStwRace::detailsChanged); - // write default settings + // init settings + this->competitionMode = false; + this->soundVolume = 1; this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); this->writeStartSoundSetting(ScStwSoundPlayer::Ready, false, 0); this->setSoundVolume(1.0); - this->competitionMode = false; + + this->settings = settings; + if(this->settings != nullptr) { + connect(this->settings, &ScStwSettings::settingChanged, this, &ScStwRace::handleSettingChange); + } } // -------------------------- @@ -81,6 +91,9 @@ ScStw::StatusCode ScStwRace::stop() { return ScStw::CurrentStateNotVaildForOperationError; } + if(this->competitionMode) + return this->cancel(); + qDebug() << "+ [INFO] stopping race"; double timeOfStop = QDateTime::currentMSecsSinceEpoch(); @@ -150,7 +163,7 @@ ScStw::StatusCode ScStwRace::reset() { ScStw::StatusCode returnCode = ScStw::Success; foreach(ScStwTimer *speedTimer, this->timers){ - if(!speedTimer->reset() && speedTimer->getState() != ScStwTimer::DISABLED) { + if(!speedTimer->reset() && speedTimer->getState() != ScStwTimer::DISABLED && speedTimer->getState() != ScStwTimer::IDLE) { returnCode = ScStw::InternalErrorTimerOperationFailed; } } @@ -190,6 +203,13 @@ ScStw::StatusCode ScStwRace::cancel() { return returnCode; } +void ScStwRace::technicalIncident() { + foreach(ScStwTimer *timer, this->timers){ + timer->cancel(); + } + this->setState(INCIDENT); +} + int ScStwRace::handleFalseStart() { if(this->getState() != STARTING && this->getState() != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; @@ -284,7 +304,7 @@ bool ScStwRace::playSoundsAndStartTimers() { // play ready tone if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) { qDebug() << "Ready sound redturned false!"; - this->setState(INCIDENT); + this->technicalIncident(); return false; } } @@ -316,7 +336,7 @@ bool ScStwRace::playSoundsAndStartTimers() { qDebug() << "now playing start sound"; double timeOfSoundPlaybackStart; if(!this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart)) { - this->setState(INCIDENT); + this->technicalIncident(); return false; } @@ -331,13 +351,13 @@ bool ScStwRace::playSoundsAndStartTimers() { } if(!startOk) { qDebug() << "[ERROR][START] error staring all timers"; - this->setState(INCIDENT); + this->technicalIncident(); return false; } if(!this->soundPlayer->waitForSoundFinish()) { qDebug() << "[ERROR][START] start sound wait error"; - this->setState(INCIDENT); + this->technicalIncident(); return false; } @@ -474,7 +494,7 @@ bool ScStwRace::getIsReadyForNextState() { subTimer->setState(ScStwTimer::CANCELLED); } - this->setState(INCIDENT); + this->technicalIncident(); qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; @@ -514,9 +534,12 @@ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wants } } -void ScStwRace::setCompetitionMode(bool competitionMode) { +bool ScStwRace::setCompetitionMode(bool competitionMode) { + if(this->settings != nullptr) + return false; + if(this->competitionMode == competitionMode) - return; + return true; qDebug() << "Setting competition mode to " << competitionMode; @@ -526,6 +549,8 @@ void ScStwRace::setCompetitionMode(bool competitionMode) { this->competitionModeChangedRecently = true; else if(this->competitionMode) this->enableAllTimers(); + + return true; } void ScStwRace::enableAllTimers() { @@ -587,20 +612,38 @@ QVariantMap ScStwRace::getCurrentStartDelay() { } bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { + if(this->settings != nullptr) + return false; + if(sound != ScStwSoundPlayer::AtYourMarks && sound != ScStwSoundPlayer::Ready) return false; - QVariantMap setting = {{"Enabled", enabled}, {"Delay", delay}}; + this->writeStartSoundSettingKey(sound, "Enabled", enabled); + this->writeStartSoundSettingKey(sound, "Delay", delay); + + return true; +} + +bool ScStwRace::writeStartSoundSettingKey(ScStwSoundPlayer::StartSound sound, QString key, QVariant value) { + + if(key != "Delay" && key != "Enabled") + return false; if(!this->startSoundSettings.contains(sound)) - this->startSoundSettings.insert(sound, setting); + this->startSoundSettings.insert(sound, {}); + + if(!this->startSoundSettings[sound].contains(key)) + this->startSoundSettings[sound].insert(key, value); else - this->startSoundSettings[sound] = setting; + this->startSoundSettings[sound][key] = value; return true; } bool ScStwRace::setSoundVolume(double volume) { + if(this->settings != nullptr) + return false; + if(volume >= 0 && volume <= 1) { this->soundVolume = volume; return true; @@ -637,6 +680,63 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { } +void ScStwRace::reloadAllSettings() { + this->writeStartSoundSetting( + ScStwSoundPlayer::AtYourMarks, + this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundEnableSetting).toBool(), + this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundDelaySetting).toDouble() + ); + + this->writeStartSoundSetting( + ScStwSoundPlayer::Ready, + this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundEnableSetting).toBool(), + this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundDelaySetting).toDouble() + ); + + this->setSoundVolume(this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble()); + + this->setCompetitionMode(this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool()); +} + +void ScStwRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { + if(keyInt == -1) { + this->reloadAllSettings(); + return; + } + + qDebug() << "Setting changed"; + + switch (keyLevel) { + case 0: { + // BaseStationSetting!! + ScStwSettings::BaseStationSetting key = static_cast(keyInt); + switch (key) { + case ScStwSettings::AtYourMarksSoundEnableSetting: + this->writeStartSoundSettingKey(ScStwSoundPlayer::AtYourMarks, "Enabled", value); + break; + case ScStwSettings::AtYourMarksSoundDelaySetting: + this->writeStartSoundSettingKey(ScStwSoundPlayer::AtYourMarks, "Delay", value); + break; + case ScStwSettings::ReadySoundEnableSetting: + this->writeStartSoundSettingKey(ScStwSoundPlayer::Ready, "Enabled", value); + break; + case ScStwSettings::ReadySoundDelaySetting: + this->writeStartSoundSettingKey(ScStwSoundPlayer::Ready, "Delay", value); + break; + case ScStwSettings::SoundVolumeSetting: + this->setSoundVolume(value.toDouble()); + break; + case ScStwSettings::CompetitionModeSetting: + this->setCompetitionMode(value.toBool()); + + default: + return; + } + break; + } + } +} + ScStwRace::RaceState ScStwRace::getState() { return this->state; } diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp index 2dcc0ee..c499f4f 100644 --- a/ScStwLibraries/sources/scstwsetting.cpp +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -35,8 +35,6 @@ QVariant ScStwSetting::getValue() { this->hasToReload = false; } - qDebug() << "Setting read: keyLevel: " << this->keyLevel << " key: " << this->key << " value: " << this->valueCache; - return this->valueCache; } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 260881f..7a10865 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -36,6 +36,13 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); this->registerKeyLevelConverters(ScStwSettings::KeyLevel, &ScStwSettings::keyToString, &ScStwSettings::keyToType); + + this->setDefaultSetting(ScStwSettings::BaseStationSetting::ReadySoundEnableSetting, false); + this->setDefaultSetting(ScStwSettings::BaseStationSetting::ReadySoundDelaySetting, 0); + this->setDefaultSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundEnableSetting, false); + this->setDefaultSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundDelaySetting, 0); + this->setDefaultSetting(ScStwSettings::SoundVolumeSetting, 1); + this->setDefaultSetting(ScStwSettings::CompetitionModeSetting, false); } QVariant ScStwSettings::readSetting(BaseStationSetting key) { From 4dd4bc21f9d5a0021098cbc9c0af1b202a8d1878 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 17:01:05 +0200 Subject: [PATCH 42/76] fixes issues with new settings approach --- ScStwLibraries/headers/scstwrace.h | 7 +- ScStwLibraries/sources/scstwrace.cpp | 128 +++++++++++++++------------ 2 files changed, 78 insertions(+), 57 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index d620eaf..3495dd6 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -128,7 +128,7 @@ public slots: virtual ScStw::StatusCode cancel(); // setters - bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); + bool setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); bool setSoundVolume(double volume); virtual bool addTimer(ScStwTimer *timer); bool setCompetitionMode(bool competitionMode); @@ -163,7 +163,10 @@ private slots: void handleTimerReadyStateChange(ScStwTimer::ReadyState readyState); // settings - bool writeStartSoundSettingKey(ScStwSoundPlayer::StartSound sound, QString key, QVariant value); + bool setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay, bool force); + bool setSoundVolume(double volume, bool force); + bool setCompetitionMode(bool competitionMode, bool force); + bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, QString key, QVariant value); virtual void handleSettingChange(int keyInt, int keyLevel, QVariant value); void reloadAllSettings(); diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 04c258f..48e8ed9 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -42,15 +42,17 @@ ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) // init settings this->competitionMode = false; + this->competitionModeChangedRecently = false; this->soundVolume = 1; this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); - this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); - this->writeStartSoundSetting(ScStwSoundPlayer::Ready, false, 0); + this->setStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); + this->setStartSoundSetting(ScStwSoundPlayer::Ready, false, 0); this->setSoundVolume(1.0); this->settings = settings; if(this->settings != nullptr) { connect(this->settings, &ScStwSettings::settingChanged, this, &ScStwRace::handleSettingChange); + this->reloadAllSettings(); } } @@ -94,7 +96,7 @@ ScStw::StatusCode ScStwRace::stop() { if(this->competitionMode) return this->cancel(); - qDebug() << "+ [INFO] stopping race"; + qDebug() << "[INFO][RACE] stopping race"; double timeOfStop = QDateTime::currentMSecsSinceEpoch(); @@ -158,7 +160,7 @@ ScStw::StatusCode ScStwRace::reset() { return ScStw::CurrentStateNotVaildForOperationError; } - qDebug() << "+ [INFO] resetting race"; + qDebug() << "[INFO][RACE] resetting race"; ScStw::StatusCode returnCode = ScStw::Success; @@ -233,7 +235,6 @@ bool ScStwRace::playSoundsAndStartTimers() { return true; // The check if all timers are ready has already happened at this point - qDebug() << "now playing at marks sound"; if(!this->doDelayAndSoundOfCurrentStartState()) return false; @@ -241,7 +242,6 @@ bool ScStwRace::playSoundsAndStartTimers() { if(!this->isStarting()) return false; - qDebug() << "Now in waiting state"; this->setState(WAITING); // do climber readiness tests @@ -299,11 +299,11 @@ bool ScStwRace::playSoundsAndStartTimers() { } while(this->startDelayTimer->remainingTime() > 0 || !timerTriggered || !this->getIsReadyForNextState()); - qDebug() << "[RACE][DEBUG] Wait finished, starting now!"; + qDebug() << "[DEBUG][RACE] Wait finished, starting now!"; // play ready tone if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) { - qDebug() << "Ready sound redturned false!"; + qDebug() << "[ERROR][RACE] Ready sound returned false!"; this->technicalIncident(); return false; } @@ -320,20 +320,16 @@ bool ScStwRace::playSoundsAndStartTimers() { } while(loopExitCode != LoopManualExit || !this->getIsReadyForNextState()); } else { - qDebug() << "now playing ready sound"; if(!this->doDelayAndSoundOfCurrentStartState()) { this->cancel(); return false; } } - qDebug() << "now in starting state"; - // enter starting state this->setState(STARTING); // play start tone - qDebug() << "now playing start sound"; double timeOfSoundPlaybackStart; if(!this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart)) { this->technicalIncident(); @@ -350,13 +346,13 @@ bool ScStwRace::playSoundsAndStartTimers() { } } if(!startOk) { - qDebug() << "[ERROR][START] error staring all timers"; + qDebug() << "[ERROR][RACE] error staring all timers"; this->technicalIncident(); return false; } if(!this->soundPlayer->waitForSoundFinish()) { - qDebug() << "[ERROR][START] start sound wait error"; + qDebug() << "[ERROR][RACE] start sound wait error"; this->technicalIncident(); return false; } @@ -442,7 +438,6 @@ void ScStwRace::setState(RaceState newState) { } void ScStwRace::refreshTimerStates() { - qDebug() << "[INFO][MAIN] refreshing timer states"; // check if the race is over @@ -483,8 +478,6 @@ bool ScStwRace::getIsReadyForNextState() { if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { - qDebug() << "Timer ready state is: " << timer->getReadyState(); - timer->technicalIncident(); foreach (ScStwTimer *subTimer, this->timers) { @@ -534,31 +527,10 @@ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wants } } -bool ScStwRace::setCompetitionMode(bool competitionMode) { - if(this->settings != nullptr) - return false; - - if(this->competitionMode == competitionMode) - return true; - - qDebug() << "Setting competition mode to " << competitionMode; - - this->competitionMode = competitionMode; - - if(this->state != IDLE) - this->competitionModeChangedRecently = true; - else if(this->competitionMode) - this->enableAllTimers(); - - return true; -} - void ScStwRace::enableAllTimers() { if(this->state != IDLE) return; - qDebug() << "ENABLING ALL TIMERS"; - foreach (ScStwTimer *timer, this->timers) { timer->setDisabled(false); } @@ -611,20 +583,53 @@ QVariantMap ScStwRace::getCurrentStartDelay() { return currentStartDelay; } -bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { +bool ScStwRace::setCompetitionMode(bool competitionMode) { if(this->settings != nullptr) return false; + return this->setCompetitionMode(competitionMode, true); +} + +bool ScStwRace::setCompetitionMode(bool competitionMode, bool force) { + if(!force) + return false; + + if(this->competitionMode == competitionMode) + return true; + + qDebug() << "[INFO][RACE] Setting competition mode to " << competitionMode; + + this->competitionMode = competitionMode; + + if(this->state != IDLE) + this->competitionModeChangedRecently = true; + else if(this->competitionMode) + this->enableAllTimers(); + + return true; +} + +bool ScStwRace::setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { + if(this->settings != nullptr) + return false; + + return this->setStartSoundSetting(sound, enabled, delay, true); +} + +bool ScStwRace::setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay, bool force) { + if(!force) + return false; + if(sound != ScStwSoundPlayer::AtYourMarks && sound != ScStwSoundPlayer::Ready) return false; - this->writeStartSoundSettingKey(sound, "Enabled", enabled); - this->writeStartSoundSettingKey(sound, "Delay", delay); + this->writeStartSoundSetting(sound, "Enabled", enabled); + this->writeStartSoundSetting(sound, "Delay", delay); return true; } -bool ScStwRace::writeStartSoundSettingKey(ScStwSoundPlayer::StartSound sound, QString key, QVariant value) { +bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, QString key, QVariant value) { if(key != "Delay" && key != "Enabled") return false; @@ -644,6 +649,13 @@ bool ScStwRace::setSoundVolume(double volume) { if(this->settings != nullptr) return false; + return this->setSoundVolume(volume, true); +} + +bool ScStwRace::setSoundVolume(double volume, bool force) { + if(!force) + return false; + if(volume >= 0 && volume <= 1) { this->soundVolume = volume; return true; @@ -681,21 +693,25 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { } void ScStwRace::reloadAllSettings() { - this->writeStartSoundSetting( + qDebug() << "reloading all settings"; + + this->setStartSoundSetting( ScStwSoundPlayer::AtYourMarks, this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundEnableSetting).toBool(), - this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundDelaySetting).toDouble() + this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundDelaySetting).toDouble(), + true ); - this->writeStartSoundSetting( + this->setStartSoundSetting( ScStwSoundPlayer::Ready, this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundEnableSetting).toBool(), - this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundDelaySetting).toDouble() + this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundDelaySetting).toDouble(), + true ); - this->setSoundVolume(this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble()); + this->setSoundVolume(this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble(), true); - this->setCompetitionMode(this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool()); + this->setCompetitionMode(this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool(), true); } void ScStwRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { @@ -704,7 +720,7 @@ void ScStwRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { return; } - qDebug() << "Setting changed"; + qDebug() << "Setting chagned: key: " << keyInt << " level: " << keyLevel << " value: " << value; switch (keyLevel) { case 0: { @@ -712,22 +728,22 @@ void ScStwRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { ScStwSettings::BaseStationSetting key = static_cast(keyInt); switch (key) { case ScStwSettings::AtYourMarksSoundEnableSetting: - this->writeStartSoundSettingKey(ScStwSoundPlayer::AtYourMarks, "Enabled", value); + this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, "Enabled", value); break; case ScStwSettings::AtYourMarksSoundDelaySetting: - this->writeStartSoundSettingKey(ScStwSoundPlayer::AtYourMarks, "Delay", value); + this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, "Delay", value); break; case ScStwSettings::ReadySoundEnableSetting: - this->writeStartSoundSettingKey(ScStwSoundPlayer::Ready, "Enabled", value); + this->writeStartSoundSetting(ScStwSoundPlayer::Ready, "Enabled", value); break; case ScStwSettings::ReadySoundDelaySetting: - this->writeStartSoundSettingKey(ScStwSoundPlayer::Ready, "Delay", value); + this->writeStartSoundSetting(ScStwSoundPlayer::Ready, "Delay", value); break; case ScStwSettings::SoundVolumeSetting: - this->setSoundVolume(value.toDouble()); + this->setSoundVolume(value.toDouble(), true); break; case ScStwSettings::CompetitionModeSetting: - this->setCompetitionMode(value.toBool()); + this->setCompetitionMode(value.toBool(), true); default: return; @@ -774,6 +790,8 @@ QVariantMap ScStwRace::getDetails() { if(this->state == WAITING) tmpDetails.insert("isReadyForNextState", this->getIsReadyForNextState()); + else + tmpDetails.insert("isReadyForNextState", true); return tmpDetails; } From 6709a1fd2b39446c965f24a341c0d3d714e6b0ad Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 17:45:54 +0200 Subject: [PATCH 43/76] changed settings approach --- ScStwLibraries/headers/scstwrace.h | 32 +-- ScStwLibraries/sources/scstwrace.cpp | 300 +++++++++------------------ 2 files changed, 105 insertions(+), 227 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 3495dd6..210a64a 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -61,7 +61,6 @@ class ScStwRace : public QObject Q_PROPERTY(QVariantMap details READ getDetails NOTIFY detailsChanged) public: - explicit ScStwRace(QObject *parent = nullptr); explicit ScStwRace(ScStwSettings *settings, QObject *parent = nullptr); friend class ScStwRemoteRace; @@ -84,17 +83,7 @@ private: // settings ScStwSettings *settings; - double soundVolume; bool competitionMode; - bool competitionModeChangedRecently; - - /*! - * \brief stores the start action settings - * - * \details Stores the settings for the action ScStwRace::AtYourMarks and ScStwRace::Ready. The settings keys are: "Enabled" and "Delay" - */ - QMap startSoundSettings; - enum LoopExitTypes { LoopAutomaticExit = 0, @@ -127,11 +116,7 @@ public slots: virtual ScStw::StatusCode reset(); virtual ScStw::StatusCode cancel(); - // setters - bool setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay); - bool setSoundVolume(double volume); virtual bool addTimer(ScStwTimer *timer); - bool setCompetitionMode(bool competitionMode); // getters RaceState getState(); @@ -150,7 +135,6 @@ private slots: int handleFalseStart(); bool playSoundsAndStartTimers(); bool doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); - void enableAllTimers(); void technicalIncident(); /** @@ -158,18 +142,18 @@ private slots: */ void handleTimerStop(); + virtual void refreshCompetitionMode(); + + double getSoundVolume(); + ScStwSoundPlayer::StartSound getSoundForState(ScStwRace::RaceState state); + bool getSoundEnabledSetting(ScStwSoundPlayer::StartSound sound); + int getSoundDelaySetting(ScStwSoundPlayer::StartSound sound); + + bool isStarting(); virtual bool getIsReadyForNextState(); void handleTimerReadyStateChange(ScStwTimer::ReadyState readyState); - // settings - bool setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay, bool force); - bool setSoundVolume(double volume, bool force); - bool setCompetitionMode(bool competitionMode, bool force); - bool writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, QString key, QVariant value); - virtual void handleSettingChange(int keyInt, int keyLevel, QVariant value); - void reloadAllSettings(); - signals: void startTimers(); void stopTimers(int type); diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 48e8ed9..a3ef689 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -18,13 +18,10 @@ #include "../headers/scstwrace.h" -ScStwRace::ScStwRace(QObject * parent) : ScStwRace(nullptr, parent) -{ -} - ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) { this->state = IDLE; + this->competitionMode = false; // configure the loop that waits for the sound effect to finish this->soundPlayer = new ScStwSoundPlayer(); @@ -41,19 +38,8 @@ ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) connect(this, &ScStwRace::stateChanged, this, &ScStwRace::detailsChanged); // init settings - this->competitionMode = false; - this->competitionModeChangedRecently = false; - this->soundVolume = 1; - this->startSoundSettings.insert(ScStwSoundPlayer::Start, {{"Enabled", true}, {"Delay", 1}}); - this->setStartSoundSetting(ScStwSoundPlayer::AtYourMarks, false, 0); - this->setStartSoundSetting(ScStwSoundPlayer::Ready, false, 0); - this->setSoundVolume(1.0); - this->settings = settings; - if(this->settings != nullptr) { - connect(this->settings, &ScStwSettings::settingChanged, this, &ScStwRace::handleSettingChange); - this->reloadAllSettings(); - } + this->refreshCompetitionMode(); } // -------------------------- @@ -74,6 +60,8 @@ ScStw::StatusCode ScStwRace::start(bool asyncronous) { return ScStw::CurrentStateNotVaildForOperationError; } + this->refreshCompetitionMode(); + if(!this->getIsReadyForNextState()) return ScStw::TimersNotReadyError; @@ -225,7 +213,7 @@ int ScStwRace::handleFalseStart() { this->setState(STOPPED); this->soundPlayer->cancel(); - this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->soundVolume); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); return returnCode; } @@ -249,14 +237,14 @@ bool ScStwRace::playSoundsAndStartTimers() { // wait until both climbers are ready // if the automatic ready tone is enabled, wait for the climbers to become ready - if(this->competitionMode && this->startSoundSettings.contains(ScStwSoundPlayer::Ready) && this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) { + if(this->competitionMode && this->getSoundEnabledSetting(ScStwSoundPlayer::Ready)) { qDebug() << "[RACE][INFO] Now waiting for climbers"; // get delay int minimumReadyDelay = 1000; - if(this->startSoundSettings[ScStwSoundPlayer::Ready]["Delay"].toInt() > 1000) - minimumReadyDelay = this->startSoundSettings[ScStwSoundPlayer::Ready]["Delay"].toInt(); + if(this->getSoundDelaySetting(ScStwSoundPlayer::Ready) > 1000) + minimumReadyDelay = this->getSoundDelaySetting(ScStwSoundPlayer::Ready); this->startDelayTimer->setInterval(minimumReadyDelay); @@ -302,7 +290,7 @@ bool ScStwRace::playSoundsAndStartTimers() { qDebug() << "[DEBUG][RACE] Wait finished, starting now!"; // play ready tone - if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->soundVolume)) { + if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->getSoundVolume())) { qDebug() << "[ERROR][RACE] Ready sound returned false!"; this->technicalIncident(); return false; @@ -369,28 +357,14 @@ bool ScStwRace::playSoundsAndStartTimers() { } bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart) { - ScStwSoundPlayer::StartSound sound; + ScStwSoundPlayer::StartSound sound = this->getSoundForState(this->state); - switch (this->state) { - case PREPAIRING: - sound = ScStwSoundPlayer::AtYourMarks; - break; - case WAITING: - sound = ScStwSoundPlayer::Ready; - break; - case STARTING: - sound = ScStwSoundPlayer::Start; - break; - default: - return false; - } - - if(this->startSoundSettings.contains(sound) && this->startSoundSettings[sound]["Enabled"].toBool()) { - if(sound != ScStwSoundPlayer::Start && this->startSoundSettings[sound]["Delay"].toInt() > 0) { + if(this->getSoundEnabledSetting(sound)) { + if(sound != ScStwSoundPlayer::Start && this->getSoundDelaySetting(sound) > 0) { // perform the delay before the start // get delay - int thisSoundDelay = this->startSoundSettings[sound]["Delay"].toInt(); + int thisSoundDelay = this->getSoundDelaySetting(sound); // perform next action if(thisSoundDelay > 0) { @@ -407,7 +381,7 @@ bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackSt if(!this->isStarting()) return false; - if(!this->soundPlayer->play(sound, this->soundVolume, timeOfSoundPlaybackStart)) + if(!this->soundPlayer->play(sound, this->getSoundVolume(), timeOfSoundPlaybackStart)) return false; } @@ -421,18 +395,7 @@ void ScStwRace::setState(RaceState newState) { emit this->stateChanged(newState); if(this->state == IDLE) { - // if we changed to IDLE -> handle timer enable / disable - if(this->competitionModeChangedRecently && this->competitionMode) { - this->enableAllTimers(); - this->competitionModeChangedRecently = false; - } - - if(!this->competitionMode) { - foreach(ScStwTimer* timer, this->timers) { - if(timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) - this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); - } - } + this->refreshCompetitionMode(); } } } @@ -527,12 +490,29 @@ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wants } } -void ScStwRace::enableAllTimers() { +void ScStwRace::refreshCompetitionMode() { if(this->state != IDLE) return; - foreach (ScStwTimer *timer, this->timers) { - timer->setDisabled(false); + bool currentCompetitionMode = this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool(); + + if(this->competitionMode != currentCompetitionMode) { + + qDebug() << "[INFO][RACE] Setting competition mode to " << currentCompetitionMode; + + this->competitionMode = currentCompetitionMode; + + if(this->competitionMode) { + foreach (ScStwTimer *timer, this->timers) { + timer->setDisabled(false); + } + } + else { + foreach(ScStwTimer* timer, this->timers) { + if(timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) + this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); + } + } } } @@ -546,7 +526,7 @@ QVariantMap ScStwRace::getCurrentStartDelay() { switch (this->state) { case WAITING: - if(!this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()) + if(!this->getSoundEnabledSetting(ScStwSoundPlayer::Ready)) return currentStartDelay; if(!this->getIsReadyForNextState()) { // indicate that we are waiting for climbers and the progress shall be zero @@ -555,7 +535,7 @@ QVariantMap ScStwRace::getCurrentStartDelay() { } break; case PREPAIRING: { - if(!this->startSoundSettings[ScStwSoundPlayer::AtYourMarks]["Enabled"].toBool()) + if(!this->getSoundEnabledSetting(ScStwSoundPlayer::AtYourMarks)) return currentStartDelay; break; @@ -583,88 +563,6 @@ QVariantMap ScStwRace::getCurrentStartDelay() { return currentStartDelay; } -bool ScStwRace::setCompetitionMode(bool competitionMode) { - if(this->settings != nullptr) - return false; - - return this->setCompetitionMode(competitionMode, true); -} - -bool ScStwRace::setCompetitionMode(bool competitionMode, bool force) { - if(!force) - return false; - - if(this->competitionMode == competitionMode) - return true; - - qDebug() << "[INFO][RACE] Setting competition mode to " << competitionMode; - - this->competitionMode = competitionMode; - - if(this->state != IDLE) - this->competitionModeChangedRecently = true; - else if(this->competitionMode) - this->enableAllTimers(); - - return true; -} - -bool ScStwRace::setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay) { - if(this->settings != nullptr) - return false; - - return this->setStartSoundSetting(sound, enabled, delay, true); -} - -bool ScStwRace::setStartSoundSetting(ScStwSoundPlayer::StartSound sound, bool enabled, int delay, bool force) { - if(!force) - return false; - - if(sound != ScStwSoundPlayer::AtYourMarks && sound != ScStwSoundPlayer::Ready) - return false; - - this->writeStartSoundSetting(sound, "Enabled", enabled); - this->writeStartSoundSetting(sound, "Delay", delay); - - return true; -} - -bool ScStwRace::writeStartSoundSetting(ScStwSoundPlayer::StartSound sound, QString key, QVariant value) { - - if(key != "Delay" && key != "Enabled") - return false; - - if(!this->startSoundSettings.contains(sound)) - this->startSoundSettings.insert(sound, {}); - - if(!this->startSoundSettings[sound].contains(key)) - this->startSoundSettings[sound].insert(key, value); - else - this->startSoundSettings[sound][key] = value; - - return true; -} - -bool ScStwRace::setSoundVolume(double volume) { - if(this->settings != nullptr) - return false; - - return this->setSoundVolume(volume, true); -} - -bool ScStwRace::setSoundVolume(double volume, bool force) { - if(!force) - return false; - - if(volume >= 0 && volume <= 1) { - this->soundVolume = volume; - return true; - } - else { - return false; - } -} - bool ScStwRace::addTimer(ScStwTimer *timer) { if(this->state != IDLE) return false; @@ -692,67 +590,6 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { } -void ScStwRace::reloadAllSettings() { - qDebug() << "reloading all settings"; - - this->setStartSoundSetting( - ScStwSoundPlayer::AtYourMarks, - this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundEnableSetting).toBool(), - this->settings->readSetting(ScStwSettings::BaseStationSetting::AtYourMarksSoundDelaySetting).toDouble(), - true - ); - - this->setStartSoundSetting( - ScStwSoundPlayer::Ready, - this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundEnableSetting).toBool(), - this->settings->readSetting(ScStwSettings::BaseStationSetting::ReadySoundDelaySetting).toDouble(), - true - ); - - this->setSoundVolume(this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble(), true); - - this->setCompetitionMode(this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool(), true); -} - -void ScStwRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { - if(keyInt == -1) { - this->reloadAllSettings(); - return; - } - - qDebug() << "Setting chagned: key: " << keyInt << " level: " << keyLevel << " value: " << value; - - switch (keyLevel) { - case 0: { - // BaseStationSetting!! - ScStwSettings::BaseStationSetting key = static_cast(keyInt); - switch (key) { - case ScStwSettings::AtYourMarksSoundEnableSetting: - this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, "Enabled", value); - break; - case ScStwSettings::AtYourMarksSoundDelaySetting: - this->writeStartSoundSetting(ScStwSoundPlayer::AtYourMarks, "Delay", value); - break; - case ScStwSettings::ReadySoundEnableSetting: - this->writeStartSoundSetting(ScStwSoundPlayer::Ready, "Enabled", value); - break; - case ScStwSettings::ReadySoundDelaySetting: - this->writeStartSoundSetting(ScStwSoundPlayer::Ready, "Delay", value); - break; - case ScStwSettings::SoundVolumeSetting: - this->setSoundVolume(value.toDouble(), true); - break; - case ScStwSettings::CompetitionModeSetting: - this->setCompetitionMode(value.toBool(), true); - - default: - return; - } - break; - } - } -} - ScStwRace::RaceState ScStwRace::getState() { return this->state; } @@ -761,6 +598,64 @@ QList ScStwRace::getTimers() { return this->timers; } +double ScStwRace::getSoundVolume() { + return this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble(); +} + +ScStwSoundPlayer::StartSound ScStwRace::getSoundForState(ScStwRace::RaceState state) { + switch (state) { + case PREPAIRING: + return ScStwSoundPlayer::AtYourMarks; + break; + case WAITING: + return ScStwSoundPlayer::Ready; + break; + case STARTING: + return ScStwSoundPlayer::Start; + break; + default: + return ScStwSoundPlayer::StartSound(-1); + } +} + +bool ScStwRace::getSoundEnabledSetting(ScStwSoundPlayer::StartSound sound) { + ScStwSettings::BaseStationSetting soundEnabledSetting; + switch (sound) { + case ScStwSoundPlayer::AtYourMarks: + soundEnabledSetting = ScStwSettings::AtYourMarksSoundEnableSetting; + break; + case ScStwSoundPlayer::Ready: + soundEnabledSetting = ScStwSettings::ReadySoundEnableSetting; + break; + case ScStwSoundPlayer::Start: + return true; + break; + default: + return false; + } + + return this->settings->readSetting(soundEnabledSetting).toBool(); +} + +int ScStwRace::getSoundDelaySetting(ScStwSoundPlayer::StartSound sound) { + ScStwSettings::BaseStationSetting soundDelaySetting; + switch (sound) { + case ScStwSoundPlayer::AtYourMarks: + soundDelaySetting = ScStwSettings::AtYourMarksSoundDelaySetting; + break; + case ScStwSoundPlayer::Ready: + soundDelaySetting = ScStwSettings::ReadySoundDelaySetting; + break; + case ScStwSoundPlayer::Start: + return 0; + break; + default: + return -1; + } + + return this->settings->readSetting(soundDelaySetting).toInt(); +} + QVariantList ScStwRace::getTimerDetailList() { QVariantList tmpTimers; @@ -770,7 +665,6 @@ QVariantList ScStwRace::getTimerDetailList() { tmpTimer.insert("state", timer->getState()); tmpTimer.insert("currentTime", timer->getCurrentTime()); tmpTimer.insert("reactionTime", timer->getReactionTime()); - tmpTimer.insert("text", timer->getText()); tmpTimer.insert("letter", timer->getLetter()); tmpTimer.insert("readyState", timer->getReadyState()); tmpTimers.append(tmpTimer); @@ -784,7 +678,7 @@ QVariantMap ScStwRace::getDetails() { tmpDetails.insert("state", this->getState()); tmpDetails.insert("competitionMode", this->competitionMode); - tmpDetails.insert("readySoundEnabled", this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool()); + tmpDetails.insert("readySoundEnabled", this->getSoundEnabledSetting(ScStwSoundPlayer::Ready)); tmpDetails.insert("currentStartDelay", this->getCurrentStartDelay()); tmpDetails.insert("timers", this->getTimerDetailList()); @@ -813,5 +707,5 @@ bool ScStwRace::getCompetitionMode() { } bool ScStwRace::getReadySoundEnabled() { - return this->startSoundSettings[ScStwSoundPlayer::Ready]["Enabled"].toBool(); + return this->getSoundEnabledSetting(ScStwSoundPlayer::Ready); } From 9c736234183e6751a9a4d29f34246469357d6887 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 18:32:39 +0200 Subject: [PATCH 44/76] some fixes to remote race --- ScStwLibraries/headers/client/scstwremoterace.h | 3 ++- ScStwLibraries/sources/client/scstwremoterace.cpp | 11 +++++------ ScStwLibraries/sources/scstwlibraries.cpp | 2 +- ScStwLibraries/sources/scstwrace.cpp | 1 + 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index c5eb83d..ccf780f 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -60,12 +60,13 @@ public slots: private slots: void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); - void handleSettingChange(int keyInt, int keyLevel, QVariant value); bool refreshRemoteTimers(QVariantList remoteTimers); void rebuildRemoteTimers(QVariantList remoteTimers); void refreshDetails(QVariantMap details); void handleClientStateChange(); + + void refreshCompetitionMode(); RaceMode getMode(); bool local(); }; diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 1dd7acc..d0ca62e 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -129,12 +129,6 @@ bool ScStwRemoteRace::local() { return this->getMode() == LOCAL; } -void ScStwRemoteRace::handleSettingChange(int keyInt, int keyLevel, QVariant value) { - if(this->local()) - return ScStwRace::handleSettingChange(keyInt, keyLevel, value); -} - - /** * @brief ScStwAppBackend::handleBaseStationUpdate * @@ -292,3 +286,8 @@ bool ScStwRemoteRace::getReadySoundEnabled() { return this->readySoundEnabled; } + +void ScStwRemoteRace::refreshCompetitionMode() { + if(this->local()) + return ScStwRace::refreshCompetitionMode(); +} diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 34b75b7..08ba19d 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -30,7 +30,7 @@ void ScStwLibraries::init() { qRegisterMetaType("ScStw::SocketCommand"); qRegisterMetaType("ScStw::StatusCode"); - qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRace"); + qmlRegisterUncreatableType("de.itsblue.ScStw", 2, 0, "ScStwRace", "ScStwRace is not creatable"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwTimer"); #ifdef ScStwLibraries_ClientLibs diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index a3ef689..0f40cd0 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -667,6 +667,7 @@ QVariantList ScStwRace::getTimerDetailList() { tmpTimer.insert("reactionTime", timer->getReactionTime()); tmpTimer.insert("letter", timer->getLetter()); tmpTimer.insert("readyState", timer->getReadyState()); + tmpTimer.insert("text", timer->getText()); tmpTimers.append(tmpTimer); } From e4700cd355087d8b46f49ada1a5d7aeb97462920 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 18:33:17 +0200 Subject: [PATCH 45/76] some more error handling for sound playing --- ScStwLibraries/headers/scstwrace.h | 2 +- ScStwLibraries/headers/scstwsoundplayer.h | 12 +++-- ScStwLibraries/sources/scstwrace.cpp | 57 +++++++++++++++------ ScStwLibraries/sources/scstwsoundplayer.cpp | 22 ++++---- ScStwLibraries/sources/scstwtimer.cpp | 3 -- 5 files changed, 64 insertions(+), 32 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 210a64a..c745038 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -134,7 +134,7 @@ private slots: void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); int handleFalseStart(); bool playSoundsAndStartTimers(); - bool doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); + ScStwSoundPlayer::PlayResult doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); void technicalIncident(); /** diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index 3356a51..28d9bdc 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -49,6 +49,12 @@ public: FalseStart = 3 }; + enum PlayResult { + Success = 0, + Cancelled = -1, + Error = -2 + }; + private: /*! * \brief A map containing all sound files @@ -91,16 +97,16 @@ public slots: * \param action The action to play (0: AtYourMarks, 1:Ready, 2:Start) * \param volume The volume to play at * \param timeOfStop The time the playback actually started (msecs since epoch) - * \return true if the playback was successfully started, false otherwise + * \return TODO true if the playback was successfully started, false otherwise */ - bool play(StartSound sound, double volume, double *timeOfStart = nullptr); + ScStwSoundPlayer::PlayResult play(StartSound sound, double volume, double *timeOfStart = nullptr); /*! * \brief Function to wait for the playback to finish * \param timeOfStop the point in time when the plyback actually stopped (msecs since epoch) * \return false if there was any error (eg. there was no playback currently), true otherwise */ - bool waitForSoundFinish(double *timeOfStop = nullptr); + ScStwSoundPlayer::PlayResult waitForSoundFinish(double *timeOfStop = nullptr); /*! * \brief Function to cancel the current playback diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index a3ef689..3f91b1c 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -197,6 +197,8 @@ void ScStwRace::technicalIncident() { foreach(ScStwTimer *timer, this->timers){ timer->cancel(); } + + this->soundPlayer->cancel(); this->setState(INCIDENT); } @@ -223,8 +225,16 @@ bool ScStwRace::playSoundsAndStartTimers() { return true; // The check if all timers are ready has already happened at this point - if(!this->doDelayAndSoundOfCurrentStartState()) + ScStwSoundPlayer::PlayResult res = this->doDelayAndSoundOfCurrentStartState(); + + if(res == ScStwSoundPlayer::Error) { + qDebug() << "[ERROR][RACE] error playing at your marks sound"; + this->technicalIncident(); return false; + } + else if(res == ScStwSoundPlayer::Cancelled) { + return false; + } // check if the start was cancelled if(!this->isStarting()) @@ -234,8 +244,6 @@ bool ScStwRace::playSoundsAndStartTimers() { // do climber readiness tests - // wait until both climbers are ready - // if the automatic ready tone is enabled, wait for the climbers to become ready if(this->competitionMode && this->getSoundEnabledSetting(ScStwSoundPlayer::Ready)) { @@ -290,11 +298,16 @@ bool ScStwRace::playSoundsAndStartTimers() { qDebug() << "[DEBUG][RACE] Wait finished, starting now!"; // play ready tone - if(!this->soundPlayer->play(ScStwSoundPlayer::Ready, this->getSoundVolume())) { - qDebug() << "[ERROR][RACE] Ready sound returned false!"; + ScStwSoundPlayer::PlayResult res = this->soundPlayer->play(ScStwSoundPlayer::Ready, this->getSoundVolume()); + + if(res == ScStwSoundPlayer::Error) { + qDebug() << "[ERROR][RACE] error playing ready sound"; this->technicalIncident(); return false; } + else if(res == ScStwSoundPlayer::Cancelled) { + return false; + } } else if(this->competitionMode) { // wait for climbers and manual start @@ -308,8 +321,14 @@ bool ScStwRace::playSoundsAndStartTimers() { } while(loopExitCode != LoopManualExit || !this->getIsReadyForNextState()); } else { - if(!this->doDelayAndSoundOfCurrentStartState()) { - this->cancel(); + ScStwSoundPlayer::PlayResult res = this->doDelayAndSoundOfCurrentStartState(); + + if(res == ScStwSoundPlayer::Error) { + qDebug() << "[ERROR][RACE] error playing ready sound"; + this->technicalIncident(); + return false; + } + else if(res == ScStwSoundPlayer::Cancelled) { return false; } } @@ -319,10 +338,16 @@ bool ScStwRace::playSoundsAndStartTimers() { // play start tone double timeOfSoundPlaybackStart; - if(!this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart)) { + res = this->doDelayAndSoundOfCurrentStartState(&timeOfSoundPlaybackStart); + + if(res == ScStwSoundPlayer::Error) { + qDebug() << "[ERROR][RACE] error playing at your marks sound"; this->technicalIncident(); return false; } + else if(res == ScStwSoundPlayer::Cancelled) { + return false; + } // perform start @@ -339,7 +364,7 @@ bool ScStwRace::playSoundsAndStartTimers() { return false; } - if(!this->soundPlayer->waitForSoundFinish()) { + if(this->soundPlayer->waitForSoundFinish() == ScStwSoundPlayer::Error) { qDebug() << "[ERROR][RACE] start sound wait error"; this->technicalIncident(); return false; @@ -347,7 +372,7 @@ bool ScStwRace::playSoundsAndStartTimers() { // check if a false start occured if(!this->isStarting()) - return true; + return false; this->setState(RUNNING); @@ -356,7 +381,7 @@ bool ScStwRace::playSoundsAndStartTimers() { } -bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart) { +ScStwSoundPlayer::PlayResult ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart) { ScStwSoundPlayer::StartSound sound = this->getSoundForState(this->state); if(this->getSoundEnabledSetting(sound)) { @@ -374,18 +399,18 @@ bool ScStwRace::doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackSt emit this->currentStartDelayChanged(); if(this->startWaitLoop->exec() == LoopCancelExit) - return false; + return ScStwSoundPlayer::Cancelled; } } if(!this->isStarting()) - return false; + return ScStwSoundPlayer::Error; - if(!this->soundPlayer->play(sound, this->getSoundVolume(), timeOfSoundPlaybackStart)) - return false; + + return this->soundPlayer->play(sound, this->getSoundVolume(), timeOfSoundPlaybackStart); } - return true; + return ScStwSoundPlayer::Success; } void ScStwRace::setState(RaceState newState) { diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index e68caee..463d716 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -35,9 +35,11 @@ ScStwSoundPlayer::ScStwSoundPlayer(QObject *parent) : QObject(parent) connect(this->soundEffect, &QSoundEffect::playingChanged, this->waitLoop, &QEventLoop::quit); } -bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, double *timeOfStart) { - if(!this->soundFiles.contains(sound)) - return false; +ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, double *timeOfStart) { + if(!this->soundFiles.contains(sound)) { + qDebug() << "[ERROR][SoundPlayer] Sound file was not found for sound" << sound; + return ScStwSoundPlayer::Error; + } // stop playback if(this->soundEffect->isPlaying()) @@ -55,6 +57,7 @@ bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, d // wait for the effect to load QEventLoop loop; while(this->soundEffect->status() != QSoundEffect::Ready) { + qDebug() << "[DEBUG][Sound] Sound is not ready yet, status is: " << this->soundEffect->status(); QObject::connect(this->soundEffect, &QSoundEffect::statusChanged, &loop, &QEventLoop::quit); loop.exec(); } @@ -76,7 +79,7 @@ bool ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound sound, double volume, d if(sound < Start) return this->waitForSoundFinish(); - return true; + return ScStwSoundPlayer::Success; } bool ScStwSoundPlayer::cancel() { @@ -85,17 +88,18 @@ bool ScStwSoundPlayer::cancel() { // stop playback this->soundEffect->stop(); - this->waitLoop->quit(); + this->waitLoop->exit(-1); return true; } -bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { +ScStwSoundPlayer::PlayResult ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { if(!this->soundEffect->isPlaying()) - return false; + return ScStwSoundPlayer::Error; // wait until the audio output reports the sound is over - waitLoop->exec(); + if(waitLoop->exec() == -1) + return ScStwSoundPlayer::Cancelled; // wait until the sound is actually over // the timeOffset is the buffer time before the audio started! @@ -113,7 +117,7 @@ bool ScStwSoundPlayer::waitForSoundFinish(double *timeOfStop) { *timeOfStop = QDateTime::currentMSecsSinceEpoch() - latency; } - return true; + return ScStwSoundPlayer::Success; } bool ScStwSoundPlayer::isPlaying() { diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index f7f77ba..efa429a 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -217,9 +217,6 @@ QString ScStwTimer::getLetter() { } QString ScStwTimer::getText() { - - qDebug() << "getting text: start time: " << this->startTime << " state: " << this->state; - QString newText = ""; int newTime = 0; switch (this->state) { From 53968ae15367bcea22829683b45701a70612e8d5 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 3 Oct 2020 21:47:53 +0200 Subject: [PATCH 46/76] fixed a bug in remote race --- ScStwLibraries/sources/client/scstwremoterace.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index d0ca62e..7ac0307 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -100,6 +100,7 @@ void ScStwRemoteRace::handleClientStateChange() { this->localTimers.clear(); this->localTimers = this->timers; this->timers.clear(); + this->remoteTimers.clear(); break; case ScStwClient::DISCONNECTED: foreach(ScStwRemoteTimer *remoteTimer, this->remoteTimers) @@ -185,7 +186,6 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { } emit this->detailsChanged(); - } void ScStwRemoteRace::rebuildRemoteTimers(QVariantList remoteTimers) { @@ -212,6 +212,7 @@ bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { if(remoteTimers.length() != this->remoteTimers.length()){ // local timers are out of sync this->rebuildRemoteTimers(remoteTimers); + qDebug() << "rebuilding remote timers"; } foreach(QVariant remoteTimer, remoteTimers){ From ade9949377ce2f058cbc316a73ae83dadfcf519a Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 01:47:50 +0200 Subject: [PATCH 47/76] changed technical incident approach --- ScStwLibraries/headers/scstwrace.h | 1 + ScStwLibraries/sources/scstwrace.cpp | 56 +++++++++++++++++----------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index c745038..87599d0 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -87,6 +87,7 @@ private: enum LoopExitTypes { LoopAutomaticExit = 0, + LoopReadyStateChangeExit = 1, LoopManualExit = 2, LoopCancelExit = 3 }; diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index f00fa40..e51e29f 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -194,12 +194,43 @@ ScStw::StatusCode ScStwRace::cancel() { } void ScStwRace::technicalIncident() { + + bool raceIsRunning = this->state == RUNNING; + + qDebug() << "[ERROR][RACE] Got a technical incident"; + foreach(ScStwTimer *timer, this->timers){ - timer->cancel(); + if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + continue; + else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + timer->technicalIncident(); + else if(!raceIsRunning) + timer->setState(ScStwTimer::CANCELLED); } - this->soundPlayer->cancel(); - this->setState(INCIDENT); + if(!raceIsRunning) { + this->startWaitLoop->exit(LoopCancelExit); + this->soundPlayer->cancel(); + this->setState(INCIDENT); + } +} + +void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { + + if(!this->competitionMode || this->state == IDLE || this->state == STOPPED || this->state == INCIDENT ) + return; + + // cancel as a technical incident if extensions are disconnected or run low on battery + if(readyState == ScStwTimer::ExtensionBatteryNotFine || readyState == ScStwTimer::ExtensionBatteryNotFine) { + this->technicalIncident(); + return; + } + + // only continue if the current state is waiting + if(this->state == WAITING) { + this->startWaitLoop->exit(ScStwRace::LoopReadyStateChangeExit); + emit this->timersChanged(); + } } int ScStwRace::handleFalseStart() { @@ -466,15 +497,6 @@ bool ScStwRace::getIsReadyForNextState() { if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { - timer->technicalIncident(); - - foreach (ScStwTimer *subTimer, this->timers) { - if(timer != subTimer && (timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine)) - subTimer->technicalIncident(); - else if(timer != subTimer) - subTimer->setState(ScStwTimer::CANCELLED); - } - this->technicalIncident(); qDebug() << "[ERROR][RACE] Could not start due to not-ready timers"; @@ -603,7 +625,6 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); - connect(timer, &ScStwTimer::readyStateChanged, this->startWaitLoop, &QEventLoop::quit); connect(timer, &ScStwTimer::readyStateChanged, this, &ScStwRace::handleTimerReadyStateChange); connect(timer, &ScStwTimer::readyStateChanged, this, &ScStwRace::isReadyForNextStateChanged); @@ -719,15 +740,6 @@ QVariantMap ScStwRace::getDetails() { bool ScStwRace::isStarting() { return this->state == PREPAIRING || this->state == WAITING || this->state == STARTING; } - -void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { - Q_UNUSED(readyState) - - // only continue if the current state is waiting - if(this->state == WAITING) - emit this->timersChanged(); -} - bool ScStwRace::getCompetitionMode() { return this->competitionMode; } From ec6723af7514be89f691f9746b0685e63ddc13c2 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 15:11:07 +0200 Subject: [PATCH 48/76] - fixed some issues with post- and during- start checks - fixed issues with timers states --- ScStwLibraries/headers/scstwrace.h | 2 +- ScStwLibraries/sources/scstwrace.cpp | 35 +++++++++++++-------- ScStwLibraries/sources/scstwsoundplayer.cpp | 2 ++ 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 87599d0..3df605b 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -131,7 +131,7 @@ public slots: protected slots: private slots: - void refreshTimerStates(); + void handleTimersStateChange(); void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); int handleFalseStart(); bool playSoundsAndStartTimers(); diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index e51e29f..2b13f53 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -197,7 +197,7 @@ void ScStwRace::technicalIncident() { bool raceIsRunning = this->state == RUNNING; - qDebug() << "[ERROR][RACE] Got a technical incident"; + qDebug() << "[ERROR][RACE] Got a technical incident, state is: " << this->state; foreach(ScStwTimer *timer, this->timers){ if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) @@ -210,7 +210,12 @@ void ScStwRace::technicalIncident() { if(!raceIsRunning) { this->startWaitLoop->exit(LoopCancelExit); - this->soundPlayer->cancel(); + + if(this->state == STARTING) { + this->soundPlayer->cancel(); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); + } + this->setState(INCIDENT); } } @@ -220,8 +225,10 @@ void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { if(!this->competitionMode || this->state == IDLE || this->state == STOPPED || this->state == INCIDENT ) return; + qDebug() << "Some ready state changed: " << readyState; + // cancel as a technical incident if extensions are disconnected or run low on battery - if(readyState == ScStwTimer::ExtensionBatteryNotFine || readyState == ScStwTimer::ExtensionBatteryNotFine) { + if(readyState == ScStwTimer::ExtensionIsNotConnected || readyState == ScStwTimer::ExtensionBatteryNotFine) { this->technicalIncident(); return; } @@ -234,13 +241,16 @@ void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { } int ScStwRace::handleFalseStart() { - if(this->getState() != STARTING && this->getState() != RUNNING) + if(this->state != STARTING && this->state != RUNNING) return ScStw::CurrentStateNotVaildForOperationError; + qDebug() << "[INFO][RACE] Got a FALSE START"; + int returnCode = ScStw::Success; + // cancel all running timers foreach(ScStwTimer *timer, this->timers) { - if(!timer->cancel() && timer->getState() != ScStwTimer::DISABLED && timer->getState() != ScStwTimer::FAILED) + if(timer->getState() != ScStwTimer::FAILED && !timer->cancel() && timer->getState() != ScStwTimer::DISABLED) returnCode = ScStw::InternalErrorTimerOperationFailed; } @@ -456,8 +466,8 @@ void ScStwRace::setState(RaceState newState) { } } -void ScStwRace::refreshTimerStates() { - qDebug() << "[INFO][MAIN] refreshing timer states"; +void ScStwRace::handleTimersStateChange() { + qDebug() << "[INFO][MAIN] handling timer state change"; // check if the race is over bool raceIsOver = true; @@ -466,14 +476,13 @@ void ScStwRace::refreshTimerStates() { if(timer->getState() < ScStwTimer::WON && timer->getState() != ScStwTimer::WAITING){ // if the timer is not in stoped state raceIsOver = false; - break; } - else if(timer->getState() == ScStwTimer::WAITING) { + else if(timer->getState() == ScStwTimer::WAITING) this->handleTimerStop(); - } - else if (timer->getState() == ScStwTimer::FAILED) { + else if (timer->getState() == ScStwTimer::FAILED) this->handleFalseStart(); - } + else if (timer->getState() == ScStwTimer::INCIDENT) + return; } if(raceIsOver) @@ -621,7 +630,7 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { this->timers.append(timer); - connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::refreshTimerStates); + connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimersStateChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 463d716..180bc53 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -62,6 +62,8 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound loop.exec(); } + qDebug() << "[DEBUG][Sound] Playing sound now: " << sound; + // start this->soundEffect->play(); From b8e8f452220637a2d76047e7b7a01fde5e704c61 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 15:22:43 +0200 Subject: [PATCH 49/76] added wildcard state --- ScStwLibraries/headers/scstwtimer.h | 10 ++++++++++ ScStwLibraries/sources/scstwrace.cpp | 7 ++++--- ScStwLibraries/sources/scstwtimer.cpp | 11 ++++++++++- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index a8a94a0..af782b8 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -86,6 +86,7 @@ public: WON, /*!< Timer has won */ LOST, /*!< Timer has lost */ FAILED, /*!< A false start occured */ + WILDCARD, /*!< The opponent has done a false start */ CANCELLED, /*!< Timer was cancelled */ INCIDENT, /*!< There was a technical incident (most likely a disconnected extension) */ DISABLED /*!< Timer is disabled */ @@ -332,6 +333,15 @@ protected slots: */ void technicalIncident(); + /*! + * \brief Function to set the timer into WILDCARD state + * + * Only works when the timer is in STARTING state. + * + * \return false if not in STARTING state + */ + bool wildcard(); + signals: /*! diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 2b13f53..a9adecc 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -248,10 +248,11 @@ int ScStwRace::handleFalseStart() { int returnCode = ScStw::Success; - // cancel all running timers + // set all running timers to wildcard foreach(ScStwTimer *timer, this->timers) { - if(timer->getState() != ScStwTimer::FAILED && !timer->cancel() && timer->getState() != ScStwTimer::DISABLED) - returnCode = ScStw::InternalErrorTimerOperationFailed; + if(timer->getState() != ScStwTimer::FAILED && timer->getState() != ScStwTimer::DISABLED) + if(!timer->wildcard()) + returnCode = ScStw::InternalErrorTimerOperationFailed; } this->setState(STOPPED); diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index efa429a..fdded29 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -71,6 +71,15 @@ void ScStwTimer::technicalIncident() { this->setState(INCIDENT); } +bool ScStwTimer::wildcard() { + if(this->state != STARTING) + return false; + + this->setState(WILDCARD); + + return true; +} + void ScStwTimer::handleClimberStart(double timeOfStart) { this->reactionTime = timeOfStart - this->startTime; qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; @@ -109,7 +118,7 @@ bool ScStwTimer::stop(StopReason reason) { } bool ScStwTimer::stop(StopReason reason, double timeOfStop) { - if(this->state != STARTING && this->state != RUNNING && this->state != WAITING){ + if(this->state != STARTING && this->state != WILDCARD && this->state != RUNNING && this->state != WAITING){ return false; } From 1138348a0e141e7b0da48a7cbf7d5581ff47a297 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 16:04:22 +0200 Subject: [PATCH 50/76] began to implement WILDCARD state --- ScStwLibraries/headers/scstwrace.h | 4 +- ScStwLibraries/headers/scstwtimer.h | 5 +- ScStwLibraries/sources/scstwrace.cpp | 158 +++++++++++++++----------- ScStwLibraries/sources/scstwtimer.cpp | 31 +++-- 4 files changed, 119 insertions(+), 79 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 3df605b..48150bf 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -131,9 +131,9 @@ public slots: protected slots: private slots: - void handleTimersStateChange(); + void handleTimerStateChange(); void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); - int handleFalseStart(); + void handleFalseStart(); bool playSoundsAndStartTimers(); ScStwSoundPlayer::PlayResult doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); void technicalIncident(); diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index af782b8..f2682c3 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -82,11 +82,12 @@ public: IDLE, /*!< Timer is waiting to be started */ STARTING, /*!< Timer is starting and will react with a false start if the climber starts */ RUNNING, /*!< Timer is running */ - WAITING, /*!< Timer was stopped and is waiting for the result */ + WAITING, /*!< Timer was stopped and is waiting to be set to either WON or LOST */ WON, /*!< Timer has won */ LOST, /*!< Timer has lost */ - FAILED, /*!< A false start occured */ + FAILING, /*!< Timer encountered a false start and is waiting to be set to either FAILED or WILDCARD */ WILDCARD, /*!< The opponent has done a false start */ + FAILED, /*!< A false start occured */ CANCELLED, /*!< Timer was cancelled */ INCIDENT, /*!< There was a technical incident (most likely a disconnected extension) */ DISABLED /*!< Timer is disabled */ diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index a9adecc..9deaa31 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -103,46 +103,6 @@ ScStw::StatusCode ScStwRace::stop() { return returnCode; } -void ScStwRace::handleTimerStop() { - if(this->state == RUNNING) { - // find out which timer has won - double lowestStoppedTime = -1; - QList timersWhichHaveWonIds; - - // iterate through all timers and find the lowest time taht was stopped - foreach(ScStwTimer * timer, this->timers) { - if(timer->getCurrentTime() > 0 && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0)) { - // this is the timer with the lowest stopped time - lowestStoppedTime = timer->getCurrentTime(); - } - } - - // append the timer(s) with the lowest stopped time to the winner list - foreach(ScStwTimer * timer, this->timers) { - if(timer->getCurrentTime() > 0 - && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0) - && timer->getState() != ScStwTimer::RUNNING - ) { - // this is the timer with the lowest stopped time - timersWhichHaveWonIds.append(timer); - } - } - - // update the states of all timers - foreach(ScStwTimer * timer, this->timers) { - if(timer->getState() == ScStwTimer::RUNNING) - continue; - - if(timersWhichHaveWonIds.contains(timer)) { - timer->setResult(ScStwTimer::WON); - } - else { - timer->setResult(ScStwTimer::LOST); - } - } - } -} - ScStw::StatusCode ScStwRace::reset() { if(this->state != STOPPED && this->state != INCIDENT) { return ScStw::CurrentStateNotVaildForOperationError; @@ -240,28 +200,6 @@ void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { } } -int ScStwRace::handleFalseStart() { - if(this->state != STARTING && this->state != RUNNING) - return ScStw::CurrentStateNotVaildForOperationError; - - qDebug() << "[INFO][RACE] Got a FALSE START"; - - int returnCode = ScStw::Success; - - // set all running timers to wildcard - foreach(ScStwTimer *timer, this->timers) { - if(timer->getState() != ScStwTimer::FAILED && timer->getState() != ScStwTimer::DISABLED) - if(!timer->wildcard()) - returnCode = ScStw::InternalErrorTimerOperationFailed; - } - - this->setState(STOPPED); - this->soundPlayer->cancel(); - this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); - - return returnCode; -} - bool ScStwRace::playSoundsAndStartTimers() { if(this->state != PREPAIRING) return true; @@ -467,20 +405,20 @@ void ScStwRace::setState(RaceState newState) { } } -void ScStwRace::handleTimersStateChange() { +void ScStwRace::handleTimerStateChange() { qDebug() << "[INFO][MAIN] handling timer state change"; // check if the race is over bool raceIsOver = true; foreach(ScStwTimer * timer, this->timers){ - if(timer->getState() < ScStwTimer::WON && timer->getState() != ScStwTimer::WAITING){ + if(timer->getState() < ScStwTimer::WAITING){ // if the timer is not in stoped state raceIsOver = false; } else if(timer->getState() == ScStwTimer::WAITING) this->handleTimerStop(); - else if (timer->getState() == ScStwTimer::FAILED) + else if (timer->getState() == ScStwTimer::FAILING) this->handleFalseStart(); else if (timer->getState() == ScStwTimer::INCIDENT) return; @@ -490,6 +428,94 @@ void ScStwRace::handleTimersStateChange() { this->setState(STOPPED); } +void ScStwRace::handleTimerStop() { + if(this->state != RUNNING) + return; + + // find out which timer has won + double lowestStoppedTime = -1; + QList timersWhichHaveWon; + + // iterate through all timers and find the lowest time that was stopped + foreach(ScStwTimer * timer, this->timers) { + if(timer->getCurrentTime() > 0 && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0)) { + // this is the timer with the lowest stopped time + lowestStoppedTime = timer->getCurrentTime(); + } + } + + // append the timer(s) with the lowest stopped time to the winner list + foreach(ScStwTimer * timer, this->timers) { + if(timer->getCurrentTime() > 0 + && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0) + && timer->getState() != ScStwTimer::RUNNING + ) { + // this is the timer with the lowest stopped time + timersWhichHaveWon.append(timer); + } + } + + // update the states of all timers + foreach(ScStwTimer * timer, this->timers) { + if(timer->getState() == ScStwTimer::RUNNING) + continue; + + if(timersWhichHaveWon.contains(timer)) { + timer->setResult(ScStwTimer::WON); + } + else { + timer->setResult(ScStwTimer::LOST); + } + } +} + +void ScStwRace::handleFalseStart() { + if(this->state != STARTING && this->state != RUNNING && this->state != STOPPED) + return; + + qDebug() << "[INFO][RACE] Got a FALSE START"; + + // set lowest to a value that is impossible to reach (start tone is only 3100ms long) + int lowestReactionTime = -4000; + + // iterate through all timers and find the lowest reactiontime that was stopped + foreach(ScStwTimer *timer, this->timers) { + if( + timer->getState() >= ScStwTimer::FAILING && + timer->getState() <= ScStwTimer::FAILED && + ( + timer->getReactionTime() < lowestReactionTime || + lowestReactionTime == -4000 + ) + ) { + lowestReactionTime = timer->getReactionTime(); + } + } + + if(lowestReactionTime == -4000) + // no timer has failed + return; + + // find out which timer(s) have lost and which get a wildcard + foreach(ScStwTimer * timer, this->timers) { + if( + timer->getState() >= ScStwTimer::FAILING && + timer->getState() <= ScStwTimer::FAILED && + timer->getCurrentTime() <= lowestReactionTime + ) { + // this is the timer with the lowest stopped time + timer->setResult(ScStwTimer::FAILED); + } + else { + timer->setResult(ScStwTimer::WILDCARD); + } + } + + this->setState(STOPPED); + this->soundPlayer->cancel(); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); +} + // ------------------------ // --- helper functions --- // ------------------------ @@ -631,7 +657,7 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { this->timers.append(timer); - connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimersStateChange); + connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimerStateChange); connect(timer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); connect(timer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); connect(timer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index fdded29..0a5eff3 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -76,7 +76,6 @@ bool ScStwTimer::wildcard() { return false; this->setState(WILDCARD); - return true; } @@ -84,7 +83,7 @@ void ScStwTimer::handleClimberStart(double timeOfStart) { this->reactionTime = timeOfStart - this->startTime; qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; - if(this->reactionTime <= 0){ + if(this->reactionTime <= 0 && this->reactionTime > -3100){ this->stop(FailStop); return; } @@ -150,19 +149,33 @@ bool ScStwTimer::stop(StopReason reason, double timeOfStop) { } bool ScStwTimer::setResult(TimerState result) { - if(this->state != WAITING) + if(this->state != FAILING && this->state != WAITING && this->state != STARTING) return false; switch (result) { case WON: - this->setState(WON); - return true; case LOST: - this->setState(LOST); - return true; + if(this->state == WAITING) { + this->setState(result); + return true; + } + break; + case WILDCARD: + if(this->state == STARTING) { + this->setState(WILDCARD); + return true; + } + case FAILED: + if(this->state == FAILING) { + this->setState(result); + return true; + } + break; default: - return false; + break; } + + return false; } bool ScStwTimer::reset(){ @@ -195,7 +208,7 @@ void ScStwTimer::setState(TimerState newState){ if(this->state != newState) { this->state = newState; - qDebug() << "+ [INFO][TIMER] timer state changed: " << newState; + qDebug() << "[INFO][TIMER] timer state changed: " << newState; emit this->stateChanged(); } } From d10803745fee19b6dba56d75647ed5b292182256 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 16:05:16 +0200 Subject: [PATCH 51/76] added som missing stuff --- ScStwLibraries/sources/client/scstwremoterace.cpp | 2 ++ ScStwLibraries/sources/scstwtimer.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 7ac0307..096dd7e 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -111,6 +111,8 @@ void ScStwRemoteRace::handleClientStateChange() { this->timers = this->localTimers; this->localTimers.clear(); emit this->timersChanged(); + emit this->detailsChanged(); + emit this->currentStartDelayChanged(); this->competitionMode = false; this->setState(IDLE); break; diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index fdded29..b0e01e5 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -250,11 +250,14 @@ QString ScStwTimer::getText() { case ScStwTimer::FAILED: newText = "false start"; break; + case ScStwTimer::WILDCARD: + newText = "wildcard"; + break; case ScStwTimer::CANCELLED: newText = "cancelled"; break; case ScStwTimer::INCIDENT: - newText = "Technical incident!"; + newText = "Technical\nincident!"; break; case ScStwTimer::DISABLED: newText = "---"; From fcd12b127ea6c745f06fd5bde73f4581cd350aea Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 16:31:49 +0200 Subject: [PATCH 52/76] finished implementing wildcard and failing state --- ScStwLibraries/headers/scstwrace.h | 14 +++++----- ScStwLibraries/headers/scstwtimer.h | 2 +- ScStwLibraries/sources/scstwrace.cpp | 39 +++++++++++++-------------- ScStwLibraries/sources/scstwtimer.cpp | 11 +++----- 4 files changed, 30 insertions(+), 36 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 48150bf..9b513dc 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -131,17 +131,19 @@ public slots: protected slots: private slots: - void handleTimerStateChange(); - void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); - void handleFalseStart(); - bool playSoundsAndStartTimers(); - ScStwSoundPlayer::PlayResult doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); - void technicalIncident(); + void handleTimerStateChange(ScStwTimer::TimerState newState); /** * \brief Function to declare the winner and looser timers after a timer has been stopped */ void handleTimerStop(); + void handleFalseStart(); + + + void handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled); + bool playSoundsAndStartTimers(); + ScStwSoundPlayer::PlayResult doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); + void technicalIncident(); virtual void refreshCompetitionMode(); diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index f2682c3..5ad69cf 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -348,7 +348,7 @@ signals: /*! * \brief Emitted when the state of the timer changed */ - void stateChanged(); + void stateChanged(TimerState state); /*! * \brief Emitted when the reaction time changed diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 9deaa31..91bed70 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -405,7 +405,15 @@ void ScStwRace::setState(RaceState newState) { } } -void ScStwRace::handleTimerStateChange() { +void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { + if( + newState == ScStwTimer::WON || + newState == ScStwTimer::LOST || + newState == ScStwTimer::WILDCARD || + newState == ScStwTimer::FAILED + ) + return; + qDebug() << "[INFO][MAIN] handling timer state change"; // check if the race is over @@ -438,7 +446,7 @@ void ScStwRace::handleTimerStop() { // iterate through all timers and find the lowest time that was stopped foreach(ScStwTimer * timer, this->timers) { - if(timer->getCurrentTime() > 0 && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0)) { + if(timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0) { // this is the timer with the lowest stopped time lowestStoppedTime = timer->getCurrentTime(); } @@ -446,26 +454,11 @@ void ScStwRace::handleTimerStop() { // append the timer(s) with the lowest stopped time to the winner list foreach(ScStwTimer * timer, this->timers) { - if(timer->getCurrentTime() > 0 - && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0) - && timer->getState() != ScStwTimer::RUNNING - ) { + if(timer->getCurrentTime() <= lowestStoppedTime) // this is the timer with the lowest stopped time - timersWhichHaveWon.append(timer); - } - } - - // update the states of all timers - foreach(ScStwTimer * timer, this->timers) { - if(timer->getState() == ScStwTimer::RUNNING) - continue; - - if(timersWhichHaveWon.contains(timer)) { timer->setResult(ScStwTimer::WON); - } - else { + else timer->setResult(ScStwTimer::LOST); - } } } @@ -476,7 +469,7 @@ void ScStwRace::handleFalseStart() { qDebug() << "[INFO][RACE] Got a FALSE START"; // set lowest to a value that is impossible to reach (start tone is only 3100ms long) - int lowestReactionTime = -4000; + double lowestReactionTime = -4000; // iterate through all timers and find the lowest reactiontime that was stopped foreach(ScStwTimer *timer, this->timers) { @@ -496,15 +489,19 @@ void ScStwRace::handleFalseStart() { // no timer has failed return; + qDebug() << "LOWEST reaction time is: " << lowestReactionTime; + // find out which timer(s) have lost and which get a wildcard foreach(ScStwTimer * timer, this->timers) { + qDebug() << "THIS TIMERS reaction time is: " << lowestReactionTime; if( timer->getState() >= ScStwTimer::FAILING && timer->getState() <= ScStwTimer::FAILED && - timer->getCurrentTime() <= lowestReactionTime + timer->getReactionTime() == lowestReactionTime ) { // this is the timer with the lowest stopped time timer->setResult(ScStwTimer::FAILED); + qDebug() << "FOUND BAD TIMER"; } else { timer->setResult(ScStwTimer::WILDCARD); diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 0a5eff3..644e9b7 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -84,8 +84,8 @@ void ScStwTimer::handleClimberStart(double timeOfStart) { qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; if(this->reactionTime <= 0 && this->reactionTime > -3100){ - this->stop(FailStop); - return; + qDebug() << "[INFO][TIMER] False Start detected: " << "start Time: " << startTime << " reactionTime: " << reactionTime; + this->setState(FAILING); } emit this->reactionTimeChanged(); @@ -134,11 +134,6 @@ bool ScStwTimer::stop(StopReason reason, double timeOfStop) { } break; } - case FailStop: { - qDebug() << "[INFO][TIMER] False Start detected: " << "start Time: " << startTime << " reactionTime: " << reactionTime; - this->setState(FAILED); - break; - } default: { return false; } @@ -209,7 +204,7 @@ void ScStwTimer::setState(TimerState newState){ if(this->state != newState) { this->state = newState; qDebug() << "[INFO][TIMER] timer state changed: " << newState; - emit this->stateChanged(); + emit this->stateChanged(newState); } } From 80aae3b22a0fc15e156feca9cb25e70845c31910 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 17:25:30 +0200 Subject: [PATCH 53/76] fixes issues with delayed triggers. --- ScStwLibraries/headers/scstwtimer.h | 38 ---------------- ScStwLibraries/sources/scstwrace.cpp | 2 + ScStwLibraries/sources/scstwtimer.cpp | 62 +++++++++++++-------------- 3 files changed, 32 insertions(+), 70 deletions(-) diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 5ad69cf..5b52247 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -94,17 +94,6 @@ public: }; Q_ENUM(TimerState); - /*! - * \brief The StopReason enum contains all possible reasons for a stop - */ - enum StopReason { - ManualStop, /*!< Timer was stopped manually */ - CancelStop, /*!< Timer was cancelled */ - FailStop, /*!< A false start occured */ - TopPadStop, /*!< Timer was stopped by a physical trigger (eg. a ScStwExtension) */ - TechnicalIncidentStop /*!< The timer was stopped due to a technical incident */ - }; - /*! * \brief The ReadyStatus enum contains all possible reasons for a timer not to be ready (>0) and the case that it is ready (0) */ @@ -283,33 +272,6 @@ protected slots: */ void handleClimberStart(double timeOfStart); - /*! - * \brief Function to stop the timer at a given point in time (past or future) - * - * To do this, the timer has to be in ScStwTimer::RUNNING state! - * - * \param reason reason for the timer stop - * \param timeOfStop the point in time (msecs since epoch) when the timer is supposted to be stopped - * - * \return false if the timer was not in the required state and therefore not stopped, true otherwise - * - * \see ScStwTimer::StopReason - */ - virtual bool stop(StopReason reason, double timeOfStop); - - /*! - * \brief Function to stop the timer - * - * To do this, the timer has to be in ScStwTimer::RUNNING state! - * - * \param reason reason for the timer stop - * - * \return false if the timer was not in the required state and therefore not stopped, true otherwise - * - * \see ScStwTimer::StopReason - */ - bool stop(StopReason reason); - /*! * \brief Function to change the state of the timer * diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 91bed70..4b3c97c 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -440,6 +440,8 @@ void ScStwRace::handleTimerStop() { if(this->state != RUNNING) return; + qDebug() << "[INFO][RACE] Got a TIMER STOP"; + // find out which timer has won double lowestStoppedTime = -1; QList timersWhichHaveWon; diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 644e9b7..c853ae3 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -83,7 +83,7 @@ void ScStwTimer::handleClimberStart(double timeOfStart) { this->reactionTime = timeOfStart - this->startTime; qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; - if(this->reactionTime <= 0 && this->reactionTime > -3100){ + if(this->reactionTime <= 0 && this->reactionTime){ qDebug() << "[INFO][TIMER] False Start detected: " << "start Time: " << startTime << " reactionTime: " << reactionTime; this->setState(FAILING); } @@ -109,58 +109,56 @@ bool ScStwTimer::stop() { } bool ScStwTimer::stop(double timeOfStop) { - return this->stop(ManualStop, timeOfStop); -} - -bool ScStwTimer::stop(StopReason reason) { - return this->stop(reason, QDateTime::currentMSecsSinceEpoch()); -} - -bool ScStwTimer::stop(StopReason reason, double timeOfStop) { - if(this->state != STARTING && this->state != WILDCARD && this->state != RUNNING && this->state != WAITING){ + if(this->state != RUNNING) return false; - } - switch (reason) { - case ManualStop: { - if(this->state == STARTING){ - this->setState(CANCELLED); - } - else { - this->stopTime = timeOfStop; + this->stopTime = timeOfStop; - // trigger an external state refresh to set the state to either WON or LOST depending on the other timers values (see ScStwRace::refreshTimerStates()) - this->setState(WAITING); - } - break; - } - default: { - return false; - } - } + // trigger an external state refresh to set the state to either WON or LOST depending on the other timers values (see ScStwRace::refreshTimerStates()) + this->setState(WAITING); qDebug() << "[INFO][TIMER] Stopped: " << "start Time: " << startTime << " stopTime: " << stopTime << " stoppedTime: " << this->getCurrentTime() << " reactionTime: " << reactionTime; return true; } bool ScStwTimer::setResult(TimerState result) { - if(this->state != FAILING && this->state != WAITING && this->state != STARTING) + + QList allowedStates = { + STARTING, + RUNNING, + WAITING, + WON, + FAILING, + FAILED + }; + + if(!allowedStates.contains(this->state)) return false; + /* The reasons why it has to accept all these states: + * + * STARTING: To set a timer to WILDCARD when its opponent has done a false start + * RUNNING: To set a timer to WILDCARD when its opponent has done a false start that was received with a delay + * WAITING: To set a timer to either WON or LOST + * WON: To set a timer to LOST when its opponent has won the race but their trigger was delayed + * FAILING: To set a timer to either FAILED or WILDCARD + * FAILED: To set a timer to WILDCARD when its opponent did an earlier false start but their tirgger was delayed + */ + switch (result) { - case WON: case LOST: - if(this->state == WAITING) { + case WON: + if(this->state == WAITING || this->state == WON) { this->setState(result); return true; } break; case WILDCARD: - if(this->state == STARTING) { + case FAILED: + if(this->state == STARTING || this->state == RUNNING || this->state == FAILED) { this->setState(WILDCARD); return true; } - case FAILED: if(this->state == FAILING) { this->setState(result); return true; From df33598049258d84bbe7f394a385d5f704eddab2 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 17:55:39 +0200 Subject: [PATCH 54/76] fixed some stuff with wildcard state and reaction time --- .../de/itsblue/ScStw/Styling/Components/TimerColumn.qml | 2 +- ScStwLibraries/sources/client/scstwremoterace.cpp | 3 ++- ScStwLibraries/sources/client/scstwremotetimer.cpp | 3 ++- ScStwLibraries/sources/scstwtimer.cpp | 9 ++++++--- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/ScStwLibraries/resources/qml/lib/de/itsblue/ScStw/Styling/Components/TimerColumn.qml b/ScStwLibraries/resources/qml/lib/de/itsblue/ScStw/Styling/Components/TimerColumn.qml index 5150516..4e252c7 100644 --- a/ScStwLibraries/resources/qml/lib/de/itsblue/ScStw/Styling/Components/TimerColumn.qml +++ b/ScStwLibraries/resources/qml/lib/de/itsblue/ScStw/Styling/Components/TimerColumn.qml @@ -87,7 +87,7 @@ Column { width: parent.width * 0.8 height: parent.height * 0.8 - color: ([ScStwTimer.WON].indexOf(control.timers[index]["state"]) >= 0 ? control.colors.success : + color: ([ScStwTimer.WON,ScStwTimer.WILDCARD].indexOf(control.timers[index]["state"]) >= 0 ? control.colors.success : [ScStwTimer.FAILED,ScStwTimer.LOST].indexOf(control.timers[index]["state"]) >= 0 ? control.colors.error: control.colors.text) diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 096dd7e..e7ddc8a 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -141,7 +141,6 @@ bool ScStwRemoteRace::local() { * @param data */ void ScStwRemoteRace::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { - //qDebug() << "got signal: " << data; switch (key) { case ScStw::RaceDetailsChanged: { @@ -156,6 +155,8 @@ void ScStwRemoteRace::handleBaseStationSignal(ScStw::SignalKey key, QVariant dat void ScStwRemoteRace::refreshDetails(QVariantMap details) { // the details of the race have changed: + qDebug() << "RACE DETAILS: " << details; + // state this->setState(ScStwRace::RaceState(details["state"].toInt())); diff --git a/ScStwLibraries/sources/client/scstwremotetimer.cpp b/ScStwLibraries/sources/client/scstwremotetimer.cpp index a1c55b2..771d0c6 100644 --- a/ScStwLibraries/sources/client/scstwremotetimer.cpp +++ b/ScStwLibraries/sources/client/scstwremotetimer.cpp @@ -19,6 +19,7 @@ void ScStwRemoteTimer::setStopTime(double stopTime) { void ScStwRemoteTimer::setReactionTime(double reactionTime) { this->reactionTime = reactionTime; + emit this->reactionTimeChanged(); } void ScStwRemoteTimer::setLetter(QString newLetter) { @@ -36,6 +37,6 @@ void ScStwRemoteTimer::setState(TimerState newState){ if(this->state != newState) { this->state = newState; qDebug() << "+ [INFO][REMOTETIMER] timer state changed: " << newState; - emit this->stateChanged(); + emit this->stateChanged(this->state); } } diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index f2beada..718d186 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -241,18 +241,21 @@ QString ScStwTimer::getText() { case ScStwTimer::STARTING: newTime = 0; break; - case ScStwTimer::WAITING: - newText = "please wait..."; - break; case ScStwTimer::RUNNING: newTime = this->getCurrentTime(); break; + case ScStwTimer::WAITING: + newText = "please wait..."; + break; case ScStwTimer::WON: newTime = this->getCurrentTime(); break; case ScStwTimer::LOST: newTime = this->getCurrentTime(); break; + case ScStwTimer::FAILING: + newText = "please wait..."; + break; case ScStwTimer::FAILED: newText = "false start"; break; From 94e5bc8e6fed0af4d380953a1516bbab41b40285 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 4 Oct 2020 18:11:44 +0200 Subject: [PATCH 55/76] fixed technical incident not working in some cases --- ScStwLibraries/sources/scstwrace.cpp | 78 +++++++++++++++------------ ScStwLibraries/sources/scstwtimer.cpp | 6 +-- 2 files changed, 44 insertions(+), 40 deletions(-) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 4b3c97c..6f7b30f 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -153,33 +153,6 @@ ScStw::StatusCode ScStwRace::cancel() { return returnCode; } -void ScStwRace::technicalIncident() { - - bool raceIsRunning = this->state == RUNNING; - - qDebug() << "[ERROR][RACE] Got a technical incident, state is: " << this->state; - - foreach(ScStwTimer *timer, this->timers){ - if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) - continue; - else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) - timer->technicalIncident(); - else if(!raceIsRunning) - timer->setState(ScStwTimer::CANCELLED); - } - - if(!raceIsRunning) { - this->startWaitLoop->exit(LoopCancelExit); - - if(this->state == STARTING) { - this->soundPlayer->cancel(); - this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); - } - - this->setState(INCIDENT); - } -} - void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { if(!this->competitionMode || this->state == IDLE || this->state == STOPPED || this->state == INCIDENT ) @@ -410,7 +383,8 @@ void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { newState == ScStwTimer::WON || newState == ScStwTimer::LOST || newState == ScStwTimer::WILDCARD || - newState == ScStwTimer::FAILED + newState == ScStwTimer::FAILED || + this->state == INCIDENT ) return; @@ -418,6 +392,7 @@ void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { // check if the race is over bool raceIsOver = true; + int incidentCount = 0; foreach(ScStwTimer * timer, this->timers){ if(timer->getState() < ScStwTimer::WAITING){ @@ -429,10 +404,14 @@ void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { else if (timer->getState() == ScStwTimer::FAILING) this->handleFalseStart(); else if (timer->getState() == ScStwTimer::INCIDENT) - return; + incidentCount ++; } - if(raceIsOver) + if(incidentCount == this->timers.length()) { + this->setState(INCIDENT); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); + } + else if(raceIsOver) this->setState(STOPPED); } @@ -495,11 +474,11 @@ void ScStwRace::handleFalseStart() { // find out which timer(s) have lost and which get a wildcard foreach(ScStwTimer * timer, this->timers) { - qDebug() << "THIS TIMERS reaction time is: " << lowestReactionTime; + qDebug() << "THIS TIMERS reaction time is: " << timer->getReactionTime(); if( timer->getState() >= ScStwTimer::FAILING && timer->getState() <= ScStwTimer::FAILED && - timer->getReactionTime() == lowestReactionTime + timer->getReactionTime() <= lowestReactionTime ) { // this is the timer with the lowest stopped time timer->setResult(ScStwTimer::FAILED); @@ -510,9 +489,38 @@ void ScStwRace::handleFalseStart() { } } - this->setState(STOPPED); - this->soundPlayer->cancel(); - this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); + if(this->state != STOPPED) { + this->setState(STOPPED); + this->soundPlayer->cancel(); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); + } +} + +void ScStwRace::technicalIncident() { + + bool raceIsRunning = this->state == RUNNING; + + qDebug() << "[ERROR][RACE] Got a technical incident, state is: " << this->state; + + if(!raceIsRunning) { + this->startWaitLoop->exit(LoopCancelExit); + + if(this->state == STARTING) { + this->soundPlayer->cancel(); + this->soundPlayer->play(ScStwSoundPlayer::FalseStart, this->getSoundVolume()); + } + + this->setState(INCIDENT); + } + + foreach(ScStwTimer *timer, this->timers){ + if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + continue; + else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + timer->technicalIncident(); + else if(!raceIsRunning) + timer->setState(ScStwTimer::CANCELLED); + } } // ------------------------ diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index c853ae3..4afbada 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -155,11 +155,7 @@ bool ScStwTimer::setResult(TimerState result) { break; case WILDCARD: case FAILED: - if(this->state == STARTING || this->state == RUNNING || this->state == FAILED) { - this->setState(WILDCARD); - return true; - } - if(this->state == FAILING) { + if(this->state == STARTING || this->state == RUNNING || this->state == FAILED || this->state == FAILING) { this->setState(result); return true; } From 620e943bd2581062aea327a1610ad0a99bd9c07f Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 5 Oct 2020 20:41:43 +0200 Subject: [PATCH 56/76] added a very fancy indicator for timer rady state during waiting state of race --- ScStwLibraries/headers/scstwrace.h | 2 +- ScStwLibraries/headers/scstwtimer.h | 1 + ScStwLibraries/sources/client/scstwremoterace.cpp | 10 +++++++--- ScStwLibraries/sources/scstwtimer.cpp | 2 +- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 9b513dc..ec6ab52 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -53,7 +53,7 @@ class ScStwRace : public QObject { Q_OBJECT Q_PROPERTY(RaceState state READ getState NOTIFY stateChanged) - Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) + Q_PROPERTY(QVariantList timers READ getTimerDetailList NOTIFY timersChanged) Q_PROPERTY(QVariantMap currentStartDelay READ getCurrentStartDelay NOTIFY currentStartDelayChanged) Q_PROPERTY(bool isReadyForNextState READ getIsReadyForNextState NOTIFY isReadyForNextStateChanged) Q_PROPERTY(bool competitionMode READ getCompetitionMode NOTIFY competitionModeChanged) diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 5b52247..bdbe780 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -105,6 +105,7 @@ public: ExtensionBatteryNotFine, /*!< The battery level of one or more extension is critical or unknown */ ClimberIsNotReady /*!< The startpad of the timer is not triggered */ }; + Q_ENUM(ReadyState) protected: /*! diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index e7ddc8a..272fa5e 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -157,9 +157,6 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { qDebug() << "RACE DETAILS: " << details; - // state - this->setState(ScStwRace::RaceState(details["state"].toInt())); - // competition mode if(this->competitionMode != details["competitionMode"].toBool()) { this->competitionMode = details["competitionMode"].toBool(); @@ -182,6 +179,9 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { // timers this->refreshRemoteTimers(details["timers"].toList()); + // state + this->setState(ScStwRace::RaceState(details["state"].toInt())); + // isReady if(this->state == WAITING) { this->isReadyForNextState = details["isReadyForNextState"].toBool(); @@ -212,6 +212,8 @@ void ScStwRemoteRace::rebuildRemoteTimers(QVariantList remoteTimers) { bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { + qDebug() << "REFRESHING TIMERS"; + if(remoteTimers.length() != this->remoteTimers.length()){ // local timers are out of sync this->rebuildRemoteTimers(remoteTimers); @@ -242,6 +244,8 @@ bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { this->remoteTimers[currId]->setState(newState); } + emit this->timersChanged(); + return true; } diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 718d186..8ffb30f 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -266,7 +266,7 @@ QString ScStwTimer::getText() { newText = "cancelled"; break; case ScStwTimer::INCIDENT: - newText = "Technical\nincident!"; + newText = "Technical incident!"; break; case ScStwTimer::DISABLED: newText = "---"; From 9bd3e53faec31885437507bd3fe76cf563f14784 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 5 Oct 2020 22:21:33 +0200 Subject: [PATCH 57/76] added command to disable and enable a timer --- ScStwLibraries/headers/ScStw.hpp | 2 ++ ScStwLibraries/headers/scstwrace.h | 2 ++ ScStwLibraries/sources/scstwrace.cpp | 12 ++++++++++++ 3 files changed, 16 insertions(+) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index a05be82..46aba53 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -81,6 +81,7 @@ public: StopRaceCommand = 1001, ResetRaceCommand = 1002, CancelRaceCommand = 1003, + SetTimerDisabled = 1004, GetRaceStateCommand = 2000, GetRaceDetailsCommand = 2001, @@ -120,6 +121,7 @@ public: CurrentStateNotVaildForOperationError = 403, AccessDeniedError = 401, NoSessionActiveError = 408, + ItemNotFoundError = 409, UpdateFailedError = 500, diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 9b513dc..97cb53b 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -117,6 +117,8 @@ public slots: virtual ScStw::StatusCode reset(); virtual ScStw::StatusCode cancel(); + virtual ScStw::StatusCode setTimerDisabled(int id, bool disabled); + virtual bool addTimer(ScStwTimer *timer); // getters diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 6f7b30f..954c0f0 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -153,6 +153,18 @@ ScStw::StatusCode ScStwRace::cancel() { return returnCode; } +ScStw::StatusCode ScStwRace::setTimerDisabled(int timerId, bool disabled) { + if(this->state != IDLE && this->state != WAITING) + return ScStw::CurrentStateNotVaildForOperationError; + + if(timerId < 0 || timerId - 1 > this->timers.length()) + return ScStw::ItemNotFoundError; + + this->timers[timerId]->setDisabled(disabled); + + return ScStw::Success; +} + void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { if(!this->competitionMode || this->state == IDLE || this->state == STOPPED || this->state == INCIDENT ) From be6aebd4588c67b19ec83c926a7a1c9a42ca4164 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 6 Oct 2020 13:58:42 +0200 Subject: [PATCH 58/76] many many fixes --- ScStwLibraries/headers/ScStw.hpp | 14 +++--- ScStwLibraries/headers/scstwrace.h | 1 + ScStwLibraries/headers/scstwtimer.h | 4 ++ ScStwLibraries/sources/scstwrace.cpp | 72 ++++++++++++++++++++------- ScStwLibraries/sources/scstwtimer.cpp | 13 ++++- 5 files changed, 77 insertions(+), 27 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 46aba53..13ba196 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -112,16 +112,16 @@ public: FirmwareAlreadyUpToDateInfo = 304, - - CommandNotFoundError = 404, - ClientSessionAlreadyActiveError = 407, - UpdateSignatureInvalidError = 402, - TimestampTooSmallError = 406, - RequiredParameterNotGivenError = 405, - CurrentStateNotVaildForOperationError = 403, AccessDeniedError = 401, + UpdateSignatureInvalidError = 402, + CurrentStateNotVaildForOperationError = 403, + CommandNotFoundError = 404, + RequiredParameterNotGivenError = 405, + TimestampTooSmallError = 406, + ClientSessionAlreadyActiveError = 407, NoSessionActiveError = 408, ItemNotFoundError = 409, + LastTimerCannotBeDisabledError = 410, UpdateFailedError = 500, diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index d00a978..7fc59c9 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -146,6 +146,7 @@ private slots: bool playSoundsAndStartTimers(); ScStwSoundPlayer::PlayResult doDelayAndSoundOfCurrentStartState(double *timeOfSoundPlaybackStart = nullptr); void technicalIncident(); + ScStw::StatusCode setTimerDisabled(ScStwTimer* timer, bool disabled); virtual void refreshCompetitionMode(); diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index bdbe780..abfa291 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -265,6 +265,10 @@ public slots: */ virtual ScStwTimer::ReadyState getReadyState(); + bool isRunning(); + + bool isDisabled(); + protected slots: /*! diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 954c0f0..f5d251a 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -112,8 +112,8 @@ ScStw::StatusCode ScStwRace::reset() { ScStw::StatusCode returnCode = ScStw::Success; - foreach(ScStwTimer *speedTimer, this->timers){ - if(!speedTimer->reset() && speedTimer->getState() != ScStwTimer::DISABLED && speedTimer->getState() != ScStwTimer::IDLE) { + foreach(ScStwTimer *timer, this->timers){ + if(!timer->reset() && timer->getState() != ScStwTimer::DISABLED && timer->getState() != ScStwTimer::IDLE) { returnCode = ScStw::InternalErrorTimerOperationFailed; } } @@ -154,15 +154,36 @@ ScStw::StatusCode ScStwRace::cancel() { } ScStw::StatusCode ScStwRace::setTimerDisabled(int timerId, bool disabled) { - if(this->state != IDLE && this->state != WAITING) - return ScStw::CurrentStateNotVaildForOperationError; - if(timerId < 0 || timerId - 1 > this->timers.length()) return ScStw::ItemNotFoundError; - this->timers[timerId]->setDisabled(disabled); + return this->setTimerDisabled(this->timers[timerId], disabled); +} + +ScStw::StatusCode ScStwRace::setTimerDisabled(ScStwTimer* timer, bool disabled) { + qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled << " this state: " << this->state; + if(this->state != IDLE && this->state != WAITING) + return ScStw::CurrentStateNotVaildForOperationError; + + if(!this->timers.contains(timer)) + return ScStw::ItemNotFoundError; + + int enabledTimerCount = 0; + + foreach(ScStwTimer *timer, this->timers) { + if(timer->getState() != ScStwTimer::DISABLED) + enabledTimerCount ++; + } + + if(disabled && enabledTimerCount <= 1) + return ScStw::LastTimerCannotBeDisabledError; + + qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled; + + timer->setDisabled(disabled); return ScStw::Success; + } void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { @@ -435,16 +456,18 @@ void ScStwRace::handleTimerStop() { // find out which timer has won double lowestStoppedTime = -1; - QList timersWhichHaveWon; // iterate through all timers and find the lowest time that was stopped foreach(ScStwTimer * timer, this->timers) { - if(timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0) { + qDebug() << "Current stopped time is: " << timer->getCurrentTime(); + if(!timer->isRunning() && !timer->isDisabled() && (timer->getCurrentTime() <= lowestStoppedTime || lowestStoppedTime < 0)) { // this is the timer with the lowest stopped time lowestStoppedTime = timer->getCurrentTime(); } } + qDebug() << "LOWEST Stop time is: " << lowestStoppedTime; + // append the timer(s) with the lowest stopped time to the winner list foreach(ScStwTimer * timer, this->timers) { if(timer->getCurrentTime() <= lowestStoppedTime) @@ -469,6 +492,7 @@ void ScStwRace::handleFalseStart() { if( timer->getState() >= ScStwTimer::FAILING && timer->getState() <= ScStwTimer::FAILED && + !timer->isDisabled() && ( timer->getReactionTime() < lowestReactionTime || lowestReactionTime == -4000 @@ -490,6 +514,7 @@ void ScStwRace::handleFalseStart() { if( timer->getState() >= ScStwTimer::FAILING && timer->getState() <= ScStwTimer::FAILED && + !timer->isDisabled() && timer->getReactionTime() <= lowestReactionTime ) { // this is the timer with the lowest stopped time @@ -563,7 +588,7 @@ bool ScStwRace::getIsReadyForNextState() { break; case WAITING: { foreach (ScStwTimer *timer, this->timers) { - if(timer->getReadyState() != ScStwTimer::IsReady) + if(timer->getReadyState() != ScStwTimer::IsReady && timer->getReadyState() != ScStwTimer::IsDisabled) return false; } break; @@ -584,11 +609,14 @@ bool ScStwRace::getIsReadyForNextState() { * @param {ScStwExtensionControlledTimer*} timer timer to be enabled */ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled) { + qDebug() << "Handling timer wants to be disabled"; if(this->competitionMode) return; if(this->state == IDLE) { - timer->setDisabled(wantsToBeDisabled); + + qDebug() << "Handling timer wants to be disabled: " << wantsToBeDisabled; + this->setTimerDisabled(timer, wantsToBeDisabled); } } @@ -603,17 +631,20 @@ void ScStwRace::refreshCompetitionMode() { qDebug() << "[INFO][RACE] Setting competition mode to " << currentCompetitionMode; this->competitionMode = currentCompetitionMode; + } - if(this->competitionMode) { - foreach (ScStwTimer *timer, this->timers) { - timer->setDisabled(false); - } + if(this->competitionMode) { + foreach (ScStwTimer *timer, this->timers) { + timer->setDisabled(false); } - else { - foreach(ScStwTimer* timer, this->timers) { - if(timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) - this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); - } + } + else { + foreach(ScStwTimer* timer, this->timers) { + if( + (timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) || + (!timer->getWantsToBeDisabled() && timer->getState() == ScStwTimer::DISABLED) + ) + this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); } } } @@ -686,6 +717,9 @@ bool ScStwRace::addTimer(ScStwTimer *timer) { if(this->competitionMode && timer->getState() == ScStwTimer::DISABLED) timer->setDisabled(false); + else if(!this->competitionMode) + this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); + return true; diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 49ed38e..01c0b02 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -278,14 +278,17 @@ QString ScStwTimer::getText() { void ScStwTimer::setDisabled(bool disabled) { if(disabled) this->setState(DISABLED); - else + else { this->setState(IDLE); + } } void ScStwTimer::setWantsToBeDisabled(bool wantsToBeDisabled) { if(this->wantsToBeDisabled == wantsToBeDisabled) return; + qDebug() << "Wants to be disabled changed: " << wantsToBeDisabled; + this->wantsToBeDisabled = wantsToBeDisabled; emit this->wantsToBeDisabledChanged(this, wantsToBeDisabled); @@ -294,3 +297,11 @@ void ScStwTimer::setWantsToBeDisabled(bool wantsToBeDisabled) { bool ScStwTimer::getWantsToBeDisabled() { return this->wantsToBeDisabled; } + +bool ScStwTimer::isRunning() { + return this->state == RUNNING; +} + +bool ScStwTimer::isDisabled() { + return this->state == DISABLED; +} From 886abb2a02f54029fe0ae8f0d34083e679b9fd3d Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 6 Oct 2020 14:00:22 +0200 Subject: [PATCH 59/76] some fixes, added timer disable function --- ScStwLibraries/headers/ScStw.hpp | 2 +- .../headers/client/scstwremoterace.h | 1 + .../sources/client/scstwremoterace.cpp | 21 +++++++++++++++++++ .../sources/styling/scstwappthememanager.cpp | 2 +- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 46aba53..c38f72f 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -81,7 +81,7 @@ public: StopRaceCommand = 1001, ResetRaceCommand = 1002, CancelRaceCommand = 1003, - SetTimerDisabled = 1004, + SetTimerDisabledCommand = 1004, GetRaceStateCommand = 2000, GetRaceDetailsCommand = 2001, diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index ccf780f..75488c7 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -53,6 +53,7 @@ public slots: ScStw::StatusCode cancel(); ScStw::StatusCode stop(); ScStw::StatusCode reset(); + ScStw::StatusCode setTimerDisabled(int id, bool disabled); bool addTimer(ScStwTimer *timer); QVariantMap getCurrentStartDelay(); bool getIsReadyForNextState(); diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 272fa5e..6d26201 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -90,6 +90,27 @@ ScStw::StatusCode ScStwRemoteRace::reset() { return ScStw::StatusCode(reply["status"].toInt()); } +ScStw::StatusCode ScStwRemoteRace::setTimerDisabled(int timerId, bool disabled) { + if(this->state != IDLE && this->state != WAITING) + return ScStw::CurrentStateNotVaildForOperationError; + + if(timerId < 0 || timerId - 1 > this->timers.length()) + return ScStw::ItemNotFoundError; + + qDebug() << "+ --- setting timer " << timerId << " to disabled: " << disabled; + + QVariantMap requestData = { + {"timerId", timerId}, + {"disabled", disabled} + }; + + QVariantMap reply = this->scStwClient->sendCommand(ScStw::SetTimerDisabledCommand, QJsonValue::fromVariant(requestData)); + + qDebug() << "+ --- timer disabled command returned: " << reply; + + return ScStw::StatusCode(reply["status"].toInt()); +} + // ------------------------- // --- Base Station sync --- // ------------------------- diff --git a/ScStwLibraries/sources/styling/scstwappthememanager.cpp b/ScStwLibraries/sources/styling/scstwappthememanager.cpp index afa31c2..e2eca13 100644 --- a/ScStwLibraries/sources/styling/scstwappthememanager.cpp +++ b/ScStwLibraries/sources/styling/scstwappthememanager.cpp @@ -116,7 +116,7 @@ ScStwAppThemeManager::ScStwAppThemeManager(QObject *parent) : QObject(parent) {"success", "#6bd43b"}, {"error", "#e03b2f"}, - {"warning", "#e0b928"}, + {"warning", "#d6ae1e"}, {"line", "grey"}, From 7d1c0b81115caf671ccd7d4913fc9451ed9133fb Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 6 Oct 2020 14:09:23 +0200 Subject: [PATCH 60/76] - added some more battery states - renamed ready state --- ScStwLibraries/headers/ScStw.hpp | 4 +++- ScStwLibraries/headers/scstwtimer.h | 2 +- ScStwLibraries/sources/scstwrace.cpp | 8 ++++---- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 13ba196..1c8fdcf 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -165,7 +165,9 @@ public: enum ExtensionBatteryState { BatteryUnknown = -1, BatteryCritical = 0, - BatteryFine = 1 + BatteryWarning = 1, + BatteryFine = 2, + BatteryCharging = 3 }; Q_ENUM(ExtensionBatteryState); diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index abfa291..9ded219 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -102,7 +102,7 @@ public: NotInIdleState, /*!< Timer is not in IDLE state */ IsDisabled, /*!< Timer is disabled */ ExtensionIsNotConnected, /*!< Not all extension of the timer are conneted */ - ExtensionBatteryNotFine, /*!< The battery level of one or more extension is critical or unknown */ + ExtensionBatteryIsCritical, /*!< The battery level of one or more extension is critical or unknown */ ClimberIsNotReady /*!< The startpad of the timer is not triggered */ }; Q_ENUM(ReadyState) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index f5d251a..0880a2c 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -194,7 +194,7 @@ void ScStwRace::handleTimerReadyStateChange(ScStwTimer::ReadyState readyState) { qDebug() << "Some ready state changed: " << readyState; // cancel as a technical incident if extensions are disconnected or run low on battery - if(readyState == ScStwTimer::ExtensionIsNotConnected || readyState == ScStwTimer::ExtensionBatteryNotFine) { + if(readyState == ScStwTimer::ExtensionIsNotConnected || readyState == ScStwTimer::ExtensionBatteryIsCritical) { this->technicalIncident(); return; } @@ -551,9 +551,9 @@ void ScStwRace::technicalIncident() { } foreach(ScStwTimer *timer, this->timers){ - if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryIsCritical) continue; - else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) + else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryIsCritical) timer->technicalIncident(); else if(!raceIsRunning) timer->setState(ScStwTimer::CANCELLED); @@ -575,7 +575,7 @@ bool ScStwRace::getIsReadyForNextState() { if(timer->getState() == ScStwTimer::DISABLED) continue; - if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryNotFine) { + if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryIsCritical) { this->technicalIncident(); From a20e7e2fc96a5352504ab49ab5fcc896b81b3e14 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Wed, 7 Oct 2020 09:48:15 +0200 Subject: [PATCH 61/76] - fix in setting - change to volume approach on raspi in sound player --- ScStwLibraries/headers/scstwsoundplayer.h | 4 ++++ ScStwLibraries/sources/client/scstwremoterace.cpp | 10 +++++++++- ScStwLibraries/sources/scstwsettings.cpp | 6 ++++-- ScStwLibraries/sources/scstwsoundplayer.cpp | 6 ++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index 28d9bdc..e89915e 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -28,6 +28,10 @@ #include #include +#ifdef RASPI +#include +#endif + /*! * \brief The ScStwSoundPlayer class is used for ultra low latency sound playback of the speed clibing start tones and commands */ diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 6d26201..2f9a756 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -22,6 +22,9 @@ ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settin { this->isReadyForNextState = true; + this->remoteTimers = {}; + this->localTimers = {};********* + this->scStwClient = scStwClient; this->scStwClient->addSignalSubscription(ScStw::RaceDetailsChanged); @@ -213,6 +216,9 @@ void ScStwRemoteRace::refreshDetails(QVariantMap details) { } void ScStwRemoteRace::rebuildRemoteTimers(QVariantList remoteTimers) { + + qDebug() << "REBUILDING TIMERS"; + // delete all current timers foreach(ScStwTimer * oldTimer, this->timers){ oldTimer->deleteLater(); @@ -271,8 +277,10 @@ bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { } bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { - if(this->local()) + if(this->local()) { + this->localTimers.append(timer); return ScStwRace::addTimer(timer); + } return false; } diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 7a10865..6f39147 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -30,8 +30,10 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) if(!this->settingsFile->open(QFile::ReadWrite)) qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path + "/settings.json")); - if(!this->loadSettingsFromFile() && this->settingsFile->size() != 0) - qFatal("[FATAL] Settings file (%s) is of invalid format!", qPrintable(path + "/settings.json")); + if(!this->loadSettingsFromFile() && this->settingsFile->size() != 0) { + this->writeSettingsToFile(); + qWarning("[WARNING] Settings file (%s) was of invalid format and therefore overwritten!", qPrintable(path + "/settings.json")); + } connect(this, &ScStwSettings::settingChanged, this, &ScStwSettings::writeSettingsToFile); diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 180bc53..1dc116a 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -49,7 +49,13 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound this->currentlyPlayingSound = sound; // update volume + +#ifdef RASPI + // set volume on raspi using alsamixer + QProcess::execute("amixer -q -M sset PCM " + QString::number(volume * 100, 'f', 0) + "%"); +#else this->soundEffect->setVolume(volume); +#endif // load this->soundEffect->setSource(this->soundFiles[sound]["path"].toString()); From f8cc23646cd77c85b4d86b145e4da3779a4766aa Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Wed, 7 Oct 2020 11:57:50 +0200 Subject: [PATCH 62/76] remove typo --- ScStwLibraries/sources/client/scstwremoterace.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 2f9a756..6b9140f 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -23,7 +23,7 @@ ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settin this->isReadyForNextState = true; this->remoteTimers = {}; - this->localTimers = {};********* + this->localTimers = {}; this->scStwClient = scStwClient; From d89ad38175a47a1e553151b7385a4f956eca0860 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Wed, 7 Oct 2020 13:02:03 +0200 Subject: [PATCH 63/76] reset timer disabled state on race reset --- ScStwLibraries/sources/scstwrace.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 0880a2c..4eff972 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -110,6 +110,11 @@ ScStw::StatusCode ScStwRace::reset() { qDebug() << "[INFO][RACE] resetting race"; + if(this->competitionMode) { + for(int i = 0; i < this->timers.length(); i++) + this->setTimerDisabled(i, false); + } + ScStw::StatusCode returnCode = ScStw::Success; foreach(ScStwTimer *timer, this->timers){ @@ -182,6 +187,8 @@ ScStw::StatusCode ScStwRace::setTimerDisabled(ScStwTimer* timer, bool disabled) timer->setDisabled(disabled); + emit this->timersChanged(); + return ScStw::Success; } From ca040a191cf9575e0b6095547522a6d1b09cecca Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 9 Oct 2020 15:18:56 +0200 Subject: [PATCH 64/76] Made all Classes usable in pure QML --- .../headers/client/scstwremoterace.h | 9 +++ .../headers/client/scstwremotesettings.h | 10 +++ .../headers/client/scstwremotetimer.h | 1 - ScStwLibraries/headers/scstwlibraries.h | 1 + ScStwLibraries/headers/scstwrace.h | 15 +++- ScStwLibraries/headers/scstwtimer.h | 5 +- .../sources/client/scstwremoterace.cpp | 36 +++++++--- .../sources/client/scstwremotesettings.cpp | 33 +++++++-- ScStwLibraries/sources/scstwlibraries.cpp | 4 +- ScStwLibraries/sources/scstwrace.cpp | 72 ++++++++++++++++++- ScStwLibraries/sources/scstwtimer.cpp | 6 +- 11 files changed, 168 insertions(+), 24 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 75488c7..7a3ba79 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -28,7 +28,10 @@ class ScStwRemoteRace : public ScStwRace { Q_OBJECT + Q_PROPERTY(ScStwClient* scStwClient READ getScStwClient WRITE setScStwClient NOTIFY scStwClientChanged) + public: + ScStwRemoteRace(QObject *parent = nullptr); ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settings = nullptr, QObject *parent = nullptr); enum RaceMode { @@ -59,6 +62,9 @@ public slots: bool getIsReadyForNextState(); bool getReadySoundEnabled(); + ScStwClient *getScStwClient(); + void setScStwClient(ScStwClient *client); + private slots: void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); @@ -70,6 +76,9 @@ private slots: void refreshCompetitionMode(); RaceMode getMode(); bool local(); + +signals: + void scStwClientChanged(); }; #endif // SCSTWREMOTEMONITORRACE_H diff --git a/ScStwLibraries/headers/client/scstwremotesettings.h b/ScStwLibraries/headers/client/scstwremotesettings.h index 2b6a9f3..e1515b5 100644 --- a/ScStwLibraries/headers/client/scstwremotesettings.h +++ b/ScStwLibraries/headers/client/scstwremotesettings.h @@ -27,7 +27,10 @@ class ScStwRemoteSettings : public ScStwSettings { Q_OBJECT + Q_PROPERTY(ScStwClient* scStwClient READ getScStwClient WRITE setScStwClient NOTIFY scStwClientChanged) + public: + ScStwRemoteSettings(QObject * parent = nullptr); ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent = nullptr); enum SettingsMode { @@ -43,10 +46,17 @@ protected: private: ScStwClient * scStwClient; +public slots: + ScStwClient *getScStwClient(); + void setScStwClient(ScStwClient *client); + private slots: void handleClientStateChange(); void handleBaseStationSignal(ScStw::SignalKey key, QVariant data); SettingsMode getMode(); + +signals: + void scStwClientChanged(); }; #endif // SCSTWREMOTESETTINGS_H diff --git a/ScStwLibraries/headers/client/scstwremotetimer.h b/ScStwLibraries/headers/client/scstwremotetimer.h index 71d5992..518140b 100644 --- a/ScStwLibraries/headers/client/scstwremotetimer.h +++ b/ScStwLibraries/headers/client/scstwremotetimer.h @@ -74,7 +74,6 @@ protected slots: */ void setState(TimerState newState); - }; #endif // SCSTWREMOTETIMER_H diff --git a/ScStwLibraries/headers/scstwlibraries.h b/ScStwLibraries/headers/scstwlibraries.h index 1965a70..5435edf 100644 --- a/ScStwLibraries/headers/scstwlibraries.h +++ b/ScStwLibraries/headers/scstwlibraries.h @@ -36,6 +36,7 @@ #include "scstwsetting.h" #include "scstwremoterace.h" #include "scstwclient.h" +#include "scstwremotesettings.h" #endif class ScStwLibraries : public QObject diff --git a/ScStwLibraries/headers/scstwrace.h b/ScStwLibraries/headers/scstwrace.h index 7fc59c9..70cc2b6 100644 --- a/ScStwLibraries/headers/scstwrace.h +++ b/ScStwLibraries/headers/scstwrace.h @@ -59,8 +59,11 @@ class ScStwRace : public QObject Q_PROPERTY(bool competitionMode READ getCompetitionMode NOTIFY competitionModeChanged) Q_PROPERTY(bool readySoundEnabled READ getReadySoundEnabled NOTIFY readySoundEnabledChanged) Q_PROPERTY(QVariantMap details READ getDetails NOTIFY detailsChanged) + Q_PROPERTY(ScStwSettings* settings READ getSettings WRITE setSettings NOTIFY settingsChanged) + Q_PROPERTY(bool autoRefreshTimerText READ getAutoRefreshTimerText WRITE setAutoRefreshTimerText NOTIFY autoRefreshTimerTextChanged) public: + explicit ScStwRace(QObject *parent = nullptr); explicit ScStwRace(ScStwSettings *settings, QObject *parent = nullptr); friend class ScStwRemoteRace; @@ -76,6 +79,7 @@ private: RaceState state; QTimer *startDelayTimer; + QTimer *timerTextRefreshTimer; QEventLoop *startWaitLoop; // sounds @@ -84,6 +88,7 @@ private: // settings ScStwSettings *settings; bool competitionMode; + bool autoRefreshTimerText; enum LoopExitTypes { LoopAutomaticExit = 0, @@ -119,7 +124,7 @@ public slots: virtual ScStw::StatusCode setTimerDisabled(int id, bool disabled); - virtual bool addTimer(ScStwTimer *timer); + Q_INVOKABLE virtual bool addTimer(ScStwTimer *timer); // getters RaceState getState(); @@ -130,6 +135,12 @@ public slots: bool getCompetitionMode(); virtual bool getReadySoundEnabled(); + ScStwSettings* getSettings(); + void setSettings(ScStwSettings* settings); + + bool getAutoRefreshTimerText(); + void setAutoRefreshTimerText(bool autoRefresh); + protected slots: private slots: @@ -171,6 +182,8 @@ signals: void detailsChanged(); void competitionModeChanged(); void readySoundEnabledChanged(); + void settingsChanged(); + void autoRefreshTimerTextChanged(); }; diff --git a/ScStwLibraries/headers/scstwtimer.h b/ScStwLibraries/headers/scstwtimer.h index 9ded219..ccd67b4 100644 --- a/ScStwLibraries/headers/scstwtimer.h +++ b/ScStwLibraries/headers/scstwtimer.h @@ -65,13 +65,16 @@ class ScStwTimer : public QObject { Q_OBJECT public: + + explicit ScStwTimer(QObject *parent = nullptr); + /*! * \brief ScStwTimer constructor * \param parent the parent object * \param directControlEnabled Defines if protected properties (startTimer, stopTime, reactionTime and state) can be directly set from outside. * \param letter the letter of the timer (only first char will be used!) */ - explicit ScStwTimer(QObject *parent = nullptr, QString letter = "" ); + explicit ScStwTimer(QString letter, QObject *parent = nullptr); friend class ScStwRace; diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 6b9140f..9d3912c 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -18,6 +18,10 @@ #include "scstwremoterace.h" +ScStwRemoteRace::ScStwRemoteRace(QObject* parent) : ScStwRemoteRace(nullptr, nullptr, parent) +{ +} + ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settings, QObject *parent) : ScStwRace(settings, parent) { this->isReadyForNextState = true; @@ -25,12 +29,7 @@ ScStwRemoteRace::ScStwRemoteRace(ScStwClient *scStwClient, ScStwSettings *settin this->remoteTimers = {}; this->localTimers = {}; - this->scStwClient = scStwClient; - - this->scStwClient->addSignalSubscription(ScStw::RaceDetailsChanged); - - connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChange); - connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteRace::handleBaseStationSignal); + this->setScStwClient(scStwClient); } // -------------------------- @@ -146,10 +145,10 @@ void ScStwRemoteRace::handleClientStateChange() { } ScStwRemoteRace::RaceMode ScStwRemoteRace::getMode() { - if(this->scStwClient->getState() == ScStwClient::CONNECTED) - return ScStwRemoteRace::REMOTE; + if(this->scStwClient == nullptr || this->scStwClient->getState() != ScStwClient::CONNECTED) + return LOCAL; else - return ScStwRemoteRace::LOCAL; + return REMOTE; } bool ScStwRemoteRace::local() { @@ -328,3 +327,22 @@ void ScStwRemoteRace::refreshCompetitionMode() { if(this->local()) return ScStwRace::refreshCompetitionMode(); } + +ScStwClient* ScStwRemoteRace::getScStwClient() { + return this->scStwClient; +} + +void ScStwRemoteRace::setScStwClient(ScStwClient* client) { + if(client == this->scStwClient) + return; + + this->scStwClient = client; + + if(this->scStwClient != nullptr) { + this->scStwClient->addSignalSubscription(ScStw::RaceDetailsChanged); + + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteRace::handleClientStateChange); + connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteRace::handleBaseStationSignal); + + } +} diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index aaecf45..4a63c5d 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -18,19 +18,21 @@ #include "../../headers/client/scstwremotesettings.h" +ScStwRemoteSettings::ScStwRemoteSettings(QObject* parent) : ScStwSettings(parent) +{ + this->scStwClient = nullptr; +} + ScStwRemoteSettings::ScStwRemoteSettings(ScStwClient * scStwClient, QObject * parent) : ScStwSettings(parent) { - this->scStwClient = scStwClient; - this->scStwClient->addSignalSubscription(ScStw::SettingChanged); - - connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteSettings::handleBaseStationSignal); + this->setScStwClient(scStwClient); } ScStwRemoteSettings::SettingsMode ScStwRemoteSettings::getMode() { - if(this->scStwClient->getState() == ScStwClient::CONNECTED) - return ScStwRemoteSettings::REMOTE; + if(this->scStwClient == nullptr || this->scStwClient->getState() != ScStwClient::CONNECTED) + return LOCAL; else - return ScStwRemoteSettings::LOCAL; + return REMOTE; } QVariant ScStwRemoteSettings::readSetting(QString key, int keyInt, int keyLevel) { @@ -76,3 +78,20 @@ void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant break; } } + +ScStwClient* ScStwRemoteSettings::getScStwClient() { + return this->scStwClient; +} + +void ScStwRemoteSettings::setScStwClient(ScStwClient* client) { + if(client == this->scStwClient) + return; + + this->scStwClient = client; + + if(this->scStwClient != nullptr) { + this->scStwClient->addSignalSubscription(ScStw::SettingChanged); + + connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteSettings::handleBaseStationSignal); + } +} diff --git a/ScStwLibraries/sources/scstwlibraries.cpp b/ScStwLibraries/sources/scstwlibraries.cpp index 08ba19d..64696c8 100644 --- a/ScStwLibraries/sources/scstwlibraries.cpp +++ b/ScStwLibraries/sources/scstwlibraries.cpp @@ -30,13 +30,15 @@ void ScStwLibraries::init() { qRegisterMetaType("ScStw::SocketCommand"); qRegisterMetaType("ScStw::StatusCode"); - qmlRegisterUncreatableType("de.itsblue.ScStw", 2, 0, "ScStwRace", "ScStwRace is not creatable"); + qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRace"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwTimer"); #ifdef ScStwLibraries_ClientLibs qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwClient"); qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwSettings"); qmlRegisterUncreatableType("de.itsblue.ScStw", 2, 0, "ScStwSetting", "The ScStwSetting is manage by a ScStwSettings instance and therefore not creatable"); + qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRemoteRace"); + qmlRegisterType("de.itsblue.ScStw", 2, 0, "ScStwRemoteSettings"); #endif #endif diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 0880a2c..2d91318 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -18,10 +18,15 @@ #include "../headers/scstwrace.h" +ScStwRace::ScStwRace(QObject* parent) : ScStwRace(nullptr, parent) +{ +} + ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) { this->state = IDLE; this->competitionMode = false; + this->autoRefreshTimerText = false; // configure the loop that waits for the sound effect to finish this->soundPlayer = new ScStwSoundPlayer(); @@ -38,8 +43,7 @@ ScStwRace::ScStwRace(ScStwSettings *settings, QObject *parent) : QObject(parent) connect(this, &ScStwRace::stateChanged, this, &ScStwRace::detailsChanged); // init settings - this->settings = settings; - this->refreshCompetitionMode(); + this->setSettings(settings); } // -------------------------- @@ -624,7 +628,10 @@ void ScStwRace::refreshCompetitionMode() { if(this->state != IDLE) return; - bool currentCompetitionMode = this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool(); + bool currentCompetitionMode = false; + + if(this->settings != nullptr) + currentCompetitionMode = this->settings->readSetting(ScStwSettings::CompetitionModeSetting).toBool(); if(this->competitionMode != currentCompetitionMode) { @@ -734,6 +741,9 @@ QList ScStwRace::getTimers() { } double ScStwRace::getSoundVolume() { + if(this->settings == nullptr) + return 1; + return this->settings->readSetting(ScStwSettings::SoundVolumeSetting).toDouble(); } @@ -769,6 +779,9 @@ bool ScStwRace::getSoundEnabledSetting(ScStwSoundPlayer::StartSound sound) { return false; } + if(this->settings == nullptr) + return false; + return this->settings->readSetting(soundEnabledSetting).toBool(); } @@ -788,6 +801,9 @@ int ScStwRace::getSoundDelaySetting(ScStwSoundPlayer::StartSound sound) { return -1; } + if(this->settings == nullptr) + return -1; + return this->settings->readSetting(soundDelaySetting).toInt(); } @@ -836,3 +852,53 @@ bool ScStwRace::getCompetitionMode() { bool ScStwRace::getReadySoundEnabled() { return this->getSoundEnabledSetting(ScStwSoundPlayer::Ready); } + +ScStwSettings* ScStwRace::getSettings() { + return this->settings; +} + +void ScStwRace::setSettings(ScStwSettings* settings) { + if(settings == this->settings) + return; + + this->settings = settings; + this->refreshCompetitionMode(); + emit this->settingsChanged(); +} + +bool ScStwRace::getAutoRefreshTimerText() { + return this->autoRefreshTimerText; +} + +void ScStwRace::setAutoRefreshTimerText(bool autoRefresh) { + if(autoRefresh == this->autoRefreshTimerText) + return; + + this->autoRefreshTimerText = autoRefresh; + + if(this->autoRefreshTimerText) { + this->timerTextRefreshTimer = new QTimer(this); + this->timerTextRefreshTimer->setInterval(1); + this->timerTextRefreshTimer->connect( + this->timerTextRefreshTimer, + &QTimer::timeout, + [=]{ + // refresh timer text + if(this->getState() == ScStwRace::RUNNING) { + emit this->timersChanged(); + } + + // refresh next start action delay progress + if(this->getState() == ScStwRace::WAITING || this->getState() == ScStwRace::PREPAIRING) { + emit this->currentStartDelayChanged(); + } + } + ); + this->timerTextRefreshTimer->start(); + } + else if(this->timerTextRefreshTimer != nullptr) { + this->timerTextRefreshTimer->deleteLater(); + } + + emit this->autoRefreshTimerTextChanged(); +} diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 01c0b02..0744a66 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -18,7 +18,11 @@ #include "../headers/scstwtimer.h" -ScStwTimer::ScStwTimer(QObject *parent, QString letter) : QObject(parent) +ScStwTimer::ScStwTimer(QObject* parent) : ScStwTimer("", parent) +{ +} + +ScStwTimer::ScStwTimer(QString letter, QObject *parent) : QObject(parent) { if(letter.length() > 1) this->letter = letter[0]; From fdb17bdc3a1356f09f14b4f8da0221aff6cc5129 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 19 Oct 2020 11:15:49 +0200 Subject: [PATCH 65/76] Fixed issues that ourred when switching between remote and local race mode --- .../headers/client/scstwremoterace.h | 2 + .../sources/client/scstwremoterace.cpp | 41 ++++++++++++++----- .../sources/client/scstwremotesettings.cpp | 5 ++- ScStwLibraries/sources/scstwsetting.cpp | 1 + 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwremoterace.h b/ScStwLibraries/headers/client/scstwremoterace.h index 7a3ba79..8c4a372 100644 --- a/ScStwLibraries/headers/client/scstwremoterace.h +++ b/ScStwLibraries/headers/client/scstwremoterace.h @@ -77,6 +77,8 @@ private slots: RaceMode getMode(); bool local(); + void setTimers(QList timers, bool deleteOldTimers); + signals: void scStwClientChanged(); }; diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 9d3912c..65bad83 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -119,20 +119,17 @@ ScStw::StatusCode ScStwRemoteRace::setTimerDisabled(int timerId, bool disabled) void ScStwRemoteRace::handleClientStateChange() { switch (this->scStwClient->getState()) { - case ScStwClient::CONNECTED: - this->localTimers.clear(); - this->localTimers = this->timers; - this->timers.clear(); + case ScStwClient::INITIALISING: + // disconnect all local timers from race + this->setTimers({}, false); + // delete all obsolete remote timers + for(ScStwRemoteTimer* oldRemoteTimer : this->remoteTimers) + oldRemoteTimer->deleteLater(); this->remoteTimers.clear(); break; case ScStwClient::DISCONNECTED: - foreach(ScStwRemoteTimer *remoteTimer, this->remoteTimers) - remoteTimer->deleteLater(); this->remoteTimers.clear(); - - this->timers.clear(); - this->timers = this->localTimers; - this->localTimers.clear(); + this->setTimers(this->localTimers, true); emit this->timersChanged(); emit this->detailsChanged(); emit this->currentStartDelayChanged(); @@ -284,6 +281,30 @@ bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { return false; } +void ScStwRemoteRace::setTimers(QList timers, bool deleteOldTimers) { + + // disconnect all signals of all current timers + qDebug() << "SETTING TIMERS"; + + foreach(ScStwTimer *existingTimer, this->timers) { + disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimerStateChange); + disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); + disconnect(existingTimer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); + disconnect(existingTimer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); + disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::handleTimerReadyStateChange); + disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::isReadyForNextStateChanged); + + if(deleteOldTimers) + existingTimer->deleteLater(); + } + + this->timers.clear(); + + for(ScStwTimer* timer : timers) { + this->addTimer(timer); + } +} + QVariantMap ScStwRemoteRace::getCurrentStartDelay() { if(this->local()) return ScStwRace::getCurrentStartDelay(); diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index 4a63c5d..db5afb9 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -65,9 +65,9 @@ bool ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant void ScStwRemoteSettings::handleClientStateChange() { if(this->scStwClient->getState() == ScStwClient::DISCONNECTED) - emit this->settingChanged(-1, 0, QVariant()); + emit this->settingChanged(-1, ScStwSettings::KeyLevel, QVariant()); else if(this->scStwClient->getState() == ScStwClient::CONNECTED) - emit this->settingChanged(-1, 0, QVariant()); + emit this->settingChanged(-1, ScStwSettings::KeyLevel, QVariant()); } void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { @@ -92,6 +92,7 @@ void ScStwRemoteSettings::setScStwClient(ScStwClient* client) { if(this->scStwClient != nullptr) { this->scStwClient->addSignalSubscription(ScStw::SettingChanged); + connect(this->scStwClient, &ScStwClient::stateChanged, this, &ScStwRemoteSettings::handleClientStateChange); connect(this->scStwClient, &ScStwClient::gotSignal, this, &ScStwRemoteSettings::handleBaseStationSignal); } } diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp index c499f4f..7880326 100644 --- a/ScStwLibraries/sources/scstwsetting.cpp +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -51,6 +51,7 @@ void ScStwSetting::handleSettingChange(int key, int keyLevel, QVariant value) { emit this->valueChanged(); } else if(key == -1 && this->key != -1 && this->keyLevel != -1 && this->keyLevel == keyLevel) { + qDebug() << "value changed!!! key: " << key << " new value " << value; this->hasToReload = true; emit this->valueChanged(); } From 45added26cc9c9af6bf215d29b838632c293b6af Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 28 Dec 2020 14:26:52 +0100 Subject: [PATCH 66/76] Add BatteryNotCharging state --- ScStwLibraries/headers/ScStw.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 31807d3..92a9bbf 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -167,7 +167,8 @@ public: BatteryCritical = 0, BatteryWarning = 1, BatteryFine = 2, - BatteryCharging = 3 + BatteryCharging = 3, + BatteryNotCharging = 4 }; Q_ENUM(ExtensionBatteryState); From 7e91a89caf0408eeb18f34da9ce16f5c87844431 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Mon, 28 Dec 2020 16:17:38 +0100 Subject: [PATCH 67/76] - bugfixes --- ScStwLibraries/sources/scstwrace.cpp | 1 + ScStwLibraries/sources/scstwtimer.cpp | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 1c6d548..77448b5 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -269,6 +269,7 @@ bool ScStwRace::playSoundsAndStartTimers() { } else { this->startDelayTimer->stop(); + this->startDelayTimer->setInterval(minimumReadyDelay); this->startDelayTimer->start(); timerTriggered = true; } diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 0744a66..ba4636e 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -280,11 +280,16 @@ QString ScStwTimer::getText() { } void ScStwTimer::setDisabled(bool disabled) { + if(this->isDisabled() == disabled) + return; + if(disabled) this->setState(DISABLED); - else { + else this->setState(IDLE); - } + + emit this->readyStateChanged(this->getReadyState()); + } void ScStwTimer::setWantsToBeDisabled(bool wantsToBeDisabled) { From 6037d29c4c74e1b5f349d2fd76e0a0c29100f87c Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 2 Jan 2021 19:03:56 +0100 Subject: [PATCH 68/76] - add error to indicate invalid format of firmware update --- ScStwLibraries/headers/ScStw.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ScStwLibraries/headers/ScStw.hpp b/ScStwLibraries/headers/ScStw.hpp index 92a9bbf..a48fe03 100644 --- a/ScStwLibraries/headers/ScStw.hpp +++ b/ScStwLibraries/headers/ScStw.hpp @@ -133,6 +133,7 @@ public: InternalErrorTimerOperationFailed = 951, ApiVersionNotSupportedError = 952, CompetitionModeProhibitsThisError = 953, + FirmwareUpdateFormatInvalidError = 954, TimersNotReadyError = 501 /*!< One or more timer is not ready */ }; Q_ENUM(ScStw::StatusCode) From 39850455da76100e5f8e7a396b105da2cffb5ceb Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Tue, 5 Jan 2021 20:12:47 +0100 Subject: [PATCH 69/76] dont connect if already connecting --- ScStwLibraries/sources/client/scstwclient.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index cf12a27..163356e 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -50,6 +50,9 @@ ScStwClient::ScStwClient(QObject * parent, QList signalSubscri void ScStwClient::connectToHost() { + if(this->state != DISCONNECTED) + return; + setState(CONNECTING); //connect From f088a79c2bd115de3c9e81d574b7cca0017b5a8e Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 9 Jan 2021 23:12:28 +0100 Subject: [PATCH 70/76] some fixes --- ScStwLibraries/headers/client/scstwclient.h | 9 +- ScStwLibraries/headers/scstwsetting.h | 1 + ScStwLibraries/sources/client/scstwclient.cpp | 94 +++++++++++------- .../sources/client/scstwremoterace.cpp | 99 ++++++++++--------- .../sources/client/scstwremotesettings.cpp | 12 ++- ScStwLibraries/sources/scstwrace.cpp | 9 +- ScStwLibraries/sources/scstwsetting.cpp | 1 + ScStwLibraries/sources/scstwtimer.cpp | 2 +- 8 files changed, 126 insertions(+), 101 deletions(-) diff --git a/ScStwLibraries/headers/client/scstwclient.h b/ScStwLibraries/headers/client/scstwclient.h index e316097..ed589ab 100644 --- a/ScStwLibraries/headers/client/scstwclient.h +++ b/ScStwLibraries/headers/client/scstwclient.h @@ -101,15 +101,14 @@ private: QString readBuffer; - int nextConnectionId; + unsigned int currentRequestId; - struct waitingRequest { - int id; + struct WaitingRequest { QEventLoop * loop; QJsonObject reply; }; - QList waitingRequests; + QMap waitingRequests; public slots: @@ -152,7 +151,7 @@ public slots: * \param key the key to read from * \return the value of the key or "false" if the key is not found or an error occured */ - QVariant readRemoteSetting(ScStwSettings::BaseStationSetting key); + QVariant readRemoteSetting(ScStwSettings::BaseStationSetting key, ScStw::StatusCode* status = nullptr); /*! Getter fuctions */ diff --git a/ScStwLibraries/headers/scstwsetting.h b/ScStwLibraries/headers/scstwsetting.h index bd57cd7..6a7b36c 100644 --- a/ScStwLibraries/headers/scstwsetting.h +++ b/ScStwLibraries/headers/scstwsetting.h @@ -28,6 +28,7 @@ class ScStwSetting : public QObject { Q_OBJECT Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged) + Q_PROPERTY(QVariant readonlyValue READ getValue NOTIFY valueChanged) protected: explicit ScStwSetting(int key, int keyLevel, ScStwSettings*scStwSettings, QObject *parent); diff --git a/ScStwLibraries/sources/client/scstwclient.cpp b/ScStwLibraries/sources/client/scstwclient.cpp index cf12a27..6fb5d94 100644 --- a/ScStwLibraries/sources/client/scstwclient.cpp +++ b/ScStwLibraries/sources/client/scstwclient.cpp @@ -23,7 +23,7 @@ ScStwClient * pGlobalScStwClient = nullptr; ScStwClient::ScStwClient(QObject * parent, QList signalSubscriptions) : QObject(parent) { this->state = DISCONNECTED; - this->nextConnectionId = 1; + this->currentRequestId = 1; this->extensions = QVariantMap({}); this->signalSubscriptions = signalSubscriptions; @@ -84,7 +84,6 @@ bool ScStwClient::init() { QVariantMap initResponse = this->sendCommand(1, sessionParams, 3000, false); if(initResponse["status"] != 200) { - this->closeConnection(); return false; } @@ -121,7 +120,17 @@ void ScStwClient::deInit() { if(this->state == DISCONNECTED) return; + this->currentRequestId = 1; + this->firmwareVersion = ""; + this->apiVersion = ""; this->setExtensions(QVariantMap({})); + + for(WaitingRequest waitingRequest : this->waitingRequests.values()) + if(waitingRequest.loop != nullptr) + waitingRequest.loop->exit(ScStw::NotConnectedError); + + this->waitingRequests.clear(); + this->setState(DISCONNECTED); } @@ -160,16 +169,22 @@ QVariantMap ScStwClient::sendCommand(int header, QJsonValue data, int timeout, b return {{"status", ScStw::NotConnectedError}, {"data", "not connected"}}; } - // generate id and witing requests entry - int thisId = nextConnectionId; + // pick a new request id that is not already active + do { + if(this->currentRequestId >= 99) + this->currentRequestId = 0; + else + this->currentRequestId ++; + } while(this->waitingRequests.contains(this->currentRequestId)); + + int thisId = currentRequestId; //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}); + this->waitingRequests.insert(thisId, {loop, reply}); QJsonObject requestObj; requestObj.insert("id", thisId); @@ -180,7 +195,7 @@ QVariantMap ScStwClient::sendCommand(int header, QJsonValue data, int timeout, b timer->setSingleShot(true); // quit the loop when the timer times out - loop->connect(timer, SIGNAL(timeout()), loop, SLOT(quit())); + connect(timer, &QTimer::timeout, [=]{loop->exit(ScStw::TimeoutError);}); // start the timer before starting to connect timer->start(timeout); @@ -191,37 +206,38 @@ QVariantMap ScStwClient::sendCommand(int header, QJsonValue data, int timeout, b socket->write(jsonRequest.toUtf8()); //wait for an answer to finish (programm gets stuck in here) - loop->exec(); + ScStw::StatusCode statusCode = ScStw::StatusCode(loop->exec()); - - - bool replyFound = false; + // delete the timer + timer->deleteLater(); // 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(this->waitingRequests.contains(thisId)) { + // request was found + // delete event loop + if(this->waitingRequests[thisId].loop != nullptr) { + this->waitingRequests[thisId].loop->deleteLater(); } - } - if(!replyFound) { + // store reply + reply = this->waitingRequests[thisId].reply; + + // remove reply from waiting list + this->waitingRequests.remove(thisId); + } + else { // some internal error occured - return {{"status", ScStw::Error}, {"data", ""}}; + return {{"status", ScStw::InternalError}, {"data", ""}}; } - if(timer->remainingTime() == -1){ + if(statusCode == ScStw::TimeoutError){ //the time has been triggered -> timeout return {{"status", ScStw::TimeoutError}, {"data", ""}}; } + else if(statusCode == ScStw::NotConnectedError) { + // connection was closed during request + return {{"status", ScStw::NotConnectedError}, {"data", ""}}; + } delete timer; return {{"status", reply.value("header").toInt()}, {"data", reply.value("data").toVariant()}}; @@ -273,7 +289,6 @@ void ScStwClient::handleReadyRead() { //qDebug() << "ready to ready " << socket->bytesAvailable() << " bytes" ; QString reply = socket->readAll(); - //qWarning() << "socket read: " << reply; processSocketMessage(reply); @@ -335,7 +350,7 @@ void ScStwClient::handleSocketMessage(QString reply) { reply.replace(ScStw::SOCKET_MESSAGE_START_KEY, ""); reply.replace(ScStw::SOCKET_MESSAGE_END_KEY, ""); - //qDebug() << "got message: " << reply; + qDebug() << "got message: " << qPrintable(reply); int id = 0; @@ -352,14 +367,12 @@ void ScStwClient::handleSocketMessage(QString reply) { } // 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; + if(this->waitingRequests.contains(id)){ + this->waitingRequests[id].reply = replyObj; + if(this->waitingRequests[id].loop != nullptr){ + this->waitingRequests[id].loop->exit(ScStw::Success); } + return; } } @@ -404,8 +417,13 @@ ScStw::StatusCode ScStwClient::writeRemoteSetting(ScStwSettings::BaseStationSett return ScStw::StatusCode(this->sendCommand(3000, requestData)["status"].toInt()); } -QVariant ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key) { - QVariantMap reply = this->sendCommand(3001, int(key)); +QVariant ScStwClient::readRemoteSetting(ScStwSettings::BaseStationSetting key, ScStw::StatusCode* status) { + QVariantMap reply = this->sendCommand(3001, int(key), 10000); + qDebug() << "Setting read status is: " << reply["status"]; + + if(status != nullptr) + *status = ScStw::StatusCode(reply["status"].toInt()); + if(reply["status"] != 200){ return "false"; } diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 65bad83..2347d50 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -102,8 +102,8 @@ ScStw::StatusCode ScStwRemoteRace::setTimerDisabled(int timerId, bool disabled) qDebug() << "+ --- setting timer " << timerId << " to disabled: " << disabled; QVariantMap requestData = { - {"timerId", timerId}, - {"disabled", disabled} + {"timerId", timerId}, + {"disabled", disabled} }; QVariantMap reply = this->scStwClient->sendCommand(ScStw::SetTimerDisabledCommand, QJsonValue::fromVariant(requestData)); @@ -125,6 +125,7 @@ void ScStwRemoteRace::handleClientStateChange() { // delete all obsolete remote timers for(ScStwRemoteTimer* oldRemoteTimer : this->remoteTimers) oldRemoteTimer->deleteLater(); + this->remoteTimers.clear(); break; case ScStwClient::DISCONNECTED: @@ -141,6 +142,30 @@ void ScStwRemoteRace::handleClientStateChange() { } } +void ScStwRemoteRace::setTimers(QList timers, bool deleteOldTimers) { + + // disconnect all signals of all current timers + //qDebug() << "SETTING TIMERS"; + + foreach(ScStwTimer *existingTimer, this->timers) { + disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimerStateChange); + disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); + disconnect(existingTimer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); + disconnect(existingTimer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); + disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::handleTimerReadyStateChange); + disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::isReadyForNextStateChanged); + + if(deleteOldTimers) + existingTimer->deleteLater(); + } + + this->timers.clear(); + + for(ScStwTimer* timer : timers) { + this->addTimer(timer); + } +} + ScStwRemoteRace::RaceMode ScStwRemoteRace::getMode() { if(this->scStwClient == nullptr || this->scStwClient->getState() != ScStwClient::CONNECTED) return LOCAL; @@ -233,43 +258,43 @@ void ScStwRemoteRace::rebuildRemoteTimers(QVariantList remoteTimers) { } } -bool ScStwRemoteRace::refreshRemoteTimers(QVariantList remoteTimers) { +bool ScStwRemoteRace::refreshRemoteTimers(QVariantList newRemoteTimers) { qDebug() << "REFRESHING TIMERS"; - if(remoteTimers.length() != this->remoteTimers.length()){ - // local timers are out of sync - this->rebuildRemoteTimers(remoteTimers); - qDebug() << "rebuilding remote timers"; - } + if(newRemoteTimers.length() != this->remoteTimers.length()){ + // local timers are out of sync + this->rebuildRemoteTimers(newRemoteTimers); + qDebug() << "rebuilding remote timers"; + } - foreach(QVariant remoteTimer, remoteTimers){ - int currId = remoteTimer.toMap()["id"].toInt(); + for(QVariant remoteTimer : newRemoteTimers){ + int currId = remoteTimer.toMap()["id"].toInt(); - if(this->remoteTimers.length() <= currId) - this->rebuildRemoteTimers(remoteTimers); + if(this->remoteTimers.length() <= currId) + this->rebuildRemoteTimers(newRemoteTimers); - ScStwTimer::TimerState newState = ScStwTimer::TimerState(remoteTimer.toMap()["state"].toInt()); + ScStwTimer::TimerState newState = ScStwTimer::TimerState(remoteTimer.toMap()["state"].toInt()); - qDebug() << "refreshing timers: id: " << currId << " state: " << newState << " readyState: " << remoteTimer.toMap()["readyState"].toInt() << " currentTime: " << remoteTimer.toMap()["currentTime"].toDouble(); + qDebug() << "refreshing timers: id: " << currId << " state: " << newState << " readyState: " << remoteTimer.toMap()["readyState"].toInt() << " currentTime: " << remoteTimer.toMap()["currentTime"].toDouble(); - double currentMSecsSinceEpoch = QDateTime::currentMSecsSinceEpoch(); + double currentMSecsSinceEpoch = QDateTime::currentMSecsSinceEpoch(); - this->remoteTimers[currId]->setStartTime(currentMSecsSinceEpoch - remoteTimer.toMap()["currentTime"].toDouble()); + this->remoteTimers[currId]->setStartTime(currentMSecsSinceEpoch - remoteTimer.toMap()["currentTime"].toDouble()); - if(newState >= ScStwTimer::WAITING) - this->remoteTimers[currId]->setStopTime(currentMSecsSinceEpoch); + if(newState >= ScStwTimer::WAITING) + this->remoteTimers[currId]->setStopTime(currentMSecsSinceEpoch); - this->remoteTimers[currId]->setReactionTime(remoteTimer.toMap()["reactionTime"].toDouble()); - this->remoteTimers[currId]->setLetter(remoteTimer.toMap()["letter"].toString()); - this->remoteTimers[currId]->setReadyState(ScStwTimer::ReadyState(remoteTimer.toMap()["readyState"].toInt())); + this->remoteTimers[currId]->setReactionTime(remoteTimer.toMap()["reactionTime"].toDouble()); + this->remoteTimers[currId]->setLetter(remoteTimer.toMap()["letter"].toString()); + this->remoteTimers[currId]->setReadyState(ScStwTimer::ReadyState(remoteTimer.toMap()["readyState"].toInt())); - this->remoteTimers[currId]->setState(newState); - } + this->remoteTimers[currId]->setState(newState); + } - emit this->timersChanged(); + emit this->timersChanged(); - return true; + return true; } bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { @@ -281,30 +306,6 @@ bool ScStwRemoteRace::addTimer(ScStwTimer* timer) { return false; } -void ScStwRemoteRace::setTimers(QList timers, bool deleteOldTimers) { - - // disconnect all signals of all current timers - qDebug() << "SETTING TIMERS"; - - foreach(ScStwTimer *existingTimer, this->timers) { - disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::handleTimerStateChange); - disconnect(existingTimer, &ScStwTimer::stateChanged, this, &ScStwRace::timersChanged); - disconnect(existingTimer, &ScStwTimer::wantsToBeDisabledChanged, this, &ScStwRace::handleTimerWantsToBeDisabledChange); - disconnect(existingTimer, &ScStwTimer::reactionTimeChanged, this, &ScStwRace::timersChanged); - disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::handleTimerReadyStateChange); - disconnect(existingTimer, &ScStwTimer::readyStateChanged, this, &ScStwRace::isReadyForNextStateChanged); - - if(deleteOldTimers) - existingTimer->deleteLater(); - } - - this->timers.clear(); - - for(ScStwTimer* timer : timers) { - this->addTimer(timer); - } -} - QVariantMap ScStwRemoteRace::getCurrentStartDelay() { if(this->local()) return ScStwRace::getCurrentStartDelay(); diff --git a/ScStwLibraries/sources/client/scstwremotesettings.cpp b/ScStwLibraries/sources/client/scstwremotesettings.cpp index db5afb9..ca30b92 100644 --- a/ScStwLibraries/sources/client/scstwremotesettings.cpp +++ b/ScStwLibraries/sources/client/scstwremotesettings.cpp @@ -41,7 +41,13 @@ QVariant ScStwRemoteSettings::readSetting(QString key, int keyInt, int keyLevel) qDebug() << "Setting read: keyLevel: " << keyLevel << " key: " << key; - return this->scStwClient->readRemoteSetting(ScStwSettings::BaseStationSetting(keyInt)); + ScStw::StatusCode status; + QVariant value = this->scStwClient->readRemoteSetting(ScStwSettings::BaseStationSetting(keyInt), &status); + + if(status == ScStw::Success) + return value; + else + return QVariant(); } bool ScStwRemoteSettings::writeSetting(QString key, QVariant value, int keyInt, int keyLevel) { @@ -66,8 +72,8 @@ bool ScStwRemoteSettings::setDefaultSetting(QString key, QVariant defaultVariant void ScStwRemoteSettings::handleClientStateChange() { if(this->scStwClient->getState() == ScStwClient::DISCONNECTED) emit this->settingChanged(-1, ScStwSettings::KeyLevel, QVariant()); - else if(this->scStwClient->getState() == ScStwClient::CONNECTED) - emit this->settingChanged(-1, ScStwSettings::KeyLevel, QVariant()); + // Dont't need to do that when changing to connected, + // as the basestation emits a wildcrd setting changed on connect anyway } void ScStwRemoteSettings::handleBaseStationSignal(ScStw::SignalKey key, QVariant data) { diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 1c6d548..3e7e8e7 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -170,7 +170,7 @@ ScStw::StatusCode ScStwRace::setTimerDisabled(int timerId, bool disabled) { } ScStw::StatusCode ScStwRace::setTimerDisabled(ScStwTimer* timer, bool disabled) { - qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled << " this state: " << this->state; + //qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled << " this state: " << this->state; if(this->state != IDLE && this->state != WAITING) return ScStw::CurrentStateNotVaildForOperationError; @@ -187,7 +187,7 @@ ScStw::StatusCode ScStwRace::setTimerDisabled(ScStwTimer* timer, bool disabled) if(disabled && enabledTimerCount <= 1) return ScStw::LastTimerCannotBeDisabledError; - qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled; + //qDebug() << "[INFO][RACE] Setting timer "<< timer->getLetter() << " to disabled: " << disabled; timer->setDisabled(disabled); @@ -620,13 +620,12 @@ bool ScStwRace::getIsReadyForNextState() { * @param {ScStwExtensionControlledTimer*} timer timer to be enabled */ void ScStwRace::handleTimerWantsToBeDisabledChange(ScStwTimer* timer, bool wantsToBeDisabled) { - qDebug() << "Handling timer wants to be disabled"; + //qDebug() << "Handling timer wants to be disabled"; if(this->competitionMode) return; if(this->state == IDLE) { - - qDebug() << "Handling timer wants to be disabled: " << wantsToBeDisabled; + //qDebug() << "Handling timer wants to be disabled: " << wantsToBeDisabled; this->setTimerDisabled(timer, wantsToBeDisabled); } } diff --git a/ScStwLibraries/sources/scstwsetting.cpp b/ScStwLibraries/sources/scstwsetting.cpp index 7880326..83e3ed3 100644 --- a/ScStwLibraries/sources/scstwsetting.cpp +++ b/ScStwLibraries/sources/scstwsetting.cpp @@ -30,6 +30,7 @@ ScStwSetting::ScStwSetting(int key, int keyLevel, ScStwSettings*scStwSettings, Q } QVariant ScStwSetting::getValue() { + qDebug() << "Getting setting: " << this->key << " has to reload: " << this->hasToReload; if(this->hasToReload) { this->valueCache = this->scStwSettings->readSetting(this->key, this->keyLevel); this->hasToReload = false; diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index 0744a66..f103875 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -29,7 +29,7 @@ ScStwTimer::ScStwTimer(QString letter, QObject *parent) : QObject(parent) else this->letter = letter; - qDebug() << "Timer created with letter: " << letter; + //qDebug() << "Timer created with letter: " << letter; this->startTime = 0; this->stopTime = 0; From 37bea9105f1c7e0c8f1a209da3d5043c61abfb44 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 15 Jan 2021 18:16:30 +0100 Subject: [PATCH 71/76] - fixed a bug that lead to segmentation faults --- ScStwLibraries/sources/client/scstwremoterace.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ScStwLibraries/sources/client/scstwremoterace.cpp b/ScStwLibraries/sources/client/scstwremoterace.cpp index 2347d50..53b3f54 100644 --- a/ScStwLibraries/sources/client/scstwremoterace.cpp +++ b/ScStwLibraries/sources/client/scstwremoterace.cpp @@ -130,7 +130,7 @@ void ScStwRemoteRace::handleClientStateChange() { break; case ScStwClient::DISCONNECTED: this->remoteTimers.clear(); - this->setTimers(this->localTimers, true); + this->setTimers(this->localTimers, false); emit this->timersChanged(); emit this->detailsChanged(); emit this->currentStartDelayChanged(); From 7529095d6ff3803c461d4d4ee337f62007d60ac6 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 19 Mar 2021 12:05:20 +0100 Subject: [PATCH 72/76] Fixed stopped and reaction time (Fix #9) --- ScStwLibraries/sources/scstwrace.cpp | 76 ++++++++++++++------------- ScStwLibraries/sources/scstwtimer.cpp | 10 ++-- 2 files changed, 44 insertions(+), 42 deletions(-) diff --git a/ScStwLibraries/sources/scstwrace.cpp b/ScStwLibraries/sources/scstwrace.cpp index 77448b5..567a794 100644 --- a/ScStwLibraries/sources/scstwrace.cpp +++ b/ScStwLibraries/sources/scstwrace.cpp @@ -72,7 +72,9 @@ ScStw::StatusCode ScStwRace::start(bool asyncronous) { this->setState(PREPAIRING); if(asyncronous) { - QTimer::singleShot(1, [=](){this->playSoundsAndStartTimers();}); + QTimer::singleShot(1, [=]() { + this->playSoundsAndStartTimers(); + }); } else this->playSoundsAndStartTimers(); @@ -94,8 +96,8 @@ ScStw::StatusCode ScStwRace::stop() { ScStw::StatusCode returnCode = ScStw::Success; - foreach(ScStwTimer *speedTimer, this->timers){ - if(!speedTimer->stop(timeOfStop) && speedTimer->getState() != ScStwTimer::DISABLED){ + foreach(ScStwTimer *speedTimer, this->timers) { + if(!speedTimer->stop(timeOfStop) && speedTimer->getState() != ScStwTimer::DISABLED) { returnCode = ScStw::InternalErrorTimerOperationFailed; } } @@ -121,7 +123,7 @@ ScStw::StatusCode ScStwRace::reset() { ScStw::StatusCode returnCode = ScStw::Success; - foreach(ScStwTimer *timer, this->timers){ + foreach(ScStwTimer *timer, this->timers) { if(!timer->reset() && timer->getState() != ScStwTimer::DISABLED && timer->getState() != ScStwTimer::IDLE) { returnCode = ScStw::InternalErrorTimerOperationFailed; } @@ -143,7 +145,7 @@ ScStw::StatusCode ScStwRace::cancel() { ScStw::StatusCode returnCode = ScStw::Success; - foreach(ScStwTimer *timer, this->timers){ + foreach(ScStwTimer *timer, this->timers) { if(!timer->cancel() && timer->getState() != ScStwTimer::DISABLED) returnCode = ScStw::InternalErrorTimerOperationFailed; } @@ -351,8 +353,8 @@ bool ScStwRace::playSoundsAndStartTimers() { // start all timers bool startOk = true; - foreach(ScStwTimer *timer, this->timers){ - if(!timer->start(timeOfSoundPlaybackStart + 3100) && timer->getState() != ScStwTimer::DISABLED){ + foreach(ScStwTimer *timer, this->timers) { + if(!timer->start(timeOfSoundPlaybackStart + 3000) && timer->getState() != ScStwTimer::DISABLED) { startOk = false; } } @@ -425,12 +427,12 @@ void ScStwRace::setState(RaceState newState) { void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { if( - newState == ScStwTimer::WON || - newState == ScStwTimer::LOST || - newState == ScStwTimer::WILDCARD || - newState == ScStwTimer::FAILED || - this->state == INCIDENT - ) + newState == ScStwTimer::WON || + newState == ScStwTimer::LOST || + newState == ScStwTimer::WILDCARD || + newState == ScStwTimer::FAILED || + this->state == INCIDENT + ) return; qDebug() << "[INFO][MAIN] handling timer state change"; @@ -439,8 +441,8 @@ void ScStwRace::handleTimerStateChange(ScStwTimer::TimerState newState) { bool raceIsOver = true; int incidentCount = 0; - foreach(ScStwTimer * timer, this->timers){ - if(timer->getState() < ScStwTimer::WAITING){ + foreach(ScStwTimer * timer, this->timers) { + if(timer->getState() < ScStwTimer::WAITING) { // if the timer is not in stoped state raceIsOver = false; } @@ -502,14 +504,14 @@ void ScStwRace::handleFalseStart() { // iterate through all timers and find the lowest reactiontime that was stopped foreach(ScStwTimer *timer, this->timers) { if( - timer->getState() >= ScStwTimer::FAILING && - timer->getState() <= ScStwTimer::FAILED && - !timer->isDisabled() && - ( - timer->getReactionTime() < lowestReactionTime || - lowestReactionTime == -4000 - ) - ) { + timer->getState() >= ScStwTimer::FAILING && + timer->getState() <= ScStwTimer::FAILED && + !timer->isDisabled() && + ( + timer->getReactionTime() < lowestReactionTime || + lowestReactionTime == -4000 + ) + ) { lowestReactionTime = timer->getReactionTime(); } } @@ -524,11 +526,11 @@ void ScStwRace::handleFalseStart() { foreach(ScStwTimer * timer, this->timers) { qDebug() << "THIS TIMERS reaction time is: " << timer->getReactionTime(); if( - timer->getState() >= ScStwTimer::FAILING && - timer->getState() <= ScStwTimer::FAILED && - !timer->isDisabled() && - timer->getReactionTime() <= lowestReactionTime - ) { + timer->getState() >= ScStwTimer::FAILING && + timer->getState() <= ScStwTimer::FAILED && + !timer->isDisabled() && + timer->getReactionTime() <= lowestReactionTime + ) { // this is the timer with the lowest stopped time timer->setResult(ScStwTimer::FAILED); qDebug() << "FOUND BAD TIMER"; @@ -562,7 +564,7 @@ void ScStwRace::technicalIncident() { this->setState(INCIDENT); } - foreach(ScStwTimer *timer, this->timers){ + foreach(ScStwTimer *timer, this->timers) { if(raceIsRunning && timer->getReadyState() == ScStwTimer::ExtensionBatteryIsCritical) continue; else if(timer->getReadyState() == ScStwTimer::ExtensionIsNotConnected || timer->getReadyState() == ScStwTimer::ExtensionBatteryIsCritical) @@ -598,7 +600,7 @@ bool ScStwRace::getIsReadyForNextState() { } break; - case WAITING: { + case WAITING: { foreach (ScStwTimer *timer, this->timers) { if(timer->getReadyState() != ScStwTimer::IsReady && timer->getReadyState() != ScStwTimer::IsDisabled) return false; @@ -656,9 +658,9 @@ void ScStwRace::refreshCompetitionMode() { else { foreach(ScStwTimer* timer, this->timers) { if( - (timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) || - (!timer->getWantsToBeDisabled() && timer->getState() == ScStwTimer::DISABLED) - ) + (timer->getWantsToBeDisabled() && timer->getState() != ScStwTimer::DISABLED) || + (!timer->getWantsToBeDisabled() && timer->getState() == ScStwTimer::DISABLED) + ) this->handleTimerWantsToBeDisabledChange(timer, timer->getWantsToBeDisabled()); } } @@ -818,7 +820,7 @@ int ScStwRace::getSoundDelaySetting(ScStwSoundPlayer::StartSound sound) { QVariantList ScStwRace::getTimerDetailList() { QVariantList tmpTimers; - foreach(ScStwTimer * timer, this->timers){ + foreach(ScStwTimer * timer, this->timers) { QVariantMap tmpTimer; tmpTimer.insert("id", this->timers.indexOf(timer)); tmpTimer.insert("state", timer->getState()); @@ -888,9 +890,9 @@ void ScStwRace::setAutoRefreshTimerText(bool autoRefresh) { this->timerTextRefreshTimer = new QTimer(this); this->timerTextRefreshTimer->setInterval(1); this->timerTextRefreshTimer->connect( - this->timerTextRefreshTimer, - &QTimer::timeout, - [=]{ + this->timerTextRefreshTimer, + &QTimer::timeout, + [=] { // refresh timer text if(this->getState() == ScStwRace::RUNNING) { emit this->timersChanged(); diff --git a/ScStwLibraries/sources/scstwtimer.cpp b/ScStwLibraries/sources/scstwtimer.cpp index ba4636e..c3b2c03 100644 --- a/ScStwLibraries/sources/scstwtimer.cpp +++ b/ScStwLibraries/sources/scstwtimer.cpp @@ -53,7 +53,7 @@ bool ScStwTimer::start(double timeOfStart) { if(timeOfStart - QDateTime::currentMSecsSinceEpoch() > 0) { this->setState(STARTING); - QTimer::singleShot(timeOfStart - QDateTime::currentMSecsSinceEpoch(), [=](){ + QTimer::singleShot(timeOfStart - QDateTime::currentMSecsSinceEpoch(), [=]() { if(this->state == STARTING) this->setState(RUNNING); }); @@ -87,7 +87,7 @@ void ScStwTimer::handleClimberStart(double timeOfStart) { this->reactionTime = timeOfStart - this->startTime; qDebug() << "+ [INFO][TIMER] reaction time: " << this->reactionTime; - if(this->reactionTime <= 0 && this->reactionTime){ + if(this->reactionTime <= 100 && this->reactionTime) { qDebug() << "[INFO][TIMER] False Start detected: " << "start Time: " << startTime << " reactionTime: " << reactionTime; this->setState(FAILING); } @@ -171,8 +171,8 @@ bool ScStwTimer::setResult(TimerState result) { return false; } -bool ScStwTimer::reset(){ - if( this->state < WON || this->state == DISABLED ){ +bool ScStwTimer::reset() { + if( this->state < WON || this->state == DISABLED ) { return false; } @@ -192,7 +192,7 @@ ScStwTimer::ReadyState ScStwTimer::getReadyState() { // --- helper functions --- // ------------------------ -void ScStwTimer::setState(TimerState newState){ +void ScStwTimer::setState(TimerState newState) { if(this->state == DISABLED && newState != IDLE) return; From b801a72d29285d43eb0f5ef788285939b28821e5 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Thu, 8 Apr 2021 19:06:36 +0200 Subject: [PATCH 73/76] fix settings path on raspi --- ScStwLibraries/sources/scstwsettings.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/sources/scstwsettings.cpp b/ScStwLibraries/sources/scstwsettings.cpp index 6f39147..d0b21b9 100644 --- a/ScStwLibraries/sources/scstwsettings.cpp +++ b/ScStwLibraries/sources/scstwsettings.cpp @@ -20,12 +20,16 @@ ScStwSettings::ScStwSettings(QObject *parent) : QObject(parent) { - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); +#ifdef RASPI + QString path = "/root/.config/ScStwBasestation"; +#else + QString path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); +#endif QDir dir(path); + if(!dir.mkpath(path)) + qFatal("[FATAL] Failed to create writable directory for settings at %s", qPrintable(path)); + this->settingsFile = new QFile(path + "/settings.json"); - if(!this->settingsFile->exists()) - if(!dir.mkpath(path)) - qFatal("[FATAL] Couldn't create settings dir %s", qPrintable(path)); if(!this->settingsFile->open(QFile::ReadWrite)) qFatal("[FATAL] Couldn't open settings file %s", qPrintable(path + "/settings.json")); From 38199766ce66ec542ad6060204e7a51bba3ab81e Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Fri, 9 Apr 2021 12:53:13 +0200 Subject: [PATCH 74/76] fixes for volume adjustment on raspi --- ScStwLibraries/sources/scstwsoundplayer.cpp | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 1dc116a..4bde4e8 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -48,11 +48,24 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound // update currently playing action this->currentlyPlayingSound = sound; - // update volume - #ifdef RASPI - // set volume on raspi using alsamixer - QProcess::execute("amixer -q -M sset PCM " + QString::number(volume * 100, 'f', 0) + "%"); + // set volume on raspi using amixer + QProcess soundProcess; + + // determine current audio output device + soundProcess.start("amixer", {"scontrols"}); + soundProcess.waitForFinished(); + QStringList outputDeviceNameList = QString(soundProcess.readAllStandardOutput()).split("'"); + + if(outputDeviceNameList.length() == 3) { + QString outputDeviceName = outputDeviceNameList[1]; + soundProcess.execute("amixer", {"sset", outputDeviceName, QString::number(volume * 100, 'f', 0) + "%"}); + } + else { + qDebug() << "[WARNING][SoundPlayer] Could not determine output device to set volume"; + } + + this->soundEffect->setVolume(1); #else this->soundEffect->setVolume(volume); #endif From 43b809d5d6a1b59fbe19f03f51cdc52ba296d1ab Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 2 May 2021 15:29:08 +0200 Subject: [PATCH 75/76] return error when unable to set sound volume --- ScStwLibraries/sources/scstwsoundplayer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 4bde4e8..2f9887d 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -63,6 +63,7 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound } else { qDebug() << "[WARNING][SoundPlayer] Could not determine output device to set volume"; + return Error; } this->soundEffect->setVolume(1); From 9dad92723992f5a75c1c10cadb6af3d5df305603 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sun, 2 May 2021 20:16:55 +0200 Subject: [PATCH 76/76] Fix issues with changing default audio device --- ScStwLibraries/ScStwLibraries.pri | 5 + ScStwLibraries/headers/scstwsoundplayer.h | 12 ++- ScStwLibraries/sources/scstwsoundplayer.cpp | 111 ++++++++++++++++---- 3 files changed, 103 insertions(+), 25 deletions(-) diff --git a/ScStwLibraries/ScStwLibraries.pri b/ScStwLibraries/ScStwLibraries.pri index 28d1ab7..60205a6 100644 --- a/ScStwLibraries/ScStwLibraries.pri +++ b/ScStwLibraries/ScStwLibraries.pri @@ -15,6 +15,11 @@ ScStwLibraries_ClientLibs { DEFINES += ScStwLibraries_ClientLibs } +ScStwLibraries_Raspi { + LIBS += -lasound + DEFINES += ScStwLibraries_Raspi +} + INCLUDEPATH += $$PWD/headers $$PWD SOURCES += \ diff --git a/ScStwLibraries/headers/scstwsoundplayer.h b/ScStwLibraries/headers/scstwsoundplayer.h index e89915e..47a678b 100644 --- a/ScStwLibraries/headers/scstwsoundplayer.h +++ b/ScStwLibraries/headers/scstwsoundplayer.h @@ -27,9 +27,10 @@ #include #include #include +#include -#ifdef RASPI -#include +#ifdef ScStwLibraries_Raspi +#include #endif /*! @@ -60,6 +61,11 @@ public: }; private: + + bool _setSoundVolume(double volume); + + void _initializeSondEffect(); + /*! * \brief A map containing all sound files * 0: AtYourMarksSound @@ -74,6 +80,8 @@ private: */ QSoundEffect *soundEffect; + QAudioDeviceInfo *_audioOutputDevice; + /*! * \brief The QEventLoop used to wait for the sound to finish */ diff --git a/ScStwLibraries/sources/scstwsoundplayer.cpp b/ScStwLibraries/sources/scstwsoundplayer.cpp index 2f9887d..3b50309 100644 --- a/ScStwLibraries/sources/scstwsoundplayer.cpp +++ b/ScStwLibraries/sources/scstwsoundplayer.cpp @@ -28,8 +28,7 @@ ScStwSoundPlayer::ScStwSoundPlayer(QObject *parent) : QObject(parent) this->soundFiles.insert(Start, {{"path","qrc:/sound/StartsignalSoundExtended.wav"}, {"duration", 3200}}); this->soundFiles.insert(FalseStart, {{"path","qrc:/sound/FalseStartSound.wav"}, {"duration", 2000}}); - this->soundEffect = new QSoundEffect(this); - this->soundEffect->setLoopCount(1); + this->_initializeSondEffect(); connect(this, &ScStwSoundPlayer::playbackStarted, this->waitLoop, &QEventLoop::quit); connect(this->soundEffect, &QSoundEffect::playingChanged, this->waitLoop, &QEventLoop::quit); @@ -48,28 +47,8 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::play(ScStwSoundPlayer::StartSound // update currently playing action this->currentlyPlayingSound = sound; -#ifdef RASPI - // set volume on raspi using amixer - QProcess soundProcess; - - // determine current audio output device - soundProcess.start("amixer", {"scontrols"}); - soundProcess.waitForFinished(); - QStringList outputDeviceNameList = QString(soundProcess.readAllStandardOutput()).split("'"); - - if(outputDeviceNameList.length() == 3) { - QString outputDeviceName = outputDeviceNameList[1]; - soundProcess.execute("amixer", {"sset", outputDeviceName, QString::number(volume * 100, 'f', 0) + "%"}); - } - else { - qDebug() << "[WARNING][SoundPlayer] Could not determine output device to set volume"; + if(!this->_setSoundVolume(volume)) return Error; - } - - this->soundEffect->setVolume(1); -#else - this->soundEffect->setVolume(volume); -#endif // load this->soundEffect->setSource(this->soundFiles[sound]["path"].toString()); @@ -145,3 +124,89 @@ ScStwSoundPlayer::PlayResult ScStwSoundPlayer::waitForSoundFinish(double *timeOf bool ScStwSoundPlayer::isPlaying() { return this->soundEffect->isPlaying(); } + +#ifdef ScStwLibraries_Raspi +void ScStwSoundPlayer::_initializeSondEffect() { + this->_audioOutputDevice = nullptr; + for(QAudioDeviceInfo info : QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) { + qDebug() << info.deviceName(); + if(info.deviceName().contains("Headphones")) + this->_audioOutputDevice = new QAudioDeviceInfo(info); + } + + if(this->_audioOutputDevice == nullptr) + this->_audioOutputDevice = new QAudioDeviceInfo(QAudioDeviceInfo::defaultOutputDevice()); + + this->soundEffect = new QSoundEffect(*this->_audioOutputDevice, this); + this->soundEffect->setLoopCount(1); +} +#else +void ScStwSoundPlayer::_initializeSondEffect() { + this->_audioOutputDevice = new QAudioDeviceInfo(QAudioDeviceInfo::defaultOutputDevice()); + this->soundEffect = new QSoundEffect(*this->_audioOutputDevice, this); + this->soundEffect->setLoopCount(1); +} +#endif + +#ifdef ScStwLibraries_Raspi +bool ScStwSoundPlayer::_setSoundVolume(double volume) { + + QString cardName = this->_audioOutputDevice->deviceName(); + QStringRef shortCardName = cardName.midRef(cardName.indexOf(QLatin1String("="), 0) + 1); + + int cardIndex = snd_card_get_index(shortCardName.toLocal8Bit().constData()); + QString soundDevice = QString(QLatin1String("hw:%1")).arg(cardIndex); + qDebug() << "[INFO][SoundPlayer] Using audio device: " << soundDevice; + + long min, max; + snd_mixer_t *handle; + snd_mixer_selem_id_t *sid; + snd_mixer_elem_t *elem; + + if(snd_mixer_open(&handle, 0) < 0) { + qDebug() << "[ERROR][SoundPlayer] Could not open mixer"; + return false; + } + if(snd_mixer_selem_register(handle, NULL, NULL) < 0) { + qDebug() << "[ERROR][SoundPlayer] Could not register selem"; + return false; + } + if(snd_mixer_attach(handle, soundDevice.toStdString().c_str()) < 0) { + qDebug() << "[ERROR][SoundPlayer] Could not attach mixer"; + return false; + } + if(snd_mixer_load(handle) < 0) { + qDebug() << "[ERROR][SoundPlayer] Could not load mixer"; + return false; + } + + // set volume for all channels + snd_mixer_selem_id_alloca(&sid); + bool success = false; + for (elem = snd_mixer_first_elem(handle); elem; elem = snd_mixer_elem_next(elem)) { + snd_mixer_selem_get_id(elem, sid); + if (!snd_mixer_selem_is_active(elem)) + continue; + + elem = snd_mixer_find_selem(handle, sid); + if(!elem) + continue; + + snd_mixer_selem_get_playback_volume_range(elem, &min, &max); + snd_mixer_selem_set_playback_volume_all(elem, min + (volume) * (max - min)); + + success = true; + } + + snd_mixer_close(handle); + + this->soundEffect->setVolume(1); + + return success; +} +#else +bool ScStwSoundPlayer::_setSoundVolume(double volume) { + this->soundEffect->setVolume(volume); + return true; +} +#endif