diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp index c09daf112..c679f4167 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp @@ -1,11 +1,13 @@ // Stub GTest smoke test for coordTrans #include -TEST(CoordTransSmokeTest, StubTest) { - EXPECT_TRUE(true); +TEST(CoordTransSmokeTest, StubTest) +{ + EXPECT_TRUE(true); } -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} \ No newline at end of file +int main(int argc, char **argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp index bf4070736..2a42c5ab4 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp @@ -3,12 +3,10 @@ class CoordTransSmokeTest : public QObject { - Q_OBJECT + Q_OBJECT private slots: - void stubTest() { - QVERIFY(true); - } + void stubTest() { QVERIFY(true); } }; -QTEST_APPLESS_MAIN(CoordTransSmokeTest) \ No newline at end of file +QTEST_APPLESS_MAIN(CoordTransSmokeTest) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h index 5ceaa3b4c..ae808883d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h @@ -8,12 +8,14 @@ #include // Minimal stub to satisfy linker requirements -namespace LtsCoordTrans { - // Placeholder types - struct UtmCoordinate { - static UtmCoordinate fromMgrs(const QString&) { return UtmCoordinate(); } - QPointF geographic() const { return QPointF(); } - }; +namespace LtsCoordTrans +{ + // Placeholder types + struct UtmCoordinate + { + static UtmCoordinate fromMgrs(const QString &) { return UtmCoordinate(); } + QPointF geographic() const { return QPointF(); } + }; } -#endif // MOCK_COORD_TRANS_H \ No newline at end of file +#endif // MOCK_COORD_TRANS_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp index bf3d02b6e..17e567c64 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp @@ -9,110 +9,108 @@ #include #include -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { - QCoreApplication a(argc, argv); + QCoreApplication a(argc, argv); - const QStringList args(a.arguments()); + const QStringList args(a.arguments()); - if (args.count() != 3) + if (args.count() != 3) + { + printf("usage: %s \n", args.at(0).toStdString().c_str()); + return -1; + } + + const QString currentSrcDir(a.arguments().at(1)); + + const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2))); + QFile f(appsJsonFilePath); + + if (!f.open(QFile::ReadOnly)) + { + printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(), f.errorString().toStdString().c_str()); + return -2; + } + + printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str()); + + QStringList lastErrors; + QStringList dummy1; + QString dummy2; + LtsAppDescriptor::AppDescriptionVector adv = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2); + + if (!lastErrors.isEmpty()) + { + printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", + appsJsonFilePath.toStdString().c_str(), + lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str()); + return 1; + } + + QFileInfoList guiPluginFiles; + QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories); + + while (it.hasNext()) + { + QString filename(it.next()); + QFileInfo file(filename); + + if (file.isDir()) + continue; + + if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive)) + guiPluginFiles.append(file); + } + + QStringList filenames; + filenames.reserve(guiPluginFiles.size()); + for (const QFileInfo &fi : std::as_const(guiPluginFiles)) + { + filenames += fi.absoluteFilePath(); + } + + QStringList guiPluginIIDs; + for (const QFileInfo &fi : std::as_const(guiPluginFiles)) + { + QFile f2(fi.absoluteFilePath()); + + if (!f2.open(QFile::ReadOnly)) + continue; + + QTextStream ts(&f2); + while (!ts.atEnd()) { - printf("usage: %s \n", args.at(0).toStdString().c_str()); - return -1; - } + QString line(ts.readLine().trimmed().simplified()); + static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA")); - const QString currentSrcDir(a.arguments().at(1)); - - const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2))); - QFile f(appsJsonFilePath); - - if (!f.open(QFile::ReadOnly)) - { - printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(), - f.errorString().toStdString().c_str()); - return -2; - } - - printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str()); - - QStringList lastErrors; - QStringList dummy1; - QString dummy2; - LtsAppDescriptor::AppDescriptionVector adv = - LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2); - - if (!lastErrors.isEmpty()) - { - printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", appsJsonFilePath.toStdString().c_str(), - lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str()); - return 1; - } - - QFileInfoList guiPluginFiles; - QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories); - - while (it.hasNext()) - { - QString filename(it.next()); - QFileInfo file(filename); - - if (file.isDir()) - continue; - - if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive)) - guiPluginFiles.append(file); - } - - QStringList filenames; - filenames.reserve(guiPluginFiles.size()); - for (const QFileInfo& fi : std::as_const(guiPluginFiles)) - { - filenames += fi.absoluteFilePath(); - } - - QStringList guiPluginIIDs; - for (const QFileInfo& fi : std::as_const(guiPluginFiles)) - { - QFile f2(fi.absoluteFilePath()); - - if (!f2.open(QFile::ReadOnly)) - continue; - - QTextStream ts(&f2); - while (!ts.atEnd()) + if (line.contains(iidIdentifier)) + { + QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))")); + QRegularExpressionMatch match = re.match(line); + if (match.hasMatch()) { - QString line(ts.readLine().trimmed().simplified()); - static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA")); + QString matched = match.captured(0); - if (line.contains(iidIdentifier)) - { - QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))")); - QRegularExpressionMatch match = re.match(line); - if (match.hasMatch()) - { - QString matched = match.captured(0); - - guiPluginIIDs += matched; - } - break; - } + guiPluginIIDs += matched; } + break; + } } + } - bool ok = true; + bool ok = true; - for (const LtsAppDescriptor::AppDescription& appdesc : std::as_const(adv)) + for (const LtsAppDescriptor::AppDescription &appdesc : std::as_const(adv)) + { + for (const LtsAppDescriptor::PluginInfo &pi : std::as_const(appdesc.pluginInfos)) { - for (const LtsAppDescriptor::PluginInfo& pi : std::as_const(appdesc.pluginInfos)) - { - if (!guiPluginIIDs.contains(pi.iid)) - { - printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n", - appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str()); - ok = false; - } - } + if (!guiPluginIIDs.contains(pi.iid)) + { + printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n", appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str()); + ok = false; + } } + } - return !ok; + return !ok; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp index 31ec47a54..9e97b3ff6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp @@ -11,20 +11,20 @@ namespace LtsAppDescriptor { -static void addOptionToPlugin(PluginInfo& pluginInfo, const PluginInfo::Flag& flag) -{ + static void addOptionToPlugin(PluginInfo &pluginInfo, const PluginInfo::Flag &flag) + { pluginInfo.flags |= flag; -} + } -static void addOptionToPlugin(QVector& pluginInfos, const PluginInfo::Flag& flag, const QString& pluginName) -{ - for (PluginInfo& pi : pluginInfos) + static void addOptionToPlugin(QVector &pluginInfos, const PluginInfo::Flag &flag, const QString &pluginName) + { + for (PluginInfo &pi : pluginInfos) { - if (pi.iid == pluginName) - { - addOptionToPlugin(pi, flag); - return; - } + if (pi.iid == pluginName) + { + addOptionToPlugin(pi, flag); + return; + } } PluginInfo pi; @@ -32,74 +32,78 @@ static void addOptionToPlugin(QVector& pluginInfos, const PluginInfo pi.type = PluginInfo::PluginType::GUI; addOptionToPlugin(pi, flag); pluginInfos.append(pi); -} + } -static bool addOptionsToPlugin(AppDescription& appDesc, const QString& optionIdentifier, - const QStringList& ignoredPlugins, const QJsonObject& optionsObject, - const PluginInfo::Flag flag, QStringList& lastErrors, bool atLeastOnePluginNeeded) -{ + static bool addOptionsToPlugin(AppDescription &appDesc, + const QString &optionIdentifier, + const QStringList &ignoredPlugins, + const QJsonObject &optionsObject, + const PluginInfo::Flag flag, + QStringList &lastErrors, + bool atLeastOnePluginNeeded) + { bool hasPlugins = false; auto optionsObjectIt = optionsObject.constFind(optionIdentifier); if (optionsObjectIt != optionsObject.constEnd()) { - const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray()); + const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray()); - for (const auto& pluginElem : plugins) + for (const auto &pluginElem : plugins) + { + const QString pluginName = pluginElem.toString(); + if (!ignoredPlugins.contains(pluginName)) { - const QString pluginName = pluginElem.toString(); - if (!ignoredPlugins.contains(pluginName)) - { - addOptionToPlugin(appDesc.pluginInfos, flag, pluginName); - hasPlugins = true; - } + addOptionToPlugin(appDesc.pluginInfos, flag, pluginName); + hasPlugins = true; } + } } if (atLeastOnePluginNeeded && !hasPlugins) { - lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'") - .arg(optionIdentifier, appDesc.appName)); - return false; + lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'").arg(optionIdentifier, appDesc.appName)); + return false; } return true; -} + } -App LtsAppDescriptor::appFromInteger(int i) -{ + App LtsAppDescriptor::appFromInteger(int i) + { switch (i) { - case int(App::Login): - case int(App::Situation): - case int(App::ResourceManager): - case int(App::PlanEditor): - case int(App::BuildingViewer): - case int(App::OC): - case int(App::OrgChart): - case int(App::Scripts): + case int(App::Login): + case int(App::Situation): + case int(App::ResourceManager): + case int(App::PlanEditor): + case int(App::BuildingViewer): + case int(App::OC): + case int(App::OrgChart): + case int(App::Scripts): - case int(App::Snapshot): - case int(App::SystemMonitor): - case int(App::Timeline): - case int(App::SymbolEditor): - case int(App::ScriptEditorEssentialsView): - case int(App::BaseDownloader): - case int(App::OnlineHelp): - case int(App::ThpSituationReplay): - case int(App::SituationTablet): - case int(App::SilhouetteEditor): - case int(App::Shootback): - case int(App::SAAs): - return static_cast(i); + case int(App::Snapshot): + case int(App::SystemMonitor): + case int(App::Timeline): + case int(App::SymbolEditor): + case int(App::ScriptEditorEssentialsView): + case int(App::BaseDownloader): + case int(App::OnlineHelp): + case int(App::ThpSituationReplay): + case int(App::SituationTablet): + case int(App::SilhouetteEditor): + case int(App::Shootback): + case int(App::SAAs): + return static_cast(i); } Q_ASSERT_X(false, "LtsAppDescriptor::appFromInteger", qPrintable(QStringLiteral("Unknown app id: %1").arg(i))); return App::Login; -} + } -AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray& jsonDocument, QStringList& lastErrors, - const QStringList& ignoredPlugins, - QString& loginPluginIid) -{ + AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray &jsonDocument, + QStringList &lastErrors, + const QStringList &ignoredPlugins, + QString &loginPluginIid) + { AppDescriptionVector appDescriptions; @@ -109,31 +113,28 @@ AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray& if (parseError.error != QJsonParseError::NoError) { - int row = 0; - int column = 0; - QChar x = QLatin1Char('\n'); + int row = 0; + int column = 0; + QChar x = QLatin1Char('\n'); - for (int i = 0; i < jsonDocument.size(); i++) + for (int i = 0; i < jsonDocument.size(); i++) + { + if (i == parseError.offset) + break; + + if (QChar::fromLatin1(jsonDocument[i]) == x) { - if (i == parseError.offset) - break; - - if (QChar::fromLatin1(jsonDocument[i]) == x) - { - row++; - column = 0; - } - else - { - column++; - } + row++; + column = 0; } + else + { + column++; + } + } - lastErrors.append(QCoreApplication::tr("JSON: %1
Row: %2, Column: %3") - .arg(parseError.errorString()) - .arg(row + 1) - .arg(column + 1)); - return appDescriptions; + lastErrors.append(QCoreApplication::tr("JSON: %1
Row: %2, Column: %3").arg(parseError.errorString()).arg(row + 1).arg(column + 1)); + return appDescriptions; } const QJsonObject root(appsDoc.object()); @@ -143,64 +144,57 @@ AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray& const QJsonArray appArray(root[QStringLiteral("Apps")].toArray()); if (appArray.isEmpty()) { - lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array")); - return appDescriptions; + lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array")); + return appDescriptions; } - for (const auto& appElem : appArray) + for (const auto &appElem : appArray) { - AppDescription appDesc; - const QJsonObject appObject = appElem.toObject(); + AppDescription appDesc; + const QJsonObject appObject = appElem.toObject(); - appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1)); - if (appDesc.id == App::Login) + appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1)); + if (appDesc.id == App::Login) + { + lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName)); + return appDescriptions; + } + + appDesc.appName = appObject.value(QStringLiteral("AppName")).toString(); + + const QJsonValue valueActive = appObject.value(QStringLiteral("Active")); + if (!valueActive.isUndefined()) + { + if (valueActive.type() != QJsonValue::Type::Bool) { - lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName)); - return appDescriptions; + lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)").arg(appDesc.appName).arg((int)valueActive.type())); + return appDescriptions; } + } + appDesc.active = valueActive.toBool(false); - appDesc.appName = appObject.value(QStringLiteral("AppName")).toString(); + const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible")); + if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool) + { + lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)").arg(appDesc.appName).arg((int)valueVisible.type())); + return appDescriptions; + } + appDesc.visible = valueVisible.toBool(true); - const QJsonValue valueActive = appObject.value(QStringLiteral("Active")); - if (!valueActive.isUndefined()) - { - if (valueActive.type() != QJsonValue::Type::Bool) - { - lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)") - .arg(appDesc.appName) - .arg((int)valueActive.type())); - return appDescriptions; - } - } - appDesc.active = valueActive.toBool(false); + const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray()); + for (const QJsonValue &value : array) + appDesc.requiredAcls.append(value.toInt()); - const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible")); - if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool) - { - lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)") - .arg(appDesc.appName) - .arg((int)valueVisible.type())); - return appDescriptions; - } - appDesc.visible = valueVisible.toBool(true); + const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject()); - const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray()); - for (const QJsonValue& value : array) - appDesc.requiredAcls.append(value.toInt()); + addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject, PluginInfo::Flag::PAYLOAD, lastErrors, false); + addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS, lastErrors, true); + addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN, lastErrors, false); - const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject()); - - addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject, - PluginInfo::Flag::PAYLOAD, lastErrors, false); - addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS, - lastErrors, true); - addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN, - lastErrors, false); - - appDescriptions.append(appDesc); + appDescriptions.append(appDesc); } return appDescriptions; -} + } } // namespace LtsAppDescriptor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h index 6c677bd7f..73638b1ef 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h @@ -14,91 +14,93 @@ #include #ifndef LTSAPPDESCRIPTOR_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSAPPDESCRIPTOR_EXPORT -# else -# if defined(MAKE_LTSAPPDESCRIPTOR_LIB) -# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT -# else -# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSAPPDESCRIPTOR_EXPORT +#else +#if defined(MAKE_LTSAPPDESCRIPTOR_LIB) +#define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT +#else +#define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace LtsAppDescriptor { -enum class App -{ - Login = -1, - Situation = 0, - ResourceManager = 1, - PlanEditor = 2, - BuildingViewer = 3, - OC = 4, - OrgChart = 5, - Scripts = 6, - // merged into Scripts (aka. ScriptEditor) ScriptPlayer = 7, - Snapshot = 8, - SystemMonitor = 9, - Timeline = 10, - SymbolEditor = 11, - ScriptEditorEssentialsView = 12, - BaseDownloader = 13, - OnlineHelp = 14, - ThpSituationReplay = 15, - SituationTablet = 17, - SilhouetteEditor = 18, // for L400P2 - Shootback = 19, // for L400P2 - SAAs = 20, //Schnittstelle Adapter Adler -}; - -struct PluginInfo -{ - enum class PluginType + enum class App { - UNKNOWN, - DATA, - GUI, - GUI_ELEMENT, + Login = -1, + Situation = 0, + ResourceManager = 1, + PlanEditor = 2, + BuildingViewer = 3, + OC = 4, + OrgChart = 5, + Scripts = 6, + // merged into Scripts (aka. ScriptEditor) ScriptPlayer = 7, + Snapshot = 8, + SystemMonitor = 9, + Timeline = 10, + SymbolEditor = 11, + ScriptEditorEssentialsView = 12, + BaseDownloader = 13, + OnlineHelp = 14, + ThpSituationReplay = 15, + SituationTablet = 17, + SilhouetteEditor = 18, // for L400P2 + Shootback = 19, // for L400P2 + SAAs = 20, //Schnittstelle Adapter Adler }; - enum class Flag + struct PluginInfo { - UNKNOWN = 1 << 0, - ACTIONS = 1 << 1, - MAIN = 1 << 2, - PAYLOAD = 1 << 3, - OPTION = 1 << 4, + enum class PluginType + { + UNKNOWN, + DATA, + GUI, + GUI_ELEMENT, + }; + + enum class Flag + { + UNKNOWN = 1 << 0, + ACTIONS = 1 << 1, + MAIN = 1 << 2, + PAYLOAD = 1 << 3, + OPTION = 1 << 4, + }; + + PluginType type = PluginType::UNKNOWN; + QString iid; + QFlags flags; + QStringList options; }; - PluginType type = PluginType::UNKNOWN; - QString iid; - QFlags flags; - QStringList options; -}; + struct AppDescription + { + App id = App::Login; + bool active = false; + bool visible = true; + QString appName; + QVector requiredAcls; + QVector pluginInfos; -struct AppDescription -{ - App id = App::Login; - bool active = false; - bool visible = true; - QString appName; - QVector requiredAcls; - QVector pluginInfos; + bool isValid() const { return !appName.isEmpty(); } + }; - bool isValid() const { return !appName.isEmpty(); } -}; - -typedef QVector AppDescriptionVector; + typedef QVector AppDescriptionVector; -namespace LtsAppDescriptor // TODO: make qobject class singleton - for tr -{ -LTSAPPDESCRIPTOR_EXPORT App appFromInteger(int i); -LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray &jsonDocument, QStringList &lastErrors, - const QStringList &ignoredPlugins, QString &loginPluginIid); -} + namespace LtsAppDescriptor // TODO: make qobject class singleton - for tr + { + LTSAPPDESCRIPTOR_EXPORT App appFromInteger(int i); + LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray &jsonDocument, + QStringList &lastErrors, + const QStringList &ignoredPlugins, + QString &loginPluginIid); + } } // namespace LtsAppDescriptor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp index 746a1826a..fe4a63017 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp @@ -13,524 +13,520 @@ #include #include -LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui_LtsAppDescriptionEditor) +LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget *parent) + : QWidget(parent) + , m_ui(new Ui_LtsAppDescriptionEditor) { - m_ui->setupUi(this); - m_vector = LtsAppDescriptor::AppDescriptionVector(); - m_appIndex = QModelIndex(); - m_pluginIndex = QModelIndex(); - m_fileName = QString(); - m_changed = false; + m_ui->setupUi(this); + m_vector = LtsAppDescriptor::AppDescriptionVector(); + m_appIndex = QModelIndex(); + m_pluginIndex = QModelIndex(); + m_fileName = QString(); + m_changed = false; - connect(m_ui->lvApps, &QListView::clicked, this, &LtsAppDescriptorEditor::onAppsClicked); - connect(m_ui->lvPlugins, &QListView::clicked, this, &LtsAppDescriptorEditor::onPluginsClicked); - connect(m_ui->lePluginType, &QLineEdit::editingFinished, this, &LtsAppDescriptorEditor::pluginTypeChanged); - connect(m_ui->pbAddApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onAppAddClicked); - connect(m_ui->pbAddPlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onPluginAddClicked); - connect(m_ui->pbDeleteApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onAppDeleteClicked); - connect(m_ui->pbDeletePlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onPluginDeletedClicked); - connect(m_ui->pbUpdate, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onUpdateClicked); - connect(m_ui->pbNewPlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onNewpluginClicked); - connect(m_ui->pbNewApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onNewAppClicked); - connect(m_ui->lePluginName, &QLineEdit::textChanged, this, &LtsAppDescriptorEditor::enableNewPlugin); - connect(m_ui->lePluginType, &QLineEdit::textChanged, this, &LtsAppDescriptorEditor::enableNewPlugin); + connect(m_ui->lvApps, &QListView::clicked, this, &LtsAppDescriptorEditor::onAppsClicked); + connect(m_ui->lvPlugins, &QListView::clicked, this, &LtsAppDescriptorEditor::onPluginsClicked); + connect(m_ui->lePluginType, &QLineEdit::editingFinished, this, &LtsAppDescriptorEditor::pluginTypeChanged); + connect(m_ui->pbAddApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onAppAddClicked); + connect(m_ui->pbAddPlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onPluginAddClicked); + connect(m_ui->pbDeleteApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onAppDeleteClicked); + connect(m_ui->pbDeletePlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onPluginDeletedClicked); + connect(m_ui->pbUpdate, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onUpdateClicked); + connect(m_ui->pbNewPlugin, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onNewpluginClicked); + connect(m_ui->pbNewApp, &QPushButton::pressed, this, &LtsAppDescriptorEditor::onNewAppClicked); + connect(m_ui->lePluginName, &QLineEdit::textChanged, this, &LtsAppDescriptorEditor::enableNewPlugin); + connect(m_ui->lePluginType, &QLineEdit::textChanged, this, &LtsAppDescriptorEditor::enableNewPlugin); - m_ui->gbPlugins->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbDeleteApp->setEnabled(false); - m_ui->pbAddPlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->pbNewApp->setEnabled(false); - QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector); + m_ui->gbPlugins->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbDeleteApp->setEnabled(false); + m_ui->pbAddPlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbNewApp->setEnabled(false); + QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector); } LtsAppDescriptorEditor::~LtsAppDescriptorEditor() { - checkSave(); - delete m_ui; + checkSave(); + delete m_ui; } void LtsAppDescriptorEditor::getAppDescriptionVector() { - m_fileName = QFileDialog::getOpenFileName( - this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), - tr("JSON File (*.json)")); - if (m_fileName.isEmpty()) - return; + m_fileName = + QFileDialog::getOpenFileName(this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), tr("JSON File (*.json)")); + if (m_fileName.isEmpty()) + return; - QFile file; - file.setFileName(m_fileName); - file.open(QIODevice::ReadOnly | QIODevice::Text); - QString val(QString::fromUtf8(file.readAll())); - file.close(); + QFile file; + file.setFileName(m_fileName); + file.open(QIODevice::ReadOnly | QIODevice::Text); + QString val(QString::fromUtf8(file.readAll())); + file.close(); - QStringList errors; - m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors); + QStringList errors; + m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors); - updateAppModel(); + updateAppModel(); } -void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex& index) +void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex &index) { - m_ui->gbPlugins->setEnabled(true); - m_ui->pbDeleteApp->setEnabled(true); - m_ui->pbAddPlugin->setEnabled(true); - m_ui->pbNewApp->setEnabled(true); - m_appIndex = index; + m_ui->gbPlugins->setEnabled(true); + m_ui->pbDeleteApp->setEnabled(true); + m_ui->pbAddPlugin->setEnabled(true); + m_ui->pbNewApp->setEnabled(true); + m_appIndex = index; - QStringList pluginList; - Q_FOREACH (const LtsAppDescriptor::PluginInfo& reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins) - { - LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type; - QString type; - if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) - type = QLatin1String("data"); - else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) - type = QLatin1String("gui"); - else - type = QLatin1String("unknown"); - - if (type == QLatin1String("data")) - pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid); - else - { - QString strFlags; - QFlags flags = reqPlugin.flags; - - bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); - if (actionsFlag) - strFlags.append(QLatin1String("actions ")); - bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); - if (mainFlag) - strFlags.append(QLatin1String("main ")); - bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); - if (payloadFlag) - strFlags.append(QLatin1String("payload ")); - bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION); - if (optionalFlag) - strFlags.append(QLatin1String("optional ")); - - pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags + - QLatin1String("]")); - } - } - updatePluginModel(pluginList); - - m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active); - m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName); -} - -void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex& index) -{ - m_pluginIndex = index; - m_ui->pbDeletePlugin->setEnabled(true); - m_ui->pbUpdate->setEnabled(true); - m_ui->pbNewPlugin->setEnabled(true); - - const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row()); - QString pluginName = plugin.iid; - m_ui->lePluginName->setText(pluginName); - - LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type; + QStringList pluginList; + Q_FOREACH (const LtsAppDescriptor::PluginInfo &reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins) + { + LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type; QString type; if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) - type = QLatin1String("data"); + type = QLatin1String("data"); else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) - type = QLatin1String("gui"); + type = QLatin1String("gui"); else - type = QLatin1String("unknown"); - m_ui->lePluginType->setText(type); + type = QLatin1String("unknown"); - if (type == QLatin1String("gui")) - { - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - - QFlags flags = plugin.flags; - bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); - m_ui->chbActions->setChecked(actionsFlag); - bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); - m_ui->chbMain->setChecked(mainFlag); - bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); - m_ui->chbPayload->setChecked(payloadFlag); - } + if (type == QLatin1String("data")) + pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid); else { - m_ui->chbActions->setChecked(false); - m_ui->chbActions->setEnabled(false); - m_ui->chbMain->setChecked(false); - m_ui->chbMain->setEnabled(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbPayload->setEnabled(false); + QString strFlags; + QFlags flags = reqPlugin.flags; + + bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); + if (actionsFlag) + strFlags.append(QLatin1String("actions ")); + bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); + if (mainFlag) + strFlags.append(QLatin1String("main ")); + bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); + if (payloadFlag) + strFlags.append(QLatin1String("payload ")); + bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION); + if (optionalFlag) + strFlags.append(QLatin1String("optional ")); + + pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags + QLatin1String("]")); } + } + updatePluginModel(pluginList); + + m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active); + m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName); +} + +void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex &index) +{ + m_pluginIndex = index; + m_ui->pbDeletePlugin->setEnabled(true); + m_ui->pbUpdate->setEnabled(true); + m_ui->pbNewPlugin->setEnabled(true); + + const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row()); + QString pluginName = plugin.iid; + m_ui->lePluginName->setText(pluginName); + + LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type; + QString type; + if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) + type = QLatin1String("data"); + else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) + type = QLatin1String("gui"); + else + type = QLatin1String("unknown"); + m_ui->lePluginType->setText(type); + + if (type == QLatin1String("gui")) + { + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + + QFlags flags = plugin.flags; + bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); + m_ui->chbActions->setChecked(actionsFlag); + bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); + m_ui->chbMain->setChecked(mainFlag); + bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); + m_ui->chbPayload->setChecked(payloadFlag); + } + else + { + m_ui->chbActions->setChecked(false); + m_ui->chbActions->setEnabled(false); + m_ui->chbMain->setChecked(false); + m_ui->chbMain->setEnabled(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbPayload->setEnabled(false); + } } void LtsAppDescriptorEditor::pluginTypeChanged() { - if (m_ui->lePluginType->text().isEmpty()) - return; + if (m_ui->lePluginType->text().isEmpty()) + return; - if (m_ui->lePluginType->text() == QLatin1String("gui")) - { - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - } - else if (m_ui->lePluginType->text() == QLatin1String("data")) - { - m_ui->chbActions->setChecked(false); - m_ui->chbActions->setEnabled(false); - m_ui->chbMain->setChecked(false); - m_ui->chbMain->setEnabled(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbPayload->setEnabled(false); - } - else - { - QMessageBox msgBox(QMessageBox::Information, tr("Error"), - tr("Plugin Type must either be \"gui\" or \"data\".")); - msgBox.exec(); - m_ui->lePluginType->setText(QString()); - } + if (m_ui->lePluginType->text() == QLatin1String("gui")) + { + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + } + else if (m_ui->lePluginType->text() == QLatin1String("data")) + { + m_ui->chbActions->setChecked(false); + m_ui->chbActions->setEnabled(false); + m_ui->chbMain->setChecked(false); + m_ui->chbMain->setEnabled(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbPayload->setEnabled(false); + } + else + { + QMessageBox msgBox(QMessageBox::Information, tr("Error"), tr("Plugin Type must either be \"gui\" or \"data\".")); + msgBox.exec(); + m_ui->lePluginType->setText(QString()); + } } void LtsAppDescriptorEditor::onAppAddClicked() { - m_changed = true; + m_changed = true; - if (m_ui->leAppName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The App needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->leAppName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The App needs to have a name.")); + msgBox.exec(); + return; + } - QStringList appList; - Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector) - { - appList << appDesc.appName; - } + QStringList appList; + Q_FOREACH (const LtsAppDescriptor::AppDescription &appDesc, m_vector) + { + appList << appDesc.appName; + } - if (appList.contains(m_ui->leAppName->text(), Qt::CaseInsensitive)) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), - tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text())); - msgBox.exec(); - return; - } + if (appList.contains(m_ui->leAppName->text(), Qt::CaseInsensitive)) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text())); + msgBox.exec(); + return; + } - LtsAppDescriptor::AppDescription newApp; - newApp.appName = m_ui->leAppName->text(); - newApp.active = m_ui->chbAppActive->isChecked(); - m_vector.append(newApp); + LtsAppDescriptor::AppDescription newApp; + newApp.appName = m_ui->leAppName->text(); + newApp.active = m_ui->chbAppActive->isChecked(); + m_vector.append(newApp); - updateAppModel(); + updateAppModel(); } void LtsAppDescriptorEditor::onPluginAddClicked() { - m_changed = true; + m_changed = true; - if (m_ui->lePluginType->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); - msgBox.exec(); - return; - } - if (m_ui->lePluginName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->lePluginType->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); + msgBox.exec(); + return; + } + if (m_ui->lePluginName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); + msgBox.exec(); + return; + } - QStringList pluginList; - Q_FOREACH (const LtsAppDescriptor::PluginInfo& pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins) - { - pluginList << pluginDesc.iid; - } + QStringList pluginList; + Q_FOREACH (const LtsAppDescriptor::PluginInfo &pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins) + { + pluginList << pluginDesc.iid; + } - if (pluginList.contains(m_ui->lePluginName->text(), Qt::CaseInsensitive)) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), - tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text())); - msgBox.exec(); - return; - } + if (pluginList.contains(m_ui->lePluginName->text(), Qt::CaseInsensitive)) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text())); + msgBox.exec(); + return; + } - LtsAppDescriptor::PluginInfo newPlugin; + LtsAppDescriptor::PluginInfo newPlugin; - newPlugin.iid = m_ui->lePluginName->text(); + newPlugin.iid = m_ui->lePluginName->text(); - if (m_ui->lePluginType->text() == QLatin1String("gui")) - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; - else if (m_ui->lePluginType->text() == QLatin1String("data")) - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; - else - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; + if (m_ui->lePluginType->text() == QLatin1String("gui")) + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; + else if (m_ui->lePluginType->text() == QLatin1String("data")) + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; + else + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; - if (m_ui->chbActions->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; - if (m_ui->chbMain->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; - if (m_ui->chbPayload->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; + if (m_ui->chbActions->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; + if (m_ui->chbMain->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; + if (m_ui->chbPayload->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin); + m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin); - onAppsClicked(m_appIndex); - onNewpluginClicked(); + onAppsClicked(m_appIndex); + onNewpluginClicked(); } void LtsAppDescriptorEditor::onAppDeleteClicked() { - m_changed = true; + m_changed = true; - if (!m_appIndex.isValid()) - return; + if (!m_appIndex.isValid()) + return; - QMessageBox msgBox(tr("Warning"), - tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()), - QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); + QMessageBox msgBox(tr("Warning"), + tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()), + QMessageBox::Warning, + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, + QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::No) - return; + if (msgBox.exec() == QMessageBox::No) + return; - m_vector.remove(m_appIndex.row()); + m_vector.remove(m_appIndex.row()); - updateAppModel(); + updateAppModel(); } void LtsAppDescriptorEditor::onPluginDeletedClicked() { - m_changed = true; + m_changed = true; - if (!m_pluginIndex.isValid()) - return; + if (!m_pluginIndex.isValid()) + return; - QMessageBox msgBox(tr("Warning"), - tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()), - QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); + QMessageBox msgBox(tr("Warning"), + tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()), + QMessageBox::Warning, + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, + QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::No) - return; + if (msgBox.exec() == QMessageBox::No) + return; - m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row()); - m_pluginIndex = QModelIndex(); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); + m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row()); + m_pluginIndex = QModelIndex(); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); - onAppsClicked(m_appIndex); + onAppsClicked(m_appIndex); } void LtsAppDescriptorEditor::onUpdateClicked() { - m_changed = true; + m_changed = true; - if (m_ui->lePluginType->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); - msgBox.exec(); - return; - } - if (m_ui->lePluginName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->lePluginType->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); + msgBox.exec(); + return; + } + if (m_ui->lePluginName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); + msgBox.exec(); + return; + } - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text(); + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text(); - if (m_ui->lePluginType->text() == QLatin1String("gui")) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = - LtsAppDescriptor::PluginInfo::PluginType::GUI; - else if (m_ui->lePluginType->text() == QLatin1String("data")) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = - LtsAppDescriptor::PluginInfo::PluginType::DATA; - else - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = - LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; + if (m_ui->lePluginType->text() == QLatin1String("gui")) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::GUI; + else if (m_ui->lePluginType->text() == QLatin1String("data")) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::DATA; + else + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags = - QFlags(); + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags = QFlags(); - if (m_ui->chbActions->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= - LtsAppDescriptor::PluginInfo::Flag::ACTIONS; - if (m_ui->chbMain->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= - LtsAppDescriptor::PluginInfo::Flag::MAIN; - if (m_ui->chbPayload->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= - LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; + if (m_ui->chbActions->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; + if (m_ui->chbMain->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; + if (m_ui->chbPayload->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - onAppsClicked(m_appIndex); - onNewpluginClicked(); + onAppsClicked(m_appIndex); + onNewpluginClicked(); } void LtsAppDescriptorEditor::onNewpluginClicked() { - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); - if (m_pluginIndex.isValid()) - m_ui->lvPlugins->selectionModel()->select(m_pluginIndex, QItemSelectionModel::Deselect); - m_pluginIndex = QModelIndex(); + if (m_pluginIndex.isValid()) + m_ui->lvPlugins->selectionModel()->select(m_pluginIndex, QItemSelectionModel::Deselect); + m_pluginIndex = QModelIndex(); } void LtsAppDescriptorEditor::onNewAppClicked() { - updatePluginModel(QStringList()); + updatePluginModel(QStringList()); - m_ui->gbPlugins->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbDeleteApp->setEnabled(false); - m_ui->pbAddPlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->leAppName->setText(QString()); - m_ui->chbAppActive->setChecked(false); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->pbNewApp->setEnabled(false); + m_ui->gbPlugins->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbDeleteApp->setEnabled(false); + m_ui->pbAddPlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->leAppName->setText(QString()); + m_ui->chbAppActive->setChecked(false); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->pbNewApp->setEnabled(false); - if (m_appIndex.isValid()) - m_ui->lvApps->selectionModel()->select(m_appIndex, QItemSelectionModel::Deselect); - m_appIndex = QModelIndex(); + if (m_appIndex.isValid()) + m_ui->lvApps->selectionModel()->select(m_appIndex, QItemSelectionModel::Deselect); + m_appIndex = QModelIndex(); } void LtsAppDescriptorEditor::updateAppModel() { - onNewAppClicked(); - QStringList appList; - Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector) - { - appList << appDesc.appName; - } + onNewAppClicked(); + QStringList appList; + Q_FOREACH (const LtsAppDescriptor::AppDescription &appDesc, m_vector) + { + appList << appDesc.appName; + } - if (!m_ui->lvApps->model()) - m_ui->lvApps->setModel(new QStringListModel(this)); - QStringListModel* m = qobject_cast(m_ui->lvApps->model()); - if (!m) - return; - m->setStringList(appList); + if (!m_ui->lvApps->model()) + m_ui->lvApps->setModel(new QStringListModel(this)); + QStringListModel *m = qobject_cast(m_ui->lvApps->model()); + if (!m) + return; + m->setStringList(appList); } -void LtsAppDescriptorEditor::updatePluginModel(const QStringList& list) +void LtsAppDescriptorEditor::updatePluginModel(const QStringList &list) { - if (!m_ui->lvPlugins->model()) - m_ui->lvPlugins->setModel(new QStringListModel(this)); - QStringListModel* m = qobject_cast(m_ui->lvPlugins->model()); - if (!m) - return; - m->setStringList(list); + if (!m_ui->lvPlugins->model()) + m_ui->lvPlugins->setModel(new QStringListModel(this)); + QStringListModel *m = qobject_cast(m_ui->lvPlugins->model()); + if (!m) + return; + m->setStringList(list); } void LtsAppDescriptorEditor::checkSave() { - if (m_changed) - { - QMessageBox msgBox(tr("Warning"), tr("The Data has been modified.\nDo you want to save your changes?"), - QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); + if (m_changed) + { + QMessageBox msgBox(tr("Warning"), + tr("The Data has been modified.\nDo you want to save your changes?"), + QMessageBox::Warning, + QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, + QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::Yes) - onSaveAsClicked(); - } + if (msgBox.exec() == QMessageBox::Yes) + onSaveAsClicked(); + } } void LtsAppDescriptorEditor::onSaveAsClicked() { - QString fileName = QFileDialog::getSaveFileName( - this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), - tr("JSON File (*.json)")); - if (fileName.isEmpty()) - return; + QString fileName = + QFileDialog::getSaveFileName(this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), tr("JSON File (*.json)")); + if (fileName.isEmpty()) + return; - QByteArray jsonByteArray; - jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector); + QByteArray jsonByteArray; + jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector); - QFile f(fileName); - f.open(QIODevice::WriteOnly); - f.write(jsonByteArray); - f.close(); + QFile f(fileName); + f.open(QIODevice::WriteOnly); + f.write(jsonByteArray); + f.close(); - m_changed = false; + m_changed = false; - QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); - msgBox.exec(); + QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); + msgBox.exec(); } void LtsAppDescriptorEditor::onSaveClicked() { - const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector)); + const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector)); - QFile f(m_fileName); - f.open(QIODevice::WriteOnly); - f.write(jsonByteArray); - f.close(); + QFile f(m_fileName); + f.open(QIODevice::WriteOnly); + f.write(jsonByteArray); + f.close(); - m_changed = false; + m_changed = false; - QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); - msgBox.exec(); + QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); + msgBox.exec(); } void LtsAppDescriptorEditor::onOpenClicked() { - checkSave(); - getAppDescriptionVector(); - m_changed = false; + checkSave(); + getAppDescriptionVector(); + m_changed = false; } void LtsAppDescriptorEditor::onNewClicked() { - checkSave(); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbAppActive->setChecked(false); - m_ui->leAppName->setText(QString()); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->gbPlugins->setEnabled(false); + checkSave(); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbAppActive->setChecked(false); + m_ui->leAppName->setText(QString()); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->gbPlugins->setEnabled(false); - m_vector = LtsAppDescriptor::AppDescriptionVector(); + m_vector = LtsAppDescriptor::AppDescriptionVector(); - updateAppModel(); - updatePluginModel(QStringList()); + updateAppModel(); + updatePluginModel(QStringList()); } void LtsAppDescriptorEditor::enableNewPlugin() { - m_ui->pbNewPlugin->setEnabled(true); + m_ui->pbNewPlugin->setEnabled(true); } void LtsAppDescriptorEditor::onQuitClicked() { - QApplication::quit(); + QApplication::quit(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h index 3a416014b..12f5666ad 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h @@ -21,45 +21,45 @@ class Ui_LtsAppDescriptionEditor; class LTSAPPDESCRIPTOREDITOR_EXPORT LtsAppDescriptorEditor : public QWidget { - Q_OBJECT + Q_OBJECT - public: - explicit LtsAppDescriptorEditor(QWidget* parent = 0); - ~LtsAppDescriptorEditor(); +public: + explicit LtsAppDescriptorEditor(QWidget *parent = 0); + ~LtsAppDescriptorEditor(); - private: - Ui_LtsAppDescriptionEditor* m_ui; - LtsAppDescriptor::AppDescriptionVector m_vector; - QModelIndex m_appIndex; - QModelIndex m_pluginIndex; +private: + Ui_LtsAppDescriptionEditor *m_ui; + LtsAppDescriptor::AppDescriptionVector m_vector; + QModelIndex m_appIndex; + QModelIndex m_pluginIndex; - QString m_fileName; + QString m_fileName; - bool m_changed; + bool m_changed; - void getAppDescriptionVector(); - void setupMainWindow(); - void updateAppModel(); - void updatePluginModel(const QStringList& list); - void checkSave(); + void getAppDescriptionVector(); + void setupMainWindow(); + void updateAppModel(); + void updatePluginModel(const QStringList &list); + void checkSave(); - private slots: - void onAppsClicked(const QModelIndex& index); - void onPluginsClicked(const QModelIndex& index); - void pluginTypeChanged(); - void onAppAddClicked(); - void onPluginAddClicked(); - void onAppDeleteClicked(); - void onPluginDeletedClicked(); - void onUpdateClicked(); - void onNewpluginClicked(); - void onNewAppClicked(); - void enableNewPlugin(); +private slots: + void onAppsClicked(const QModelIndex &index); + void onPluginsClicked(const QModelIndex &index); + void pluginTypeChanged(); + void onAppAddClicked(); + void onPluginAddClicked(); + void onAppDeleteClicked(); + void onPluginDeletedClicked(); + void onUpdateClicked(); + void onNewpluginClicked(); + void onNewAppClicked(); + void enableNewPlugin(); - public slots: - void onSaveClicked(); - void onSaveAsClicked(); - void onOpenClicked(); - void onNewClicked(); - void onQuitClicked(); +public slots: + void onSaveClicked(); + void onSaveAsClicked(); + void onOpenClicked(); + void onNewClicked(); + void onQuitClicked(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp index 7f86c565a..29da67bfc 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp @@ -7,49 +7,49 @@ #include #include -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { - QApplication a(argc, argv); + QApplication a(argc, argv); - QMainWindow* mainWindow = new QMainWindow(); - QMenu* fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File")); + QMainWindow *mainWindow = new QMainWindow(); + QMenu *fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File")); - QAction* openAct = new QAction(QObject::tr("&Open"), mainWindow); - openAct->setShortcuts(QKeySequence::Open); - openAct->setStatusTip(QObject::tr("Open an existing file")); - fileMenu->addAction(openAct); + QAction *openAct = new QAction(QObject::tr("&Open"), mainWindow); + openAct->setShortcuts(QKeySequence::Open); + openAct->setStatusTip(QObject::tr("Open an existing file")); + fileMenu->addAction(openAct); - QAction* newAct = new QAction(QObject::tr("&New"), mainWindow); - newAct->setShortcuts(QKeySequence::New); - newAct->setStatusTip(QObject::tr("Create a new App")); - fileMenu->addAction(newAct); + QAction *newAct = new QAction(QObject::tr("&New"), mainWindow); + newAct->setShortcuts(QKeySequence::New); + newAct->setStatusTip(QObject::tr("Create a new App")); + fileMenu->addAction(newAct); - QAction* saveAct = new QAction(QObject::tr("&Save"), mainWindow); - saveAct->setShortcuts(QKeySequence::Save); - saveAct->setStatusTip(QObject::tr("Save modified file")); - fileMenu->addAction(saveAct); + QAction *saveAct = new QAction(QObject::tr("&Save"), mainWindow); + saveAct->setShortcuts(QKeySequence::Save); + saveAct->setStatusTip(QObject::tr("Save modified file")); + fileMenu->addAction(saveAct); - QAction* saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow); - saveAsAct->setShortcuts(QKeySequence::SaveAs); - saveAsAct->setStatusTip(QObject::tr("Save modified file as")); - fileMenu->addAction(saveAsAct); + QAction *saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow); + saveAsAct->setShortcuts(QKeySequence::SaveAs); + saveAsAct->setStatusTip(QObject::tr("Save modified file as")); + fileMenu->addAction(saveAsAct); - QAction* quitAct = new QAction(QObject::tr("&Quit"), mainWindow); - quitAct->setShortcuts(QKeySequence::Quit); - quitAct->setStatusTip(QObject::tr("Quit the Application")); - fileMenu->addAction(quitAct); + QAction *quitAct = new QAction(QObject::tr("&Quit"), mainWindow); + quitAct->setShortcuts(QKeySequence::Quit); + quitAct->setStatusTip(QObject::tr("Quit the Application")); + fileMenu->addAction(quitAct); - LtsAppDescriptorEditor* editor = new LtsAppDescriptorEditor(mainWindow); - mainWindow->setCentralWidget(editor); - QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked); - QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked); - QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked); - QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked); - QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked); + LtsAppDescriptorEditor *editor = new LtsAppDescriptorEditor(mainWindow); + mainWindow->setCentralWidget(editor); + QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked); + QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked); + QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked); + QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked); + QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked); - mainWindow->show(); + mainWindow->show(); - int ret = a.exec(); - delete mainWindow; - return ret; + int ret = a.exec(); + delete mainWindow; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp index 6f12713a7..f5a47362f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp @@ -10,171 +10,166 @@ namespace LtsCommandLineParser { -static constexpr int s_maxDomainId = 232; + static constexpr int s_maxDomainId = 232; -LtsCommandLineParser::LtsCommandLineParser(ProvideCommandLineParameterOptions opts) - : QCommandLineParser(), m_enabledOptions(opts) -{ + LtsCommandLineParser::LtsCommandLineParser(ProvideCommandLineParameterOptions opts) + : QCommandLineParser() + , m_enabledOptions(opts) + { if (NGL::isAppInBuildBasePath() || m_enabledOptions.testFlag(CreateDomainIdFromIp)) { - const QList addresses = QNetworkInterface::allAddresses(); - for (const QHostAddress& address : addresses) - { - if (address.isLoopback() || address.isNull()) - continue; - if (address.protocol() != QAbstractSocket::IPv4Protocol) - continue; + const QList addresses = QNetworkInterface::allAddresses(); + for (const QHostAddress &address : addresses) + { + if (address.isLoopback() || address.isNull()) + continue; + if (address.protocol() != QAbstractSocket::IPv4Protocol) + continue; - m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232; - if (m_generatedDomainId == 0) - m_generatedDomainId = s_maxDomainId; - break; - } + m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232; + if (m_generatedDomainId == 0) + m_generatedDomainId = s_maxDomainId; + break; + } } if (m_enabledOptions.testFlag(ExerciseId)) - addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")}, - QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"), - QStringLiteral("exerciseId"), - QStringLiteral("-1")}); + addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")}, + QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"), + QStringLiteral("exerciseId"), + QStringLiteral("-1")}); if (m_enabledOptions.testFlag(DomainId)) - addOption({{QStringLiteral("d"), QStringLiteral("domainid")}, - QStringLiteral("Default: ") + QString::number(m_generatedDomainId), - QStringLiteral("domainId"), - QString::number(m_generatedDomainId)}); + addOption({{QStringLiteral("d"), QStringLiteral("domainid")}, + QStringLiteral("Default: ") + QString::number(m_generatedDomainId), + QStringLiteral("domainId"), + QString::number(m_generatedDomainId)}); if (m_enabledOptions.testFlag(CustomConfigFile)) { - const QString cf(NGL::findProjectConfigFile()); - addOption({{QStringLiteral("i"), QStringLiteral("ini")}, - QStringLiteral("Default: ") + cf, - QStringLiteral("filename"), - cf}); + const QString cf(NGL::findProjectConfigFile()); + addOption({{QStringLiteral("i"), QStringLiteral("ini")}, QStringLiteral("Default: ") + cf, QStringLiteral("filename"), cf}); } if (m_enabledOptions.testFlag(TcpConnectionUrl)) { - const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400")); - addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")}, - QStringLiteral("Default: ") + defaultTcpUrl, - QStringLiteral("hostname:port"), - defaultTcpUrl}); + const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400")); + addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")}, QStringLiteral("Default: ") + defaultTcpUrl, QStringLiteral("hostname:port"), defaultTcpUrl}); } addHelpOption(); if (!m_enabledOptions.testFlag(NoVersion)) - addVersionOption(); -} + addVersionOption(); + } -int LtsCommandLineParser::domainId() const -{ + int LtsCommandLineParser::domainId() const + { if (m_domainId == 0 && m_generatedDomainId != 0 && !m_domainIdSetByFunction) { #ifdef WIN32 - fprintf(stdout, - "\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default " - "domainid is %d\n\n", - m_generatedDomainId); + fprintf(stdout, + "\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default " + "domainid is %d\n\n", + m_generatedDomainId); #else - fprintf(stdout, - "\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - " - "default domainid is %d\e[0m\n\n", - m_generatedDomainId); + fprintf(stdout, + "\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - " + "default domainid is %d\e[0m\n\n", + m_generatedDomainId); #endif - return m_generatedDomainId; + return m_generatedDomainId; } return m_domainId; -} + } -void LtsCommandLineParser::setDomainId(int id) -{ + void LtsCommandLineParser::setDomainId(int id) + { m_domainIdSetByFunction = true; m_domainId = id; -} + } -bool LtsCommandLineParser::iniFileSet() const -{ + bool LtsCommandLineParser::iniFileSet() const + { if (!m_enabledOptions.testFlag(CustomConfigFile)) - return false; + return false; return isSet(QStringLiteral("i")); -} + } -bool LtsCommandLineParser::useTcpConnection() const -{ + bool LtsCommandLineParser::useTcpConnection() const + { if (!m_enabledOptions.testFlag(TcpConnectionUrl)) - return false; + return false; return isSet(QStringLiteral("t")); -} + } -QUrl LtsCommandLineParser::tcpConnectionUrl() const -{ + QUrl LtsCommandLineParser::tcpConnectionUrl() const + { if (!m_enabledOptions.testFlag(TcpConnectionUrl)) - return QUrl(); + return QUrl(); if (!useTcpConnection()) - return QUrl(); + return QUrl(); QString str = value(QStringLiteral("t")); str.replace(QLatin1String("tcpv4_lan"), QLatin1String("tcpv4lan")); QUrl url = QUrl::fromUserInput(str); if (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("file")) - url.setScheme(QStringLiteral("tcpv4lan")); + url.setScheme(QStringLiteral("tcpv4lan")); return url; -} + } -bool LtsCommandLineParser::init(bool bParseHelp) -{ + bool LtsCommandLineParser::init(bool bParseHelp) + { if (!parse(QCoreApplication::arguments())) { - fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText())); - if (!m_unitModuleTestMode) - return false; + fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText())); + if (!m_unitModuleTestMode) + return false; } if (m_enabledOptions.testFlag(ExerciseId)) - m_exerciseId = value(QStringLiteral("e")).toInt(); + m_exerciseId = value(QStringLiteral("e")).toInt(); if (m_enabledOptions.testFlag(DomainId)) - m_domainId = value(QStringLiteral("d")).toInt(); + m_domainId = value(QStringLiteral("d")).toInt(); if (m_enabledOptions.testFlag(CustomConfigFile)) - m_iniFile = value(QStringLiteral("i")); + m_iniFile = value(QStringLiteral("i")); if (bParseHelp && isSet(QStringLiteral("h"))) - showHelp(); + showHelp(); if (!m_unitModuleTestMode && isSet(QStringLiteral("v"))) - showVersion(); + showVersion(); if (!domainIdProvided()) { - const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile; - if (!iniFile.isEmpty()) - { - QSettings s(iniFile, QSettings::IniFormat); - bool bOk; - int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk); - if (bOk && domainId > 0 && domainId <= s_maxDomainId) - m_domainId = domainId; - } + const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile; + if (!iniFile.isEmpty()) + { + QSettings s(iniFile, QSettings::IniFormat); + bool bOk; + int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk); + if (bOk && domainId > 0 && domainId <= s_maxDomainId) + m_domainId = domainId; + } } return true; -} + } -void LtsCommandLineParser::showHelp(int exitCode) -{ + void LtsCommandLineParser::showHelp(int exitCode) + { if (!m_additionalHelpStr.isEmpty()) - fprintf(stdout, "%s", qPrintable(m_additionalHelpStr)); + fprintf(stdout, "%s", qPrintable(m_additionalHelpStr)); QCommandLineParser::showHelp(exitCode); -} + } -bool LtsCommandLineParser::domainIdProvided() const -{ + bool LtsCommandLineParser::domainIdProvided() const + { if (!m_enabledOptions.testFlag(DomainId)) - return false; + return false; return isSet(QStringLiteral("d")); -} + } -bool LtsCommandLineParser::exerciseIdProvided() const -{ + bool LtsCommandLineParser::exerciseIdProvided() const + { if (!m_enabledOptions.testFlag(ExerciseId)) - return false; + return false; return isSet(QStringLiteral("e")); -} + } } // namespace LtsCommandLineParser diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h index 48a348555..f638a29e2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h @@ -10,34 +10,29 @@ class QUrl; namespace LtsCommandLineParser { -class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLineParser -{ + class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLineParser + { public: - enum ProvideCommandLineParameterOptions { - None = 0x0000, - CreateDomainIdFromIp = 0x0001, - DomainId = 0x0002, - ExerciseId = 0x0004, - CustomConfigFile = 0x0008, - TcpConnectionUrl = 0x0010, - NoVersion = 0x0020 + enum ProvideCommandLineParameterOptions + { + None = 0x0000, + CreateDomainIdFromIp = 0x0001, + DomainId = 0x0002, + ExerciseId = 0x0004, + CustomConfigFile = 0x0008, + TcpConnectionUrl = 0x0010, + NoVersion = 0x0020 }; - explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions( - CreateDomainIdFromIp | DomainId | ExerciseId | CustomConfigFile)); + explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions(CreateDomainIdFromIp | DomainId | ExerciseId | + CustomConfigFile)); virtual ~LtsCommandLineParser() = default; int domainId() const; void setDomainId(int id); - int exerciseId() const - { - return m_exerciseId; - } + int exerciseId() const { return m_exerciseId; } - QString iniFile() const - { - return m_iniFile; - } + QString iniFile() const { return m_iniFile; } bool iniFileSet() const; bool useTcpConnection() const; @@ -48,10 +43,7 @@ class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLinePars bool domainIdProvided() const; bool exerciseIdProvided() const; - void setUnitModuleTestMode(bool onOff) - { - m_unitModuleTestMode = onOff; - } + void setUnitModuleTestMode(bool onOff) { m_unitModuleTestMode = onOff; } protected: QString m_additionalHelpStr; @@ -64,6 +56,6 @@ class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLinePars bool m_domainIdSetByFunction{false}; bool m_unitModuleTestMode{false}; QString m_iniFile; -}; + }; } // namespace LtsCommandLineParser diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp index bb1f4aad7..a6fd4984a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp @@ -5,60 +5,70 @@ #include #include -int main(int argc, char** argv) +int main(int argc, char **argv) { - if (argc < 3 || argc > 5) - { - fprintf(stderr, "Usage: %s []\n", argv[0]); - fprintf(stderr, "Usage: %s -r []\n", argv[0]); - return -1; - } + if (argc < 3 || argc > 5) + { + fprintf(stderr, "Usage: %s []\n", argv[0]); + fprintf(stderr, "Usage: %s -r []\n", argv[0]); + return -1; + } - bool lonLatInRad = false; - double lon = atof(argv[1]); - double lat = atof(argv[2]); - int prec = 5; - if (argc >= 4) + bool lonLatInRad = false; + double lon = atof(argv[1]); + double lat = atof(argv[2]); + int prec = 5; + if (argc >= 4) + { + int precArgId = -1; + if (strcmp(argv[3], "-r") == 0) { - int precArgId = -1; - if (strcmp(argv[3], "-r") == 0) - { - lonLatInRad = true; - if (argc == 5) - precArgId = 4; - } - else - precArgId = 3; - if (precArgId > 0) - prec = atoi(argv[precArgId]); + lonLatInRad = true; + if (argc == 5) + precArgId = 4; } + else + precArgId = 3; + if (precArgId > 0) + prec = atoi(argv[precArgId]); + } - std::string mgrs; + std::string mgrs; - int zone; - bool northp; - double x, y; - try - { - const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat; - const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon; - GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - } - catch (...) - { - fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon); - return -2; - } - std::string part1, part2, part3, part4; - part1 = mgrs.substr(0, 3); - part2 = mgrs.substr(3, 2); - if (prec > 0) - { - part3 = mgrs.substr(5, prec); - part4 = mgrs.substr(5 + prec, prec); - } - fprintf(stdout, "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", lon, lat, part1.c_str(), part2.c_str(), - part3.c_str(), part4.c_str(), zone, x, y, northp ? 'N' : 'S'); - return 0; + int zone; + bool northp; + double x, y; + try + { + const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat; + const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon; + GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + } + catch (...) + { + fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon); + return -2; + } + std::string part1, part2, part3, part4; + part1 = mgrs.substr(0, 3); + part2 = mgrs.substr(3, 2); + if (prec > 0) + { + part3 = mgrs.substr(5, prec); + part4 = mgrs.substr(5 + prec, prec); + } + fprintf(stdout, + "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", + lon, + lat, + part1.c_str(), + part2.c_str(), + part3.c_str(), + part4.c_str(), + zone, + x, + y, + northp ? 'N' : 'S'); + return 0; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp index 419335571..ebcabb72e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp @@ -15,110 +15,108 @@ namespace LtsCoordTrans { -static long s_conversion_counter_MGRS_Forward = 0; -static long s_conversion_counter_MGRS_Reverse = 0; + static long s_conversion_counter_MGRS_Forward = 0; + static long s_conversion_counter_MGRS_Reverse = 0; -static long s_conversion_counter_WGS84_Forward = 0; -static long s_conversion_counter_WGS84_Reverse = 0; + static long s_conversion_counter_WGS84_Forward = 0; + static long s_conversion_counter_WGS84_Reverse = 0; -static long s_conversion_counter_UTMUPS_Forward = 0; -static long s_conversion_counter_UTMUPS_Reverse = 0; + static long s_conversion_counter_UTMUPS_Forward = 0; + static long s_conversion_counter_UTMUPS_Reverse = 0; -inline void incrementCounter(long& counterRef) -{ + inline void incrementCounter(long &counterRef) + { #ifdef LTS_DEBUG ++counterRef; #endif -} + } -static inline std::string cleanupMgrsString(const QString& in) -{ + static inline std::string cleanupMgrsString(const QString &in) + { const QByteArray ba(in.toLatin1()); std::string ret; ret.reserve(ba.size()); for (const char c : ba) { - if (c != ' ') - ret += c; + if (c != ' ') + ret += c; } return ret; -} + } -QString UtmCoordinate::mgrs(int prec, bool withSpaces) const -{ + QString UtmCoordinate::mgrs(int prec, bool withSpaces) const + { if (prec < 0) - prec = 0; + prec = 0; if (prec > 11) - prec = 11; + prec = 11; std::string mgrs; try { - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - incrementCounter(s_conversion_counter_MGRS_Forward); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + incrementCounter(s_conversion_counter_MGRS_Forward); } - catch (const std::exception& e) + catch (const std::exception &e) { - fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what()); - mgrs.clear(); + fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what()); + mgrs.clear(); } QString ret; if (withSpaces && mgrs.size() == static_cast(5 + 2 * prec)) { - const char* ptr = mgrs.c_str(); + const char *ptr = mgrs.c_str(); - ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') + QString::fromLatin1(ptr + 3, 2); - if (prec > 0) - { - ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + QLatin1Char(' ') + - QString::fromLatin1(ptr + 5 + prec, prec); - } + ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') + QString::fromLatin1(ptr + 3, 2); + if (prec > 0) + { + ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + QLatin1Char(' ') + QString::fromLatin1(ptr + 5 + prec, prec); + } } else - ret = QString::fromLatin1(mgrs.c_str(), mgrs.size()); + ret = QString::fromLatin1(mgrs.c_str(), mgrs.size()); return ret; -} + } -QPointF UtmCoordinate::toPoint() const -{ + QPointF UtmCoordinate::toPoint() const + { return {x, y}; -} + } -QPointF UtmCoordinate::geographic(double offsetX, double offsetY) const -{ + QPointF UtmCoordinate::geographic(double offsetX, double offsetY) const + { QPointF ret; try { - GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx()); - incrementCounter(s_conversion_counter_UTMUPS_Reverse); + GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx()); + incrementCounter(s_conversion_counter_UTMUPS_Reverse); } - catch (const std::exception& e) + catch (const std::exception &e) { - fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX, - y + offsetY, e.what()); - ret = QPointF(); + fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX, y + offsetY, e.what()); + ret = QPointF(); } return ret * deg2rad(); -} + } -QPointF UtmCoordinate::geographic(const QPointF& offset) const -{ + QPointF UtmCoordinate::geographic(const QPointF &offset) const + { return geographic(offset.x(), offset.y()); -} + } -QPointF UtmCoordinate::relativeTo(const UtmCoordinate& other) const -{ + QPointF UtmCoordinate::relativeTo(const UtmCoordinate &other) const + { if (zone == other.zone) - return QPointF(x - other.x, y - other.y); + return QPointF(x - other.x, y - other.y); UtmCoordinate otherInMyZone = fromGeographic(other.geographic(), zone); return QPointF(x - otherInMyZone.x, y - otherInMyZone.y); -} + } -UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone) -{ + UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone) + { lon *= rad2deg(); lat *= rad2deg(); @@ -127,81 +125,81 @@ UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone) try { - GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone); - incrementCounter(s_conversion_counter_UTMUPS_Forward); + GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone); + incrementCounter(s_conversion_counter_UTMUPS_Forward); } - catch (const std::exception& e) + catch (const std::exception &e) { - fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what()); - ret = UtmCoordinate(); + fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what()); + ret = UtmCoordinate(); } return ret; -} + } -UtmCoordinate UtmCoordinate::fromGeographic(const QPointF& lonLat, int setZone) -{ + UtmCoordinate UtmCoordinate::fromGeographic(const QPointF &lonLat, int setZone) + { return fromGeographic(lonLat.x(), lonLat.y(), setZone); -} + } -UtmCoordinate UtmCoordinate::fromMgrs(const QString& mgrs) -{ + UtmCoordinate UtmCoordinate::fromMgrs(const QString &mgrs) + { UtmCoordinate utm; try { - int prec; + int prec; - GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true); - incrementCounter(s_conversion_counter_MGRS_Reverse); + GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true); + incrementCounter(s_conversion_counter_MGRS_Reverse); } - catch (const std::exception& e) + catch (const std::exception &e) { - fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what()); - utm = UtmCoordinate(); + fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what()); + utm = UtmCoordinate(); } return utm; -} + } -QString mgrsFromGeographic(double lon, double lat, int prec, bool withSpaces) -{ + QString mgrsFromGeographic(double lon, double lat, int prec, bool withSpaces) + { return UtmCoordinate::fromGeographic(lon, lat, -1).mgrs(prec, withSpaces); -} + } -QPointF geographicFromMgrs(const QString& mgrs) -{ + QPointF geographicFromMgrs(const QString &mgrs) + { return UtmCoordinate::fromMgrs(mgrs).geographic(); -} + } -QVector& staticDefaultSquaresHelper() -{ + QVector &staticDefaultSquaresHelper() + { static QVector s_defaultMgrsSquares; return s_defaultMgrsSquares; -} + } -UtmCoordinate& staticPreferedMgrsSquareHelper() -{ + UtmCoordinate &staticPreferedMgrsSquareHelper() + { static UtmCoordinate s_preferedMgrsSquare; return s_preferedMgrsSquare; -} + } -QVector& staticMgrsSquaresWithOffsetsHelper() -{ + QVector &staticMgrsSquaresWithOffsetsHelper() + { static QVector s_mgrsSquaresWithOffsets; return s_mgrsSquaresWithOffsets; -} + } -QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter) -{ + QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter) + { double lonMin, lonMax, latMin, latMmax; rect_LatLon_radiant.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); LtsCoordTrans::UtmCoordinate basePoint; { - const QPointF centerRad = rect_LatLon_radiant.center(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); - mgrs += QStringLiteral("00000000000000"); + const QPointF centerRad = rect_LatLon_radiant.center(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); + mgrs += QStringLiteral("00000000000000"); - basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); + basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); } const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone)); @@ -215,27 +213,26 @@ QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMet QRectF res = QRectF(topLeft, bottomRight); return res; -} + } -QVector getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares, bool setAsPreferedSquare, - bool setAsSquareWithMargin) -{ + QVector getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin) + { QVector ret = getMgrsSquaresInternal(rect); if (setAsDefaultSquares) - staticDefaultSquaresHelper() = ret; + staticDefaultSquaresHelper() = ret; if (setAsPreferedSquare) - staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center()); + staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center()); if (setAsSquareWithMargin) - staticMgrsSquaresWithOffsetsHelper() = ret; + staticMgrsSquaresWithOffsetsHelper() = ret; return ret; -} + } -QVector getMgrsSquaresInternal(const QRectF& rect) -{ + QVector getMgrsSquaresInternal(const QRectF &rect) + { QVector ret; QVector tmpMgrsSquares; @@ -244,19 +241,19 @@ QVector getMgrsSquaresInternal(const QRectF& rect) bool withInSingleUtmSquare = true; { - const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax)); - const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin)); - withInSingleUtmSquare = upperRight.zone == lowerLeft.zone; + const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax)); + const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin)); + withInSingleUtmSquare = upperRight.zone == lowerLeft.zone; } LtsCoordTrans::UtmCoordinate basePoint; { - QPointF centerRad = rect.center(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); - mgrs += QStringLiteral("00000000000000"); + QPointF centerRad = rect.center(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); + mgrs += QStringLiteral("00000000000000"); - basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); + basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); } const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone)); @@ -268,180 +265,173 @@ QVector getMgrsSquaresInternal(const QRectF& rect) const int increment = withInSingleUtmSquare ? 10000 : 1000; for (double x = 0; x <= maxX + increment; x += increment) { - const double xOfs = std::min(x, maxX); - for (double y = 0; y <= maxY + increment; y += increment) + const double xOfs = std::min(x, maxX); + for (double y = 0; y <= maxY + increment; y += increment) + { + const double yOfs = std::min(y, maxY); + + const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs))); + const QString mgrs(utm.mgrs(0)); + + if (!tmpMgrsSquares.contains(mgrs)) { - const double yOfs = std::min(y, maxY); - - const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs))); - const QString mgrs(utm.mgrs(0)); - - if (!tmpMgrsSquares.contains(mgrs)) - { - tmpMgrsSquares += mgrs; - ret += utm; - } + tmpMgrsSquares += mgrs; + ret += utm; } + } } return ret; -} + } -QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter) -{ + QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter) + { const QVector mainUtms = getMgrsSquaresInternal(geoRect); QStringList mainSquares; mainSquares.reserve(mainUtms.count()); - for (const auto& utm : mainUtms) - mainSquares.append(utm.mgrs(0)); + for (const auto &utm : mainUtms) + mainSquares.append(utm.mgrs(0)); const QRectF rectWithOffset = addMarginToArea(geoRect, offsetMeter); QVector mainUtmsWithOffset = getMgrsSquaresInternal(rectWithOffset); QStringList mainSquaresWithOffset; mainSquaresWithOffset.reserve(mainUtmsWithOffset.count()); - for (const auto& utm : std::as_const(mainUtmsWithOffset)) - mainSquaresWithOffset.append(utm.mgrs(0)); + for (const auto &utm : std::as_const(mainUtmsWithOffset)) + mainSquaresWithOffset.append(utm.mgrs(0)); QStringList surroundingSquares; surroundingSquares.reserve(mainSquaresWithOffset.count()); - for (const auto& mgrs0 : mainSquaresWithOffset) + for (const auto &mgrs0 : mainSquaresWithOffset) { - if (!mainSquares.contains(mgrs0)) - surroundingSquares.append(mgrs0); + if (!mainSquares.contains(mgrs0)) + surroundingSquares.append(mgrs0); } return surroundingSquares; -} + } -QVector defaultMgrsSquareWithOffsets() -{ + QVector defaultMgrsSquareWithOffsets() + { return staticMgrsSquaresWithOffsetsHelper(); -} + } -void setDefaultMgrsSquares(const QVector& squares) -{ + void setDefaultMgrsSquares(const QVector &squares) + { QVector coords; coords.reserve(squares.size()); - for (const QString& s : squares) - coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000")); + for (const QString &s : squares) + coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000")); staticDefaultSquaresHelper() = coords; -} + } -QVector defaultMgrsSquares() -{ + QVector defaultMgrsSquares() + { return staticDefaultSquaresHelper(); -} + } -UtmCoordinate preferedMgrsSquare() -{ + UtmCoordinate preferedMgrsSquare() + { return staticPreferedMgrsSquareHelper(); -} + } -bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut, double& zOut) -{ + bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut) + { lon *= rad2deg(); lat *= rad2deg(); try { - GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut); - incrementCounter(s_conversion_counter_WGS84_Forward); + GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut); + incrementCounter(s_conversion_counter_WGS84_Forward); } catch (...) { - xOut = 0; - yOut = 0; - zOut = 0; - return false; + xOut = 0; + yOut = 0; + zOut = 0; + return false; } return true; -} + } -bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat, double& altitude) -{ + bool geocentric2LonLatAlt(double x, double y, double z, double &lon, double &lat, double &altitude) + { try { - GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude); - incrementCounter(s_conversion_counter_WGS84_Reverse); + GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude); + incrementCounter(s_conversion_counter_WGS84_Reverse); } catch (...) { - lon = 0; - lat = 0; - altitude = 0; - return false; + lon = 0; + lat = 0; + altitude = 0; + return false; } lon *= deg2rad(); lat *= deg2rad(); return true; -} + } -double distance(const QPointF& p1, const QPointF& p2) -{ + double distance(const QPointF &p1, const QPointF &p2) + { return distance(p1.x(), p1.y(), p2.x(), p2.y()); -} + } -double squareDistance(const QPointF& p1, const QPointF& p2) -{ + double squareDistance(const QPointF &p1, const QPointF &p2) + { return squareDistance(p1.x(), p1.y(), p2.x(), p2.y()); -} + } -std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord) -{ + std::ostream &operator<<(std::ostream &stream, const UtmCoordinate &coord) + { - stream << "UtmCoordinate(" << std::setprecision(8) << coord.x << "#" << std::setprecision(8) << coord.y - << " zone=" << coord.zone << ")"; + stream << "UtmCoordinate(" << std::setprecision(8) << coord.x << "#" << std::setprecision(8) << coord.y << " zone=" << coord.zone << ")"; return stream; -} + } -void dumpConversionCounter() -{ - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n", - s_conversion_counter_MGRS_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n", - s_conversion_counter_MGRS_Reverse); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n", - s_conversion_counter_WGS84_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n", - s_conversion_counter_WGS84_Reverse); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n", - s_conversion_counter_UTMUPS_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n", - s_conversion_counter_UTMUPS_Reverse); -} + void dumpConversionCounter() + { + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n", s_conversion_counter_MGRS_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n", s_conversion_counter_MGRS_Reverse); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n", s_conversion_counter_WGS84_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n", s_conversion_counter_WGS84_Reverse); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n", s_conversion_counter_UTMUPS_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n", s_conversion_counter_UTMUPS_Reverse); + } -long getConversionCounter_MGRS_Forward() -{ + long getConversionCounter_MGRS_Forward() + { return s_conversion_counter_MGRS_Forward; -} + } -long getConversionCounter_MGRS_Reverse() -{ + long getConversionCounter_MGRS_Reverse() + { return s_conversion_counter_MGRS_Reverse; -} + } -long getConversionCounter_WGS84_Forward() -{ + long getConversionCounter_WGS84_Forward() + { return s_conversion_counter_WGS84_Forward; -} + } -long getConversionCounter_WGS84_Reverse() -{ + long getConversionCounter_WGS84_Reverse() + { return s_conversion_counter_WGS84_Reverse; -} + } -long getConversionCounter_UTMUPS_Forward() -{ + long getConversionCounter_UTMUPS_Forward() + { return s_conversion_counter_UTMUPS_Forward; -} + } -long getConversionCounter_UTMUPS_Reverse() -{ + long getConversionCounter_UTMUPS_Reverse() + { return s_conversion_counter_UTMUPS_Reverse; -} + } } // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h index 2ddc0f58a..77ca90681 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h @@ -14,23 +14,23 @@ class QString; namespace LtsCoordTrans { -inline Q_CONSTEXPR double pi() -{ + inline Q_CONSTEXPR double pi() + { return M_PI; -} + } -inline Q_CONSTEXPR double deg2rad() -{ + inline Q_CONSTEXPR double deg2rad() + { return pi() / 180.; -} + } -inline Q_CONSTEXPR double rad2deg() -{ + inline Q_CONSTEXPR double rad2deg() + { return 1. / deg2rad(); -} + } -struct LTSCOORDTRANS_EXPORT UtmCoordinate -{ + struct LTSCOORDTRANS_EXPORT UtmCoordinate + { int zone = -1; bool northp = true; double x = 0.; @@ -38,152 +38,146 @@ struct LTSCOORDTRANS_EXPORT UtmCoordinate UtmCoordinate() = default; - UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true) : zone(zone_), northp(northp_), x(x_), y(y_) {} - - bool isValid() const + UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true) + : zone(zone_) + , northp(northp_) + , x(x_) + , y(y_) { - return zone > 0 && zone <= 60; } + bool isValid() const { return zone > 0 && zone <= 60; } + QString mgrs(int prec = 5, bool withSpaces = true) const; QPointF toPoint() const; QPointF geographic(double offsetX = 0., double offsetY = 0.) const; - QPointF geographic(const QPointF& offset) const; + QPointF geographic(const QPointF &offset) const; - QPointF relativeTo(const UtmCoordinate& other) const; + QPointF relativeTo(const UtmCoordinate &other) const; static UtmCoordinate fromGeographic(double lon, double lat, int setZone = -1); - static UtmCoordinate fromGeographic(const QPointF& lonLat, int setZone = -1); + static UtmCoordinate fromGeographic(const QPointF &lonLat, int setZone = -1); - static UtmCoordinate fromMgrs(const QString& mgrs); -}; + static UtmCoordinate fromMgrs(const QString &mgrs); + }; -LTSCOORDTRANS_EXPORT QString mgrsFromGeographic(double lon, double lat, int prec = 5, bool withSpaces = true); + LTSCOORDTRANS_EXPORT QString mgrsFromGeographic(double lon, double lat, int prec = 5, bool withSpaces = true); -LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString& mgrs); + LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString &mgrs); -LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter); + LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter); -LTSCOORDTRANS_EXPORT QVector getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares, - bool setAsPreferedSquare, - bool setAsSquareWithMargin = false); + LTSCOORDTRANS_EXPORT QVector getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin = false); -QVector getMgrsSquaresInternal(const QRectF& rect); + QVector getMgrsSquaresInternal(const QRectF &rect); -QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter); + QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter); -LTSCOORDTRANS_EXPORT QVector defaultMgrsSquareWithOffsets(); + LTSCOORDTRANS_EXPORT QVector defaultMgrsSquareWithOffsets(); -LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector& squares); + LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector &squares); -LTSCOORDTRANS_EXPORT QVector defaultMgrsSquares(); + LTSCOORDTRANS_EXPORT QVector defaultMgrsSquares(); -LTSCOORDTRANS_EXPORT UtmCoordinate preferedMgrsSquare(); + LTSCOORDTRANS_EXPORT UtmCoordinate preferedMgrsSquare(); -LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut, - double& zOut); + LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut); -LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat, - double& altitude); + LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z, double &lon, double &lat, double &altitude); -inline double squareDistance(const UtmCoordinate& p1, const UtmCoordinate& p2) -{ + inline double squareDistance(const UtmCoordinate &p1, const UtmCoordinate &p2) + { if (p1.zone != p2.zone) { - Q_ASSERT(false); - return std::nan(""); + Q_ASSERT(false); + return std::nan(""); } return std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2); -} + } -LTSCOORDTRANS_EXPORT double squareDistance(const QPointF& p1, const QPointF& p2); + LTSCOORDTRANS_EXPORT double squareDistance(const QPointF &p1, const QPointF &p2); -inline double squareDistance(const double lon1, const double lat1, const double lon2, const double lat2) -{ + inline double squareDistance(const double lon1, const double lat1, const double lon2, const double lat2) + { const auto p1(UtmCoordinate::fromGeographic(lon1, lat1)); const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); return squareDistance(p1, p2); -} + } -inline double squareDistance(const UtmCoordinate& p1, const double lon2, const double lat2) -{ + inline double squareDistance(const UtmCoordinate &p1, const double lon2, const double lat2) + { const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); return squareDistance(p1, p2); -} + } -inline double distance(const UtmCoordinate& p1, const UtmCoordinate& p2) -{ + inline double distance(const UtmCoordinate &p1, const UtmCoordinate &p2) + { if (p1.zone != p2.zone) { - Q_ASSERT(false); - return std::nan(""); + Q_ASSERT(false); + return std::nan(""); } return sqrt(squareDistance(p1, p2)); -} + } -LTSCOORDTRANS_EXPORT double distance(const QPointF& p1, const QPointF& p2); + LTSCOORDTRANS_EXPORT double distance(const QPointF &p1, const QPointF &p2); -inline double distance(const double lon1, const double lat1, const double lon2, const double lat2) -{ + inline double distance(const double lon1, const double lat1, const double lon2, const double lat2) + { return sqrt(squareDistance(lon1, lat1, lon2, lat2)); -} + } -inline double distance(const UtmCoordinate& p1, const double lon2, const double lat2) -{ + inline double distance(const UtmCoordinate &p1, const double lon2, const double lat2) + { return sqrt(squareDistance(p1, lon2, lat2)); -} + } -LTSCOORDTRANS_EXPORT void dumpConversionCounter(); + LTSCOORDTRANS_EXPORT void dumpConversionCounter(); -LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Forward(); -LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Reverse(); -LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Forward(); -LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Reverse(); -LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Forward(); -LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Reverse(); + LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Forward(); + LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Reverse(); + LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Forward(); + LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Reverse(); + LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Forward(); + LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Reverse(); -LTSCOORDTRANS_EXPORT std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord); + LTSCOORDTRANS_EXPORT std::ostream &operator<<(std::ostream &stream, const UtmCoordinate &coord); -class LTSCOORDTRANS_EXPORT UtmCoordinate3D : public LtsCoordTrans::UtmCoordinate -{ + class LTSCOORDTRANS_EXPORT UtmCoordinate3D : public LtsCoordTrans::UtmCoordinate + { using BaseClass = LtsCoordTrans::UtmCoordinate; public: - UtmCoordinate3D() - { - reset(); - } + UtmCoordinate3D() { reset(); } - explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate& utm2d, double _zValue = std::nan("")) : BaseClass() + explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate &utm2d, double _zValue = std::nan("")) + : BaseClass() { - zone = utm2d.zone; - northp = utm2d.northp; - x = utm2d.x; - y = utm2d.y; - zValue = _zValue; + zone = utm2d.zone; + northp = utm2d.northp; + x = utm2d.x; + y = utm2d.y; + zValue = _zValue; } void reset() { - zone = -1; - northp = true; + zone = -1; + northp = true; - x = 0.; - y = 0.; - zValue = std::nan(""); + x = 0.; + y = 0.; + zValue = std::nan(""); } - double z() const - { - return zValue; - } + double z() const { return zValue; } protected: double zValue{std::nan("")}; -}; + }; } // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp index 5c7a7b163..20c3b552c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp @@ -13,7 +13,7 @@ QTEST_MAIN(coordtrans_test) void coordtrans_test::initTestCase() { - qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate)); + qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate)); } void coordtrans_test::cleanupTestCase() {} @@ -21,380 +21,394 @@ void coordtrans_test::cleanupTestCase() {} void coordtrans_test::testFromGeographic() { - LtsCoordTrans::UtmCoordinate utm; - QPointF lonlat; + LtsCoordTrans::UtmCoordinate utm; + QPointF lonlat; - lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999")); + lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999")); - lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000")); + lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000")); - lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000")); + lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000")); - utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000")); - QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM")); + utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000")); + QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM")); } void coordtrans_test::testMgrsFromGeographic() { - QString mgrs; - QPointF lonlat; + QString mgrs; + QPointF lonlat; - lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); + lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false); - QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000")); + mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false); + QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000")); } void coordtrans_test::testRelativeMetricalOffet_data() { - QTest::addColumn("offset"); - QTest::addColumn("correctMgrs"); + QTest::addColumn("offset"); + QTest::addColumn("correctMgrs"); - QTest::newRow("set 1") << QPoint(5, 5) << QStringLiteral("32U PD 99995 99995"); + QTest::newRow("set 1") << QPoint(5, 5) << QStringLiteral("32U PD 99995 99995"); - QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090"); - QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490"); + QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090"); + QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490"); } void coordtrans_test::testRelativeMetricalOffet() { - QFETCH(QPoint, offset); - QFETCH(QString, correctMgrs); + QFETCH(QPoint, offset); + QFETCH(QString, correctMgrs); - const LtsCoordTrans::UtmCoordinate& utmRef = - LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990")); - qDebug() << "utmRef = " << utmRef.mgrs(); + const LtsCoordTrans::UtmCoordinate &utmRef = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990")); + qDebug() << "utmRef = " << utmRef.mgrs(); - { - LtsCoordTrans::UtmCoordinate utmRaw; - utmRaw.x = utmRef.x + offset.x(); - utmRaw.y = utmRef.y + offset.y(); - utmRaw.zone = utmRef.zone; - qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs(); + { + LtsCoordTrans::UtmCoordinate utmRaw; + utmRaw.x = utmRef.x + offset.x(); + utmRaw.y = utmRef.y + offset.y(); + utmRaw.zone = utmRef.zone; + qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs(); - QCOMPARE(utmRaw.mgrs(), correctMgrs); - } + QCOMPARE(utmRaw.mgrs(), correctMgrs); + } - { - const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone, utmRef.x + offset.x(), utmRef.y + offset.y()); + { + const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone, utmRef.x + offset.x(), utmRef.y + offset.y()); - qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs(); - QCOMPARE(utmSimple.mgrs(), correctMgrs); - } + qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs(); + QCOMPARE(utmSimple.mgrs(), correctMgrs); + } } -QRectF createArea(const QString& base, int xCenter, int yCenter, int width, int height) +QRectF createArea(const QString &base, int xCenter, int yCenter, int width, int height) { - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase( - LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - QRectF rect(topLeft, bottomRight); - return rect; + QRectF rect(topLeft, bottomRight); + return rect; } void coordtrans_test::testAddMarginToArea() { - { - qDebug() << "Altmark"; - QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000); - QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000)); + { + qDebug() << "Altmark"; + QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000); + QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000)); - qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() - << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); - qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() - << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); - qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() - << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); - qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() - << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() + << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); - QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); - QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); + QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); + QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); - QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); - QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); - } + QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); + QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); + } - { - qDebug() << "Luxemburg"; - QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000); - QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000)); + { + qDebug() << "Luxemburg"; + QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000); + QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000)); - qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() - << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); - qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() - << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); - qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() - << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); - qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() - << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() + << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); - QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); - QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); + QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); + QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); - QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); - QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); - } + QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); + QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); + } } void coordtrans_test::testIncreaseRect() { - QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); + QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - const LtsCoordTrans::UtmCoordinate centerPoint = - LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - LtsCoordTrans::UtmCoordinate topLeftUtm; - LtsCoordTrans::UtmCoordinate topLeftUtm2; + LtsCoordTrans::UtmCoordinate topLeftUtm; + LtsCoordTrans::UtmCoordinate topLeftUtm2; - { - QPointF topLeftGeo = centerPoint.geographic(-1111, 2222); - QPointF bottomRightGeo = centerPoint.geographic(3000, -4000); + { + QPointF topLeftGeo = centerPoint.geographic(-1111, 2222); + QPointF bottomRightGeo = centerPoint.geographic(3000, -4000); - topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo); - const LtsCoordTrans::UtmCoordinate bottomRightUtm = - LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo); - qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y; - qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15) - << bottomRightUtm.y; - } + topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo); + const LtsCoordTrans::UtmCoordinate bottomRightUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo); + qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y; + qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm.y; + } - { - topLeftUtm2.x = centerPoint.x - 1111; - topLeftUtm2.y = centerPoint.y + 2222; + { + topLeftUtm2.x = centerPoint.x - 1111; + topLeftUtm2.y = centerPoint.y + 2222; - LtsCoordTrans::UtmCoordinate bottomRightUtm2; - bottomRightUtm2.x = centerPoint.x + 3000; - bottomRightUtm2.y = centerPoint.y - 4000; + LtsCoordTrans::UtmCoordinate bottomRightUtm2; + bottomRightUtm2.x = centerPoint.x + 3000; + bottomRightUtm2.y = centerPoint.y - 4000; - qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y; - qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15) - << bottomRightUtm2.y; - } + qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y; + qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm2.y; + } - QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed"); - QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed"); + QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed"); + QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed"); } void coordtrans_test::testIncreaseRect2() { - QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); + QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - QRectF myRect; - QRectF myRectIncreased; + QRectF myRect; + QRectF myRectIncreased; - { - const LtsCoordTrans::UtmCoordinate centerPoint = - LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + { + const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QPointF topLeftGeo = centerPoint.geographic(-3000, 2000); - QPointF bottomRightGeo = centerPoint.geographic(3000, -2000); - myRect = QRectF(topLeftGeo, bottomRightGeo).normalized(); + QPointF topLeftGeo = centerPoint.geographic(-3000, 2000); + QPointF bottomRightGeo = centerPoint.geographic(3000, -2000); + myRect = QRectF(topLeftGeo, bottomRightGeo).normalized(); - qDebug() << "myRect : " << myRect; - qDebug() << "myRect center : " << myRect.center(); - qDebug() << "myRect height : " << myRect.height(); - } + qDebug() << "myRect : " << myRect; + qDebug() << "myRect center : " << myRect.center(); + qDebug() << "myRect height : " << myRect.height(); + } - { - const QPointF centerGeo = myRect.center(); - const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo); + { + const QPointF centerGeo = myRect.center(); + const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo); - QPointF topLeftGeo = centerUtm.geographic(-6000, 4000); - QPointF bottomRightGeo = centerUtm.geographic(6000, -4000); + QPointF topLeftGeo = centerUtm.geographic(-6000, 4000); + QPointF bottomRightGeo = centerUtm.geographic(6000, -4000); - myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized(); + myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized(); - qDebug() << "myRectIncreased : " << myRectIncreased; - qDebug() << "myRectIncreased center: " << myRectIncreased.center(); - qDebug() << "myRectIncreased height: " << myRectIncreased.height(); - } + qDebug() << "myRectIncreased : " << myRectIncreased; + qDebug() << "myRectIncreased center: " << myRectIncreased.center(); + qDebug() << "myRectIncreased height: " << myRectIncreased.height(); + } - QVERIFY2((int)(myRectIncreased.center().x() * 10000) == (int)(myRect.center().x() * 10000), - "testIncreaseRect2 centerX failed"); - QVERIFY2((int)(myRectIncreased.center().y() * 10000) == (int)(myRect.center().y() * 10000), - "testIncreaseRect2 centerY failed"); + QVERIFY2((int)(myRectIncreased.center().x() * 10000) == (int)(myRect.center().x() * 10000), "testIncreaseRect2 centerX failed"); + QVERIFY2((int)(myRectIncreased.center().y() * 10000) == (int)(myRect.center().y() * 10000), "testIncreaseRect2 centerY failed"); - QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed"); - QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed"); + QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed"); + QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed"); } void coordtrans_test::testGeographicFromMgrs() { - QString mgrs(QStringLiteral("32UPD7654398765")); + QString mgrs(QStringLiteral("32UPD7654398765")); - QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs); - QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad()); + QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs); + QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad()); } void coordtrans_test::testMgrsSquares() { - checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000, - {QStringLiteral("32U PC"), QStringLiteral("32U PD")}); - checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000, - {QStringLiteral("32U MC"), QStringLiteral("32U MD")}); - checkArea(QStringLiteral("32U MD 0000000000"), 89999, 89999, 21000, 21000, - {QStringLiteral("32U MD"), QStringLiteral("32U ME"), QStringLiteral("32U ND"), QStringLiteral("32U NE")}); + checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000, {QStringLiteral("32U PC"), QStringLiteral("32U PD")}); + checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000, {QStringLiteral("32U MC"), QStringLiteral("32U MD")}); + checkArea(QStringLiteral("32U MD 0000000000"), + 89999, + 89999, + 21000, + 21000, + {QStringLiteral("32U MD"), QStringLiteral("32U ME"), QStringLiteral("32U ND"), QStringLiteral("32U NE")}); - checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000, - {QStringLiteral("39Q XG"), QStringLiteral("39R XG")}); - checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, {QStringLiteral("40R CP")}); - checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000, - {QStringLiteral("40R CN"), QStringLiteral("40R DN")}); - checkArea(QStringLiteral("40R DN 0000000000"), 500, 96760, 30000, 30000, - {QStringLiteral("40R CN"), QStringLiteral("40R CP"), QStringLiteral("40R DN"), QStringLiteral("40R DP")}); - checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000, - {QStringLiteral("40Q BM"), QStringLiteral("40R BM")}); + checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000, {QStringLiteral("39Q XG"), QStringLiteral("39R XG")}); + checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, {QStringLiteral("40R CP")}); + checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000, {QStringLiteral("40R CN"), QStringLiteral("40R DN")}); + checkArea(QStringLiteral("40R DN 0000000000"), + 500, + 96760, + 30000, + 30000, + {QStringLiteral("40R CN"), QStringLiteral("40R CP"), QStringLiteral("40R DN"), QStringLiteral("40R DP")}); + checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000, {QStringLiteral("40Q BM"), QStringLiteral("40R BM")}); - checkArea(QStringLiteral("32U LA 0000000000"), 10000, 10000, 5000, 5000, - { - QStringLiteral("32U LA"), - }); + checkArea(QStringLiteral("32U LA 0000000000"), + 10000, + 10000, + 5000, + 5000, + { + QStringLiteral("32U LA"), + }); - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 60000, 60000, - {QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("32U KA"), QStringLiteral("32U KV"), - QStringLiteral("32U LA"), QStringLiteral("32U LV")}); + checkArea(QStringLiteral("32U LA 0000000000"), + 100, + 100, + 60000, + 60000, + {QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("32U KA"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LV")}); - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 150000, 150000, - {QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GQ"), QStringLiteral("31U GR"), - QStringLiteral("32U KA"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LV")}); + checkArea(QStringLiteral("32U LA 0000000000"), + 100, + 100, + 150000, + 150000, + {QStringLiteral("31U FQ"), + QStringLiteral("31U FR"), + QStringLiteral("31U GQ"), + QStringLiteral("31U GR"), + QStringLiteral("32U KA"), + QStringLiteral("32U KV"), + QStringLiteral("32U LA"), + QStringLiteral("32U LV")}); - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 200000, 200000, - {QStringLiteral("31U FP"), QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GP"), - QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("31U GS"), QStringLiteral("32U KA"), - QStringLiteral("32U KB"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LB"), - QStringLiteral("32U LV"), QStringLiteral("32U MA"), QStringLiteral("32U MB"), QStringLiteral("32U MV")}); + checkArea(QStringLiteral("32U LA 0000000000"), + 100, + 100, + 200000, + 200000, + {QStringLiteral("31U FP"), + QStringLiteral("31U FQ"), + QStringLiteral("31U FR"), + QStringLiteral("31U GP"), + QStringLiteral("31U GQ"), + QStringLiteral("31U GR"), + QStringLiteral("31U GS"), + QStringLiteral("32U KA"), + QStringLiteral("32U KB"), + QStringLiteral("32U KV"), + QStringLiteral("32U LA"), + QStringLiteral("32U LB"), + QStringLiteral("32U LV"), + QStringLiteral("32U MA"), + QStringLiteral("32U MB"), + QStringLiteral("32U MV")}); } -QVector checkAreaGetMgrsSquares(const QString& base, int xCenter, int yCenter, int width, - int height) +QVector checkAreaGetMgrsSquares(const QString &base, int xCenter, int yCenter, int width, int height) { - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase( - LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); + const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); - QStringList src; - src.reserve(squares.size()); - for (const auto& utm : squares) - src += utm.mgrs(0); - src.sort(); + QStringList src; + src.reserve(squares.size()); + for (const auto &utm : squares) + src += utm.mgrs(0); + src.sort(); - return squares; + return squares; } void coordtrans_test::testMgrsSquaresWithSurrounding() { - int initialSize = 5000; + int initialSize = 5000; - QVector squares1 = - checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize); + QVector squares1 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize); - QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed"); + QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed"); - int biggerSize = initialSize + (1 * 110000); - QVector squares9 = - checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize); + int biggerSize = initialSize + (1 * 110000); + QVector squares9 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize); - QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed"); + QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed"); - int muchBiggerSize = initialSize + (3 * 110000); - QVector square33 = - checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize); + int muchBiggerSize = initialSize + (3 * 110000); + QVector square33 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize); - QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed"); + QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed"); - QStringList string1; - string1.reserve(squares1.size()); - for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares1)) - string1.append(item.mgrs(0)); + QStringList string1; + string1.reserve(squares1.size()); + for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares1)) + string1.append(item.mgrs(0)); - QStringList string9; - string9.reserve(squares9.size()); - for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares9)) - string9.append(item.mgrs(0)); + QStringList string9; + string9.reserve(squares9.size()); + for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares9)) + string9.append(item.mgrs(0)); - QStringList string33; - string33.reserve(square33.size()); - for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(square33)) - string33.append(item.mgrs(0)); + QStringList string33; + string33.reserve(square33.size()); + for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(square33)) + string33.append(item.mgrs(0)); - { - QStringList surroundingStrings; - surroundingStrings.reserve(squares9.size()); - for (const QString& str : std::as_const(string9)) - if (!string1.contains(str)) - surroundingStrings.append(str); + { + QStringList surroundingStrings; + surroundingStrings.reserve(squares9.size()); + for (const QString &str : std::as_const(string9)) + if (!string1.contains(str)) + surroundingStrings.append(str); - QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed"); - } + QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed"); + } - { - QStringList surroundingStrings; - surroundingStrings.reserve(string33.size()); - for (const QString& str : std::as_const(string33)) - if (!string1.contains(str)) - surroundingStrings.append(str); + { + QStringList surroundingStrings; + surroundingStrings.reserve(string33.size()); + for (const QString &str : std::as_const(string33)) + if (!string1.contains(str)) + surroundingStrings.append(str); - QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed"); - } + QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed"); + } } -void coordtrans_test::checkArea(const QString& base, int xCenter, int yCenter, int width, int height, - const QStringList& coords) +void coordtrans_test::checkArea(const QString &base, int xCenter, int yCenter, int width, int height, const QStringList &coords) { - qDebug() << "checkArea : base: " << base; - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase( - LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg(); - qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg(); + qDebug() << "checkArea : base: " << base; + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); + qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg(); + qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg(); - const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); + const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); - QStringList src; - src.reserve(squares.size()); - for (const auto& utm : squares) - src += utm.mgrs(0); - src.sort(); - qDebug() << "src: '" << src << "' expected: '" << coords << "'"; - QCOMPARE(src, coords); + QStringList src; + src.reserve(squares.size()); + for (const auto &utm : squares) + src += utm.mgrs(0); + src.sort(); + qDebug() << "src: '" << src << "' expected: '" << coords << "'"; + QCOMPARE(src, coords); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h index 3e42c9eba..8a84c92b3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h @@ -7,25 +7,25 @@ class coordtrans_test : public QObject { - Q_OBJECT - private Q_SLOTS: - void initTestCase(); - void cleanupTestCase(); - void testFromGeographic(); - void testMgrsFromGeographic(); + Q_OBJECT +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + void testFromGeographic(); + void testMgrsFromGeographic(); - void testRelativeMetricalOffet_data(); - void testRelativeMetricalOffet(); + void testRelativeMetricalOffet_data(); + void testRelativeMetricalOffet(); - void testAddMarginToArea(); - void testIncreaseRect(); - void testIncreaseRect2(); + void testAddMarginToArea(); + void testIncreaseRect(); + void testIncreaseRect2(); - void testGeographicFromMgrs(); - void testMgrsSquares(); + void testGeographicFromMgrs(); + void testMgrsSquares(); - void testMgrsSquaresWithSurrounding(); + void testMgrsSquaresWithSurrounding(); - private: - void checkArea(const QString& base, int xCenter, int yCenter, int width, int height, const QStringList& coords); +private: + void checkArea(const QString &base, int xCenter, int yCenter, int width, int height, const QStringList &coords); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp index 801000c50..d4e359cf1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp @@ -10,178 +10,177 @@ namespace LtsCoordWidget { -LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget* parent) : QWidget(parent), m_displayType(dt) -{ + LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget *parent) + : QWidget(parent) + , m_displayType(dt) + { setFocusPolicy(Qt::StrongFocus); rebuildUi(); -} + } -void LtsCoordWidget::setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue) -{ + void LtsCoordWidget::setCoordinate(const QPointF &geoCoord, bool bUseAsDefaultValue) + { if (m_coordinate != geoCoord) - emit coordinateChanged(geoCoord); + emit coordinateChanged(geoCoord); if (bUseAsDefaultValue) - m_defaultCoordinate = geoCoord; + m_defaultCoordinate = geoCoord; if (m_inputWidgetHandler) - m_inputWidgetHandler->setCoordinate(geoCoord); -} + m_inputWidgetHandler->setCoordinate(geoCoord); + } -void LtsCoordWidget::clear() -{ + void LtsCoordWidget::clear() + { if (m_inputWidgetHandler) - m_inputWidgetHandler->clear(); -} + m_inputWidgetHandler->clear(); + } -void LtsCoordWidget::setCoordinate(double lon, double lat, bool bUseAsDefaultValue) -{ + void LtsCoordWidget::setCoordinate(double lon, double lat, bool bUseAsDefaultValue) + { setCoordinate(QPointF(lon, lat), bUseAsDefaultValue); -} + } -QPointF LtsCoordWidget::coordinate() const -{ + QPointF LtsCoordWidget::coordinate() const + { if (!m_inputWidgetHandler) - return QPointF(); + return QPointF(); return m_inputWidgetHandler->coordinate(); -} + } -LtsCoordWidget::DisplayType LtsCoordWidget::displayType() const -{ + LtsCoordWidget::DisplayType LtsCoordWidget::displayType() const + { return m_displayType; -} + } -void LtsCoordWidget::setDisplayType(LtsCoordWidget::DisplayType dt) -{ + void LtsCoordWidget::setDisplayType(LtsCoordWidget::DisplayType dt) + { if (m_displayType == dt) - return; + return; m_displayType = dt; rebuildUi(); -} + } -bool LtsCoordWidget::withResetButton() const -{ + bool LtsCoordWidget::withResetButton() const + { return m_bWithResetButton; -} + } -void LtsCoordWidget::setWithResetButton(bool bWith) -{ + void LtsCoordWidget::setWithResetButton(bool bWith) + { if (m_bWithResetButton == bWith) - return; + return; m_bWithResetButton = bWith; if (m_inputWidgetHandler) - m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); -} + m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); + } -bool LtsCoordWidget::showToolTip() const -{ + bool LtsCoordWidget::showToolTip() const + { return m_bShowToolTip; -} + } -void LtsCoordWidget::setShowToolTip(bool bShow) -{ + void LtsCoordWidget::setShowToolTip(bool bShow) + { if (m_bShowToolTip == bShow) - return; + return; m_bShowToolTip = bShow; updateToolTip(); -} + } -bool LtsCoordWidget::mgrsSquareEditable() const -{ + bool LtsCoordWidget::mgrsSquareEditable() const + { return m_bMgrsSquareEditable; -} + } -void LtsCoordWidget::setMgrsSquareEditable(bool bEditable) -{ + void LtsCoordWidget::setMgrsSquareEditable(bool bEditable) + { if (m_bMgrsSquareEditable == bEditable) - return; + return; m_bMgrsSquareEditable = bEditable; if (m_inputWidgetHandler) - m_inputWidgetHandler->setSquaresEditable(bEditable); -} + m_inputWidgetHandler->setSquaresEditable(bEditable); + } -void LtsCoordWidget::setWithSurroundingMgrsSquares(bool bEnable) -{ + void LtsCoordWidget::setWithSurroundingMgrsSquares(bool bEnable) + { if (m_inputWidgetHandler) - m_inputWidgetHandler->setWithSurroundingSquare(bEnable); -} + m_inputWidgetHandler->setWithSurroundingSquare(bEnable); + } -void LtsCoordWidget::setMgrsSquares(const QVector& geoCoords) -{ + void LtsCoordWidget::setMgrsSquares(const QVector &geoCoords) + { if (m_inputWidgetHandler) - m_inputWidgetHandler->setMgrsSquares(geoCoords); -} + m_inputWidgetHandler->setMgrsSquares(geoCoords); + } -bool LtsCoordWidget::event(QEvent* event) -{ + bool LtsCoordWidget::event(QEvent *event) + { if (event->type() == QEvent::ToolTip) - updateToolTip(); + updateToolTip(); return QWidget::event(event); -} + } -void LtsCoordWidget::rebuildUi() -{ + void LtsCoordWidget::rebuildUi() + { if (m_inputWidgetHandler) { - m_inputWidgetHandler->cleanup(); - delete m_inputWidgetHandler; - delete layout(); + m_inputWidgetHandler->cleanup(); + delete m_inputWidgetHandler; + delete layout(); } switch (m_displayType) { - case DisplayType::MGRS5: - m_inputWidgetHandler = new MgrsEdit(5, this); - break; - case DisplayType::MGRS7: - m_inputWidgetHandler = new MgrsEdit(7, this); - break; - case DisplayType::UTM: + case DisplayType::MGRS5: + m_inputWidgetHandler = new MgrsEdit(5, this); + break; + case DisplayType::MGRS7: + m_inputWidgetHandler = new MgrsEdit(7, this); + break; + case DisplayType::UTM: - qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__); - break; - case DisplayType::WGS84: - m_inputWidgetHandler = new Wgs84Edit(this); - break; + qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__); + break; + case DisplayType::WGS84: + m_inputWidgetHandler = new Wgs84Edit(this); + break; } if (!m_inputWidgetHandler) - return; + return; m_inputWidgetHandler->setSquaresEditable(m_bMgrsSquareEditable); m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); - connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked, this, - &LtsCoordWidget::onResetToDefaultCoordinate); - connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged, this, - &LtsCoordWidget::coordinateChanged); - connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate, this, - &LtsCoordWidget::invalidCoordinate); + connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked, this, &LtsCoordWidget::onResetToDefaultCoordinate); + connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged, this, &LtsCoordWidget::coordinateChanged); + connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate, this, &LtsCoordWidget::invalidCoordinate); if (!m_defaultCoordinate.isNull()) - m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); -} + m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); + } -void LtsCoordWidget::updateToolTip() -{ + void LtsCoordWidget::updateToolTip() + { QString tt; if (m_bShowToolTip) { - const QPointF p(coordinate()); - if (!p.isNull()) - { - const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y()); - const QPointF p2(p * LtsCoordTrans::rad2deg()); - tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10); - } + const QPointF p(coordinate()); + if (!p.isNull()) + { + const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y()); + const QPointF p2(p * LtsCoordTrans::rad2deg()); + tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10); + } } setToolTip(tt); -} + } -void LtsCoordWidget::onResetToDefaultCoordinate() -{ + void LtsCoordWidget::onResetToDefaultCoordinate() + { if (!m_inputWidgetHandler) - return; + return; if (m_defaultCoordinate.isNull()) - m_inputWidgetHandler->clear(); + m_inputWidgetHandler->clear(); m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); -} + } } // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h index d402cd4bc..e3ce908d3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h @@ -10,43 +10,53 @@ class QToolButton; namespace LtsCoordWidget { -class LtsCoordInputWidgetHandler; + class LtsCoordInputWidgetHandler; -class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget -{ + class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget + { Q_OBJECT public: - enum class DisplayType { MGRS5, MGRS7, UTM, WGS84, MGRS = DisplayType::MGRS5 }; + enum class DisplayType + { + MGRS5, + MGRS7, + UTM, + WGS84, + MGRS = DisplayType::MGRS5 + }; Q_ENUM(DisplayType) Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType) Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton) Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip) Q_PROPERTY(bool mgrsSquareEditable READ mgrsSquareEditable WRITE setMgrsSquareEditable) - explicit LtsCoordWidget(QWidget* parent = nullptr) : LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent) {} + explicit LtsCoordWidget(QWidget *parent = nullptr) + : LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent) + { + } - explicit LtsCoordWidget(DisplayType dt, QWidget* parent = nullptr); + explicit LtsCoordWidget(DisplayType dt, QWidget *parent = nullptr); QPointF coordinate() const; DisplayType displayType() const; bool withResetButton() const; bool showToolTip() const; bool mgrsSquareEditable() const; - bool event(QEvent* event) override; + bool event(QEvent *event) override; public Q_SLOTS: - void setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue = true); + void setCoordinate(const QPointF &geoCoord, bool bUseAsDefaultValue = true); void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true); void setDisplayType(LtsCoordWidget::DisplayType dt); void setWithResetButton(bool bWith); void setShowToolTip(bool bShow); void setMgrsSquareEditable(bool bEditable); void setWithSurroundingMgrsSquares(bool bEnable); - void setMgrsSquares(const QVector& geoCoords); + void setMgrsSquares(const QVector &geoCoords); void clear(); Q_SIGNALS: - void coordinateChanged(const QPointF& newGeoCoord); + void coordinateChanged(const QPointF &newGeoCoord); void invalidCoordinate(); private: @@ -60,8 +70,8 @@ class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget bool m_bShowToolTip = true; bool m_bMgrsSquareEditable = false; LtsCoordWidget::DisplayType m_displayType = LtsCoordWidget::DisplayType::MGRS; - LtsCoordInputWidgetHandler* m_inputWidgetHandler = nullptr; + LtsCoordInputWidgetHandler *m_inputWidgetHandler = nullptr; QPointF m_coordinate; QPointF m_defaultCoordinate; -}; + }; } // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp index ebc7bbb86..add40a9d7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp @@ -7,70 +7,71 @@ namespace LtsCoordWidget { -void LtsCoordInputWidgetHandler::onCoordinateDataChanged() -{ + void LtsCoordInputWidgetHandler::onCoordinateDataChanged() + { const QPointF coord(coordinate()); if (coord.isNull()) { - emit invalidCoordinate(); - return; + emit invalidCoordinate(); + return; } emit coordinateChanged(coord); -} + } -MgrsEdit::MgrsEdit(int precision, QWidget* widget) - : LtsCoordInputWidgetHandler(widget), m_precision(precision), m_ui(new Ui::Mgrs) -{ + MgrsEdit::MgrsEdit(int precision, QWidget *widget) + : LtsCoordInputWidgetHandler(widget) + , m_precision(precision) + , m_ui(new Ui::Mgrs) + { m_ui->setupUi(widget); if (m_precision < 0) - m_precision = 0; + m_precision = 0; if (m_precision > 11) - m_precision = 11; + m_precision = 11; const int upperLimit = pow(10, m_precision) - 1; m_ui->leEast->setValidator(new QIntValidator(0, upperLimit, m_ui->leEast)); m_ui->leNorth->setValidator(new QIntValidator(0, upperLimit, m_ui->leNorth)); setDefaultMgrsSquares(); - connect(m_ui->cbxZone, QOverload::of(&QComboBox::currentIndexChanged), this, - &MgrsEdit::onCoordinateDataChanged); + connect(m_ui->cbxZone, QOverload::of(&QComboBox::currentIndexChanged), this, &MgrsEdit::onCoordinateDataChanged); connect(m_ui->leEast, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged); connect(m_ui->leNorth, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged); -} + } -MgrsEdit::~MgrsEdit() -{ + MgrsEdit::~MgrsEdit() + { delete m_ui; -} + } -bool MgrsEdit::isValid() -{ + bool MgrsEdit::isValid() + { - const QString& east = m_ui->leEast->text(); + const QString &east = m_ui->leEast->text(); if (east.size() != m_precision) - return false; + return false; - const QString& north = m_ui->leNorth->text(); + const QString &north = m_ui->leNorth->text(); if (north.size() != m_precision) - return false; + return false; if (m_ui->cbxZone->currentIndex() < 0) - return false; + return false; if (m_ui->cbxZone->currentText().isEmpty()) - return false; + return false; return true; -} + } -void MgrsEdit::setCoordinate(const QPointF& geoCoord) -{ + void MgrsEdit::setCoordinate(const QPointF &geoCoord) + { const QString mgrsString = LtsCoordTrans::mgrsFromGeographic(geoCoord.x(), geoCoord.y(), m_precision, false); if (mgrsString.isEmpty()) { - m_ui->leEast->clear(); - m_ui->leNorth->clear(); - return; + m_ui->leEast->clear(); + m_ui->leNorth->clear(); + return; } m_ui->leEast->setText(QString()); @@ -82,135 +83,137 @@ void MgrsEdit::setCoordinate(const QPointF& geoCoord) int idx = m_ui->cbxZone->findText(mgrsSquare); if (idx < 0) { - addMgrsSquare(mgrsSquare); - idx = m_ui->cbxZone->findText(mgrsSquare); + addMgrsSquare(mgrsSquare); + idx = m_ui->cbxZone->findText(mgrsSquare); } m_ui->cbxZone->setCurrentIndex(idx); m_ui->leEast->setText(east); m_ui->leNorth->setText(north); -} + } -static inline QString getMgrsCoord(QLineEdit* le, int prec) -{ + static inline QString getMgrsCoord(QLineEdit *le, int prec) + { QString ret = le->text(); if (ret.isEmpty()) - return ret; + return ret; while (ret.size() < prec) - ret += QLatin1Char('0'); + ret += QLatin1Char('0'); le->setText(ret); return ret; -} + } -QPointF MgrsEdit::coordinate() const -{ + QPointF MgrsEdit::coordinate() const + { const QString east = getMgrsCoord(m_ui->leEast, m_precision); const QString north = getMgrsCoord(m_ui->leNorth, m_precision); if (east.isEmpty() || north.isEmpty() || m_ui->cbxZone->currentIndex() < 0) - return QPointF(); + return QPointF(); const QString mgrsString(m_ui->cbxZone->currentText() + east + north); return LtsCoordTrans::geographicFromMgrs(mgrsString); -} + } -QToolButton* MgrsEdit::resetButton() -{ + QToolButton *MgrsEdit::resetButton() + { return m_ui->tbReset; -} + } -void MgrsEdit::cleanup() -{ + void MgrsEdit::cleanup() + { delete m_ui->horizontalLayout; delete m_ui->cbxZone; delete m_ui->leEast; delete m_ui->leNorth; delete m_ui->tbReset; -} + } -void MgrsEdit::clear() -{ + void MgrsEdit::clear() + { m_ui->cbxZone->clear(); m_ui->leEast->clear(); m_ui->leNorth->clear(); setDefaultMgrsSquares(); -} + } -void MgrsEdit::setSquaresEditable(bool bEditable) -{ + void MgrsEdit::setSquaresEditable(bool bEditable) + { m_ui->cbxZone->setEditable(bEditable); -} + } -void MgrsEdit::setWithSurroundingSquare(bool bEnabled) -{ + void MgrsEdit::setWithSurroundingSquare(bool bEnabled) + { m_withMgrsSquareOffset = bEnabled; -} + } -static QStringList defaultMgrsSquares() -{ + static QStringList defaultMgrsSquares() + { const QVector squares(LtsCoordTrans::defaultMgrsSquares()); QStringList sl; sl.reserve(squares.size()); - for (const LtsCoordTrans::UtmCoordinate& c : squares) - sl += c.mgrs(0); + for (const LtsCoordTrans::UtmCoordinate &c : squares) + sl += c.mgrs(0); std::sort(sl.begin(), sl.end()); return sl; -} + } -static QString preferedMgrsSquare() -{ + static QString preferedMgrsSquare() + { const LtsCoordTrans::UtmCoordinate c(LtsCoordTrans::preferedMgrsSquare()); return c.mgrs(0); -} + } -void MgrsEdit::setDefaultMgrsSquares() -{ + void MgrsEdit::setDefaultMgrsSquares() + { m_ui->cbxZone->addItems(defaultMgrsSquares()); m_ui->cbxZone->setCurrentIndex(m_ui->cbxZone->findText(preferedMgrsSquare())); -} + } -void MgrsEdit::addMgrsSquare(const QString& newMgrsSquare) -{ + void MgrsEdit::addMgrsSquare(const QString &newMgrsSquare) + { QStringList sl = defaultMgrsSquares(); sl += newMgrsSquare; if (m_withMgrsSquareOffset) { - QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets()); + QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets()); - for (const auto& sq : std::as_const(squares)) - if (!sl.contains(sq)) - sl.append(sq); + for (const auto &sq : std::as_const(squares)) + if (!sl.contains(sq)) + sl.append(sq); } std::sort(sl.begin(), sl.end()); m_ui->cbxZone->clear(); m_ui->cbxZone->addItems(sl); -} + } -QStringList MgrsEdit::utmCoordsToList(const QVector& coords) -{ + QStringList MgrsEdit::utmCoordsToList(const QVector &coords) + { QStringList list; list.reserve(coords.count()); - for (const auto& utm : coords) - list.append(utm.mgrs(0)); + for (const auto &utm : coords) + list.append(utm.mgrs(0)); return list; -} + } -void MgrsEdit::setMgrsSquares(const QVector& geoCoords) -{ + void MgrsEdit::setMgrsSquares(const QVector &geoCoords) + { QStringList sl = utmCoordsToList(geoCoords); if (sl.isEmpty()) - return; + return; std::sort(sl.begin(), sl.end()); m_ui->cbxZone->clear(); m_ui->cbxZone->addItems(sl); -} + } -Wgs84Edit::Wgs84Edit(QWidget* widget) : LtsCoordInputWidgetHandler(widget), m_ui(new Ui::Wgs84) -{ + Wgs84Edit::Wgs84Edit(QWidget *widget) + : LtsCoordInputWidgetHandler(widget) + , m_ui(new Ui::Wgs84) + { m_ui->setupUi(widget); - DoubleValidator* v = new DoubleValidator(-180, 180, 9, m_ui->leLon); + DoubleValidator *v = new DoubleValidator(-180, 180, 9, m_ui->leLon); v->setNotation(QDoubleValidator::StandardNotation); m_ui->leLon->setValidator(v); @@ -220,50 +223,50 @@ Wgs84Edit::Wgs84Edit(QWidget* widget) : LtsCoordInputWidgetHandler(widget), m_ui connect(m_ui->leLon, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged); connect(m_ui->leLat, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged); -} + } -Wgs84Edit::~Wgs84Edit() -{ + Wgs84Edit::~Wgs84Edit() + { delete m_ui; -} + } -bool Wgs84Edit::isValid() -{ + bool Wgs84Edit::isValid() + { return (!m_ui->leLon->text().isEmpty()) && (!m_ui->leLat->text().isEmpty()); -} + } -void Wgs84Edit::setCoordinate(const QPointF& geoCoord) -{ + void Wgs84Edit::setCoordinate(const QPointF &geoCoord) + { const QPointF coord(geoCoord * LtsCoordTrans::rad2deg()); const QLocale l; m_ui->leLon->setText(l.toString(coord.x(), 'f', 9)); m_ui->leLat->setText(l.toString(coord.y(), 'f', 9)); -} + } -QPointF Wgs84Edit::coordinate() const -{ + QPointF Wgs84Edit::coordinate() const + { QPointF ret; const QLocale l; const QString lonStr = m_ui->leLon->text().remove(l.groupSeparator()); const QString latStr = m_ui->leLat->text().remove(l.groupSeparator()); if (lonStr.isEmpty() || latStr.isEmpty()) - return ret; + return ret; ret.rx() = l.toDouble(lonStr); ret.ry() = l.toDouble(latStr); return ret * LtsCoordTrans::deg2rad(); -} + } -QToolButton* Wgs84Edit::resetButton() -{ + QToolButton *Wgs84Edit::resetButton() + { return m_ui->tbReset; -} + } -void Wgs84Edit::cleanup() -{ + void Wgs84Edit::cleanup() + { delete m_ui->horizontalLayout; delete m_ui->leLon; @@ -271,31 +274,31 @@ void Wgs84Edit::cleanup() delete m_ui->tbReset; delete m_ui->lblLon; delete m_ui->lblLat; -} + } -void Wgs84Edit::clear() -{ + void Wgs84Edit::clear() + { m_ui->leLon->clear(); m_ui->leLat->clear(); -} + } -DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject* parent) - : QDoubleValidator(bottom, top, decimals, parent) -{ -} + DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject *parent) + : QDoubleValidator(bottom, top, decimals, parent) + { + } -QValidator::State DoubleValidator::validate(QString& input, int& pos) const -{ + QValidator::State DoubleValidator::validate(QString &input, int &pos) const + { const QValidator::State ret = QDoubleValidator::validate(input, pos); if (ret != QValidator::Acceptable) - return ret; + return ret; QLocale l; const QChar gs = l.groupSeparator().at(0); if (gs.isNull()) - return ret; + return ret; if (input.contains(gs)) - return QValidator::Invalid; + return QValidator::Invalid; return ret; -} + } } // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h index 2ba810b0b..4ed42bfe2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h @@ -13,95 +13,89 @@ namespace LtsCoordWidget { -class LtsCoordInputWidgetHandler : public QObject -{ + class LtsCoordInputWidgetHandler : public QObject + { Q_OBJECT public: - explicit LtsCoordInputWidgetHandler(QObject* parent) : QObject(parent) {} + explicit LtsCoordInputWidgetHandler(QObject *parent) + : QObject(parent) + { + } virtual bool isValid() = 0; - virtual void setCoordinate(const QPointF& geoCoord) = 0; + virtual void setCoordinate(const QPointF &geoCoord) = 0; virtual QPointF coordinate() const = 0; - virtual QToolButton* resetButton() = 0; + virtual QToolButton *resetButton() = 0; virtual void cleanup() = 0; virtual void clear() = 0; virtual void setSquaresEditable(bool bEditable) = 0; virtual void setWithSurroundingSquare(bool bEnabled) = 0; - virtual void setMgrsSquares(const QVector& geoCoords) = 0; + virtual void setMgrsSquares(const QVector &geoCoords) = 0; protected Q_SLOTS: void onCoordinateDataChanged(); Q_SIGNALS: - void coordinateChanged(const QPointF& newGeoCoord); + void coordinateChanged(const QPointF &newGeoCoord); void invalidCoordinate(); -}; + }; -class MgrsEdit final : public LtsCoordInputWidgetHandler -{ + class MgrsEdit final : public LtsCoordInputWidgetHandler + { Q_OBJECT public: - explicit MgrsEdit(int precision, QWidget* widget); + explicit MgrsEdit(int precision, QWidget *widget); ~MgrsEdit(); bool isValid() override; - void setCoordinate(const QPointF& geoCoord) override; + void setCoordinate(const QPointF &geoCoord) override; QPointF coordinate() const override; - QToolButton* resetButton() override; + QToolButton *resetButton() override; void cleanup() override; void clear() override; void setSquaresEditable(bool bEditable) override; void setWithSurroundingSquare(bool bEnabled) override; - void setMgrsSquares(const QVector& geoCoords) override; + void setMgrsSquares(const QVector &geoCoords) override; private: void setDefaultMgrsSquares(); - void addMgrsSquare(const QString& newMgrsSquare); - QStringList utmCoordsToList(const QVector& coords); + void addMgrsSquare(const QString &newMgrsSquare); + QStringList utmCoordsToList(const QVector &coords); private: int m_precision; bool m_withMgrsSquareOffset = false; - Ui::Mgrs* m_ui; -}; + Ui::Mgrs *m_ui; + }; -class Wgs84Edit final : public LtsCoordInputWidgetHandler -{ + class Wgs84Edit final : public LtsCoordInputWidgetHandler + { Q_OBJECT public: - explicit Wgs84Edit(QWidget* widget); + explicit Wgs84Edit(QWidget *widget); ~Wgs84Edit(); bool isValid() override; - void setCoordinate(const QPointF& geoCoord) override; + void setCoordinate(const QPointF &geoCoord) override; QPointF coordinate() const override; - QToolButton* resetButton() override; + QToolButton *resetButton() override; void cleanup() override; void clear() override; - void setSquaresEditable(bool bEditable) override - { - Q_UNUSED(bEditable); - } + void setSquaresEditable(bool bEditable) override { Q_UNUSED(bEditable); } - void setWithSurroundingSquare(bool bEnabled) override - { - Q_UNUSED(bEnabled); - } + void setWithSurroundingSquare(bool bEnabled) override { Q_UNUSED(bEnabled); } - void setMgrsSquares(const QVector& geoCoords) override - { - Q_UNUSED(geoCoords); - } + void setMgrsSquares(const QVector &geoCoords) override { Q_UNUSED(geoCoords); } private: - Ui::Wgs84* m_ui; -}; + Ui::Wgs84 *m_ui; + }; -class DoubleValidator final : public QDoubleValidator -{ + class DoubleValidator final : public QDoubleValidator + { Q_OBJECT public: - DoubleValidator(double bottom, double top, int decimals, QObject* parent = nullptr); + DoubleValidator(double bottom, double top, int decimals, QObject *parent = nullptr); - QValidator::State validate(QString& input, int& pos) const override; -}; + QValidator::State validate(QString &input, int &pos) const override; + }; } // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp index e9c4b4a4d..6ad271fce 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp @@ -9,98 +9,92 @@ #include #include -static void updateLabel(const QPointF& coord, QLabel* lbl, int prec) +static void updateLabel(const QPointF &coord, QLabel *lbl, int prec) { - QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec); - QString str = QStringLiteral("mgrs: %1, lon: %2, lat: %3") - .arg(mgrs) - .arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10) - .arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10); - lbl->setText(str); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec); + QString str = + QStringLiteral("mgrs: %1, lon: %2, lat: %3").arg(mgrs).arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10).arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10); + lbl->setText(str); } -int main(int argc, char** argv) +int main(int argc, char **argv) { - QApplication app(argc, argv); + QApplication app(argc, argv); - LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00"))); - QPointF topLeft(base.geographic(+50000, -50000)); - QPointF bottomRight(base.geographic(-50000, 50000)); - LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true); + LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00"))); + QPointF topLeft(base.geographic(+50000, -50000)); + QPointF bottomRight(base.geographic(-50000, 50000)); + LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true); - QDialog* dialog(new QDialog); - QVBoxLayout* lay(new QVBoxLayout(dialog)); + QDialog *dialog(new QDialog); + QVBoxLayout *lay(new QVBoxLayout(dialog)); - const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad()); + const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad()); - LtsCoordWidget::LtsCoordWidget* wMgrs5( - new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog)); - wMgrs5->setWithResetButton(true); - wMgrs5->setCoordinate(defCoord, true); - lay->addWidget(wMgrs5); - QLabel* lbl5(new QLabel(dialog)); - lay->addWidget(lbl5); - QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, lbl5, - [lbl5](const QPointF& coord) { updateLabel(coord, lbl5, 5); }); + LtsCoordWidget::LtsCoordWidget *wMgrs5(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog)); + wMgrs5->setWithResetButton(true); + wMgrs5->setCoordinate(defCoord, true); + lay->addWidget(wMgrs5); + QLabel *lbl5(new QLabel(dialog)); + lay->addWidget(lbl5); + QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, lbl5, [lbl5](const QPointF &coord) { updateLabel(coord, lbl5, 5); }); - LtsCoordWidget::LtsCoordWidget* wMgrs7( - new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog)); - wMgrs7->setWithResetButton(true); - wMgrs7->setCoordinate(defCoord, true); - lay->addWidget(wMgrs7); - QLabel* lbl7(new QLabel(dialog)); - lay->addWidget(lbl7); - QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, wMgrs7, - [lbl7](const QPointF& coord) { updateLabel(coord, lbl7, 7); }); + LtsCoordWidget::LtsCoordWidget *wMgrs7(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog)); + wMgrs7->setWithResetButton(true); + wMgrs7->setCoordinate(defCoord, true); + lay->addWidget(wMgrs7); + QLabel *lbl7(new QLabel(dialog)); + lay->addWidget(lbl7); + QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, wMgrs7, [lbl7](const QPointF &coord) { updateLabel(coord, lbl7, 7); }); - LtsCoordWidget::LtsCoordWidget* w84( - new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); - w84->setWithResetButton(true); - w84->setCoordinate(defCoord, true); - lay->addWidget(w84); - QLabel* lbl84(new QLabel(dialog)); - lay->addWidget(lbl84); - QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, w84, - [lbl84](const QPointF& coord) { updateLabel(coord, lbl84, 11); }); + LtsCoordWidget::LtsCoordWidget *w84(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); + w84->setWithResetButton(true); + w84->setCoordinate(defCoord, true); + lay->addWidget(w84); + QLabel *lbl84(new QLabel(dialog)); + lay->addWidget(lbl84); + QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, w84, [lbl84](const QPointF &coord) { updateLabel(coord, lbl84, 11); }); - QHBoxLayout* hLay = new QHBoxLayout; - lay->addLayout(hLay); - LtsCoordWidget::LtsCoordWidget* wChange( - new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); - wChange->setWithResetButton(true); - wChange->setCoordinate(defCoord, true); - hLay->addWidget(wChange); - QPushButton* pbReset(new QPushButton(QStringLiteral("With Reset"), dialog)); - hLay->addWidget(pbReset); - QObject::connect(pbReset, &QPushButton::clicked, wChange, - [wChange]() { wChange->setWithResetButton(!wChange->withResetButton()); }); - QPushButton* pbNext(new QPushButton(QStringLiteral("Next Type"), dialog)); - hLay->addWidget(pbNext); - QObject::connect(pbNext, &QPushButton::clicked, wChange, [wChange]() { - LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType(); - switch (dt) - { - case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7; - break; - case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84; - break; - case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5; - break; - default: - break; - } - wChange->setDisplayType(dt); - }); + QHBoxLayout *hLay = new QHBoxLayout; + lay->addLayout(hLay); + LtsCoordWidget::LtsCoordWidget *wChange(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); + wChange->setWithResetButton(true); + wChange->setCoordinate(defCoord, true); + hLay->addWidget(wChange); + QPushButton *pbReset(new QPushButton(QStringLiteral("With Reset"), dialog)); + hLay->addWidget(pbReset); + QObject::connect(pbReset, &QPushButton::clicked, wChange, [wChange]() { wChange->setWithResetButton(!wChange->withResetButton()); }); + QPushButton *pbNext(new QPushButton(QStringLiteral("Next Type"), dialog)); + hLay->addWidget(pbNext); + QObject::connect(pbNext, + &QPushButton::clicked, + wChange, + [wChange]() + { + LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType(); + switch (dt) + { + case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7; + break; + case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84; + break; + case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5; + break; + default: + break; + } + wChange->setDisplayType(dt); + }); - QPushButton* pb(new QPushButton(QStringLiteral("Quit"), dialog)); - lay->addWidget(pb); - QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit); + QPushButton *pb(new QPushButton(QStringLiteral("Quit"), dialog)); + lay->addWidget(pb); + QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit); - dialog->show(); - int ret = app.exec(); - delete dialog; - return ret; + dialog->show(); + int ret = app.exec(); + delete dialog; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp index d15a8b78e..c7f50af6c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp @@ -4,41 +4,49 @@ #include #include -int main(int argc, char** argv) +int main(int argc, char **argv) { - if (argc != 2) - { - fprintf(stderr, "Usage: %s \n", argv[0]); - return -1; - } + if (argc != 2) + { + fprintf(stderr, "Usage: %s \n", argv[0]); + return -1; + } - std::string mgrs = argv[1]; - mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end()); + std::string mgrs = argv[1]; + mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end()); - int prec; - double lonDeg, latDeg; - try - { - int zone; - bool northp; - double x, y; - GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true); - GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg); + int prec; + double lonDeg, latDeg; + try + { + int zone; + bool northp; + double x, y; + GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true); + GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg); - GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - } - catch (...) - { - fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str()); - return -2; - } - std::string part1, part2, part3, part4; - part1 = mgrs.substr(0, 3); - part2 = mgrs.substr(3, 2); - part3 = mgrs.substr(5, prec); - part4 = mgrs.substr(5 + prec, prec); - fprintf(stdout, "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", part1.c_str(), part2.c_str(), - part3.c_str(), part4.c_str(), lonDeg, latDeg, lonDeg / 180. * M_PI, latDeg / 180. * M_PI); - return 0; + GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + } + catch (...) + { + fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str()); + return -2; + } + std::string part1, part2, part3, part4; + part1 = mgrs.substr(0, 3); + part2 = mgrs.substr(3, 2); + part3 = mgrs.substr(5, prec); + part4 = mgrs.substr(5 + prec, prec); + fprintf(stdout, + "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", + part1.c_str(), + part2.c_str(), + part3.c_str(), + part4.c_str(), + lonDeg, + latDeg, + lonDeg / 180. * M_PI, + latDeg / 180. * M_PI); + return 0; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp index b3fc1e98c..af94c4595 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp @@ -10,43 +10,43 @@ namespace LtsLicence { -struct AesCryptPrivate -{ + struct AesCryptPrivate + { AesCryptPrivate() - : passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)), - logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt")) + : passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)) + , logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt")) { #if OPENSSL_VERSION_NUMBER < 0x1010000fL - ERR_load_crypto_strings(); + ERR_load_crypto_strings(); #endif } ~AesCryptPrivate() { #if OPENSSL_VERSION_NUMBER < 0x1010000fL - ERR_free_strings(); + ERR_free_strings(); #endif } QString passPhrase; - NGL::INGLLogger& logger; -}; -Q_GLOBAL_STATIC(AesCryptPrivate, s_Private) + NGL::INGLLogger &logger; + }; + Q_GLOBAL_STATIC(AesCryptPrivate, s_Private) -void setPassPhrase(const QString& passPhrase) -{ + void setPassPhrase(const QString &passPhrase) + { s_Private->passPhrase = passPhrase; -} + } -QString passPhrase() -{ + QString passPhrase() + { return s_Private->passPhrase; -} + } -QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw, bool* bOk) -{ + QByteArray decryptData(const QByteArray &dataToDecrypt, const QString &pw, bool *bOk) + { if (bOk) - *bOk = false; + *bOk = false; int ret; int outSize1 = 0; @@ -54,53 +54,53 @@ QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw, bool* unsigned char key[32]; const QByteArray baPassword = pw.toUtf8(); - const unsigned char* dataPw = reinterpret_cast(baPassword.data()); + const unsigned char *dataPw = reinterpret_cast(baPassword.data()); int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr); if (i != 32) { - ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; - return QByteArray(); + ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; + return QByteArray(); } const QByteArray baSalt = dataToDecrypt.left(EVP_MAX_IV_LENGTH); - const unsigned char* salt = reinterpret_cast(baSalt.data()); + const unsigned char *salt = reinterpret_cast(baSalt.data()); const QByteArray bufEncrypted = dataToDecrypt.mid(EVP_MAX_IV_LENGTH); - EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); ret = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed"; + return QByteArray(); } QByteArray bufDecrypted; bufDecrypted.resize(bufEncrypted.size() + EVP_CIPHER_CTX_block_size(ctx)); - const unsigned char* dataIn = reinterpret_cast(bufEncrypted.data()); - unsigned char* dataOut = reinterpret_cast(bufDecrypted.data()); + const unsigned char *dataIn = reinterpret_cast(bufEncrypted.data()); + unsigned char *dataOut = reinterpret_cast(bufDecrypted.data()); ret = EVP_DecryptUpdate(ctx, dataOut, &outSize1, dataIn, bufEncrypted.size()); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed"; + return QByteArray(); } ret = EVP_DecryptFinal_ex(ctx, dataOut + outSize1, &outSize2); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed"; + return QByteArray(); } EVP_CIPHER_CTX_free(ctx); @@ -108,14 +108,14 @@ QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw, bool* bufDecrypted.resize(outSize1 + outSize2); if (bOk) - *bOk = true; + *bOk = true; return bufDecrypted; -} + } -QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw, bool* bOk) -{ + QByteArray encryptData(const QByteArray &dataToEncrypt, const QString &pw, bool *bOk) + { if (bOk) - *bOk = false; + *bOk = false; int ret; int outSize1 = 0; @@ -124,53 +124,53 @@ QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw, bool* QByteArray bufEncrypted; const QByteArray baPassword = pw.toUtf8(); - const unsigned char* dataPw = reinterpret_cast(baPassword.data()); + const unsigned char *dataPw = reinterpret_cast(baPassword.data()); int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr); if (i != 32) { - ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; - return QByteArray(); + ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; + return QByteArray(); } QByteArray baSalt(EVP_MAX_IV_LENGTH, 0); for (int i = 0; i < EVP_MAX_IV_LENGTH; ++i) - baSalt[i] = static_cast(QRandomGenerator::global()->bounded(256)); - const unsigned char* salt = reinterpret_cast(baSalt.data()); + baSalt[i] = static_cast(QRandomGenerator::global()->bounded(256)); + const unsigned char *salt = reinterpret_cast(baSalt.data()); - EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); ret = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed"; + return QByteArray(); } - bufEncrypted = QByteArray::fromRawData(reinterpret_cast(salt), EVP_MAX_IV_LENGTH); + bufEncrypted = QByteArray::fromRawData(reinterpret_cast(salt), EVP_MAX_IV_LENGTH); bufEncrypted.resize(bufEncrypted.size() + dataToEncrypt.size() + EVP_CIPHER_CTX_block_size(ctx)); - const unsigned char* dataIn = reinterpret_cast(dataToEncrypt.data()); - unsigned char* dataOut = reinterpret_cast(bufEncrypted.data()); + const unsigned char *dataIn = reinterpret_cast(dataToEncrypt.data()); + unsigned char *dataOut = reinterpret_cast(bufEncrypted.data()); dataOut += baSalt.size(); ret = EVP_EncryptUpdate(ctx, dataOut, &outSize1, dataIn, dataToEncrypt.size()); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed"; + return QByteArray(); } ret = EVP_EncryptFinal_ex(ctx, dataOut + outSize1, &outSize2); if (ret == 0) { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed"; - return QByteArray(); + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed"; + return QByteArray(); } EVP_CIPHER_CTX_free(ctx); @@ -178,8 +178,8 @@ QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw, bool* bufEncrypted.resize(outSize1 + outSize2 + baSalt.size()); if (bOk) - *bOk = true; + *bOk = true; return bufEncrypted; -} + } } // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h index 43c457194..ace1aee40 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h @@ -9,12 +9,10 @@ namespace LtsLicence { -LTSLICENCE_EXPORT void setPassPhrase(const QString& passPhrase); -LTSLICENCE_EXPORT QString passPhrase(); + LTSLICENCE_EXPORT void setPassPhrase(const QString &passPhrase); + LTSLICENCE_EXPORT QString passPhrase(); -LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw = passPhrase(), - bool* bOk = nullptr); + LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray &dataToDecrypt, const QString &pw = passPhrase(), bool *bOk = nullptr); -LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw = passPhrase(), - bool* bOk = nullptr); + LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray &dataToEncrypt, const QString &pw = passPhrase(), bool *bOk = nullptr); } // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp index f1d983370..96b18ab95 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp @@ -13,41 +13,41 @@ QTEST_MAIN(aes_crypt_test) void aes_crypt_test::initTestCase() { - NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); + NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); } void aes_crypt_test::truePassTest() { - qDebug("Simple TestCase"); - bool bOk; - const QByteArray content("30.06.2013"); - const QString pw(QStringLiteral("aes_crypt_test")); - const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); + qDebug("Simple TestCase"); + bool bOk; + const QByteArray content("30.06.2013"); + const QString pw(QStringLiteral("aes_crypt_test")); + const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); - QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size()); - const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - QCOMPARE(dec, content); + QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size()); + const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + QCOMPARE(dec, content); - const QByteArray bigContent(12345, '1'); - const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); + const QByteArray bigContent(12345, '1'); + const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); - QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size()); + QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size()); } void aes_crypt_test::falsePassTest() { - qDebug("False Password TestCase"); - bool bOk; - const QByteArray content("30.06.2013"); - const QString pw(QStringLiteral("aes_crypt_test")); - const QString pw2(QStringLiteral("aes_crypt_test2")); - const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - QVERIFY2(enc.size() != 20, "Error encrypting data..."); - const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk); - QVERIFY2(!bOk, "Error encrypting data..."); - QVERIFY2(dec.isEmpty(), "decrypted data is not empty..."); + qDebug("False Password TestCase"); + bool bOk; + const QByteArray content("30.06.2013"); + const QString pw(QStringLiteral("aes_crypt_test")); + const QString pw2(QStringLiteral("aes_crypt_test2")); + const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + QVERIFY2(enc.size() != 20, "Error encrypting data..."); + const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk); + QVERIFY2(!bOk, "Error encrypting data..."); + QVERIFY2(dec.isEmpty(), "decrypted data is not empty..."); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h index 20f113ce2..e11f4c10c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h @@ -6,9 +6,9 @@ class aes_crypt_test : public QObject { - Q_OBJECT - private Q_SLOTS: - void initTestCase(); - void truePassTest(); - void falsePassTest(); + Q_OBJECT +private Q_SLOTS: + void initTestCase(); + void truePassTest(); + void falsePassTest(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp index 7b47979ad..576d313f7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp @@ -8,15 +8,15 @@ namespace LtsLicence { -static bool extractLicence(const QDomElement& licenceElement, QVector& licenceVec); + static bool extractLicence(const QDomElement &licenceElement, QVector &licenceVec); -static NGL::INGLLogger& getLogger() -{ + static NGL::INGLLogger &getLogger() + { return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicence"); -} + } -QVector readLicences(const QByteArray& unencryptedXmlData) -{ + QVector readLicences(const QByteArray &unencryptedXmlData) + { QVector licenceVec; QDomDocument xmlDoc; @@ -24,10 +24,10 @@ QVector readLicences(const QByteArray& unencryptedXmlData) const auto parseResult = xmlDoc.setContent(unencryptedXmlData); if (!parseResult) { - ERROR_LOG(getLogger()) << "Error reading xml data, " - << "error in line " << int(parseResult.errorLine) << ", column " << int(parseResult.errorColumn) - << ", message: " << parseResult.errorMessage; - return licenceVec; + ERROR_LOG(getLogger()) << "Error reading xml data, " + << "error in line " << int(parseResult.errorLine) << ", column " << int(parseResult.errorColumn) + << ", message: " << parseResult.errorMessage; + return licenceVec; } INFO_LOG(getLogger()) << "Try to extract licences"; @@ -36,23 +36,22 @@ QVector readLicences(const QByteArray& unencryptedXmlData) while (!licenceElement.isNull()) { - if (!extractLicence(licenceElement, licenceVec)) - { - licenceVec.clear(); - return licenceVec; - } + if (!extractLicence(licenceElement, licenceVec)) + { + licenceVec.clear(); + return licenceVec; + } - licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence")); + licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence")); } return licenceVec; -} + } -QByteArray writeUnencryptedLicences(const QVector& licences) -{ + QByteArray writeUnencryptedLicences(const QVector &licences) + { QDomDocument xmlDoc; - QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction( - QLatin1String("xml"), QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'")); + QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction(QLatin1String("xml"), QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'")); xmlDoc.appendChild(instr); QDomElement root = xmlDoc.createElement(QLatin1String("licences")); @@ -60,43 +59,43 @@ QByteArray writeUnencryptedLicences(const QVector& licences) for (int i = 0; i < licences.size(); ++i) { - QDomElement lic = xmlDoc.createElement(QLatin1String("licence")); - root.appendChild(lic); + QDomElement lic = xmlDoc.createElement(QLatin1String("licence")); + root.appendChild(lic); - QDomElement element = xmlDoc.createElement(QLatin1String("name")); - QDomText text = xmlDoc.createTextNode(licences[i].name); - element.appendChild(text); - lic.appendChild(element); + QDomElement element = xmlDoc.createElement(QLatin1String("name")); + QDomText text = xmlDoc.createTextNode(licences[i].name); + element.appendChild(text); + lic.appendChild(element); - element = xmlDoc.createElement(QLatin1String("ignoreMaxCount")); - text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("ignoreMaxCount")); + text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount)); + element.appendChild(text); + lic.appendChild(element); - element = xmlDoc.createElement(QLatin1String("ignoreExpiration")); - text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("ignoreExpiration")); + text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration)); + element.appendChild(text); + lic.appendChild(element); - element = xmlDoc.createElement(QLatin1String("maxCount")); - text = xmlDoc.createTextNode(QString::number(licences[i].maxCount)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("maxCount")); + text = xmlDoc.createTextNode(QString::number(licences[i].maxCount)); + element.appendChild(text); + lic.appendChild(element); - const QLatin1String format("dd.MM.yyyy hh:mm:ss"); - const QString qs = licences[i].expiration.toString(format); + const QLatin1String format("dd.MM.yyyy hh:mm:ss"); + const QString qs = licences[i].expiration.toString(format); - element = xmlDoc.createElement(QLatin1String("expiration")); - text = xmlDoc.createTextNode(qs); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("expiration")); + text = xmlDoc.createTextNode(qs); + element.appendChild(text); + lic.appendChild(element); } INFO_LOG(getLogger()) << "Generated XML Data...\n" << xmlDoc.toByteArray(); return xmlDoc.toByteArray(); -} + } -bool extractLicence(const QDomElement& licenceElement, QVector& licenceVec) -{ + bool extractLicence(const QDomElement &licenceElement, QVector &licenceVec) + { Licence licence; QDomElement tag = licenceElement.firstChildElement(QLatin1String("name")); @@ -120,29 +119,28 @@ bool extractLicence(const QDomElement& licenceElement, QVector& licence if (!qdt.isValid()) { - ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs << " used format: " << format; - return false; + ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs << " used format: " << format; + return false; } licence.expiration = qdt; INFO_LOG(getLogger()) << "Read licence for:'" << licence.name << "'" - << " IgnoreMaxCount: " << licence.ignoreMaxCount - << " IgnoreExpiration: " << licence.ignoreExpiration << " MaxCount: " << licence.maxCount - << " Expiration: " << licence.expiration.date().toString() << " " - << licence.expiration.time().toString() << " RefCount: " << licence.licenceRefCount; + << " IgnoreMaxCount: " << licence.ignoreMaxCount << " IgnoreExpiration: " << licence.ignoreExpiration << " MaxCount: " << licence.maxCount + << " Expiration: " << licence.expiration.date().toString() << " " << licence.expiration.time().toString() + << " RefCount: " << licence.licenceRefCount; licenceVec.append(licence); return true; -} + } -QString Licence::toString() const -{ + QString Licence::toString() const + { return QObject::tr("Name: %1, Count: %2, ExpireDate: %3, Expires: %4, UseMaxCount: %5") .arg(name) .arg(maxCount) .arg(expiration.toString()) .arg(ignoreExpiration) .arg(ignoreMaxCount); -} + } } // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h index 119656c18..29d38ed92 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h @@ -11,8 +11,8 @@ namespace LtsLicence { -struct LTSLICENCE_EXPORT Licence -{ + struct LTSLICENCE_EXPORT Licence + { QString name; bool ignoreMaxCount = false; bool ignoreExpiration = false; @@ -21,9 +21,9 @@ struct LTSLICENCE_EXPORT Licence int licenceRefCount = 0; QString toString() const; -}; + }; -LTSLICENCE_EXPORT QVector readLicences(const QByteArray& unencryptedXmlData); + LTSLICENCE_EXPORT QVector readLicences(const QByteArray &unencryptedXmlData); -LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector& licences); + LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector &licences); } // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp index d231c8bec..5d7de83d4 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp @@ -9,56 +9,58 @@ namespace LtsNotification { -LtsNotification::LtsNotification(LtsNotificationController* ctl) : QObject(), m_controller(ctl) -{ + LtsNotification::LtsNotification(LtsNotificationController *ctl) + : QObject() + , m_controller(ctl) + { connect(ctl, &LtsNotificationController::destroyed, this, &LtsNotification::slotCtlDestroyed); -} + } -LtsNotification::~LtsNotification() -{ + LtsNotification::~LtsNotification() + { delete m_controller; -} + } -void LtsNotification::setIcon(const QIcon& icon) -{ + void LtsNotification::setIcon(const QIcon &icon) + { m_controller->setIcon(icon); -} + } -void LtsNotification::setAction(const std::function& action) -{ + void LtsNotification::setAction(const std::function &action) + { m_controller->setAction(action); -} + } -void LtsNotification::setToolTip(const QString& toolTip) -{ + void LtsNotification::setToolTip(const QString &toolTip) + { m_controller->setToolTip(toolTip); -} + } -const QString& LtsNotification::tooltip() const -{ + const QString &LtsNotification::tooltip() const + { return m_controller->tooltip(); -} + } -void LtsNotification::setCount(const int count) -{ + void LtsNotification::setCount(const int count) + { m_controller->setCount(count); -} + } -void LtsNotification::setEnabled(bool enable) -{ + void LtsNotification::setEnabled(bool enable) + { m_controller->setEnabled(enable); -} + } -void LtsNotification::setBackground(const int r, const int g, const int b) -{ + void LtsNotification::setBackground(const int r, const int g, const int b) + { m_controller->setBackground(r, g, b); -} + } -void LtsNotification::slotCtlDestroyed(QObject* obj) -{ + void LtsNotification::slotCtlDestroyed(QObject *obj) + { (void)obj; m_controller = nullptr; -} + } } // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h index 7d35b43a0..7607b9927 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h @@ -11,35 +11,35 @@ namespace LtsSession { -class LtsSession; + class LtsSession; } namespace LtsNotification { -class LtsNotificationController; + class LtsNotificationController; -class LTSNOTIFICATION_EXPORT LtsNotification : public QObject -{ + class LTSNOTIFICATION_EXPORT LtsNotification : public QObject + { Q_OBJECT public: - explicit LtsNotification(LtsNotificationController* ctl); + explicit LtsNotification(LtsNotificationController *ctl); ~LtsNotification(); - void setIcon(const QIcon& icon); - void setAction(const std::function& action); - void setToolTip(const QString& toolTip); + void setIcon(const QIcon &icon); + void setAction(const std::function &action); + void setToolTip(const QString &toolTip); void setCount(const int count); void setEnabled(bool enable); void setBackground(const int r, const int g, const int b); - const QString& tooltip() const; + const QString &tooltip() const; private: - LtsNotificationController* m_controller; + LtsNotificationController *m_controller; private slots: - void slotCtlDestroyed(QObject* obj); -}; + void slotCtlDestroyed(QObject *obj); + }; } // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp index 775e42f3c..17da5514e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp @@ -13,94 +13,95 @@ namespace LtsNotification { -LtsNotificationController::LtsNotificationController(const QString& identifier) - : QObject(), m_count(0), m_identifier(QStringLiteral("LtsNotification%1").arg(identifier)) -{ -} + LtsNotificationController::LtsNotificationController(const QString &identifier) + : QObject() + , m_count(0) + , m_identifier(QStringLiteral("LtsNotification%1").arg(identifier)) + { + } -LtsNotificationController::~LtsNotificationController() -{ + LtsNotificationController::~LtsNotificationController() + { qDeleteAll(m_notiList); -} + } -void LtsNotificationController::setIcon(const QIcon& icon) -{ + void LtsNotificationController::setIcon(const QIcon &icon) + { m_icon = icon; setAllIcons(); -} + } -void LtsNotificationController::setCount(const int count) -{ + void LtsNotificationController::setCount(const int count) + { m_count = count; setAllIcons(); -} + } -void LtsNotificationController::setBackground(const int r, const int g, const int b) -{ + void LtsNotificationController::setBackground(const int r, const int g, const int b) + { - for (QToolButton* tb : std::as_const(m_notiList)) + for (QToolButton *tb : std::as_const(m_notiList)) { - QString stylesheet; + QString stylesheet; - if (r == -1 && g == -1 && b == -1) - stylesheet = QStringLiteral(""); - else - stylesheet = QStringLiteral("QToolButton {background-color: rgb(") + QString::number(r) + - QStringLiteral(",") + QString::number(g) + QStringLiteral(",") + QString::number(b) + - QStringLiteral(");}"); + if (r == -1 && g == -1 && b == -1) + stylesheet = QStringLiteral(""); + else + stylesheet = QStringLiteral("QToolButton {background-color: rgb(") + QString::number(r) + QStringLiteral(",") + QString::number(g) + QStringLiteral(",") + + QString::number(b) + QStringLiteral(");}"); - tb->setStyleSheet(stylesheet); + tb->setStyleSheet(stylesheet); } -} + } -void LtsNotificationController::setEnabled(bool enable) -{ + void LtsNotificationController::setEnabled(bool enable) + { m_enable = enable; setAllIcons(); -} + } -void LtsNotificationController::setAction(const std::function& action) -{ + void LtsNotificationController::setAction(const std::function &action) + { m_action = action; -} + } -void LtsNotificationController::setToolTip(const QString& toolTip) -{ + void LtsNotificationController::setToolTip(const QString &toolTip) + { m_toolTip = toolTip; - for (QToolButton* tb : std::as_const(m_notiList)) + for (QToolButton *tb : std::as_const(m_notiList)) { - tb->setToolTip(toolTip); - tb->setIconSize(QSize(30, 30)); + tb->setToolTip(toolTip); + tb->setIconSize(QSize(30, 30)); } -} + } -void LtsNotificationController::setAllIcons() -{ + void LtsNotificationController::setAllIcons() + { if (m_icon.isNull()) - return; + return; QIcon icon = modifyIcon(m_icon); - for (QToolButton* tb : std::as_const(m_notiList)) + for (QToolButton *tb : std::as_const(m_notiList)) { - tb->setIcon(icon); - tb->setIconSize(QSize(30, 30)); - tb->setEnabled(m_enable); + tb->setIcon(icon); + tb->setIconSize(QSize(30, 30)); + tb->setEnabled(m_enable); } -} + } #define SIZE 40 -QIcon LtsNotificationController::modifyIcon(const QIcon& icon) -{ + QIcon LtsNotificationController::modifyIcon(const QIcon &icon) + { if (m_count < 1) - return icon; + return icon; QPixmap iconImage(icon.pixmap(SIZE * 8 / 10, SIZE * 8 / 10)); QPainter painter(&iconImage); @@ -121,11 +122,11 @@ QIcon LtsNotificationController::modifyIcon(const QIcon& icon) painter.restore(); return iconImage; -} + } -QToolButton* LtsNotificationController::createWidget() -{ - QToolButton* b = new QToolButton(); + QToolButton *LtsNotificationController::createWidget() + { + QToolButton *b = new QToolButton(); b->setToolButtonStyle(Qt::ToolButtonIconOnly); b->setObjectName(m_identifier); @@ -133,23 +134,27 @@ QToolButton* LtsNotificationController::createWidget() b->setMaximumSize(SIZE, SIZE); connect(b, &QToolButton::destroyed, this, &LtsNotificationController::slotNotiWidgetDestroyed); - connect(b, &QToolButton::clicked, this, [this]() { - if (m_action) - m_action(); - }); + connect(b, + &QToolButton::clicked, + this, + [this]() + { + if (m_action) + m_action(); + }); if (!m_icon.isNull()) - b->setIcon(modifyIcon(m_icon)); + b->setIcon(modifyIcon(m_icon)); b->setToolTip(m_toolTip); m_notiList.append(b); return b; -} + } -void LtsNotificationController::slotNotiWidgetDestroyed(QObject* obj) -{ - m_notiList.removeAll(static_cast(obj)); -} + void LtsNotificationController::slotNotiWidgetDestroyed(QObject *obj) + { + m_notiList.removeAll(static_cast(obj)); + } } // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h index a8727fc54..3a80222e6 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h @@ -14,43 +14,37 @@ class QToolButton; namespace LtsSession { -class LtsSession; + class LtsSession; } namespace LtsNotification { -class LtsNotificationWidget; + class LtsNotificationWidget; -class LTSNOTIFICATION_EXPORT LtsNotificationController : public QObject -{ + class LTSNOTIFICATION_EXPORT LtsNotificationController : public QObject + { Q_OBJECT public: - explicit LtsNotificationController(const QString& identifier); + explicit LtsNotificationController(const QString &identifier); ~LtsNotificationController(); - QToolButton* createWidget(); + QToolButton *createWidget(); - void setIcon(const QIcon& icon); - void setAction(const std::function& action); - void setToolTip(const QString& toolTip); + void setIcon(const QIcon &icon); + void setAction(const std::function &action); + void setToolTip(const QString &toolTip); void setCount(const int count); void setBackground(const int r, const int g, const int b); - const QString& identifier() const - { - return m_identifier; - } + const QString &identifier() const { return m_identifier; } - const QString& tooltip() const - { - return m_toolTip; - } + const QString &tooltip() const { return m_toolTip; } void setEnabled(bool enable); private: - QList m_notiList; + QList m_notiList; QIcon m_icon; std::function m_action; @@ -60,10 +54,10 @@ class LTSNOTIFICATION_EXPORT LtsNotificationController : public QObject QString m_identifier; void setAllIcons(); - QIcon modifyIcon(const QIcon& icon); + QIcon modifyIcon(const QIcon &icon); private slots: - void slotNotiWidgetDestroyed(QObject* obj); -}; + void slotNotiWidgetDestroyed(QObject *obj); + }; } // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.cpp index ca95d69f4..f04fa4892 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.cpp @@ -16,157 +16,160 @@ namespace LtsCommon { -LtsRestClient::LtsRestClient(const QString &baseUrl, QObject *parent) - : QObject(parent) - , m_baseUrl(baseUrl) - , m_manager(new QNetworkAccessManager(this)) -{ -} - -void LtsRestClient::ping(PingSuccessCallback onSuccess, ErrorCallback onError, int timeoutMs) -{ - const QNetworkRequest request((QUrl(m_baseUrl))); - QNetworkReply *reply = m_manager->head(request); - - if (!reply) + LtsRestClient::LtsRestClient(const QString &baseUrl, QObject *parent) + : QObject(parent) + , m_baseUrl(baseUrl) + , m_manager(new QNetworkAccessManager(this)) { - if (onError) - onError(QStringLiteral("Failed to initiate ping.")); - - return; } - // 1. Setup the timer (parented to reply for auto-cleanup) - QTimer *timeoutTimer = new QTimer(reply); - timeoutTimer->setSingleShot(true); - - // 2. Connect the timeout signal to abort the request - connect(timeoutTimer, &QTimer::timeout, this, [reply]() + void LtsRestClient::ping(PingSuccessCallback onSuccess, ErrorCallback onError, int timeoutMs) { - if (reply && reply->isRunning()) - reply->abort(); // Triggers finished() with OperationCanceledError - }); + const QNetworkRequest request((QUrl(m_baseUrl))); + QNetworkReply *reply = m_manager->head(request); - // 3. Connect the finished signal to handle the response - connect(reply, - &QNetworkReply::finished, - this, - [reply, timeoutTimer, onSuccess, onError]() - { - timeoutTimer->stop(); - reply->deleteLater(); - - if (reply->error() != QNetworkReply::NoError) + if (!reply) { if (onError) - { - if (reply->error() == QNetworkReply::OperationCanceledError) - onError(QStringLiteral("Ping timed out.")); - else - onError(reply->errorString()); - } + onError(QStringLiteral("Failed to initiate ping.")); return; } - const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + // 1. Setup the timer (parented to reply for auto-cleanup) + QTimer *timeoutTimer = new QTimer(reply); + timeoutTimer->setSingleShot(true); - if (onSuccess) - onSuccess(statusCode); - }); + // 2. Connect the timeout signal to abort the request + connect(timeoutTimer, + &QTimer::timeout, + this, + [reply]() + { + if (reply && reply->isRunning()) + reply->abort(); // Triggers finished() with OperationCanceledError + }); - // 4. Start the timer only after all connections are successfully established - timeoutTimer->start(timeoutMs); -} + // 3. Connect the finished signal to handle the response + connect(reply, + &QNetworkReply::finished, + this, + [reply, timeoutTimer, onSuccess, onError]() + { + timeoutTimer->stop(); + reply->deleteLater(); -void LtsRestClient::get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError) -{ - sendRequest(QStringLiteral("GET"), endpoint, QByteArray(), onSuccess, onError); -} + if (reply->error() != QNetworkReply::NoError) + { + if (onError) + { + if (reply->error() == QNetworkReply::OperationCanceledError) + onError(QStringLiteral("Ping timed out.")); + else + onError(reply->errorString()); + } -void LtsRestClient::post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError) -{ - sendRequest(QStringLiteral("POST"), endpoint, json.toJson(), onSuccess, onError); -} + return; + } -void LtsRestClient::put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError) -{ - sendRequest(QStringLiteral("PUT"), endpoint, json.toJson(), onSuccess, onError); -} + const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); -void LtsRestClient::del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError) -{ - sendRequest(QStringLiteral("DELETE"), endpoint, QByteArray(), onSuccess, onError); -} + if (onSuccess) + onSuccess(statusCode); + }); -void LtsRestClient::sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError) -{ - QUrl url(m_baseUrl); - url.setPath(url.path() + endpoint); - - QNetworkRequest request(url); - request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json")); - - QNetworkReply *reply = nullptr; - - if (method == QStringLiteral("GET")) - reply = m_manager->get(request); - else if (method == QStringLiteral("POST")) - reply = m_manager->post(request, data); - else if (method == QStringLiteral("PUT")) - reply = m_manager->put(request, data); - else if (method == QStringLiteral("DELETE")) - reply = m_manager->deleteResource(request); - - if (!reply) - { - if (onError) - onError(QStringLiteral("Failed to initiate request.")); - - return; + // 4. Start the timer only after all connections are successfully established + timeoutTimer->start(timeoutMs); } - connect(reply, - &QNetworkReply::finished, - this, - [reply, onSuccess, onError]() + void LtsRestClient::get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError) { - reply->deleteLater(); + sendRequest(QStringLiteral("GET"), endpoint, QByteArray(), onSuccess, onError); + } - // Handle network errors - if (reply->error() != QNetworkReply::NoError) + void LtsRestClient::post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError) + { + sendRequest(QStringLiteral("POST"), endpoint, json.toJson(), onSuccess, onError); + } + + void LtsRestClient::put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError) + { + sendRequest(QStringLiteral("PUT"), endpoint, json.toJson(), onSuccess, onError); + } + + void LtsRestClient::del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError) + { + sendRequest(QStringLiteral("DELETE"), endpoint, QByteArray(), onSuccess, onError); + } + + void LtsRestClient::sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError) + { + QUrl url(m_baseUrl); + url.setPath(url.path() + endpoint); + + QNetworkRequest request(url); + request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json")); + + QNetworkReply *reply = nullptr; + + if (method == QStringLiteral("GET")) + reply = m_manager->get(request); + else if (method == QStringLiteral("POST")) + reply = m_manager->post(request, data); + else if (method == QStringLiteral("PUT")) + reply = m_manager->put(request, data); + else if (method == QStringLiteral("DELETE")) + reply = m_manager->deleteResource(request); + + if (!reply) { if (onError) - onError(reply->errorString()); + onError(QStringLiteral("Failed to initiate request.")); return; } - // Handle HTTP errors - const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if (statusCode >= 400) - { - if (onError) - onError(QStringLiteral("HTTP Error %1").arg(statusCode)); + connect(reply, + &QNetworkReply::finished, + this, + [reply, onSuccess, onError]() + { + reply->deleteLater(); - return; - } + // Handle network errors + if (reply->error() != QNetworkReply::NoError) + { + if (onError) + onError(reply->errorString()); - // Parse JSON safely - QJsonParseError parseError; - const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &parseError); + return; + } - if (parseError.error != QJsonParseError::NoError) - { - if (onError) - onError(QStringLiteral("JSON Parse Error: ") + parseError.errorString()); + // Handle HTTP errors + const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if (statusCode >= 400) + { + if (onError) + onError(QStringLiteral("HTTP Error %1").arg(statusCode)); - return; - } + return; + } - if (onSuccess) - onSuccess(doc); - }); -} + // Parse JSON safely + QJsonParseError parseError; + const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &parseError); + + if (parseError.error != QJsonParseError::NoError) + { + if (onError) + onError(QStringLiteral("JSON Parse Error: ") + parseError.errorString()); + + return; + } + + if (onSuccess) + onSuccess(doc); + }); + } } // namespace LtsCommon diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.h index 9b838b226..704f8c568 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsRestClient/lts_rest_client.h @@ -21,31 +21,31 @@ class QNetworkAccessManager; namespace LtsCommon { -class LTSRESTCLIENT_EXPORT LtsRestClient : public QObject -{ - Q_OBJECT + class LTSRESTCLIENT_EXPORT LtsRestClient : public QObject + { + Q_OBJECT public: - explicit LtsRestClient(const QString &baseUrl, QObject *parent = nullptr); + explicit LtsRestClient(const QString &baseUrl, QObject *parent = nullptr); - // type aliases - using PingSuccessCallback = std::function; - using SuccessCallback = std::function; - using ErrorCallback = std::function; + // type aliases + using PingSuccessCallback = std::function; + using SuccessCallback = std::function; + using ErrorCallback = std::function; - // HTTP Header Ping to m_baseUrl to check server availability - void ping(PingSuccessCallback onSuccess, ErrorCallback onError = nullptr, int timeoutMs = 3000); + // HTTP Header Ping to m_baseUrl to check server availability + void ping(PingSuccessCallback onSuccess, ErrorCallback onError = nullptr, int timeoutMs = 3000); - // HTTP Methods - void get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr); - void post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr); - void put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr); - void del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr); + // HTTP Methods + void get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr); + void post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr); + void put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr); + void del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr); private: - void sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError); + void sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError); - QString m_baseUrl; - QNetworkAccessManager *m_manager; -}; // class RestClient + QString m_baseUrl; + QNetworkAccessManager *m_manager; + }; // class RestClient } // namespace LtsCommon diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp index 36061e248..609be00fa 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp @@ -7,8 +7,8 @@ namespace LtsSerialPortQuerry { -LOGGER_T getLogger(const char* name) -{ + LOGGER_T getLogger(const char *name) + { static const char ns[] = "SPQ."; std::string loggerName; const size_t len = strlen(name); @@ -18,13 +18,13 @@ LOGGER_T getLogger(const char* name) try { - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); } - catch (const std::exception& ex) + catch (const std::exception &ex) { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); } -} + } } // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h index c3e498bbc..e366567d0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h @@ -6,12 +6,12 @@ namespace LtsSerialPortQuerry { -typedef NGL::INGLLogger& LOGGER_T; + typedef NGL::INGLLogger &LOGGER_T; -LOGGER_T getLogger(const char* name); + LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString& loggerName) -{ + inline LOGGER_T getLogger(const QString &loggerName) + { return getLogger(loggerName.toUtf8().constData()); -} + } } // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h index 2670e4d86..66e66b83f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h @@ -9,24 +9,27 @@ namespace LtsSerialPortQuerry { -class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject -{ + class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject + { Q_OBJECT public: - explicit LtsSerialPortQuerry(QObject* parent = nullptr); + explicit LtsSerialPortQuerry(QObject *parent = nullptr); - void setSerialPortSettings(const QSerialPort::BaudRate& baudRate, const QSerialPort::OpenModeFlag& openModeFlag, - const QSerialPort::DataBits& dataBits, const QSerialPort::FlowControl& flowControll, - const QSerialPort::Parity& parity, const QSerialPort::StopBits& stopBits); + void setSerialPortSettings(const QSerialPort::BaudRate &baudRate, + const QSerialPort::OpenModeFlag &openModeFlag, + const QSerialPort::DataBits &dataBits, + const QSerialPort::FlowControl &flowControll, + const QSerialPort::Parity &parity, + const QSerialPort::StopBits &stopBits); void continueQuerry(); void restartQuerry(); - QSerialPort* currentSerialPort(); + QSerialPort *currentSerialPort(); signals: void connectionEstablished(); private: - void querrySerialPort(const QSerialPortInfo& info); + void querrySerialPort(const QSerialPortInfo &info); void closeAndDeleteCurrentPort(); private: @@ -41,7 +44,7 @@ class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject QSerialPort::FlowControl m_flowControll; QSerialPort::Parity m_parity; QSerialPort::StopBits m_stopBits; - QSerialPort* m_currentSerialPort; -}; + QSerialPort *m_currentSerialPort; + }; } // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp index 41e87cc1a..02ce1695e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp @@ -5,59 +5,65 @@ namespace LtsSerialPortQuerry { -LtsSerialPortQuerry::LtsSerialPortQuerry(QObject* parent) - : QObject(parent), m_logger(getLogger("LtsSerialPortQuerry")), m_currentQuerry(0), - m_baudRate(QSerialPort::Baud115200), m_openModeFlag(QSerialPort::ReadWrite), m_dataBits(QSerialPort::Data8), - m_flowControll(QSerialPort::NoFlowControl), m_parity(QSerialPort::NoParity), m_stopBits(QSerialPort::OneStop), - m_currentSerialPort(nullptr) -{ -} + LtsSerialPortQuerry::LtsSerialPortQuerry(QObject *parent) + : QObject(parent) + , m_logger(getLogger("LtsSerialPortQuerry")) + , m_currentQuerry(0) + , m_baudRate(QSerialPort::Baud115200) + , m_openModeFlag(QSerialPort::ReadWrite) + , m_dataBits(QSerialPort::Data8) + , m_flowControll(QSerialPort::NoFlowControl) + , m_parity(QSerialPort::NoParity) + , m_stopBits(QSerialPort::OneStop) + , m_currentSerialPort(nullptr) + { + } -void LtsSerialPortQuerry::setSerialPortSettings(const QSerialPort::BaudRate& baudRate, - const QIODevice::OpenModeFlag& openModeFlag, - const QSerialPort::DataBits& dataBits, - const QSerialPort::FlowControl& flowControll, - const QSerialPort::Parity& parity, - const QSerialPort::StopBits& stopBits) -{ + void LtsSerialPortQuerry::setSerialPortSettings(const QSerialPort::BaudRate &baudRate, + const QIODevice::OpenModeFlag &openModeFlag, + const QSerialPort::DataBits &dataBits, + const QSerialPort::FlowControl &flowControll, + const QSerialPort::Parity &parity, + const QSerialPort::StopBits &stopBits) + { m_baudRate = baudRate; m_openModeFlag = openModeFlag; m_dataBits = dataBits; m_flowControll = flowControll; m_parity = parity; m_stopBits = stopBits; -} + } -void LtsSerialPortQuerry::continueQuerry() -{ + void LtsSerialPortQuerry::continueQuerry() + { m_currentQuerry++; if (m_currentQuerry >= m_serialPortInfos.size()) { - restartQuerry(); - return; + restartQuerry(); + return; } querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); -} + } -void LtsSerialPortQuerry::restartQuerry() -{ + void LtsSerialPortQuerry::restartQuerry() + { DEBUG_LOG(m_logger) << "restart querry "; m_serialPortInfos = QSerialPortInfo::availablePorts(); m_currentQuerry = 0; if (m_serialPortInfos.size()) - querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); + querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); else - QTimer::singleShot(1000, this, &LtsSerialPortQuerry::restartQuerry); -} + QTimer::singleShot(1000, this, &LtsSerialPortQuerry::restartQuerry); + } -QSerialPort* LtsSerialPortQuerry::currentSerialPort() -{ + QSerialPort *LtsSerialPortQuerry::currentSerialPort() + { return m_currentSerialPort; -} + } -void LtsSerialPortQuerry::querrySerialPort(const QSerialPortInfo& info) -{ + void LtsSerialPortQuerry::querrySerialPort(const QSerialPortInfo &info) + { closeAndDeleteCurrentPort(); m_currentSerialPort = new QSerialPort(info, this); m_currentSerialPort->setBaudRate(m_baudRate); @@ -66,75 +72,76 @@ void LtsSerialPortQuerry::querrySerialPort(const QSerialPortInfo& info) m_currentSerialPort->setStopBits(m_stopBits); m_currentSerialPort->setFlowControl(m_flowControll); - DEBUG_LOG(m_logger) << "Try opening Comport:" << m_currentSerialPort->portName() - << " index is: " << m_currentQuerry; + DEBUG_LOG(m_logger) << "Try opening Comport:" << m_currentSerialPort->portName() << " index is: " << m_currentQuerry; if (!m_currentSerialPort->open(QSerialPort::ReadWrite)) { - DEBUG_LOG(m_logger) << "Oppening failed query next"; + DEBUG_LOG(m_logger) << "Oppening failed query next"; - continueQuerry(); + continueQuerry(); } else { - connect(m_currentSerialPort, &QSerialPort::errorOccurred, this, &LtsSerialPortQuerry::onSerialPortError, - Qt::UniqueConnection); - DEBUG_LOG(m_logger) << "Oppened comport" << m_currentSerialPort->portName(); - emit connectionEstablished(); + connect(m_currentSerialPort, &QSerialPort::errorOccurred, this, &LtsSerialPortQuerry::onSerialPortError, Qt::UniqueConnection); + DEBUG_LOG(m_logger) << "Oppened comport" << m_currentSerialPort->portName(); + emit connectionEstablished(); } -} + } -void LtsSerialPortQuerry::closeAndDeleteCurrentPort() -{ + void LtsSerialPortQuerry::closeAndDeleteCurrentPort() + { if (m_currentSerialPort) { - m_currentSerialPort->disconnect(); - if (m_currentSerialPort->isOpen()) - m_currentSerialPort->close(); - m_currentSerialPort->deleteLater(); + m_currentSerialPort->disconnect(); + if (m_currentSerialPort->isOpen()) + m_currentSerialPort->close(); + m_currentSerialPort->deleteLater(); - m_currentSerialPort = nullptr; + m_currentSerialPort = nullptr; } -} + } -void LtsSerialPortQuerry::onSerialPortError(QSerialPort::SerialPortError serialPortError) -{ + void LtsSerialPortQuerry::onSerialPortError(QSerialPort::SerialPortError serialPortError) + { if (!m_currentSerialPort) - return; + return; DEBUG_LOG(m_logger) << "Spontaneous error " << serialPortError << " doesn't have to be an error ..."; - const QString errStr(QStringLiteral("QSerialPort::SerialPortError ") + QString::number(serialPortError) + - QStringLiteral(" from serial port ") + m_currentSerialPort->portName() + - QStringLiteral(" error: ") + m_currentSerialPort->errorString()); + const QString errStr(QStringLiteral("QSerialPort::SerialPortError ") + QString::number(serialPortError) + QStringLiteral(" from serial port ") + + m_currentSerialPort->portName() + QStringLiteral(" error: ") + m_currentSerialPort->errorString()); switch (serialPortError) { - case QSerialPort::SerialPortError::NoError: { + case QSerialPort::SerialPortError::NoError: + { - break; - } - case QSerialPort::SerialPortError::DeviceNotFoundError: - case QSerialPort::SerialPortError::PermissionError: - case QSerialPort::SerialPortError::OpenError: - case QSerialPort::SerialPortError::NotOpenError: - case QSerialPort::SerialPortError::UnknownError: { - ERROR_LOG(m_logger) << "Closing port and try to reopen it. " << m_currentSerialPort->portName(); - continueQuerry(); + break; + } + case QSerialPort::SerialPortError::DeviceNotFoundError: + case QSerialPort::SerialPortError::PermissionError: + case QSerialPort::SerialPortError::OpenError: + case QSerialPort::SerialPortError::NotOpenError: + case QSerialPort::SerialPortError::UnknownError: + { + ERROR_LOG(m_logger) << "Closing port and try to reopen it. " << m_currentSerialPort->portName(); + continueQuerry(); - Q_FALLTHROUGH(); - } - case QSerialPort::SerialPortError::UnsupportedOperationError: { - ERROR_LOG(m_logger) << errStr; - break; - } - default: { - ERROR_LOG(m_logger) << "Got an Error> " << errStr << "restarting"; - continueQuerry(); + Q_FALLTHROUGH(); + } + case QSerialPort::SerialPortError::UnsupportedOperationError: + { + ERROR_LOG(m_logger) << errStr; + break; + } + default: + { + ERROR_LOG(m_logger) << "Got an Error> " << errStr << "restarting"; + continueQuerry(); - break; - } + break; + } } -} + } } // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h index 9eb2d0a8d..d4df15461 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h @@ -9,18 +9,21 @@ namespace LtsSerialPortQuerry { -class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject -{ + class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject + { Q_OBJECT public: - explicit LtsSerialPortQuerry(QObject* parent = nullptr); + explicit LtsSerialPortQuerry(QObject *parent = nullptr); - void setSerialPortSettings(const QSerialPort::BaudRate& baudRate, const QSerialPort::OpenModeFlag& openModeFlag, - const QSerialPort::DataBits& dataBits, const QSerialPort::FlowControl& flowControll, - const QSerialPort::Parity& parity, const QSerialPort::StopBits& stopBits); + void setSerialPortSettings(const QSerialPort::BaudRate &baudRate, + const QSerialPort::OpenModeFlag &openModeFlag, + const QSerialPort::DataBits &dataBits, + const QSerialPort::FlowControl &flowControll, + const QSerialPort::Parity &parity, + const QSerialPort::StopBits &stopBits); void restartQuerry(); - QSerialPort* currentSerialPort(); + QSerialPort *currentSerialPort(); public slots: void continueQuerry(); @@ -29,8 +32,8 @@ class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject void connectionEstablished(); private: - NGL::INGLLogger& m_logger; - void querrySerialPort(const QSerialPortInfo& info); + NGL::INGLLogger &m_logger; + void querrySerialPort(const QSerialPortInfo &info); void closeAndDeleteCurrentPort(); void onSerialPortError(QSerialPort::SerialPortError serialPortError); QList m_serialPortInfos; @@ -41,7 +44,7 @@ class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject QSerialPort::FlowControl m_flowControll; QSerialPort::Parity m_parity; QSerialPort::StopBits m_stopBits; - QSerialPort* m_currentSerialPort; -}; + QSerialPort *m_currentSerialPort; + }; } // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp index 69a5142e0..9c3fb38ef 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp @@ -34,619 +34,609 @@ using namespace LtsUtils; namespace QTest { -template <> char* toString(const QVector& vec) -{ + template <> char *toString(const QVector &vec) + { QStringList sl; sl.reserve(vec.size()); for (int i : vec) - sl += QString::number(i); + sl += QString::number(i); return qstrdup(sl.join(QLatin1Char(',')).toLatin1().constData()); -} + } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) -template -inline bool qCompare(const T1& t1, const T2& t2, const char* actual, const char* expected, const char* file, int line) -{ - return compare_helper(t1 == t2, "Compared values are not the same", toString(t1), toString(t2), actual, expected, - file, line); -} + template inline bool qCompare(const T1 &t1, const T2 &t2, const char *actual, const char *expected, const char *file, int line) + { + return compare_helper(t1 == t2, "Compared values are not the same", toString(t1), toString(t2), actual, expected, file, line); + } #endif } // namespace QTest -int main(int argc, char* argv[]) +int main(int argc, char *argv[]) { - QCoreApplication app(argc, argv); - LtsUtilsTest tc; - return QTest::qExec(&tc, argc, argv); + QCoreApplication app(argc, argv); + LtsUtilsTest tc; + return QTest::qExec(&tc, argc, argv); } void LtsUtilsTest::test_promise() { - QVector results; + QVector results; - results.append(1); + results.append(1); - LtsUtils::Promise p([&results](LtsUtils::ResultFunction resolve, LtsUtils::ResultFunction) { + LtsUtils::Promise p( + [&results](LtsUtils::ResultFunction resolve, LtsUtils::ResultFunction) + { results.append(4); qDebug() << "LtsUtils Promise: Promise executed! Resolving now"; resolve(QStringLiteral("hello world!")); - }); + }); - results.append(2); + results.append(2); - bool resolved = false; - p.resolved([&resolved, &results](const QVariant& value) { + bool resolved = false; + p.resolved( + [&resolved, &results](const QVariant &value) + { results.append(5); qDebug() << "LtsUtils Promise: Promise was resolved with value" << value; resolved = true; - }); + }); - p.rejected([](const QVariant& val) { + p.rejected( + [](const QVariant &val) + { qCritical() << "rejected with val" << val; QFAIL("Promise unexpectedly rejected"); - }); + }); - results.append(3); + results.append(3); - QTRY_VERIFY2(resolved, "Promise was not resolved"); - QCOMPARE((QVector() << 1 << 2 << 3 << 4 << 5), results); + QTRY_VERIFY2(resolved, "Promise was not resolved"); + QCOMPARE((QVector() << 1 << 2 << 3 << 4 << 5), results); } void LtsUtilsTest::test_promise_example1() { - qDebug("LtsUtils: test_promise_example1"); + qDebug("LtsUtils: test_promise_example1"); - LtsUtils::PromiseExample1 p; + LtsUtils::PromiseExample1 p; - QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); + QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); } void LtsUtilsTest::test_promise_example2() { - qDebug("LtsUtils: test_promise_example2"); + qDebug("LtsUtils: test_promise_example2"); - LtsUtils::PromiseExample2 p; + LtsUtils::PromiseExample2 p; - QTRY_VERIFY2(p.isSuccess(), "Promise didn't reject as expected"); + QTRY_VERIFY2(p.isSuccess(), "Promise didn't reject as expected"); } void LtsUtilsTest::test_promise_example3() { - qDebug("LtsUtils: test_promise_example3"); + qDebug("LtsUtils: test_promise_example3"); - LtsUtils::PromiseExample3 p; + LtsUtils::PromiseExample3 p; - qDebug() << "waiting for expected reject to happen, and wait 2 seconds to see if the timeout triggers even though " - "it shouldn't, because the promise was already rejected"; + qDebug() << "waiting for expected reject to happen, and wait 2 seconds to see if the timeout triggers even though " + "it shouldn't, because the promise was already rejected"; - QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); + QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); } void LtsUtilsTest::test_toIntArray() { - qDebug("LtsUtils: test_toIntArray"); + qDebug("LtsUtils: test_toIntArray"); - QString str; - std::vector vec; + QString str; + std::vector vec; - str = QLatin1String("{0,1,2,3,4,999999999,-2147483647,2147483647}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 8, "Wrong size of QVector! (expected 8)"); + str = QLatin1String("{0,1,2,3,4,999999999,-2147483647,2147483647}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 8, "Wrong size of QVector! (expected 8)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == 1, "Wrong value on position 1"); - QVERIFY2(vec[2] == 2, "Wrong value on position 2"); - QVERIFY2(vec[3] == 3, "Wrong value on position 3"); - QVERIFY2(vec[4] == 4, "Wrong value on position 4"); - QVERIFY2(vec[5] == 999999999, "Wrong value on position 5"); - QVERIFY2(vec[6] == -2147483647, "Wrong vtest_fromIntArray2Dalue on position 6"); - QVERIFY2(vec[7] == 2147483647, "Wrong value on position 7"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == 1, "Wrong value on position 1"); + QVERIFY2(vec[2] == 2, "Wrong value on position 2"); + QVERIFY2(vec[3] == 3, "Wrong value on position 3"); + QVERIFY2(vec[4] == 4, "Wrong value on position 4"); + QVERIFY2(vec[5] == 999999999, "Wrong value on position 5"); + QVERIFY2(vec[6] == -2147483647, "Wrong vtest_fromIntArray2Dalue on position 6"); + QVERIFY2(vec[7] == 2147483647, "Wrong value on position 7"); - str = QLatin1String("1,2,3,"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); + str = QLatin1String("1,2,3,"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); - QVERIFY2(vec[0] == 1, "Wrong value on position 0"); - QVERIFY2(vec[1] == 2, "Wrong value on position 1"); - QVERIFY2(vec[2] == 3, "Wrong value on position 2"); + QVERIFY2(vec[0] == 1, "Wrong value on position 0"); + QVERIFY2(vec[1] == 2, "Wrong value on position 1"); + QVERIFY2(vec[2] == 3, "Wrong value on position 2"); - str = QLatin1String("{a,2,3}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); + str = QLatin1String("{a,2,3}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - str = QLatin1String("{abc}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); + str = QLatin1String("{abc}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); } void LtsUtilsTest::test_fromIntArray() { - qDebug("LtsUtils: test_fromIntArray"); + qDebug("LtsUtils: test_fromIntArray"); - QString str = LtsUtils::IntArray({0, 1, 2, 3, 999999999, -2147483647, 2147483647}).toPgString(); + QString str = LtsUtils::IntArray({0, 1, 2, 3, 999999999, -2147483647, 2147483647}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{0,1,2,3,999999999,-2147483647,2147483647}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{0,1,2,3,999999999,-2147483647,2147483647}")); - str = LtsUtils::IntArray(std::vector()).toPgString(); + str = LtsUtils::IntArray(std::vector()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } void LtsUtilsTest::test_toBigintArray() { - qDebug("LtsUtils: test_toBigintArray"); + qDebug("LtsUtils: test_toBigintArray"); - QString str; - std::vector vec; + QString str; + std::vector vec; - str = QLatin1String("{0,1,2147483647,-2147483647,999999999999}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{0,1,2147483647,-2147483647,999999999999}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == 1, "Wrong value on position 1"); - QVERIFY2(vec[2] == 2147483647, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 999999999999, "Wrong value on position 4"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == 1, "Wrong value on position 1"); + QVERIFY2(vec[2] == 2147483647, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 999999999999, "Wrong value on position 4"); - str = QLatin1String("0,-2147483647,999999999999,"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); + str = QLatin1String("0,-2147483647,999999999999,"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == -2147483647, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == -2147483647, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); - str = QLatin1String("{a,2,3}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); + str = QLatin1String("{a,2,3}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - str = QLatin1String("{abc}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); + str = QLatin1String("{abc}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); } void LtsUtilsTest::test_fromBigintArray() { - qDebug("LtsUtils: test_fromBigintArray"); + qDebug("LtsUtils: test_fromBigintArray"); - QString str = LtsUtils::BigintArray({0, -2147483647, 2147483647, 999999999999, 123456789}).toPgString(); + QString str = LtsUtils::BigintArray({0, -2147483647, 2147483647, 999999999999, 123456789}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{0,-2147483647,2147483647,999999999999,123456789}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{0,-2147483647,2147483647,999999999999,123456789}")); - str = LtsUtils::BigintArray(std::vector()).toPgString(); + str = LtsUtils::BigintArray(std::vector()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } void LtsUtilsTest::test_toIntArray2D() { - qDebug("LtsUtils: test_toIntArray2D"); + qDebug("LtsUtils: test_toIntArray2D"); - QString str; - std::map vec; + QString str; + std::map vec; - str = QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647}}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray2D::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647}}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray2D::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); } void LtsUtilsTest::test_fromIntArray2D() { - qDebug("LtsUtils: test_fromIntArray2D"); + qDebug("LtsUtils: test_fromIntArray2D"); - QString str = LtsUtils::IntArray2D({{0, 2}, {1, 3}, {2, 999999999}, {3, -2147483647}, {4, 2147483647}, {5, 123456}}) - .toPgString(); + QString str = LtsUtils::IntArray2D({{0, 2}, {1, 3}, {2, 999999999}, {3, -2147483647}, {4, 2147483647}, {5, 123456}}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647},{5,123456}}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647},{5,123456}}")); - str = LtsUtils::IntArray2D(std::map()).toPgString(); + str = LtsUtils::IntArray2D(std::map()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } void LtsUtilsTest::test_toBigintArray2D() { - qDebug("LtsUtils: test_toBigintArray2D"); + qDebug("LtsUtils: test_toBigintArray2D"); - QString str; - std::map vec; + QString str; + std::map vec; - str = QLatin1String("{{0,2},{1,3},{2,999999999999},{3,-2147483647},{4,2147483647}}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray2D::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{{0,2},{1,3},{2,999999999999},{3,-2147483647},{4,2147483647}}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray2D::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); } void LtsUtilsTest::test_fromBigintArray2D() { - qDebug("LtsUtils: test_fromBigintArray2D"); + qDebug("LtsUtils: test_fromBigintArray2D"); - QString str = - LtsUtils::BigintArray2D({{0, -123456789}, {1, -2147483647}, {2, 999999999999}, {3, 123456789}, {4, 2147483647}}) - .toPgString(); + QString str = LtsUtils::BigintArray2D({{0, -123456789}, {1, -2147483647}, {2, 999999999999}, {3, 123456789}, {4, 2147483647}}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{{0,-123456789},{1,-2147483647},{2,999999999999},{3,123456789},{4,2147483647}}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{{0,-123456789},{1,-2147483647},{2,999999999999},{3,123456789},{4,2147483647}}")); - str = LtsUtils::BigintArray2D(std::map()).toPgString(); + str = LtsUtils::BigintArray2D(std::map()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } void LtsUtilsTest::test_QPoint3D() { - qDebug("LtsUtils: test_QPoint3D"); + qDebug("LtsUtils: test_QPoint3D"); - LtsUtils::QPoint3D pos(0, 0, 0); + LtsUtils::QPoint3D pos(0, 0, 0); - qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; + qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; - QVERIFY2(pos.x() == 0, "Wrong position (X)"); - QVERIFY2(pos.y() == 0, "Wrong position (Y)"); - QVERIFY2(pos.z() == 0, "Wrong position (Z)"); + QVERIFY2(pos.x() == 0, "Wrong position (X)"); + QVERIFY2(pos.y() == 0, "Wrong position (Y)"); + QVERIFY2(pos.z() == 0, "Wrong position (Z)"); - pos.setX(92000); - pos.setY(77400); - pos.setZ(0); + pos.setX(92000); + pos.setY(77400); + pos.setZ(0); - qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; + qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; - QVERIFY2(pos.x() == 92000, "Wrong position (X)"); - QVERIFY2(pos.y() == 77400, "Wrong position (Y)"); - QVERIFY2(pos.z() == 0, "Wrong position (Z)"); + QVERIFY2(pos.x() == 92000, "Wrong position (X)"); + QVERIFY2(pos.y() == 77400, "Wrong position (Y)"); + QVERIFY2(pos.z() == 0, "Wrong position (Z)"); } void LtsUtilsTest::test_bitArray() { - qDebug("LtsUtils: test_bitArray"); + qDebug("LtsUtils: test_bitArray"); + { + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(8)).size() == 1, " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(9)).size() == 2, " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(16)).size() == 2, " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(17)).size() == 3, " wrong size of underlying data"); + } + + { + QBitArray ba(10); { - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(8)).size() == 1, - " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(9)).size() == 2, - " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(16)).size() == 2, - " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(17)).size() == 3, - " wrong size of underlying data"); + int i = 0; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; } - { - QBitArray ba(10); - { - int i = 0; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; + const std::vector bArray = LtsUtils::BitArray::convert>(ba); - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; - } - - const std::vector bArray = LtsUtils::BitArray::convert>(ba); - - for (int position = 0; position < 20; ++position) - LtsUtils::BitArray::testBit(bArray, position); - - { - QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); - QVERIFY2(ba == retrievedBd, " forward/backward failed"); - } - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - } - - std::vector bArrayCopy; - { - QBitArray ba(10); - { - int i = 0; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; - - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; - } - - const std::vector bArray = LtsUtils::BitArray::convert>(ba); - - { - QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); - QVERIFY2(ba == retrievedBd, " forward/backward failed"); - } - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - - bArrayCopy = bArray; - } + for (int position = 0; position < 20; ++position) + LtsUtils::BitArray::testBit(bArray, position); { - - LtsUtils::BitArray::clearBit(bArrayCopy, 0); - LtsUtils::BitArray::clearBit(bArrayCopy, 1); - LtsUtils::BitArray::clearBit(bArrayCopy, 2); - LtsUtils::BitArray::clearBit(bArrayCopy, 3); - LtsUtils::BitArray::clearBit(bArrayCopy, 4); - QVERIFY2(bArrayCopy[0] == 0, " clearBit failed"); - - LtsUtils::BitArray::setBit(bArrayCopy, 1); - LtsUtils::BitArray::setBit(bArrayCopy, 2); - LtsUtils::BitArray::setBit(bArrayCopy, 3); - LtsUtils::BitArray::setBit(bArrayCopy, 4); - LtsUtils::BitArray::setBit(bArrayCopy, 5); - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - - { - QBitArray ba = LtsUtils::BitArray::convert(bArrayCopy, 10); - const std::vector retrievedVec = LtsUtils::BitArray::convert>(ba); - QVERIFY2(bArrayCopy == retrievedVec, " forward/backward failed"); - } + QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); + QVERIFY2(ba == retrievedBd, " forward/backward failed"); } + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + } + + std::vector bArrayCopy; + { + QBitArray ba(10); + { + int i = 0; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; + + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + } + + const std::vector bArray = LtsUtils::BitArray::convert>(ba); + + { + QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); + QVERIFY2(ba == retrievedBd, " forward/backward failed"); + } + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + + bArrayCopy = bArray; + } + + { + + LtsUtils::BitArray::clearBit(bArrayCopy, 0); + LtsUtils::BitArray::clearBit(bArrayCopy, 1); + LtsUtils::BitArray::clearBit(bArrayCopy, 2); + LtsUtils::BitArray::clearBit(bArrayCopy, 3); + LtsUtils::BitArray::clearBit(bArrayCopy, 4); + QVERIFY2(bArrayCopy[0] == 0, " clearBit failed"); + + LtsUtils::BitArray::setBit(bArrayCopy, 1); + LtsUtils::BitArray::setBit(bArrayCopy, 2); + LtsUtils::BitArray::setBit(bArrayCopy, 3); + LtsUtils::BitArray::setBit(bArrayCopy, 4); + LtsUtils::BitArray::setBit(bArrayCopy, 5); + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + + { + QBitArray ba = LtsUtils::BitArray::convert(bArrayCopy, 10); + const std::vector retrievedVec = LtsUtils::BitArray::convert>(ba); + QVERIFY2(bArrayCopy == retrievedVec, " forward/backward failed"); + } + } } void LtsUtilsTest::test_convert() { - constexpr int containerLen = 50; + constexpr int containerLen = 50; - QByteArray ba(containerLen, Qt::Uninitialized); - for (int i = 0; i < containerLen; ++i) - ba[i] = i + 1; - const auto result = LtsUtils::convert>(ba); - const auto resultBA = LtsUtils::toQByteArray(result); - QCOMPARE(result.size(), containerLen); - QCOMPARE(resultBA.size(), containerLen); - for (int i = 0; i < containerLen; ++i) - QCOMPARE(resultBA.at(i), i + 1); + QByteArray ba(containerLen, Qt::Uninitialized); + for (int i = 0; i < containerLen; ++i) + ba[i] = i + 1; + const auto result = LtsUtils::convert>(ba); + const auto resultBA = LtsUtils::toQByteArray(result); + QCOMPARE(result.size(), containerLen); + QCOMPARE(resultBA.size(), containerLen); + for (int i = 0; i < containerLen; ++i) + QCOMPARE(resultBA.at(i), i + 1); - QVector> outer; - outer.reserve(containerLen); + QVector> outer; + outer.reserve(containerLen); + for (int i = 0; i < containerLen; ++i) + outer.push_back(result); + const auto resultVec = LtsUtils::convert>>(outer); + const auto resultQVec = LtsUtils::convert>>(resultVec); + QCOMPARE(resultVec.size(), containerLen); + QCOMPARE(resultQVec.size(), containerLen); + for (const auto &inner : resultQVec) + { for (int i = 0; i < containerLen; ++i) - outer.push_back(result); - const auto resultVec = LtsUtils::convert>>(outer); - const auto resultQVec = LtsUtils::convert>>(resultVec); - QCOMPARE(resultVec.size(), containerLen); - QCOMPARE(resultQVec.size(), containerLen); - for (const auto& inner : resultQVec) - { - for (int i = 0; i < containerLen; ++i) - QCOMPARE(inner.at(i), i + 1); - } + QCOMPARE(inner.at(i), i + 1); + } - QVERIFY(!LtsUtils::isInVector(result, 0)); - QVERIFY(LtsUtils::isInVector(result, 1)); - QVERIFY(LtsUtils::isInVector(result, containerLen)); - QVERIFY(!LtsUtils::isInVector(result, containerLen + 1)); + QVERIFY(!LtsUtils::isInVector(result, 0)); + QVERIFY(LtsUtils::isInVector(result, 1)); + QVERIFY(LtsUtils::isInVector(result, containerLen)); + QVERIFY(!LtsUtils::isInVector(result, containerLen + 1)); } class Emitter : public QObject { - Q_OBJECT + Q_OBJECT - signals: - void signal1(); - void signal2(int i); +signals: + void signal1(); + void signal2(int i); }; class Spy : public QObject { - Q_OBJECT + Q_OBJECT - public slots: +public slots: - void slot1() - { - ++m_slot1Count; - } + void slot1() { ++m_slot1Count; } - public: - int m_slot1Count{0}; +public: + int m_slot1Count{0}; }; void LtsUtilsTest::test_connection() { - Emitter emitter; - Spy spy; - std::unique_ptr conn( - LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 0); + Emitter emitter; + Spy spy; + std::unique_ptr conn(LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 0); - conn->connect(); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 1); + conn->connect(); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 1); - conn->disconnect(); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 1); + conn->disconnect(); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_queuedConnection() { - Emitter emitter; - Spy spy; - std::unique_ptr conn( - LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 0); + Emitter emitter; + Spy spy; + std::unique_ptr conn(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 0); - conn->connect(Qt::QueuedConnection); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 0); + conn->connect(Qt::QueuedConnection); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 0); - QTRY_COMPARE(spy.m_slot1Count, 1); + QTRY_COMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_signalSignalConnection() { - Emitter emitter; - Spy spy; - std::unique_ptr signalSignalConn( - LtsUtils::createConnection(&emitter, &Emitter::signal2, &emitter, &Emitter::signal1)); - std::unique_ptr signalSlotConn( - LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); + Emitter emitter; + Spy spy; + std::unique_ptr signalSignalConn(LtsUtils::createConnection(&emitter, &Emitter::signal2, &emitter, &Emitter::signal1)); + std::unique_ptr signalSlotConn(LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); - signalSignalConn->connect(); - signalSlotConn->connect(); + signalSignalConn->connect(); + signalSlotConn->connect(); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 1); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_danglingConnection1() { - Spy spy; - std::unique_ptr conn; + Spy spy; + std::unique_ptr conn; - { - Emitter emitter; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - } + { + Emitter emitter; + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + } - conn->connect(); - conn->disconnect(); + conn->connect(); + conn->disconnect(); } void LtsUtilsTest::test_danglingConnection2() { - Emitter emitter; - std::unique_ptr conn; + Emitter emitter; + std::unique_ptr conn; - { - Spy spy; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - } + { + Spy spy; + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + } - conn->connect(); - conn->disconnect(); + conn->connect(); + conn->disconnect(); } void LtsUtilsTest::test_danglingConnection3() { - Emitter emitter; - std::unique_ptr spy(new Spy); - std::unique_ptr conn; + Emitter emitter; + std::unique_ptr spy(new Spy); + std::unique_ptr conn; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, spy.get(), &Spy::slot1)); + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, spy.get(), &Spy::slot1)); - conn->connect(); - spy.reset(); - conn->disconnect(); + conn->connect(); + spy.reset(); + conn->disconnect(); } void LtsUtilsTest::test_jsonObject_fromJson() { - { - std::string json = R"({})"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = R"({})"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(obj.isValid()); + QVERIFY(obj.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": true})"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(obj.isValid()); - QVERIFY(!obj.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": true})"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(obj.isValid()); + QVERIFY(!obj.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": })"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(!obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": })"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(!obj.isValid()); + QVERIFY(obj.isEmpty()); + } - { - std::string json = "[1, 2, 3, 4]"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(!obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = "[1, 2, 3, 4]"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(!obj.isValid()); + QVERIFY(obj.isEmpty()); + } } void LtsUtilsTest::test_jsonObject_contains() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {}, "int array": [1, 2, 3], "string array": ["hello", "json"], @@ -654,173 +644,173 @@ void LtsUtilsTest::test_jsonObject_contains() "int map": {"i": 1, "j": 2, "k": 3}, "mixed map": {"i": 1, "j": 2, "k": "3"} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QVERIFY(obj.contains("int")); - QVERIFY(obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); + QVERIFY(obj.contains("int")); + QVERIFY(obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("double")); - QVERIFY(obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(obj.contains("string")); - QVERIFY(obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(obj.contains("string")); + QVERIFY(obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(obj.contains("null")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(obj.contains("object")); - QVERIFY(obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(obj.contains("object")); + QVERIFY(obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(obj.contains("int array")); - QVERIFY(obj.contains("int array")); - QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(obj.contains("int array")); + QVERIFY(obj.contains("int array")); + QVERIFY(!obj.contains("int array")); - QVERIFY(obj.contains("mixed array")); - QVERIFY(obj.contains("mixed array")); + QVERIFY(obj.contains("mixed array")); + QVERIFY(obj.contains("mixed array")); - QVERIFY(obj.contains>("int array")); - QVERIFY(!obj.contains>("int array")); - QVERIFY(obj.contains>("int array")); - QVERIFY(!obj.contains>("int array")); + QVERIFY(obj.contains>("int array")); + QVERIFY(!obj.contains>("int array")); + QVERIFY(obj.contains>("int array")); + QVERIFY(!obj.contains>("int array")); - QVERIFY((obj.contains>("int map"))); - QVERIFY(!(obj.contains>("mixed map"))); - QVERIFY((obj.contains>("int map"))); - QVERIFY(!(obj.contains>("mixed map"))); + QVERIFY((obj.contains>("int map"))); + QVERIFY(!(obj.contains>("mixed map"))); + QVERIFY((obj.contains>("int map"))); + QVERIFY(!(obj.contains>("mixed map"))); } void LtsUtilsTest::test_jsonObject_value() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {"a": 1, "b": 2, "c": 3}, "int array": [1, 2, 3], "string array": ["hello", "json"], "mixed array": ["hello", 42], "int map": {"i": 1, "j": 2, "k": 3} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QCOMPARE(obj.value("int"), 42); - QCOMPARE(obj.value("double"), 3.14); - QCOMPARE(obj.value("string").c_str(), "hello json"); - QCOMPARE(obj.value("string"), QStringLiteral("hello json")); - QCOMPARE(obj.value("bool"), true); + QCOMPARE(obj.value("int"), 42); + QCOMPARE(obj.value("double"), 3.14); + QCOMPARE(obj.value("string").c_str(), "hello json"); + QCOMPARE(obj.value("string"), QStringLiteral("hello json")); + QCOMPARE(obj.value("bool"), true); - QJsonObject expectedObject{{QStringLiteral("a"), 1}, {QStringLiteral("b"), 2}, {QStringLiteral("c"), 3}}; - QCOMPARE(obj.value("object"), expectedObject); - QCOMPARE(obj.value("object"), JsonObject(expectedObject)); + QJsonObject expectedObject{{QStringLiteral("a"), 1}, {QStringLiteral("b"), 2}, {QStringLiteral("c"), 3}}; + QCOMPARE(obj.value("object"), expectedObject); + QCOMPARE(obj.value("object"), JsonObject(expectedObject)); - QJsonArray expectedMixedArray{QStringLiteral("hello"), 42}; - QCOMPARE(obj.value("mixed array"), expectedMixedArray); - QCOMPARE(obj.value("mixed array"), JsonArray(expectedMixedArray)); + QJsonArray expectedMixedArray{QStringLiteral("hello"), 42}; + QCOMPARE(obj.value("mixed array"), expectedMixedArray); + QCOMPARE(obj.value("mixed array"), JsonArray(expectedMixedArray)); - QVector expectedIntArray{1, 2, 3}; - QCOMPARE(obj.value>("int array"), expectedIntArray); + QVector expectedIntArray{1, 2, 3}; + QCOMPARE(obj.value>("int array"), expectedIntArray); - std::vector expectedStdIntArray{1, 2, 3}; - QCOMPARE(obj.value>("int array"), expectedStdIntArray); + std::vector expectedStdIntArray{1, 2, 3}; + QCOMPARE(obj.value>("int array"), expectedStdIntArray); - QVector expectedStringArray{QStringLiteral("hello"), QStringLiteral("json")}; - QCOMPARE(obj.value>("string array"), expectedStringArray); + QVector expectedStringArray{QStringLiteral("hello"), QStringLiteral("json")}; + QCOMPARE(obj.value>("string array"), expectedStringArray); - std::vector expectedStdStringArray{"hello", "json"}; - QCOMPARE(obj.value>("string array"), expectedStdStringArray); + std::vector expectedStdStringArray{"hello", "json"}; + QCOMPARE(obj.value>("string array"), expectedStdStringArray); - QMap expectedIntMap{{QStringLiteral("i"), 1}, {QStringLiteral("j"), 2}, {QStringLiteral("k"), 3}}; - QCOMPARE((obj.value>("int map")), expectedIntMap); + QMap expectedIntMap{{QStringLiteral("i"), 1}, {QStringLiteral("j"), 2}, {QStringLiteral("k"), 3}}; + QCOMPARE((obj.value>("int map")), expectedIntMap); - std::map expectedStdIntMap{{"i", 1}, {"j", 2}, {"k", 3}}; - QCOMPARE((obj.value>("int map")), expectedStdIntMap); + std::map expectedStdIntMap{{"i", 1}, {"j", 2}, {"k", 3}}; + QCOMPARE((obj.value>("int map")), expectedStdIntMap); - QVERIFY(obj.isNull("null")); + QVERIFY(obj.isNull("null")); } void LtsUtilsTest::test_jsonObject_valueWithError() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {"a": 1, "b": 2, "c": 3}, "int array": [1, 2, 3], "string array": ["hello", "json"], "mixed array": ["hello", 42], "mixed map": {"i": 1, "j": 2, "k": "3"} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QVERIFY_EXCEPTION_THROWN(obj.value("unknown key"), JsonKeyError); + QVERIFY_EXCEPTION_THROWN(obj.value("unknown key"), JsonKeyError); - QVERIFY_EXCEPTION_THROWN(obj.value("double"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("string"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("object"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value>("mixed array"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); - QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("double"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("string"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("object"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value>("mixed array"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); + QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); } void LtsUtilsTest::test_jsonObject_valueOr() { - QJsonObject obj_{{QStringLiteral("int"), 42}}; - JsonObject obj(obj_); + QJsonObject obj_{{QStringLiteral("int"), 42}}; + JsonObject obj(obj_); - QCOMPARE(obj.valueOr("int", -1), 42); + QCOMPARE(obj.valueOr("int", -1), 42); - QCOMPARE(obj.valueOr("string", -1), -1); + QCOMPARE(obj.valueOr("string", -1), -1); - QVERIFY_EXCEPTION_THROWN(obj.valueOr("int", QString()), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.valueOr("int", QString()), JsonTypeError); } void LtsUtilsTest::test_jsonObject_integers() { - std::string json = R"({ + std::string json = R"({ "int16_min": -32768, "int16_max": 32767, "int16_min-1": -32769, @@ -847,316 +837,313 @@ void LtsUtilsTest::test_jsonObject_integers() "uint64_max": 9007199254740991, "uint64_max+1": 9007199254740992 })"; - JsonObject obj = JsonObject::fromJson(json); - QVERIFY(obj.contains("int16_min")); - QVERIFY(obj.contains("int16_max")); - QVERIFY(!obj.contains("int16_min-1")); - QVERIFY(!obj.contains("int16_max+1")); - QVERIFY(obj.contains("int16_min-1")); - QVERIFY(obj.contains("int16_max+1")); + JsonObject obj = JsonObject::fromJson(json); + QVERIFY(obj.contains("int16_min")); + QVERIFY(obj.contains("int16_max")); + QVERIFY(!obj.contains("int16_min-1")); + QVERIFY(!obj.contains("int16_max+1")); + QVERIFY(obj.contains("int16_min-1")); + QVERIFY(obj.contains("int16_max+1")); - QVERIFY(obj.contains("int32_min")); - QVERIFY(obj.contains("int32_max")); - QVERIFY(!obj.contains("int32_min-1")); - QVERIFY(!obj.contains("int32_max+1")); - QVERIFY(obj.contains("int32_min-1")); - QVERIFY(obj.contains("int32_max+1")); + QVERIFY(obj.contains("int32_min")); + QVERIFY(obj.contains("int32_max")); + QVERIFY(!obj.contains("int32_min-1")); + QVERIFY(!obj.contains("int32_max+1")); + QVERIFY(obj.contains("int32_min-1")); + QVERIFY(obj.contains("int32_max+1")); - QVERIFY(obj.contains("int64_min")); - QVERIFY(obj.contains("int64_max")); - QVERIFY(!obj.contains("int64_min-1")); - QVERIFY(!obj.contains("int64_max+1")); + QVERIFY(obj.contains("int64_min")); + QVERIFY(obj.contains("int64_max")); + QVERIFY(!obj.contains("int64_min-1")); + QVERIFY(!obj.contains("int64_max+1")); - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint16_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint16_max+1")); - QVERIFY(obj.contains("uint16_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint16_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint16_max+1")); + QVERIFY(obj.contains("uint16_max+1")); - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint32_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint32_max+1")); - QVERIFY(obj.contains("uint32_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint32_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint32_max+1")); + QVERIFY(obj.contains("uint32_max+1")); - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint64_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint64_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint64_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint64_max+1")); } void LtsUtilsTest::test_jsonObject_nullValues() { - std::string jsonNullMap = R"( {"a": null, "b": null, "c": null} )"; - JsonObject obj = JsonObject::fromJson(jsonNullMap); - QVERIFY(obj.isMap()); + std::string jsonNullMap = R"( {"a": null, "b": null, "c": null} )"; + JsonObject obj = JsonObject::fromJson(jsonNullMap); + QVERIFY(obj.isMap()); } void LtsUtilsTest::test_jsonArray_fromJson() { - { - std::string json = "[]"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = "[]"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(arr.isValid()); + QVERIFY(arr.isEmpty()); + } - { - std::string json = R"([1, 2, true, false, null])"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(arr.isValid()); - QVERIFY(!arr.isEmpty()); - } + { + std::string json = R"([1, 2, true, false, null])"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(arr.isValid()); + QVERIFY(!arr.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": })"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(!arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": })"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(!arr.isValid()); + QVERIFY(arr.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": true})"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(!arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": true})"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(!arr.isValid()); + QVERIFY(arr.isEmpty()); + } } void LtsUtilsTest::test_jsonArray() { - std::string jsonIntArray = R"( [0, 1, 2, 3] )"; - JsonArray array = JsonArray::fromJson(jsonIntArray); - QCOMPARE(array.size(), 4); + std::string jsonIntArray = R"( [0, 1, 2, 3] )"; + JsonArray array = JsonArray::fromJson(jsonIntArray); + QCOMPARE(array.size(), 4); - QVERIFY(array.contains(0)); - QVERIFY(!array.contains(0)); - QCOMPARE(array.at(0), 0); + QVERIFY(array.contains(0)); + QVERIFY(!array.contains(0)); + QCOMPARE(array.at(0), 0); - QVERIFY_EXCEPTION_THROWN(array.at(0), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(array.at(0), JsonTypeError); - QVERIFY_EXCEPTION_THROWN((void)array.contains(-1), JsonRangeError); - QVERIFY_EXCEPTION_THROWN((void)array.contains(4), JsonRangeError); - QVERIFY_EXCEPTION_THROWN(array.at(-1), JsonRangeError); - QVERIFY_EXCEPTION_THROWN(array.at(4), JsonRangeError); + QVERIFY_EXCEPTION_THROWN((void)array.contains(-1), JsonRangeError); + QVERIFY_EXCEPTION_THROWN((void)array.contains(4), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.at(-1), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.at(4), JsonRangeError); - QVERIFY(array.isVector()); - QVERIFY(!array.isVector()); - QCOMPARE(array.toVector(), QVector({0, 1, 2, 3})); - QCOMPARE(array.toStdVector(), std::vector({0, 1, 2, 3})); + QVERIFY(array.isVector()); + QVERIFY(!array.isVector()); + QCOMPARE(array.toVector(), QVector({0, 1, 2, 3})); + QCOMPARE(array.toStdVector(), std::vector({0, 1, 2, 3})); } void LtsUtilsTest::test_jsonArray_nullArray() { - std::string jsonNullArray = R"( [null, null, null, null] )"; - JsonArray array = JsonArray::fromJson(jsonNullArray); - QVERIFY(array.isNull(0)); - QVERIFY(array.isVector()); + std::string jsonNullArray = R"( [null, null, null, null] )"; + JsonArray array = JsonArray::fromJson(jsonNullArray); + QVERIFY(array.isNull(0)); + QVERIFY(array.isVector()); } void LtsUtilsTest::test_byteStreamFromSfmMessage() { - SfmMessage msg; + SfmMessage msg; - msg.setId(16); - msg.setRtr(true); - const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50}; - msg.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); + msg.setId(16); + msg.setRtr(true); + const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50}; + msg.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); - const quint8 expectedResultArray[] = {0x02, 0x80, 0x00, 0x10, 0x05, 0x80, 0x91, 0x80, - 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0x03}; - QByteArray expectedResult = - QByteArray(reinterpret_cast(expectedResultArray), sizeof(expectedResultArray)); + const quint8 expectedResultArray[] = {0x02, 0x80, 0x00, 0x10, 0x05, 0x80, 0x91, 0x80, 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0x03}; + QByteArray expectedResult = QByteArray(reinterpret_cast(expectedResultArray), sizeof(expectedResultArray)); - QByteArray byteMessage = byteStreamFromSfmMessage(msg); + QByteArray byteMessage = byteStreamFromSfmMessage(msg); - QCOMPARE(byteMessage, expectedResult); + QCOMPARE(byteMessage, expectedResult); } void LtsUtilsTest::test_byteStreamFromSfmMessage2() { - SfmMessage msg = LtsUtils::byteStreamToSfmMessage(QByteArray::fromHex("0280004f003003")); - QCOMPARE(msg.rtr(), true); - QVERIFY2(msg.id() == 0x4f, "Value not expected"); - QVERIFY2((msg.id() | (msg.rtr() << 15)) == 0x804f, "Value not expected"); + SfmMessage msg = LtsUtils::byteStreamToSfmMessage(QByteArray::fromHex("0280004f003003")); + QCOMPARE(msg.rtr(), true); + QVERIFY2(msg.id() == 0x4f, "Value not expected"); + QVERIFY2((msg.id() | (msg.rtr() << 15)) == 0x804f, "Value not expected"); } void LtsUtilsTest::test_byteStreamToSfmMessage() { - SfmMessage msgComplete; - msgComplete.setId(16); - msgComplete.setRtr(true); + SfmMessage msgComplete; + msgComplete.setId(16); + msgComplete.setRtr(true); - const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50, 0x00}; - msgComplete.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); + const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50, 0x00}; + msgComplete.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); - const quint8 dataArray[] = {0x02, 0x80, 0x00, 0x10, 0x06, 0x80, 0x91, 0x80, - 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0xFF, 0x03}; - QByteArray dataComplete = QByteArray(reinterpret_cast(dataArray), sizeof(dataArray)); + const quint8 dataArray[] = {0x02, 0x80, 0x00, 0x10, 0x06, 0x80, 0x91, 0x80, 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0xFF, 0x03}; + QByteArray dataComplete = QByteArray(reinterpret_cast(dataArray), sizeof(dataArray)); - SfmMessage result; - try - { - result = byteStreamToSfmMessage(dataComplete); - } - catch (const ConversionError& ex) - { - qDebug() << ex.what(); - } - QCOMPARE(result, msgComplete); + SfmMessage result; + try + { + result = byteStreamToSfmMessage(dataComplete); + } + catch (const ConversionError &ex) + { + qDebug() << ex.what(); + } + QCOMPARE(result, msgComplete); - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(QByteArray()), ConversionError); + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(QByteArray()), ConversionError); - QByteArray framingError = dataComplete; - framingError.chop(1); - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(framingError), ConversionError); + QByteArray framingError = dataComplete; + framingError.chop(1); + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(framingError), ConversionError); - QByteArray checksumError = dataComplete; - checksumError[14] = 0x01; - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(checksumError), ConversionError); + QByteArray checksumError = dataComplete; + checksumError[14] = 0x01; + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(checksumError), ConversionError); - QByteArray lengthError = dataComplete; - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(lengthError.remove(13, 1)), ConversionError); + QByteArray lengthError = dataComplete; + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(lengthError.remove(13, 1)), ConversionError); } void LtsUtilsTest::byteAccess() { - QByteArray ba; - LtsUtils::set1Byte(0x67, ba); - LtsUtils::set1Byte(0xcb, ba); - LtsUtils::set2Byte(0x1234, ba); - LtsUtils::set2Byte(0x9876, ba); - LtsUtils::set3Byte(0x6263fb, ba); - LtsUtils::set3Byte(0x80e87b, ba); - LtsUtils::set4Byte(0x66b9dd15, ba); - LtsUtils::set4Byte(0xa254a715, ba); - LtsUtils::set8Byte(0x1234567812345678, ba); - LtsUtils::set8Byte(0x8234567812345678, ba); + QByteArray ba; + LtsUtils::set1Byte(0x67, ba); + LtsUtils::set1Byte(0xcb, ba); + LtsUtils::set2Byte(0x1234, ba); + LtsUtils::set2Byte(0x9876, ba); + LtsUtils::set3Byte(0x6263fb, ba); + LtsUtils::set3Byte(0x80e87b, ba); + LtsUtils::set4Byte(0x66b9dd15, ba); + LtsUtils::set4Byte(0xa254a715, ba); + LtsUtils::set8Byte(0x1234567812345678, ba); + LtsUtils::set8Byte(0x8234567812345678, ba); - { - int64_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, 6448123); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, -8329093); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, 1723456789); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, -1571510507); - LtsUtils::get8Byte(ba, pos, i); - QCOMPARE(i, 0x1234567812345678); - LtsUtils::get8Byte(ba, pos, i); - QCOMPARE(i, 0x8234567812345678); + { + int64_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, 6448123); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, -8329093); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, 1723456789); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, -1571510507); + LtsUtils::get8Byte(ba, pos, i); + QCOMPARE(i, 0x1234567812345678); + LtsUtils::get8Byte(ba, pos, i); + QCOMPARE(i, 0x8234567812345678); - uint64_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 6448123); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 8448123); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 1723456789); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 2723456789); - LtsUtils::get8Byte(ba, pos, u); - QCOMPARE(u, 0x1234567812345678); - LtsUtils::get8Byte(ba, pos, u); - QCOMPARE(u, 0x8234567812345678); - } - { - int32_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, 6448123); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, -8329093); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, 1723456789); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, -1571510507); + uint64_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 6448123); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 8448123); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 1723456789); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 2723456789); + LtsUtils::get8Byte(ba, pos, u); + QCOMPARE(u, 0x1234567812345678); + LtsUtils::get8Byte(ba, pos, u); + QCOMPARE(u, 0x8234567812345678); + } + { + int32_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, 6448123); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, -8329093); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, 1723456789); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, -1571510507); - uint32_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 6448123); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 8448123); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 1723456789); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 2723456789); - } - { - int16_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); + uint32_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 6448123); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 8448123); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 1723456789); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 2723456789); + } + { + int16_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); - uint16_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - } - { - int8_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); + uint16_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + } + { + int8_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); - uint8_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - } + uint8_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + } } #include "utils_test.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h index bac3ffac8..cd1267ca7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h @@ -6,50 +6,50 @@ class LtsUtilsTest : public QObject { - Q_OBJECT - private Q_SLOTS: + Q_OBJECT +private Q_SLOTS: - void test_toIntArray(); - void test_fromIntArray(); - void test_toBigintArray(); - void test_fromBigintArray(); - void test_toIntArray2D(); - void test_fromIntArray2D(); - void test_toBigintArray2D(); - void test_fromBigintArray2D(); + void test_toIntArray(); + void test_fromIntArray(); + void test_toBigintArray(); + void test_fromBigintArray(); + void test_toIntArray2D(); + void test_fromIntArray2D(); + void test_toBigintArray2D(); + void test_fromBigintArray2D(); - void test_QPoint3D(); + void test_QPoint3D(); - void test_bitArray(); + void test_bitArray(); - void test_convert(); + void test_convert(); - void test_connection(); - void test_queuedConnection(); - void test_signalSignalConnection(); - void test_danglingConnection1(); - void test_danglingConnection2(); - void test_danglingConnection3(); + void test_connection(); + void test_queuedConnection(); + void test_signalSignalConnection(); + void test_danglingConnection1(); + void test_danglingConnection2(); + void test_danglingConnection3(); - void test_jsonObject_fromJson(); - void test_jsonObject_contains(); - void test_jsonObject_value(); - void test_jsonObject_valueWithError(); - void test_jsonObject_valueOr(); - void test_jsonObject_integers(); - void test_jsonObject_nullValues(); - void test_jsonArray_fromJson(); - void test_jsonArray(); - void test_jsonArray_nullArray(); + void test_jsonObject_fromJson(); + void test_jsonObject_contains(); + void test_jsonObject_value(); + void test_jsonObject_valueWithError(); + void test_jsonObject_valueOr(); + void test_jsonObject_integers(); + void test_jsonObject_nullValues(); + void test_jsonArray_fromJson(); + void test_jsonArray(); + void test_jsonArray_nullArray(); - void test_byteStreamFromSfmMessage(); - void test_byteStreamFromSfmMessage2(); - void test_byteStreamToSfmMessage(); + void test_byteStreamFromSfmMessage(); + void test_byteStreamFromSfmMessage2(); + void test_byteStreamToSfmMessage(); - void test_promise(); - void test_promise_example1(); - void test_promise_example2(); - void test_promise_example3(); + void test_promise(); + void test_promise_example1(); + void test_promise_example2(); + void test_promise_example3(); - void byteAccess(); + void byteAccess(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h index f10d64e0f..82bf8bf28 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h @@ -7,28 +7,25 @@ namespace LtsUtils { -template -void addConnect(QEventLoop& x, bool& success, const typename QtPrivate::FunctionPointer::Object* sender, - Func signal, bool isSuccess) -{ + template void addConnect(QEventLoop &x, bool &success, const typename QtPrivate::FunctionPointer::Object *sender, Func signal, bool isSuccess) + { if (isSuccess) { - QObject::connect(sender, signal, &x, [&success]() { success = true; }); + QObject::connect(sender, signal, &x, [&success]() { success = true; }); } QObject::connect(sender, signal, &x, &QEventLoop::quit, Qt::QueuedConnection); -} + } -template -void addConnect(QEventLoop& x, bool& success, const typename QtPrivate::FunctionPointer::Object* sender, - Func signal, bool isSuccess, Connect... connects) -{ + template + void addConnect(QEventLoop &x, bool &success, const typename QtPrivate::FunctionPointer::Object *sender, Func signal, bool isSuccess, Connect... connects) + { addConnect(x, success, sender, signal, isSuccess); addConnect(x, success, connects...); -} + } -template void await(Connect... connects) noexcept(false) -{ + template void await(Connect... connects) noexcept(false) + { QEventLoop x; bool success = false; @@ -39,24 +36,28 @@ template void await(Connect... connects) noexcept(false) if (!success) { - throw std::runtime_error("Failed."); + throw std::runtime_error("Failed."); } -} + } -template void awaitTimeout(const int timeoutMs, Connect... connects) noexcept(false) -{ + template void awaitTimeout(const int timeoutMs, Connect... connects) noexcept(false) + { std::unique_ptr t(new QTimer); bool timeout = false; if (timeoutMs > -1) { - t->setInterval(timeoutMs); - t->setSingleShot(true); - QObject::connect(t.get(), &QTimer::timeout, t.get(), [&timeout]() { - fprintf(stderr, "awaitTimeout: timed out!\n"); - timeout = true; - }); - t->start(); + t->setInterval(timeoutMs); + t->setSingleShot(true); + QObject::connect(t.get(), + &QTimer::timeout, + t.get(), + [&timeout]() + { + fprintf(stderr, "awaitTimeout: timed out!\n"); + timeout = true; + }); + t->start(); } await(t.get(), &QTimer::timeout, false, connects...); @@ -64,21 +65,23 @@ template void awaitTimeout(const int timeoutMs, Connect... if (timeout) { - throw std::runtime_error("Timeout."); + throw std::runtime_error("Timeout."); } -} + } -template -void awaitWithCancelationSignal(const typename QtPrivate::FunctionPointer::Object* sender1, Func1 signal1, - const typename QtPrivate::FunctionPointer::Object* sender2, Func2 signal2, - const int timeoutMs = 0) noexcept(false) -{ + template + void awaitWithCancelationSignal(const typename QtPrivate::FunctionPointer::Object *sender1, + Func1 signal1, + const typename QtPrivate::FunctionPointer::Object *sender2, + Func2 signal2, + const int timeoutMs = 0) noexcept(false) + { if (timeoutMs > 0) { - awaitTimeout(timeoutMs, sender1, signal1, true, sender2, signal2, false); - return; + awaitTimeout(timeoutMs, sender1, signal1, true, sender2, signal2, false); + return; } await(sender1, signal1, true, sender2, signal2, false); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h index 537457118..dfbc0c278 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h @@ -11,36 +11,36 @@ namespace LtsUtils { -class IConnection -{ + class IConnection + { public: virtual ~IConnection() = default; virtual void connect(Qt::ConnectionType = Qt::AutoConnection) = 0; virtual void disconnect() = 0; -}; + }; -class DummyConnection : public IConnection -{ + class DummyConnection : public IConnection + { public: void connect(Qt::ConnectionType = Qt::AutoConnection) override {} void disconnect() override {} -}; + }; -namespace detail -{ + namespace detail + { -template struct ExtractClass; + template struct ExtractClass; -template struct ExtractClass -{ - using type = T; -}; + template struct ExtractClass + { + using type = T; + }; -} // namespace detail + } // namespace detail -template class Connection : public IConnection -{ + template class Connection : public IConnection + { static_assert(std::is_member_function_pointer_v, "Must be a pointer to method"); static_assert(std::is_member_function_pointer_v, "Must be a pointer to method"); @@ -51,36 +51,39 @@ template class Connection : public IConnection static_assert(std::is_base_of_v, "Must be derived from QObject"); public: - Connection(Emitter* emitter, Signal signal, Target* target, Slot slot) - : m_emitter(emitter), m_signal(signal), m_target(target), m_slot(slot) + Connection(Emitter *emitter, Signal signal, Target *target, Slot slot) + : m_emitter(emitter) + , m_signal(signal) + , m_target(target) + , m_slot(slot) { - Q_ASSERT(emitter); - Q_ASSERT(signal); - Q_ASSERT(target); - Q_ASSERT(slot); + Q_ASSERT(emitter); + Q_ASSERT(signal); + Q_ASSERT(target); + Q_ASSERT(slot); } void connect(Qt::ConnectionType connectionType = Qt::AutoConnection) override { - Q_ASSERT(!m_connected); + Q_ASSERT(!m_connected); - m_connected = true; + m_connected = true; - if (!m_emitter || !m_target) - return; + if (!m_emitter || !m_target) + return; - m_conn = QObject::connect(m_emitter.data(), m_signal, m_target.data(), m_slot, connectionType); - Q_ASSERT(m_conn); + m_conn = QObject::connect(m_emitter.data(), m_signal, m_target.data(), m_slot, connectionType); + Q_ASSERT(m_conn); } void disconnect() override { - Q_ASSERT(m_connected); + Q_ASSERT(m_connected); - if (m_conn) - QObject::disconnect(m_conn); + if (m_conn) + QObject::disconnect(m_conn); - m_connected = false; + m_connected = false; } private: @@ -90,13 +93,15 @@ template class Connection : public IConnection QPointer m_target; Slot m_slot; QMetaObject::Connection m_conn; -}; + }; -template -Connection* createConnection(typename detail::ExtractClass::type* emitter, Signal signal, - typename detail::ExtractClass::type* target, Slot slot) -{ + template + Connection *createConnection(typename detail::ExtractClass::type *emitter, + Signal signal, + typename detail::ExtractClass::type *target, + Slot slot) + { return new Connection(emitter, signal, target, slot); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h index 4d151b181..1e3b1669b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h @@ -4,21 +4,26 @@ #include -enum class DataModification { eAdded, eModified, eRemoved }; - -inline std::ostream& operator<<(std::ostream& str, DataModification mod) +enum class DataModification { - switch (mod) - { - case DataModification::eAdded: - str << "DataModification::eAdded"; - break; - case DataModification::eModified: - str << "DataModification::eModified"; - break; - case DataModification::eRemoved: - str << "DataModification::eRemoved"; - break; - } - return str; + eAdded, + eModified, + eRemoved +}; + +inline std::ostream &operator<<(std::ostream &str, DataModification mod) +{ + switch (mod) + { + case DataModification::eAdded: + str << "DataModification::eAdded"; + break; + case DataModification::eModified: + str << "DataModification::eModified"; + break; + case DataModification::eRemoved: + str << "DataModification::eRemoved"; + break; + } + return str; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h index f33f617ce..80279af05 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h @@ -9,82 +9,82 @@ namespace LtsUtils { -namespace BitArray -{ -constexpr inline int bitNumber(int position) -{ - return 7 - (position % 8); -} - -template inline bool testBit(const T& bitField, int position, bool* oob = nullptr) -{ - const size_t byteNum = position / 8; - if (byteNum >= bitField.size()) + namespace BitArray + { + constexpr inline int bitNumber(int position) { - if (oob) - *oob = true; - return false; + return 7 - (position % 8); } - if (oob) + + template inline bool testBit(const T &bitField, int position, bool *oob = nullptr) + { + const size_t byteNum = position / 8; + if (byteNum >= bitField.size()) + { + if (oob) + *oob = true; + return false; + } + if (oob) *oob = false; - const typename T::value_type mask = 1 << bitNumber(position); - return ((bitField.at(byteNum) & mask) == mask); -} + const typename T::value_type mask = 1 << bitNumber(position); + return ((bitField.at(byteNum) & mask) == mask); + } -template inline bool setBit(T& bitField, int position, bool set = true) -{ - const size_t byteNum = position / 8; - if (byteNum >= bitField.size()) + template inline bool setBit(T &bitField, int position, bool set = true) + { + const size_t byteNum = position / 8; + if (byteNum >= bitField.size()) return false; - const typename T::value_type mask = 1 << bitNumber(position); - if (set) + const typename T::value_type mask = 1 << bitNumber(position); + if (set) bitField[byteNum] |= mask; - else + else bitField[byteNum] &= ~mask; - return true; -} + return true; + } -template inline bool clearBit(T& bitField, int position) -{ - return setBit(bitField, position, false); -} + template inline bool clearBit(T &bitField, int position) + { + return setBit(bitField, position, false); + } #ifdef SUPPORT_QBITARRAY -template inline T convert(const QBitArray& bitArray) -{ - T ret; - ret.resize((bitArray.size() + 7) / 8, 0); - - for (int i = 0; i < bitArray.size(); ++i) + template inline T convert(const QBitArray &bitArray) { + T ret; + ret.resize((bitArray.size() + 7) / 8, 0); + + for (int i = 0; i < bitArray.size(); ++i) + { const size_t byteNum = i / 8; const typename T::value_type mask = (1 << bitNumber(i)); if (bitArray[i]) - ret[byteNum] |= mask; + ret[byteNum] |= mask; else - ret[byteNum] &= ~mask; + ret[byteNum] &= ~mask; + } + return ret; } - return ret; -} -template inline QBitArray convert(T& bitField, int realSize) -{ - QBitArray ba(realSize); - for (int32_t i = 0; i < realSize; ++i) + template inline QBitArray convert(T &bitField, int realSize) { + QBitArray ba(realSize); + for (int32_t i = 0; i < realSize; ++i) + { const size_t byteNum = i / 8; const typename T::value_type mask = (1 << bitNumber(i)); bool bit = ((bitField[byteNum] & mask) == mask); ba[i] = bit; + } + return ba; } - return ba; -} #endif -} // namespace BitArray + } // namespace BitArray } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h index 83ada7a98..88bf36b8a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h @@ -8,30 +8,30 @@ namespace LtsUtils { -template inline void convert(const S& in, T& out) -{ + template inline void convert(const S &in, T &out) + { static_assert(!std::is_same_v, "Try to convert a type to the same type - is useless"); out.reserve(static_cast(in.size())); std::copy(in.begin(), in.end(), std::back_inserter(out)); -} + } -template inline T convert(const S& in) -{ + template inline T convert(const S &in) + { static_assert(!std::is_same_v, "Try to convert a type to the same type - is useless"); T out; convert(in, out); return out; -} + } -template inline QByteArray toQByteArray(const T& in) -{ + template inline QByteArray toQByteArray(const T &in) + { return convert(in); -} + } -template bool isInVector(const T& vec, const V& valueToSearch) -{ + template bool isInVector(const T &vec, const V &valueToSearch) + { const auto end = vec.end(); return std::find(vec.begin(), end, valueToSearch) != end; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h index 3c19be186..f1568222a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h @@ -14,11 +14,11 @@ class QImage; namespace LtsUtils { -LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector& data); -LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray& data); -LTSUTILSCORE_EXPORT QImage getImage(const std::vector& data); -LTSUTILSCORE_EXPORT QImage getImage(const QByteArray& data); -LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng = nullptr); -LTSUTILSCORE_EXPORT std::vector fromImage(const QImage& image, bool* bIsPng = nullptr); + LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector &data); + LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray &data); + LTSUTILSCORE_EXPORT QImage getImage(const std::vector &data); + LTSUTILSCORE_EXPORT QImage getImage(const QByteArray &data); + LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng = nullptr); + LTSUTILSCORE_EXPORT std::vector fromImage(const QImage &image, bool *bIsPng = nullptr); } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h index ecb7d4c0e..d551e8b94 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h @@ -21,95 +21,81 @@ namespace LtsUtils { -class JsonParseError : public std::runtime_error -{ + class JsonParseError : public std::runtime_error + { public: - JsonParseError(const QJsonParseError& err) - : std::runtime_error("json parse error: " + err.errorString().toStdString() + " - at offset " + - std::to_string(err.offset)) + JsonParseError(const QJsonParseError &err) + : std::runtime_error("json parse error: " + err.errorString().toStdString() + " - at offset " + std::to_string(err.offset)) { } -}; + }; -class JsonError : public std::runtime_error -{ + class JsonError : public std::runtime_error + { public: using std::runtime_error::runtime_error; -}; + }; -class JsonKeyError : public JsonError -{ + class JsonKeyError : public JsonError + { public: using JsonError::JsonError; -}; + }; -class JsonRangeError : public JsonError -{ + class JsonRangeError : public JsonError + { public: using JsonError::JsonError; -}; + }; -class JsonTypeError : public JsonError -{ + class JsonTypeError : public JsonError + { public: using JsonError::JsonError; -}; + }; -class JsonObject -{ + class JsonObject + { public: class Key; JsonObject() = default; - explicit JsonObject(const QJsonObject& json) : m_json(json), m_jsonIsSet(true) {} - - explicit JsonObject(QJsonObject&& json) : m_json(std::move(json)), m_jsonIsSet(true) {} - - static inline JsonObject fromJson(const char* json, int len = -1); - - static inline JsonObject fromJson(const QByteArray& json) + explicit JsonObject(const QJsonObject &json) + : m_json(json) + , m_jsonIsSet(true) { - return fromJson(json.data(), json.size()); } - static inline JsonObject fromJson(const std::string& json) + explicit JsonObject(QJsonObject &&json) + : m_json(std::move(json)) + , m_jsonIsSet(true) { - return fromJson(json.c_str(), json.size()); } - static inline JsonObject fromJsonSafe(const char* json, int len = -1) noexcept(false); + static inline JsonObject fromJson(const char *json, int len = -1); - static inline JsonObject fromJsonSafe(const QByteArray& json) noexcept(false) - { - return fromJsonSafe(json.data(), json.size()); - } + static inline JsonObject fromJson(const QByteArray &json) { return fromJson(json.data(), json.size()); } - static inline JsonObject fromJsonSafe(const std::string& json) noexcept(false) - { - return fromJsonSafe(json.c_str(), json.size()); - } + static inline JsonObject fromJson(const std::string &json) { return fromJson(json.c_str(), json.size()); } - template [[nodiscard]] bool contains(const Key& key) const; + static inline JsonObject fromJsonSafe(const char *json, int len = -1) noexcept(false); - [[nodiscard]] bool isNull(const Key& key) const - { - return contains(key); - } + static inline JsonObject fromJsonSafe(const QByteArray &json) noexcept(false) { return fromJsonSafe(json.data(), json.size()); } - [[nodiscard]] bool isEmpty() const - { - return m_json.isEmpty(); - } + static inline JsonObject fromJsonSafe(const std::string &json) noexcept(false) { return fromJsonSafe(json.c_str(), json.size()); } - [[nodiscard]] bool isValid() const - { - return m_jsonIsSet; - } + template [[nodiscard]] bool contains(const Key &key) const; - template T value(const Key& key) const noexcept(false); + [[nodiscard]] bool isNull(const Key &key) const { return contains(key); } - template T valueOr(const Key& key, const T& defaultValue) const noexcept(false); + [[nodiscard]] bool isEmpty() const { return m_json.isEmpty(); } + + [[nodiscard]] bool isValid() const { return m_jsonIsSet; } + + template T value(const Key &key) const noexcept(false); + + template T valueOr(const Key &key, const T &defaultValue) const noexcept(false); template [[nodiscard]] bool isMap() const; @@ -117,138 +103,113 @@ class JsonObject template std::map toStdMap() const; - bool operator==(const JsonObject& other) const - { - return m_json == other.m_json; - } + bool operator==(const JsonObject &other) const { return m_json == other.m_json; } - bool operator!=(const JsonObject& other) const - { - return !(*this == other); - } + bool operator!=(const JsonObject &other) const { return !(*this == other); } class Key { - public: - Key(QString s) : m_s(std::move(s)) {} + public: + Key(QString s) + : m_s(std::move(s)) + { + } - Key(const std::string& s) : m_s(QString::fromStdString(s)) {} + Key(const std::string &s) + : m_s(QString::fromStdString(s)) + { + } - Key(const char* s) : m_s(QString::fromUtf8(s)) {} + Key(const char *s) + : m_s(QString::fromUtf8(s)) + { + } - operator const QString&() const - { - return m_s; - } + operator const QString &() const { return m_s; } - private: - const QString m_s; + private: + const QString m_s; }; - operator const QJsonObject&() const - { - return m_json; - } + operator const QJsonObject &() const { return m_json; } - [[nodiscard]] const QJsonObject& object() const - { - return m_json; - } + [[nodiscard]] const QJsonObject &object() const { return m_json; } private: - [[nodiscard]] bool containsAny(const QString& key) const - { - return m_json.contains(key); - } + [[nodiscard]] bool containsAny(const QString &key) const { return m_json.contains(key); } QJsonObject m_json; bool m_jsonIsSet = false; -}; + }; -JsonObject JsonObject::fromJson(const char* json, int len) -{ + JsonObject JsonObject::fromJson(const char *json, int len) + { if (len < 0) - len = strlen(json); + len = strlen(json); QJsonParseError error; const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); if (error.error != QJsonParseError::NoError) - return {}; + return {}; if (!doc.isObject()) - return {}; + return {}; return JsonObject(doc.object()); -} + } -JsonObject JsonObject::fromJsonSafe(const char* json, int len) noexcept(false) -{ + JsonObject JsonObject::fromJsonSafe(const char *json, int len) noexcept(false) + { if (len < 0) - len = strlen(json); + len = strlen(json); QJsonParseError error; const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); if (error.error != QJsonParseError::NoError) - throw JsonParseError(error); + throw JsonParseError(error); if (!doc.isObject()) - throw JsonTypeError("JSON root is not an object"); + throw JsonTypeError("JSON root is not an object"); return JsonObject(doc.object()); -} + } -class JsonArray -{ + class JsonArray + { public: JsonArray() = default; - explicit JsonArray(const QJsonArray& json) : m_json(json), m_jsonIsSet(true) {} - - explicit JsonArray(QJsonArray&& json) : m_json(std::move(json)), m_jsonIsSet(true) {} - - static inline JsonArray fromJson(const char* json, int len = -1); - - static inline JsonArray fromJson(const QByteArray& json) + explicit JsonArray(const QJsonArray &json) + : m_json(json) + , m_jsonIsSet(true) { - return fromJson(json.data(), json.size()); } - static inline JsonArray fromJson(const std::string& json) + explicit JsonArray(QJsonArray &&json) + : m_json(std::move(json)) + , m_jsonIsSet(true) { - return fromJson(json.c_str(), json.size()); } - static inline JsonArray fromJsonSafe(const char* json, int len = -1) noexcept(false); + static inline JsonArray fromJson(const char *json, int len = -1); - static inline JsonArray fromJsonSafe(const QByteArray& json) noexcept(false) - { - return fromJson(json.data(), json.size()); - } + static inline JsonArray fromJson(const QByteArray &json) { return fromJson(json.data(), json.size()); } - static inline JsonArray fromJsonSafe(const std::string& json) noexcept(false) - { - return fromJson(json.c_str(), json.size()); - } + static inline JsonArray fromJson(const std::string &json) { return fromJson(json.c_str(), json.size()); } - [[nodiscard]] int size() const - { - return m_json.size(); - } + static inline JsonArray fromJsonSafe(const char *json, int len = -1) noexcept(false); - [[nodiscard]] bool isEmpty() const - { - return m_json.isEmpty(); - } + static inline JsonArray fromJsonSafe(const QByteArray &json) noexcept(false) { return fromJson(json.data(), json.size()); } - [[nodiscard]] bool isValid() const - { - return m_jsonIsSet; - } + static inline JsonArray fromJsonSafe(const std::string &json) noexcept(false) { return fromJson(json.c_str(), json.size()); } + + [[nodiscard]] int size() const { return m_json.size(); } + + [[nodiscard]] bool isEmpty() const { return m_json.isEmpty(); } + + [[nodiscard]] bool isValid() const { return m_jsonIsSet; } template [[nodiscard]] bool contains(int index) const noexcept(false); - [[nodiscard]] bool isNull(int index) const noexcept(false) - { - return contains(index); - } + [[nodiscard]] bool isNull(int index) const noexcept(false) { return contains(index); } template T at(int index) const noexcept(false); @@ -258,431 +219,361 @@ class JsonArray template std::vector toStdVector() const; - bool operator==(const JsonArray& other) const - { - return m_json == other.m_json; - } + bool operator==(const JsonArray &other) const { return m_json == other.m_json; } - bool operator!=(const JsonArray& other) const - { - return !(*this == other); - } + bool operator!=(const JsonArray &other) const { return !(*this == other); } - const QJsonArray& operator()() const - { - return m_json; - } + const QJsonArray &operator()() const { return m_json; } private: QJsonArray m_json; bool m_jsonIsSet = false; -}; + }; -JsonArray JsonArray::fromJson(const char* json, int len) -{ + JsonArray JsonArray::fromJson(const char *json, int len) + { if (len < 0) - len = strlen(json); + len = strlen(json); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); if (error.error != QJsonParseError::NoError) - return {}; + return {}; if (!doc.isArray()) - return {}; + return {}; return JsonArray(doc.array()); -} + } -JsonArray JsonArray::fromJsonSafe(const char* json, int len) noexcept(false) -{ + JsonArray JsonArray::fromJsonSafe(const char *json, int len) noexcept(false) + { if (len < 0) - len = strlen(json); + len = strlen(json); QJsonParseError error; const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); if (error.error != QJsonParseError::NoError) - throw JsonParseError(error); + throw JsonParseError(error); if (!doc.isArray()) - throw JsonTypeError("JSON root is not an array"); + throw JsonTypeError("JSON root is not an array"); return JsonArray(doc.array()); -} + } -template struct JsonValue; + template struct JsonValue; -template struct JsonLimits -{ - static constexpr Int lowest() + template struct JsonLimits + { + static constexpr Int lowest() { return std::numeric_limits::lowest(); } + + static constexpr Int max() { return std::numeric_limits::max(); } + }; + + template <> struct JsonLimits + { + static constexpr int64_t lowest() { return -(static_cast(1) << 53) + 1; } + + static constexpr int64_t max() { return (static_cast(1) << 53) - 1; } + }; + + template <> struct JsonLimits + { + static constexpr uint64_t lowest() { return 0; } + + static constexpr uint64_t max() { return JsonLimits::max(); } + }; + + template struct JsonIntValue + { + static bool matchesType(const QJsonValue &value) { - return std::numeric_limits::lowest(); - } - - static constexpr Int max() - { - return std::numeric_limits::max(); - } -}; - -template <> struct JsonLimits -{ - static constexpr int64_t lowest() - { - return -(static_cast(1) << 53) + 1; - } - - static constexpr int64_t max() - { - return (static_cast(1) << 53) - 1; - } -}; - -template <> struct JsonLimits -{ - static constexpr uint64_t lowest() - { - return 0; - } - - static constexpr uint64_t max() - { - return JsonLimits::max(); - } -}; - -template struct JsonIntValue -{ - static bool matchesType(const QJsonValue& value) - { - if (!value.isDouble()) - return false; - double val = value.toDouble(); - - if (val < JsonLimits::lowest()) - return false; - if (val > JsonLimits::max()) - return false; - - double wholeInt = static_cast(val); - return val == wholeInt; - } - - static Int value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Int"); - return static_cast(value.toDouble()); - } -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue : JsonIntValue -{ -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isDouble(); - } - - static double value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Double"); - return value.toDouble(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isBool(); - } - - static bool value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Bool"); - return value.toBool(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isString(); - } - - static QString value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type String"); - return value.toString(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isString(); - } - - static std::string value(const QJsonValue& value) - { - return JsonValue::value(value).toStdString(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isObject(); - } - - static QJsonObject value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Object"); - return value.toObject(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isObject(); - } - - static JsonObject value(const QJsonValue& value) - { - return JsonObject(JsonValue::value(value)); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isNull(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isArray(); - } - - static QJsonArray value(const QJsonValue& value) noexcept(false) - { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Array"); - return value.toArray(); - } -}; - -template <> struct JsonValue -{ - static bool matchesType(const QJsonValue& value) - { - return value.isArray(); - } - - static JsonArray value(const QJsonValue& value) - { - return JsonArray(JsonValue::value(value)); - } -}; - -template struct JsonValue> -{ - static bool matchesType(const QJsonValue& value) - { - if (!value.isArray()) - return false; - - const JsonArray array(value.toArray()); - return array.isVector(); - } - - static QVector value(const QJsonValue& value) - { - const JsonArray array(JsonValue::value(value)); - return array.toVector(); - } -}; - -template struct JsonValue> -{ - static bool matchesType(const QJsonValue& value) - { - return JsonValue>::matchesType(value); - } - - static std::vector value(const QJsonValue& value) - { - const JsonArray array(JsonValue::value(value)); - return array.toStdVector(); - } -}; - -template struct JsonValue> -{ - static bool matchesType(const QJsonValue& value) - { - if (!value.isObject()) - return false; - - const JsonObject obj(JsonValue::value(value)); - return obj.isMap(); - } - - static QMap value(const QJsonValue& value) - { - const JsonObject obj(JsonValue::value(value)); - return obj.toMap(); - } -}; - -template struct JsonValue> -{ - static bool matchesType(const QJsonValue& value) - { - return JsonValue>::matchesType(value); - } - - static std::map value(const QJsonValue& value) - { - const JsonObject obj(JsonValue::value(value)); - return obj.toStdMap(); - } -}; - -template bool JsonObject::contains(const Key& key) const -{ - if (!m_json.contains(key)) + if (!value.isDouble()) return false; + double val = value.toDouble(); + + if (val < JsonLimits::lowest()) + return false; + if (val > JsonLimits::max()) + return false; + + double wholeInt = static_cast(val); + return val == wholeInt; + } + + static Int value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Int"); + return static_cast(value.toDouble()); + } + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue : JsonIntValue + { + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isDouble(); } + + static double value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Double"); + return value.toDouble(); + } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isBool(); } + + static bool value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Bool"); + return value.toBool(); + } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isString(); } + + static QString value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type String"); + return value.toString(); + } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isString(); } + + static std::string value(const QJsonValue &value) { return JsonValue::value(value).toStdString(); } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isObject(); } + + static QJsonObject value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Object"); + return value.toObject(); + } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isObject(); } + + static JsonObject value(const QJsonValue &value) { return JsonObject(JsonValue::value(value)); } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isNull(); } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isArray(); } + + static QJsonArray value(const QJsonValue &value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Array"); + return value.toArray(); + } + }; + + template <> struct JsonValue + { + static bool matchesType(const QJsonValue &value) { return value.isArray(); } + + static JsonArray value(const QJsonValue &value) { return JsonArray(JsonValue::value(value)); } + }; + + template struct JsonValue> + { + static bool matchesType(const QJsonValue &value) + { + if (!value.isArray()) + return false; + + const JsonArray array(value.toArray()); + return array.isVector(); + } + + static QVector value(const QJsonValue &value) + { + const JsonArray array(JsonValue::value(value)); + return array.toVector(); + } + }; + + template struct JsonValue> + { + static bool matchesType(const QJsonValue &value) { return JsonValue>::matchesType(value); } + + static std::vector value(const QJsonValue &value) + { + const JsonArray array(JsonValue::value(value)); + return array.toStdVector(); + } + }; + + template struct JsonValue> + { + static bool matchesType(const QJsonValue &value) + { + if (!value.isObject()) + return false; + + const JsonObject obj(JsonValue::value(value)); + return obj.isMap(); + } + + static QMap value(const QJsonValue &value) + { + const JsonObject obj(JsonValue::value(value)); + return obj.toMap(); + } + }; + + template struct JsonValue> + { + static bool matchesType(const QJsonValue &value) { return JsonValue>::matchesType(value); } + + static std::map value(const QJsonValue &value) + { + const JsonObject obj(JsonValue::value(value)); + return obj.toStdMap(); + } + }; + + template bool JsonObject::contains(const Key &key) const + { + if (!m_json.contains(key)) + return false; return JsonValue::matchesType(m_json.value(key)); -} + } -template T JsonObject::value(const Key& key) const noexcept(false) -{ + template T JsonObject::value(const Key &key) const noexcept(false) + { if (!containsAny(key)) - throw JsonKeyError("no element with key: " + static_cast(key).toStdString()); + throw JsonKeyError("no element with key: " + static_cast(key).toStdString()); try { - return JsonValue::value(m_json.value(key)); + return JsonValue::value(m_json.value(key)); } - catch (const JsonTypeError& typeError) + catch (const JsonTypeError &typeError) { - throw JsonTypeError(std::string(typeError.what()) + - " - key: " + static_cast(key).toStdString()); + throw JsonTypeError(std::string(typeError.what()) + " - key: " + static_cast(key).toStdString()); } -} + } -template T JsonObject::valueOr(const Key& key, const T& defaultValue) const -{ + template T JsonObject::valueOr(const Key &key, const T &defaultValue) const + { try { - return value(key); + return value(key); } - catch (const JsonKeyError&) + catch (const JsonKeyError &) { - return defaultValue; + return defaultValue; } -} + } -template bool JsonObject::isMap() const -{ + template bool JsonObject::isMap() const + { const QStringList keys = m_json.keys(); - for (const auto& key : keys) - if (!JsonValue::matchesType(m_json.value(key))) - return false; + for (const auto &key : keys) + if (!JsonValue::matchesType(m_json.value(key))) + return false; return true; -} + } -template QMap JsonObject::toMap() const -{ + template QMap JsonObject::toMap() const + { QMap result; for (auto current = m_json.begin(); current != m_json.end(); ++current) - result.insert(current.key(), JsonValue::value(current.value())); + result.insert(current.key(), JsonValue::value(current.value())); return result; -} + } -template std::map JsonObject::toStdMap() const -{ + template std::map JsonObject::toStdMap() const + { std::map result; for (auto current = m_json.begin(); current != m_json.end(); ++current) - result.insert({current.key().toStdString(), JsonValue::value(current.value())}); + result.insert({current.key().toStdString(), JsonValue::value(current.value())}); return result; -} + } -template bool JsonArray::contains(int index) const noexcept(false) -{ + template bool JsonArray::contains(int index) const noexcept(false) + { if (index < 0 || index >= m_json.size()) - throw JsonRangeError("index out of range: " + std::to_string(index)); + throw JsonRangeError("index out of range: " + std::to_string(index)); return JsonValue::matchesType(m_json.at(index)); -} + } -template T JsonArray::at(int index) const noexcept(false) -{ + template T JsonArray::at(int index) const noexcept(false) + { if (index < 0 || index >= m_json.size()) - throw JsonRangeError("index out of range: " + std::to_string(index)); + throw JsonRangeError("index out of range: " + std::to_string(index)); return JsonValue::value(m_json.at(index)); -} + } -template bool JsonArray::isVector() const -{ - for (const QJsonValue& value : m_json) - if (!JsonValue::matchesType(value)) - return false; + template bool JsonArray::isVector() const + { + for (const QJsonValue &value : m_json) + if (!JsonValue::matchesType(value)) + return false; return true; -} + } -template QVector JsonArray::toVector() const -{ + template QVector JsonArray::toVector() const + { QVector result; result.reserve(m_json.size()); - for (const QJsonValue& value : m_json) - result.push_back(JsonValue::value(value)); + for (const QJsonValue &value : m_json) + result.push_back(JsonValue::value(value)); return result; -} + } -template std::vector JsonArray::toStdVector() const -{ + template std::vector JsonArray::toStdVector() const + { std::vector result; result.reserve(m_json.size()); - for (const QJsonValue& value : m_json) - result.push_back(JsonValue::value(value)); + for (const QJsonValue &value : m_json) + result.push_back(JsonValue::value(value)); return result; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp index 9973dd562..80e4527ae 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp @@ -3,12 +3,12 @@ namespace LtsUtils { -LtsUtils::LtsPortRange fromQPoint(const QPoint& point) -{ + LtsUtils::LtsPortRange fromQPoint(const QPoint &point) + { if (point.x() < 1025 || point.y() > 65535 || point.x() > point.y()) - return {}; + return {}; return {static_cast(point.x()), static_cast(point.y())}; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h index e0f209e46..94eebaf6c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h @@ -7,7 +7,7 @@ namespace LtsUtils { -typedef QPair LtsPortRange; + typedef QPair LtsPortRange; -LTSUTILSCORE_EXPORT LtsPortRange fromQPoint(const QPoint& point); + LTSUTILSCORE_EXPORT LtsPortRange fromQPoint(const QPoint &point); } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp index 2878e4114..4f47bf052 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp @@ -6,17 +6,17 @@ namespace LtsUtils { -LtsTranslatableIdentifier::LtsTranslatableIdentifier(const QString& identifier, const QObject* context, - const char* translatableText) - : m_identifier(identifier), m_translationContext(context->metaObject()->className()), - m_translatableText(translatableText) -{ -} + LtsTranslatableIdentifier::LtsTranslatableIdentifier(const QString &identifier, const QObject *context, const char *translatableText) + : m_identifier(identifier) + , m_translationContext(context->metaObject()->className()) + , m_translatableText(translatableText) + { + } -const QString LtsTranslatableIdentifier::translatedText(const char* disambiguation, int n) const -{ + const QString LtsTranslatableIdentifier::translatedText(const char *disambiguation, int n) const + { if (m_identifier.isEmpty() || m_translationContext == nullptr || m_translatableText == nullptr) - return {}; + return {}; return QCoreApplication::translate(m_translationContext, m_translatableText, disambiguation, n); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h index d32833e11..9a939318a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h @@ -7,29 +7,27 @@ namespace LtsUtils { -class LTSUTILSCORE_EXPORT LtsTranslatableIdentifier -{ + class LTSUTILSCORE_EXPORT LtsTranslatableIdentifier + { public: - LtsTranslatableIdentifier() : m_translationContext(nullptr), m_translatableText("") {} - - LtsTranslatableIdentifier(const QString& identifier, const QObject* context, const char* translatableText); - - const QString& identifier() const + LtsTranslatableIdentifier() + : m_translationContext(nullptr) + , m_translatableText("") { - return m_identifier; } - const QString translatedText(const char* disambiguation = nullptr, int n = -1) const; + LtsTranslatableIdentifier(const QString &identifier, const QObject *context, const char *translatableText); - const QString _context() const - { - return QString::fromUtf8(m_translationContext); - } + const QString &identifier() const { return m_identifier; } + + const QString translatedText(const char *disambiguation = nullptr, int n = -1) const; + + const QString _context() const { return QString::fromUtf8(m_translationContext); } private: QString m_identifier; - const char* m_translationContext; + const char *m_translationContext; - const char* m_translatableText; -}; + const char *m_translatableText; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h index 0d1ad9ab8..ad18c0d7a 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h @@ -18,4 +18,4 @@ #define LTSUTILSCORE_EXPORT Q_DECL_IMPORT #endif #endif -#endif \ No newline at end of file +#endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h index 8ee74b67a..4b525fda0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h @@ -6,9 +6,9 @@ namespace LtsUtils { -inline bool isPositionTimeOutdated(qint64 curTime, qint64 posTime) -{ + inline bool isPositionTimeOutdated(qint64 curTime, qint64 posTime) + { return curTime > posTime + 11 * 60 * 1000; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp index 334d46098..a7560e0dc 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp @@ -11,141 +11,135 @@ namespace LtsUtils { -template static inline QString convertToPgString(const std::vector& data) -{ + template static inline QString convertToPgString(const std::vector &data) + { if (data.size() == 0) - return QLatin1String("{}"); + return QLatin1String("{}"); QString ret(QLatin1Char('{')); for (T i : data) - ret += QString::number(i) + QLatin1Char(','); + ret += QString::number(i) + QLatin1Char(','); ret.chop(1); ret += QLatin1Char('}'); return ret; -} + } -template <> LTSUTILSCORE_EXPORT QString IntArray::toPgString() const -{ + template <> LTSUTILSCORE_EXPORT QString IntArray::toPgString() const + { return convertToPgString(m_data); -} + } -template <> LTSUTILSCORE_EXPORT QString BigintArray::toPgString() const -{ + template <> LTSUTILSCORE_EXPORT QString BigintArray::toPgString() const + { return convertToPgString(m_data); -} + } -template -static inline T convertFromPgString(const QString& str, - const std::function& convertFunc) -{ + template static inline T convertFromPgString(const QString &str, const std::function &convertFunc) + { typename T::ContainerType result; int idxStart = str.indexOf(QLatin1Char('{')); int idxEnd = str.lastIndexOf(QLatin1Char('}')); if (idxEnd < idxStart) - return T(result); + return T(result); if (idxStart < 0 && idxEnd < 0) { - idxStart = -1; - idxEnd = str.length() + 1; + idxStart = -1; + idxEnd = str.length() + 1; } const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); const QVector vec = strRef.split(QLatin1Char(','), Qt::SkipEmptyParts); result.reserve(vec.size()); - for (const QStringView& s : vec) + for (const QStringView &s : vec) { - bool ok = false; - const typename T::Type i = convertFunc(s, &ok); - if (ok) - result.push_back(i); + bool ok = false; + const typename T::Type i = convertFunc(s, &ok); + if (ok) + result.push_back(i); } return T(result); -} + } -template <> LTSUTILSCORE_EXPORT IntArray IntArray::fromPgString(const QString& str) -{ - return convertFromPgString(str, [](QStringView val, bool* bOk) { return val.toString().toInt(bOk); }); -} + template <> LTSUTILSCORE_EXPORT IntArray IntArray::fromPgString(const QString &str) + { + return convertFromPgString(str, [](QStringView val, bool *bOk) { return val.toString().toInt(bOk); }); + } -template <> LTSUTILSCORE_EXPORT BigintArray BigintArray::fromPgString(const QString& str) -{ - return convertFromPgString(str, - [](QStringView val, bool* bOk) { return val.toString().toLongLong(bOk); }); -} + template <> LTSUTILSCORE_EXPORT BigintArray BigintArray::fromPgString(const QString &str) + { + return convertFromPgString(str, [](QStringView val, bool *bOk) { return val.toString().toLongLong(bOk); }); + } -template static inline QString convertToPgString(const std::map& data) -{ + template static inline QString convertToPgString(const std::map &data) + { if (data.size() == 0) - return QLatin1String("{}"); + return QLatin1String("{}"); QString ret(QLatin1Char('{')); - for (const auto& it : data) + for (const auto &it : data) { - ret += QLatin1Char('{') + QString::number(it.first) + QLatin1Char(',') + QString::number(it.second) + - QLatin1String("},"); + ret += QLatin1Char('{') + QString::number(it.first) + QLatin1Char(',') + QString::number(it.second) + QLatin1String("},"); } ret.chop(1); ret += QLatin1Char('}'); return ret; -} + } -template <> LTSUTILSCORE_EXPORT QString IntArray2D::toPgString() const -{ + template <> LTSUTILSCORE_EXPORT QString IntArray2D::toPgString() const + { return convertToPgString(m_data); -} + } -template <> LTSUTILSCORE_EXPORT QString BigintArray2D::toPgString() const -{ + template <> LTSUTILSCORE_EXPORT QString BigintArray2D::toPgString() const + { return convertToPgString(m_data); -} + } -template -static inline T convertFromPgString2D(const QString& str, - const std::function& convertFunc) -{ + template static inline T convertFromPgString2D(const QString &str, const std::function &convertFunc) + { typename T::ContainerType ret; int idxStart = str.indexOf(QLatin1Char('{')); int idxEnd = str.lastIndexOf(QLatin1Char('}')); if (idxEnd < idxStart) - return T(ret); + return T(ret); if (idxStart < 0 && idxEnd < 0) { - idxStart = -1; - idxEnd = str.length() + 1; + idxStart = -1; + idxEnd = str.length() + 1; } const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); idxStart = strRef.indexOf(QLatin1Char('{')); while (idxStart >= 0) { - idxEnd = strRef.indexOf(QLatin1Char('}'), idxStart); - if (idxEnd < 0) - break; + idxEnd = strRef.indexOf(QLatin1Char('}'), idxStart); + if (idxEnd < 0) + break; - const QStringView keyValueStr = strRef.mid(idxStart + 1, idxEnd - idxStart - 1); - const QVector keyValuePair = keyValueStr.split(QLatin1Char(','), Qt::SkipEmptyParts); - if (keyValuePair.size() != 2) - break; - const typename T::Type key = convertFunc(keyValuePair.at(0).trimmed()); - const typename T::Type value = convertFunc(keyValuePair.at(1).trimmed()); - ret.insert(std::make_pair(key, value)); + const QStringView keyValueStr = strRef.mid(idxStart + 1, idxEnd - idxStart - 1); + const QVector keyValuePair = keyValueStr.split(QLatin1Char(','), Qt::SkipEmptyParts); + if (keyValuePair.size() != 2) + break; + const typename T::Type key = convertFunc(keyValuePair.at(0).trimmed()); + const typename T::Type value = convertFunc(keyValuePair.at(1).trimmed()); + ret.insert(std::make_pair(key, value)); - idxStart = strRef.indexOf(QLatin1Char('{'), idxEnd + 1); + idxStart = strRef.indexOf(QLatin1Char('{'), idxEnd + 1); } return T(ret); -} + } -template <> LTSUTILSCORE_EXPORT IntArray2D IntArray2D::fromPgString(const QString& str) -{ + template <> LTSUTILSCORE_EXPORT IntArray2D IntArray2D::fromPgString(const QString &str) + { return convertFromPgString2D(str, [](QStringView val) { return val.toString().toInt(); }); -} + } -template <> LTSUTILSCORE_EXPORT BigintArray2D BigintArray2D::fromPgString(const QString& str) -{ + template <> LTSUTILSCORE_EXPORT BigintArray2D BigintArray2D::fromPgString(const QString &str) + { return convertFromPgString2D(str, [](QStringView val) { return val.toString().toLongLong(); }); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h index 42823273b..f460a18c4 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h @@ -9,32 +9,32 @@ namespace LtsUtils { -template class PgArray -{ + template class PgArray + { public: using Type = T; using ContainerType = C; PgArray() = default; - Q_DECL_CONSTEXPR explicit PgArray(const C& data) : m_data(data) {} - - Q_DECL_CONSTEXPR C operator()() const + Q_DECL_CONSTEXPR explicit PgArray(const C &data) + : m_data(data) { - return m_data; } + Q_DECL_CONSTEXPR C operator()() const { return m_data; } + [[nodiscard]] QString toPgString() const; - static PgArray fromPgString(const QString& str); + static PgArray fromPgString(const QString &str); private: C m_data; -}; + }; -using IntArray = PgArray>; -using BigintArray = PgArray>; + using IntArray = PgArray>; + using BigintArray = PgArray>; -using IntArray2D = PgArray>; -using BigintArray2D = PgArray>; + using IntArray2D = PgArray>; + using BigintArray2D = PgArray>; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp index c9b5b98d1..112105fdc 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp @@ -7,74 +7,76 @@ namespace LtsUtils { -Promise::Promise(const std::function& function, QObject* parent) - : QObject(parent), m_functionAlreadySet(false), m_timeout(new QTimer(this)), m_resultSet(false), m_timeoutSet(false) -{ + Promise::Promise(const std::function &function, QObject *parent) + : QObject(parent) + , m_functionAlreadySet(false) + , m_timeout(new QTimer(this)) + , m_resultSet(false) + , m_timeoutSet(false) + { m_timeout->setSingleShot(true); connect(m_timeout, &QTimer::timeout, this, &Promise::slotTimeout); setFunction(function); -} + } -void Promise::setFunction(const std::function& function) -{ + void Promise::setFunction(const std::function &function) + { if (!function || m_functionAlreadySet) - return; + return; m_functionAlreadySet = true; if (m_timeoutSet) - m_timeout->start(); + m_timeout->start(); - QTimer::singleShot(0, this, [this, function]() { - function([this](const QVariant& value) { resolve(value); }, [this](const QVariant& value) { reject(value); }); - }); -} + QTimer::singleShot(0, this, [this, function]() { function([this](const QVariant &value) { resolve(value); }, [this](const QVariant &value) { reject(value); }); }); + } -void Promise::setTimeout(int interval) -{ + void Promise::setTimeout(int interval) + { m_timeout->stop(); m_timeout->setInterval(interval); m_timeoutSet = (interval != 0); if (interval != 0 && m_functionAlreadySet) - m_timeout->start(); -} + m_timeout->start(); + } -void Promise::slotTimeout() -{ + void Promise::slotTimeout() + { reject(QStringLiteral("timeout")); -} + } -void Promise::resolve(const QVariant& value) -{ + void Promise::resolve(const QVariant &value) + { if (m_resultSet) - return; + return; m_resultSet = true; m_timeout->stop(); m_resolveFn(value); -} + } -void Promise::reject(const QVariant& value) -{ + void Promise::reject(const QVariant &value) + { if (m_resultSet) - return; + return; m_resultSet = true; m_timeout->stop(); m_rejectFn(value); -} + } -Promise& Promise::resolved(ResultFunction resolveFn) -{ + Promise &Promise::resolved(ResultFunction resolveFn) + { m_resolveFn = resolveFn; return *this; -} + } -Promise& Promise::rejected(ResultFunction rejectFn) -{ + Promise &Promise::rejected(ResultFunction rejectFn) + { m_rejectFn = rejectFn; return *this; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h index 389b9afc6..fb130938c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h @@ -10,39 +10,38 @@ class QTimer; namespace LtsUtils { -typedef std::function RawResultFunction; -typedef const RawResultFunction& ResultFunction; + typedef std::function RawResultFunction; + typedef const RawResultFunction &ResultFunction; -class LTSUTILSCORE_EXPORT Promise : public QObject -{ + class LTSUTILSCORE_EXPORT Promise : public QObject + { Q_OBJECT public: - Promise(const std::function& function, - QObject* parent = nullptr); + Promise(const std::function &function, QObject *parent = nullptr); - void setFunction(const std::function& function); + void setFunction(const std::function &function); - void resolve(const QVariant& value = QVariant()); + void resolve(const QVariant &value = QVariant()); - void reject(const QVariant& value = QVariant()); + void reject(const QVariant &value = QVariant()); void setTimeout(int interval); - Promise& resolved(ResultFunction resolveFn); + Promise &resolved(ResultFunction resolveFn); - Promise& rejected(ResultFunction rejectFn); + Promise &rejected(ResultFunction rejectFn); private: RawResultFunction m_resolveFn; RawResultFunction m_rejectFn; bool m_functionAlreadySet; - QTimer* m_timeout; + QTimer *m_timeout; bool m_resultSet; bool m_timeoutSet; private slots: void slotTimeout(); -}; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp index 7787c019c..503d0e433 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp @@ -9,57 +9,72 @@ namespace LtsUtils { -void PromiseExample1_Class::doSomethingAsync1() -{ + void PromiseExample1_Class::doSomethingAsync1() + { QTimer::singleShot(200, this, [this]() { emit signalDone1(true); }); -} + } -void PromiseExample1_Class::doSomethingAsync2() -{ + void PromiseExample1_Class::doSomethingAsync2() + { QTimer::singleShot(450, this, [this]() { emit signalDone2(true, 1234); }); -} + } -PromiseExample1::PromiseExample1(QObject* parent) : QObject(parent), m_success(false) -{ + PromiseExample1::PromiseExample1(QObject *parent) + : QObject(parent) + , m_success(false) + { - auto func = [this](ResultFunction resolve, ResultFunction reject) { - PromiseExample1_Class* c = new PromiseExample1_Class(this); + auto func = [this](ResultFunction resolve, ResultFunction reject) + { + PromiseExample1_Class *c = new PromiseExample1_Class(this); - connect(c, &PromiseExample1_Class::signalDone1, this, [this, c, resolve, reject](bool didThisWork) { - if (!didThisWork) - { + connect(c, + &PromiseExample1_Class::signalDone1, + this, + [this, c, resolve, reject](bool didThisWork) + { + if (!didThisWork) + { - reject(QStringLiteral("First Action did not succeed")); - return; - } - else - { + reject(QStringLiteral("First Action did not succeed")); + return; + } + else + { - connect(c, &PromiseExample1_Class::signalDone2, this, - [resolve, reject](bool didThisWork, int someNumberThatReturns) { + connect(c, + &PromiseExample1_Class::signalDone2, + this, + [resolve, reject](bool didThisWork, int someNumberThatReturns) + { if (didThisWork) - resolve(someNumberThatReturns); + resolve(someNumberThatReturns); else - reject(QStringLiteral("Second Action did not succeed")); - }); + reject(QStringLiteral("Second Action did not succeed")); + }); - c->doSomethingAsync2(); - } - }); + c->doSomethingAsync2(); + } + }); - c->doSomethingAsync1(); + c->doSomethingAsync1(); }; - Promise* p = new Promise(func, this); + Promise *p = new Promise(func, this); - p->resolved([this](const QVariant& value) { - qDebug() << "example1 promise succeeded! 'someNumberThatReturns' was" << value; + p->resolved( + [this](const QVariant &value) + { + qDebug() << "example1 promise succeeded! 'someNumberThatReturns' was" << value; - m_success = true; - }).rejected([](const QVariant& value) { qDebug() << "example1 promise failed.." << value; }); -} + m_success = true; + }) + .rejected([](const QVariant &value) { qDebug() << "example1 promise failed.." << value; }); + } -PromiseExample2::PromiseExample2(QObject* parent) : QObject(parent), m_success(false) -{ + PromiseExample2::PromiseExample2(QObject *parent) + : QObject(parent) + , m_success(false) + { Promise* p = new Promise( [](ResultFunction, ResultFunction) { @@ -69,32 +84,39 @@ PromiseExample2::PromiseExample2(QObject* parent) : QObject(parent), m_success(f p->setTimeout(1000); - p->resolved([](const QVariant&) { QFAIL("This test case's promise should never resolve"); }); + p->resolved([](const QVariant &) { QFAIL("This test case's promise should never resolve"); }); - p->rejected([this](const QVariant& val) { - QVERIFY2(val == QStringLiteral("timeout"), "Promise didn't reject with string \"timeout\""); - qDebug() << "Promise rejected as expected"; - m_success = true; - }); -} + p->rejected( + [this](const QVariant &val) + { + QVERIFY2(val == QStringLiteral("timeout"), "Promise didn't reject with string \"timeout\""); + qDebug() << "Promise rejected as expected"; + m_success = true; + }); + } -PromiseExample3::PromiseExample3(QObject* parent) : QObject(parent), m_success(true), m_alreadyRejected(false) -{ + PromiseExample3::PromiseExample3(QObject *parent) + : QObject(parent) + , m_success(true) + , m_alreadyRejected(false) + { - Promise* p = new Promise([](ResultFunction, ResultFunction reject) { reject(QString()); }, this); + Promise *p = new Promise([](ResultFunction, ResultFunction reject) { reject(QString()); }, this); p->setTimeout(1000); - p->resolved([](const QVariant&) { QFAIL("This test case's promise should never resolve"); }); + p->resolved([](const QVariant &) { QFAIL("This test case's promise should never resolve"); }); - p->rejected([this](const QVariant& val) { - qDebug() << "rejected with val" << val; - QVERIFY2(val == QString(), "Promise didn't reject with an expected empty string."); - QVERIFY2(!m_alreadyRejected, "Promise rejected more than once"); + p->rejected( + [this](const QVariant &val) + { + qDebug() << "rejected with val" << val; + QVERIFY2(val == QString(), "Promise didn't reject with an expected empty string."); + QVERIFY2(!m_alreadyRejected, "Promise rejected more than once"); - m_alreadyRejected = true; - qDebug() << "Promise rejected as expected"; - }); -} + m_alreadyRejected = true; + qDebug() << "Promise rejected as expected"; + }); + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h index 5aacc7468..3c5fcf9bd 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h @@ -5,8 +5,8 @@ namespace LtsUtils { -class PromiseExample1_Class : public QObject -{ + class PromiseExample1_Class : public QObject + { Q_OBJECT public: using QObject::QObject; @@ -17,52 +17,43 @@ class PromiseExample1_Class : public QObject signals: void signalDone1(bool didThisWork); void signalDone2(bool didThisWork, int someNumberThatReturns); -}; + }; -class PromiseExample1 : public QObject -{ + class PromiseExample1 : public QObject + { Q_OBJECT public: - explicit PromiseExample1(QObject* parent = nullptr); + explicit PromiseExample1(QObject *parent = nullptr); - [[nodiscard]] bool isSuccess() const - { - return m_success; - } + [[nodiscard]] bool isSuccess() const { return m_success; } private: bool m_success; -}; + }; -class PromiseExample2 : public QObject -{ + class PromiseExample2 : public QObject + { Q_OBJECT public: - explicit PromiseExample2(QObject* parent = nullptr); + explicit PromiseExample2(QObject *parent = nullptr); - [[nodiscard]] bool isSuccess() const - { - return m_success; - } + [[nodiscard]] bool isSuccess() const { return m_success; } private: bool m_success; -}; + }; -class PromiseExample3 : public QObject -{ + class PromiseExample3 : public QObject + { Q_OBJECT public: - explicit PromiseExample3(QObject* parent = nullptr); + explicit PromiseExample3(QObject *parent = nullptr); - [[nodiscard]] bool isSuccess() const - { - return m_success; - } + [[nodiscard]] bool isSuccess() const { return m_success; } private: bool m_success; bool m_alreadyRejected; -}; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h index 14ede78dc..6be021532 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h @@ -8,8 +8,8 @@ namespace LtsUtils { -template void inline set8Byte(const T in, QByteArray& out) -{ + template void inline set8Byte(const T in, QByteArray &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); out += (in & 0xFF00000000000000UL) >> 56; out += (in & 0x00FF000000000000UL) >> 48; @@ -19,34 +19,35 @@ template void inline set8Byte(const T in, QByteArray& out) out += (in & 0x0000000000FF0000UL) >> 16; out += (in & 0x000000000000FF00UL) >> 8; out += (in & 0x00000000000000FFUL); -} + } -template <> void inline set8Byte(const double in, QByteArray& out) -{ - union hack { - double d; - int64_t i; + template <> void inline set8Byte(const double in, QByteArray &out) + { + union hack + { + double d; + int64_t i; } h; h.d = in; set8Byte(h.i, out); -} + } -template bool inline get8Byte(const QByteArray& baData, size_t& pos, T& out) -{ + template bool inline get8Byte(const QByteArray &baData, size_t &pos, T &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); static_assert(sizeof(T) >= 8, "sizeof(out) is smaller than 8 bytes - will not fit"); out = T(); if (size_t(baData.size()) < pos + 8) - return false; + return false; - const char* data = baData.data() + pos; + const char *data = baData.data() + pos; if (std::numeric_limits::is_signed) - out |= static_cast(data[0]) << 56; + out |= static_cast(data[0]) << 56; else - out |= (data[0] & 0xFFULL) << 56; + out |= (data[0] & 0xFFULL) << 56; out |= (data[1] & 0xFFULL) << 48; out |= (data[2] & 0xFFULL) << 40; out |= (data[3] & 0xFFULL) << 32; @@ -58,59 +59,60 @@ template bool inline get8Byte(const QByteArray& baData, size_t& pos pos += 8; return true; -} + } -template <> bool inline get8Byte(const QByteArray& baData, size_t& pos, double& out) -{ + template <> bool inline get8Byte(const QByteArray &baData, size_t &pos, double &out) + { out = 0.; - union hack { - double d; - int64_t i; + union hack + { + double d; + int64_t i; } h; if (!get8Byte(baData, pos, h.i)) - return false; + return false; out = h.d; return true; -} + } -template bool inline get8Byte(const QByteArray& data, T& out) -{ + template bool inline get8Byte(const QByteArray &data, T &out) + { size_t pos = 0; return get8Byte(data, pos, out); -} + } -template void inline set4Byte(const T in, QByteArray& out) -{ + template void inline set4Byte(const T in, QByteArray &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); out += (in & 0xFF000000) >> 24; out += (in & 0x00FF0000) >> 16; out += (in & 0x0000FF00) >> 8; out += (in & 0x000000FF); -} + } -template <> void inline set4Byte(const double in, QByteArray& out) -{ + template <> void inline set4Byte(const double in, QByteArray &out) + { int tmp = qRound(in); return set4Byte(tmp, out); -} + } -template bool inline get4Byte(const QByteArray& baData, size_t& pos, T& out) -{ + template bool inline get4Byte(const QByteArray &baData, size_t &pos, T &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); static_assert(sizeof(T) >= 4, "sizeof(out) is smaller than 4 bytes - will not fit"); out = T(); if (size_t(baData.size()) < pos + 4) - return false; + return false; - const char* data = baData.data() + pos; + const char *data = baData.data() + pos; if (std::numeric_limits::is_signed) - out |= data[0] << 24; + out |= data[0] << 24; else - out |= (data[0] & 0xFFU) << 24; + out |= (data[0] & 0xFFU) << 24; out |= (data[1] & 0xFFU) << 16; out |= (data[2] & 0xFFU) << 8; out |= (data[3] & 0xFFU); @@ -118,124 +120,124 @@ template bool inline get4Byte(const QByteArray& baData, size_t& pos pos += 4; return true; -} + } -template <> bool inline get4Byte(const QByteArray& baData, size_t& pos, double& out) -{ + template <> bool inline get4Byte(const QByteArray &baData, size_t &pos, double &out) + { out = 0.; int tmp; if (!get4Byte(baData, pos, tmp)) - return false; + return false; out = tmp; return true; -} + } -template bool inline get4Byte(const QByteArray& data, T& out) -{ + template bool inline get4Byte(const QByteArray &data, T &out) + { size_t pos = 0; return get4Byte(data, pos, out); -} + } -template void inline set3Byte(const T in, QByteArray& out) -{ + template void inline set3Byte(const T in, QByteArray &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); out += (in & 0x00FF0000) >> 16; out += (in & 0x0000FF00) >> 8; out += (in & 0x000000FF); -} + } -template bool inline get3Byte(const QByteArray& baData, size_t& pos, T& out) -{ + template bool inline get3Byte(const QByteArray &baData, size_t &pos, T &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); static_assert(sizeof(T) >= 3, "sizeof(out) is smaller than 3 bytes - will not fit"); out = T(); if (size_t(baData.size()) < pos + 3) - return false; + return false; - const char* data = baData.data() + pos; + const char *data = baData.data() + pos; if (std::numeric_limits::is_signed) - out |= data[0] << 16; + out |= data[0] << 16; else - out |= (data[0] & 0xFFU) << 16; + out |= (data[0] & 0xFFU) << 16; out |= (data[1] & 0xFFU) << 8; out |= (data[2] & 0xFFU); pos += 3; return true; -} + } -template bool inline get3Byte(const QByteArray& data, T& out) -{ + template bool inline get3Byte(const QByteArray &data, T &out) + { size_t pos = 0; return get3Byte(data, pos, out); -} + } -template void inline set2Byte(const T in, QByteArray& out) -{ + template void inline set2Byte(const T in, QByteArray &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); out += (in & 0x0000FF00) >> 8; out += (in & 0x000000FF); -} + } -template bool inline get2Byte(const QByteArray& baData, size_t& pos, T& out) -{ + template bool inline get2Byte(const QByteArray &baData, size_t &pos, T &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); static_assert(sizeof(T) >= 2, "sizeof(out) is smaller than 2 bytes - will not fit"); out = T(); if (size_t(baData.size()) < pos + 2) - return false; + return false; - const char* data = baData.data() + pos; + const char *data = baData.data() + pos; if (std::numeric_limits::is_signed) - out |= data[0] << 8; + out |= data[0] << 8; else - out |= (data[0] & 0xFFU) << 8; + out |= (data[0] & 0xFFU) << 8; out |= data[1] & 0xFFU; pos += 2; return true; -} + } -template bool inline get2Byte(const QByteArray& data, T& out) -{ + template bool inline get2Byte(const QByteArray &data, T &out) + { size_t pos = 0; return get2Byte(data, pos, out); -} + } -template void inline set1Byte(const T in, QByteArray& out) -{ + template void inline set1Byte(const T in, QByteArray &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); unsigned char c = static_cast(in); out += c; -} + } -template bool inline get1Byte(const QByteArray& baData, size_t& pos, T& out) -{ + template bool inline get1Byte(const QByteArray &baData, size_t &pos, T &out) + { static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); out = T(); if (size_t(baData.size()) < pos + 1) - return false; + return false; if (std::numeric_limits::is_signed) - out = (T)(baData.at(pos)); + out = (T)(baData.at(pos)); else - out = (T)(baData.at(pos) & 0xFF); + out = (T)(baData.at(pos) & 0xFF); pos += 1; return true; -} + } -template bool inline get1Byte(const QByteArray& data, T& out) -{ + template bool inline get1Byte(const QByteArray &data, T &out) + { size_t pos = 0; return get1Byte(data, pos, out); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp index 963c1de0d..2453034d5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp @@ -5,69 +5,72 @@ namespace LtsUtils { -QPlane3D::QPlane3D(const QPoint3D& pos, const QPoint3D& vec1, const QPoint3D& vec2) - : m_pos(pos), m_vec1(vec1), m_vec2(vec2) -{ + QPlane3D::QPlane3D(const QPoint3D &pos, const QPoint3D &vec1, const QPoint3D &vec2) + : m_pos(pos) + , m_vec1(vec1) + , m_vec2(vec2) + { m_normal = QPoint3D::crossProduct(m_vec1, m_vec2); m_planeC = QPoint3D::dotProduct(m_pos, m_normal); -} + } -QPoint3D QPlane3D::intersection(const QPoint3D& point, const QPoint3D& direction) const -{ + QPoint3D QPlane3D::intersection(const QPoint3D &point, const QPoint3D &direction) const + { const double dotProduct = QPoint3D::dotProduct(direction, m_normal); if (qFuzzyIsNull(dotProduct)) - return inPlane(point) ? point : QPoint3D(); + return inPlane(point) ? point : QPoint3D(); const double distance = distanceTo(point) / std::abs(dotProduct); return point + distance * direction; -} + } -bool QPlane3D::intersects(const QPoint3D& direction) const -{ + bool QPlane3D::intersects(const QPoint3D &direction) const + { return !isParallel(direction); -} + } -bool QPlane3D::isParallel(const QPoint3D& direction) const -{ + bool QPlane3D::isParallel(const QPoint3D &direction) const + { return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, direction)); -} + } -bool QPlane3D::inPlane(const QPoint3D& point) const -{ + bool QPlane3D::inPlane(const QPoint3D &point) const + { if (point == m_pos) - return true; + return true; return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, point - m_pos)); -} + } -double QPlane3D::distanceTo(const QPoint3D& point) const -{ + double QPlane3D::distanceTo(const QPoint3D &point) const + { return QPoint3D::dotProduct(point - m_pos, m_normal); -} + } -QPolygon3D::QPolygon3D(const QVector& vertices) - : QPlane3D(vertices[0], vertices[1], vertices[2]), m_vertices(vertices) -{ -} + QPolygon3D::QPolygon3D(const QVector &vertices) + : QPlane3D(vertices[0], vertices[1], vertices[2]) + , m_vertices(vertices) + { + } -bool QPolygon3D::containsPoint(const QPoint3D& point) const -{ + bool QPolygon3D::containsPoint(const QPoint3D &point) const + { if (!inPlane(point)) - return false; + return false; if (contains(point)) - return true; + return true; double angleSum = 0.; double cosTheta = 0.; const int numberOfVertices = m_vertices.size(); for (int i = 0; i < m_vertices.size(); ++i) { - const QPoint3D& first = m_vertices[i % numberOfVertices] - point; - const QPoint3D& second = m_vertices[(i + 1) % numberOfVertices] - point; + const QPoint3D &first = m_vertices[i % numberOfVertices] - point; + const QPoint3D &second = m_vertices[(i + 1) % numberOfVertices] - point; - cosTheta = QPoint3D::dotProduct(first, second) / (first.length() * second.length()); - angleSum += acos(cosTheta); + cosTheta = QPoint3D::dotProduct(first, second) / (first.length() * second.length()); + angleSum += acos(cosTheta); } return qFuzzyIsNull(M_2_PI - angleSum); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h index 651559a7b..4f624f00b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h @@ -11,42 +11,27 @@ namespace LtsUtils { -class LTSUTILSCORE_EXPORT QPlane3D -{ + class LTSUTILSCORE_EXPORT QPlane3D + { public: - QPlane3D(const QPoint3D& pos, const QPoint3D& vec1, const QPoint3D& vec2); + QPlane3D(const QPoint3D &pos, const QPoint3D &vec1, const QPoint3D &vec2); - QPoint3D intersection(const QPoint3D& point, const QPoint3D& direction) const; - bool intersects(const QPoint3D& direction) const; - bool isParallel(const QPoint3D& direction) const; - bool inPlane(const QPoint3D& point) const; - double distanceTo(const QPoint3D& point) const; + QPoint3D intersection(const QPoint3D &point, const QPoint3D &direction) const; + bool intersects(const QPoint3D &direction) const; + bool isParallel(const QPoint3D &direction) const; + bool inPlane(const QPoint3D &point) const; + double distanceTo(const QPoint3D &point) const; - const QPoint3D& pos() const - { - return m_pos; - } + const QPoint3D &pos() const { return m_pos; } - const QPoint3D& vec1() const - { - return m_vec1; - } + const QPoint3D &vec1() const { return m_vec1; } - const QPoint3D& vec2() const - { - return m_vec2; - } + const QPoint3D &vec2() const { return m_vec2; } - const QPoint3D& normal() const - { - return m_normal; - } + const QPoint3D &normal() const { return m_normal; } - double planeC() const - { - return m_planeC; - } + double planeC() const { return m_planeC; } protected: QPoint3D m_pos; @@ -54,23 +39,20 @@ class LTSUTILSCORE_EXPORT QPlane3D QPoint3D m_vec2; QPoint3D m_normal; double m_planeC; -}; + }; -class LTSUTILSCORE_EXPORT QPolygon3D : public QPlane3D -{ + class LTSUTILSCORE_EXPORT QPolygon3D : public QPlane3D + { public: - QPolygon3D(const QVector& vertices); + QPolygon3D(const QVector &vertices); - bool contains(const QPoint3D& point) const - { - return m_vertices.contains(point); - } + bool contains(const QPoint3D &point) const { return m_vertices.contains(point); } - bool containsPoint(const QPoint3D& point) const; + bool containsPoint(const QPoint3D &point) const; private: QVector m_vertices; -}; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp index 1e4ec07e4..ba68a335b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp @@ -7,14 +7,14 @@ namespace LtsUtils { -QDataStream& operator<<(QDataStream& s, const QPoint3D& p) -{ + QDataStream &operator<<(QDataStream &s, const QPoint3D &p) + { s << p.x() << p.y() << p.z(); return s; -} + } -QDataStream& operator>>(QDataStream& s, QPoint3D& p) -{ + QDataStream &operator>>(QDataStream &s, QPoint3D &p) + { double x, y, z; s >> x; p.rx() = x; @@ -23,6 +23,6 @@ QDataStream& operator>>(QDataStream& s, QPoint3D& p) s >> z; p.rz() = z; return s; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h index ee2713c40..fcf261370 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h @@ -13,15 +13,24 @@ namespace LtsUtils { -class QPoint3D -{ + class QPoint3D + { public: - enum class Axis { X, Y, Z }; + enum class Axis + { + X, + Y, + Z + }; constexpr QPoint3D() = default; constexpr QPoint3D(double xpos, double ypos, double zpos); - template explicit QPoint3D(const T& data) : xp(data.offsetX()), yp(data.offsetY()), zp(data.offsetZ()) + template + explicit QPoint3D(const T &data) + : xp(data.offsetX()) + , yp(data.offsetY()) + , zp(data.offsetZ()) { } @@ -34,275 +43,244 @@ class QPoint3D constexpr inline void setY(double ypos); constexpr inline void setZ(double zpos); - constexpr inline double& rx(); - constexpr inline double& ry(); - constexpr inline double& rz(); + constexpr inline double &rx(); + constexpr inline double &ry(); + constexpr inline double &rz(); constexpr inline QPointF toPointF() const; - static QPoint3D fromQPointF(const QPointF& p) - { - return QPoint3D(p.x(), p.y(), .0); - } + static QPoint3D fromQPointF(const QPointF &p) { return QPoint3D(p.x(), p.y(), .0); } - inline double lengthSquared() const - { - return (xp * xp) + (yp * yp) + (zp * zp); - } + inline double lengthSquared() const { return (xp * xp) + (yp * yp) + (zp * zp); } - inline double length() const - { - return std::sqrt(lengthSquared()); - } + inline double length() const { return std::sqrt(lengthSquared()); } inline void normalize() { - double len = xp * xp + yp * yp + zp * zp; - if (qFuzzyIsNull(len - 1.0f) || qFuzzyIsNull(len)) - return; + double len = xp * xp + yp * yp + zp * zp; + if (qFuzzyIsNull(len - 1.0f) || qFuzzyIsNull(len)) + return; - len = std::sqrt(len); + len = std::sqrt(len); - xp /= len; - yp /= len; - zp /= len; + xp /= len; + yp /= len; + zp /= len; } inline QPoint3D normalized() const { - double len = xp * xp + yp * yp + zp * zp; - if (qFuzzyIsNull(len - 1.0f)) - return *this; - else if (!qFuzzyIsNull(len)) - return *this / std::sqrt(len); - else - return QPoint3D(*this); + double len = xp * xp + yp * yp + zp * zp; + if (qFuzzyIsNull(len - 1.0f)) + return *this; + else if (!qFuzzyIsNull(len)) + return *this / std::sqrt(len); + else + return QPoint3D(*this); } - inline void rotate(const double& phi, const Axis& axis) + inline void rotate(const double &phi, const Axis &axis) { - const double sin = std::sin(phi); - const double cos = std::cos(phi); - switch (axis) + const double sin = std::sin(phi); + const double cos = std::cos(phi); + switch (axis) + { + case Axis::X: { - case Axis::X: { - const double _yp = (cos * yp) - (sin * zp); - const double _zp = (sin * yp) + (cos * zp); - yp = _yp; - zp = _zp; - break; - } - case Axis::Y: { - const double _xp = (cos * xp) + (sin * zp); - const double _zp = (-sin * xp) + (cos * zp); - xp = _xp; - zp = _zp; - break; - } - case Axis::Z: { - const double _xp = (cos * xp) - (sin * yp); - const double _yp = (sin * xp) + (cos * yp); - xp = _xp; - yp = _yp; - break; - } + const double _yp = (cos * yp) - (sin * zp); + const double _zp = (sin * yp) + (cos * zp); + yp = _yp; + zp = _zp; + break; } + case Axis::Y: + { + const double _xp = (cos * xp) + (sin * zp); + const double _zp = (-sin * xp) + (cos * zp); + xp = _xp; + zp = _zp; + break; + } + case Axis::Z: + { + const double _xp = (cos * xp) - (sin * yp); + const double _yp = (sin * xp) + (cos * yp); + xp = _xp; + yp = _yp; + break; + } + } } - inline QPoint3D rotated(const double& phi, const Axis& axis) const + inline QPoint3D rotated(const double &phi, const Axis &axis) const { - QPoint3D p(*this); - p.rotate(phi, axis); - return p; + QPoint3D p(*this); + p.rotate(phi, axis); + return p; } - inline double distanceToLine(const QPoint3D& point, const QPoint3D& direction) const - { - if (direction.isNull()) - return (*this - point).length(); - QPoint3D p = point + dotProduct(*this - point, direction) * direction; - return (*this - p).length(); - } - inline double distanceToPlane(const QPoint3D& plane, const QPoint3D& normal) const - { - return dotProduct(*this - plane, normal); - } - inline double distanceToPlane(const QPoint3D& plane1, const QPoint3D& plane2, const QPoint3D& plane3) const - { - QPoint3D n = normal(plane2 - plane1, plane3 - plane1); - return dotProduct(*this - plane1, n); - } - inline double distanceToPoint(const QPoint3D& point) const + inline double distanceToLine(const QPoint3D &point, const QPoint3D &direction) const { + if (direction.isNull()) return (*this - point).length(); + QPoint3D p = point + dotProduct(*this - point, direction) * direction; + return (*this - p).length(); + } + inline double distanceToPlane(const QPoint3D &plane, const QPoint3D &normal) const { return dotProduct(*this - plane, normal); } + inline double distanceToPlane(const QPoint3D &plane1, const QPoint3D &plane2, const QPoint3D &plane3) const + { + QPoint3D n = normal(plane2 - plane1, plane3 - plane1); + return dotProduct(*this - plane1, n); + } + inline double distanceToPoint(const QPoint3D &point) const { return (*this - point).length(); } + + friend constexpr inline bool operator==(const QPoint3D &p1, const QPoint3D &p2); + friend constexpr inline bool operator!=(const QPoint3D &p1, const QPoint3D &p2); + + friend constexpr inline QPoint3D operator+(const QPoint3D &p1, const QPoint3D &p2) { return QPoint3D(p1.xp + p2.xp, p1.yp + p2.yp, p1.zp + p2.zp); } + + friend constexpr inline QPoint3D operator-(const QPoint3D &p1, const QPoint3D &p2) { return QPoint3D(p1.xp - p2.xp, p1.yp - p2.yp, p1.zp - p2.zp); } + + friend constexpr inline QPoint3D operator*(const QPoint3D &p1, double factor) { return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); } + + friend constexpr inline QPoint3D operator*(double factor, const QPoint3D &p1) { return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); } + + friend constexpr inline QPoint3D operator/(const QPoint3D &p1, double factor) { return QPoint3D(p1.xp / factor, p1.yp / factor, p1.zp / factor); } + + constexpr inline QPoint3D &operator+=(const QPoint3D &o) + { + xp += o.xp; + yp += o.yp; + zp += o.zp; + return *this; } - friend constexpr inline bool operator==(const QPoint3D& p1, const QPoint3D& p2); - friend constexpr inline bool operator!=(const QPoint3D& p1, const QPoint3D& p2); - - friend constexpr inline QPoint3D operator+(const QPoint3D& p1, const QPoint3D& p2) + constexpr inline QPoint3D &operator-=(const QPoint3D &o) { - return QPoint3D(p1.xp + p2.xp, p1.yp + p2.yp, p1.zp + p2.zp); + xp -= o.xp; + yp -= o.yp; + zp -= o.zp; + return *this; } - friend constexpr inline QPoint3D operator-(const QPoint3D& p1, const QPoint3D& p2) + constexpr inline QPoint3D &operator*=(double factor) { - return QPoint3D(p1.xp - p2.xp, p1.yp - p2.yp, p1.zp - p2.zp); + xp *= factor; + yp *= factor; + zp *= factor; + return *this; } - friend constexpr inline QPoint3D operator*(const QPoint3D& p1, double factor) + constexpr inline QPoint3D &operator/=(double divisor) { - return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); + xp /= divisor; + yp /= divisor; + zp /= divisor; + return *this; } - friend constexpr inline QPoint3D operator*(double factor, const QPoint3D& p1) + constexpr static inline double dotProduct(const QPoint3D &v1, const QPoint3D &v2) { return v1.xp * v2.xp + v1.yp * v2.yp + v1.zp * v2.zp; } + + constexpr static inline QPoint3D crossProduct(const QPoint3D &v1, const QPoint3D &v2) { - return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); + return QPoint3D(v1.yp * v2.zp - v1.zp * v2.yp, v1.zp * v2.xp - v1.xp * v2.zp, v1.xp * v2.yp - v1.yp * v2.xp); } - friend constexpr inline QPoint3D operator/(const QPoint3D& p1, double factor) - { - return QPoint3D(p1.xp / factor, p1.yp / factor, p1.zp / factor); - } + static inline QPoint3D normal(const QPoint3D &v1, const QPoint3D &v2) { return crossProduct(v1, v2).normalized(); } - constexpr inline QPoint3D& operator+=(const QPoint3D& o) - { - xp += o.xp; - yp += o.yp; - zp += o.zp; - return *this; - } + static inline QPoint3D normal(const QPoint3D &v1, const QPoint3D &v2, const QPoint3D &v3) { return crossProduct((v2 - v1), (v3 - v1)).normalized(); } - constexpr inline QPoint3D& operator-=(const QPoint3D& o) + friend inline bool qFuzzyCompare(const QPoint3D &v1, const QPoint3D &v2) { - xp -= o.xp; - yp -= o.yp; - zp -= o.zp; - return *this; - } - - constexpr inline QPoint3D& operator*=(double factor) - { - xp *= factor; - yp *= factor; - zp *= factor; - return *this; - } - - constexpr inline QPoint3D& operator/=(double divisor) - { - xp /= divisor; - yp /= divisor; - zp /= divisor; - return *this; - } - - constexpr static inline double dotProduct(const QPoint3D& v1, const QPoint3D& v2) - { - return v1.xp * v2.xp + v1.yp * v2.yp + v1.zp * v2.zp; - } - - constexpr static inline QPoint3D crossProduct(const QPoint3D& v1, const QPoint3D& v2) - { - return QPoint3D(v1.yp * v2.zp - v1.zp * v2.yp, v1.zp * v2.xp - v1.xp * v2.zp, v1.xp * v2.yp - v1.yp * v2.xp); - } - - static inline QPoint3D normal(const QPoint3D& v1, const QPoint3D& v2) - { - return crossProduct(v1, v2).normalized(); - } - - static inline QPoint3D normal(const QPoint3D& v1, const QPoint3D& v2, const QPoint3D& v3) - { - return crossProduct((v2 - v1), (v3 - v1)).normalized(); - } - - friend inline bool qFuzzyCompare(const QPoint3D& v1, const QPoint3D& v2) - { - return ::qFuzzyCompare(v1.xp, v2.xp) && ::qFuzzyCompare(v1.yp, v2.yp) && ::qFuzzyCompare(v1.zp, v2.zp); + return ::qFuzzyCompare(v1.xp, v2.xp) && ::qFuzzyCompare(v1.yp, v2.yp) && ::qFuzzyCompare(v1.zp, v2.zp); } private: double xp = 0; double yp = 0; double zp = 0; -}; + }; -// QDataStream& operator<<(QDataStream& s, const QPoint3D& p); -// QDataStream& operator>>(QDataStream& s, QPoint3D& p); + // QDataStream& operator<<(QDataStream& s, const QPoint3D& p); + // QDataStream& operator>>(QDataStream& s, QPoint3D& p); -constexpr inline QPoint3D::QPoint3D(double xpos, double ypos, double zpos) : xp(xpos), yp(ypos), zp(zpos) {} + constexpr inline QPoint3D::QPoint3D(double xpos, double ypos, double zpos) + : xp(xpos) + , yp(ypos) + , zp(zpos) + { + } -inline bool QPoint3D::isNull() const -{ + inline bool QPoint3D::isNull() const + { return qIsNull(xp) && qIsNull(yp) && qIsNull(zp); -} + } -constexpr inline double QPoint3D::x() const -{ + constexpr inline double QPoint3D::x() const + { return xp; -} + } -constexpr inline double QPoint3D::y() const -{ + constexpr inline double QPoint3D::y() const + { return yp; -} + } -constexpr inline double QPoint3D::z() const -{ + constexpr inline double QPoint3D::z() const + { return zp; -} + } -constexpr inline void QPoint3D::setX(double xpos) -{ + constexpr inline void QPoint3D::setX(double xpos) + { xp = xpos; -} + } -constexpr inline void QPoint3D::setY(double ypos) -{ + constexpr inline void QPoint3D::setY(double ypos) + { yp = ypos; -} + } -constexpr inline void QPoint3D::setZ(double zpos) -{ + constexpr inline void QPoint3D::setZ(double zpos) + { zp = zpos; -} + } -constexpr inline double& QPoint3D::rx() -{ + constexpr inline double &QPoint3D::rx() + { return xp; -} + } -constexpr inline double& QPoint3D::ry() -{ + constexpr inline double &QPoint3D::ry() + { return yp; -} + } -constexpr inline double& QPoint3D::rz() -{ + constexpr inline double &QPoint3D::rz() + { return zp; -} + } -constexpr inline QPointF QPoint3D::toPointF() const -{ + constexpr inline QPointF QPoint3D::toPointF() const + { return QPointF(xp, yp); -} + } -constexpr inline bool operator==(const QPoint3D& p1, const QPoint3D& p2) -{ + constexpr inline bool operator==(const QPoint3D &p1, const QPoint3D &p2) + { return p1.xp == p2.xp && p1.yp == p2.yp && p1.zp == p2.zp; -} + } -constexpr inline bool operator!=(const QPoint3D& p1, const QPoint3D& p2) -{ + constexpr inline bool operator!=(const QPoint3D &p1, const QPoint3D &p2) + { return p1.xp != p2.xp || p1.yp != p2.yp || p1.zp != p2.zp; -} + } -inline std::ostream& operator<<(std::ostream& stream, const QPoint3D& pos) -{ + inline std::ostream &operator<<(std::ostream &stream, const QPoint3D &pos) + { stream << "(" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; return stream; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp index 560111eb3..c1fbc03f0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp @@ -7,15 +7,16 @@ namespace LtsUtils { -ScopedConnection::ScopedConnection(IConnection* connection, Qt::ConnectionType connType) : m_conn(connection) -{ + ScopedConnection::ScopedConnection(IConnection *connection, Qt::ConnectionType connType) + : m_conn(connection) + { Q_ASSERT(connection); m_conn->connect(connType); -} + } -ScopedConnection::~ScopedConnection() -{ + ScopedConnection::~ScopedConnection() + { m_conn->disconnect(); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h index 329b52712..88d9ebbc5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h @@ -9,16 +9,16 @@ namespace LtsUtils { -class IConnection; + class IConnection; -class LTSUTILSCORE_EXPORT ScopedConnection -{ + class LTSUTILSCORE_EXPORT ScopedConnection + { public: - explicit ScopedConnection(IConnection* connection, Qt::ConnectionType = Qt::AutoConnection); + explicit ScopedConnection(IConnection *connection, Qt::ConnectionType = Qt::AutoConnection); ~ScopedConnection(); private: - IConnection* m_conn; -}; + IConnection *m_conn; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp index c6530d694..3cf6892cf 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp @@ -5,24 +5,24 @@ namespace LtsUtils { -static constexpr unsigned char XON = 0x11; -static constexpr unsigned char XOFF = 0x13; -static constexpr unsigned char STX = 0x02; -static constexpr unsigned char ETX = 0x03; -static constexpr unsigned char SUBST = 0x80; + static constexpr unsigned char XON = 0x11; + static constexpr unsigned char XOFF = 0x13; + static constexpr unsigned char STX = 0x02; + static constexpr unsigned char ETX = 0x03; + static constexpr unsigned char SUBST = 0x80; -static constexpr unsigned char SUB_XON = 0x91; -static constexpr unsigned char SUB_XOFF = 0x93; -static constexpr unsigned char SUB_STX = 0x82; -static constexpr unsigned char SUB_ETX = 0x83; -static constexpr unsigned char SUB_SUBST = 0x00; + static constexpr unsigned char SUB_XON = 0x91; + static constexpr unsigned char SUB_XOFF = 0x93; + static constexpr unsigned char SUB_STX = 0x82; + static constexpr unsigned char SUB_ETX = 0x83; + static constexpr unsigned char SUB_SUBST = 0x00; -static constexpr int HEADER_SIZE = 3; -static constexpr int CHECKSUM_SIZE = 1; -static constexpr int MINIMUM_BYTE_SIZE = 1 + HEADER_SIZE + CHECKSUM_SIZE + 1; + static constexpr int HEADER_SIZE = 3; + static constexpr int CHECKSUM_SIZE = 1; + static constexpr int MINIMUM_BYTE_SIZE = 1 + HEADER_SIZE + CHECKSUM_SIZE + 1; -static SfmMessage getSfmMessage(const QByteArray& p_data) -{ + static SfmMessage getSfmMessage(const QByteArray &p_data) + { unsigned short id = 0; id |= (((unsigned short)p_data[0]) & 0x7F) << 8; @@ -34,10 +34,10 @@ static SfmMessage getSfmMessage(const QByteArray& p_data) msg.setPayload(p_data.right(p_data.size() - HEADER_SIZE)); return msg; -} + } -static QByteArray getHeader(const SfmMessage& p_msg) -{ + static QByteArray getHeader(const SfmMessage &p_msg) + { QByteArray header(2, Qt::Uninitialized); header[0] = ((p_msg.id() >> 8) & 0x7f) | (p_msg.rtr() << 7); @@ -45,184 +45,184 @@ static QByteArray getHeader(const SfmMessage& p_msg) header[1] = (p_msg.id() >> 0) & 0xff; return header; -} + } -static inline char getChecksum(const QByteArray& p_data) -{ + static inline char getChecksum(const QByteArray &p_data) + { char sum = 0; for (const char c : p_data) - sum += c; + sum += c; return sum ^ 0xff; -} + } -static QByteArray removeChecksum(const QByteArray& p_data) -{ + static QByteArray removeChecksum(const QByteArray &p_data) + { QByteArray withoutChecksum(p_data); ConversionError error("Checksum error"); if (p_data.size() >= CHECKSUM_SIZE) { - withoutChecksum.chop(1); + withoutChecksum.chop(1); - if (p_data.at(p_data.size() - 1) != getChecksum(withoutChecksum)) - throw error; + if (p_data.at(p_data.size() - 1) != getChecksum(withoutChecksum)) + throw error; } else - throw error; + throw error; return withoutChecksum; -} + } -static QByteArray maskData(const QByteArray& p_data) -{ + static QByteArray maskData(const QByteArray &p_data) + { QByteArray maskData; maskData.reserve(p_data.size() * 8 / 6); for (const unsigned char byte : p_data) { - switch (byte) - { - case XON: - maskData.append(SUBST); - maskData.append(SUB_XON); - break; - case XOFF: - maskData.append(SUBST); - maskData.append(SUB_XOFF); - break; - case STX: - maskData.append(SUBST); - maskData.append(SUB_STX); - break; - case ETX: - maskData.append(SUBST); - maskData.append(SUB_ETX); - break; - case SUBST: - maskData.append(SUBST); - maskData.append(static_cast(SUB_SUBST)); - break; - default: - maskData.append(byte); - break; - } + switch (byte) + { + case XON: + maskData.append(SUBST); + maskData.append(SUB_XON); + break; + case XOFF: + maskData.append(SUBST); + maskData.append(SUB_XOFF); + break; + case STX: + maskData.append(SUBST); + maskData.append(SUB_STX); + break; + case ETX: + maskData.append(SUBST); + maskData.append(SUB_ETX); + break; + case SUBST: + maskData.append(SUBST); + maskData.append(static_cast(SUB_SUBST)); + break; + default: + maskData.append(byte); + break; + } } return maskData; -} + } -static bool mustBeMasked(const unsigned char byte) -{ + static bool mustBeMasked(const unsigned char byte) + { switch (byte) { - case XON: - case XOFF: - case STX: - case ETX: - case SUBST: - return true; - default: - break; + case XON: + case XOFF: + case STX: + case ETX: + case SUBST: + return true; + default: + break; } return false; -} + } -int lenMaskedData(const QByteArray& data) -{ + int lenMaskedData(const QByteArray &data) + { int ret = data.length(); const unsigned char upperLen = ((data.length() & 0xff00) >> 8); const unsigned char lowerLen = ((data.length() & 0x00ff) >> 0); if (mustBeMasked(upperLen)) - ++ret; + ++ret; if (mustBeMasked(lowerLen)) - ++ret; + ++ret; for (const unsigned char byte : data) { - if (mustBeMasked(byte)) - ++ret; + if (mustBeMasked(byte)) + ++ret; } if (mustBeMasked(getChecksum(data))) - ++ret; + ++ret; return ret; -} + } -static QByteArray unmaskData(const QByteArray& p_data) -{ + static QByteArray unmaskData(const QByteArray &p_data) + { QByteArray unmaskData; unmaskData.reserve(p_data.size()); for (int position = 0; position < p_data.size(); ++position) { - unsigned char byte = p_data.at(position); - if (byte == SUBST) - { - ++position; - byte = p_data.at(position); + unsigned char byte = p_data.at(position); + if (byte == SUBST) + { + ++position; + byte = p_data.at(position); - switch (byte) - { - case SUB_XON: - unmaskData.append(XON); - break; - case SUB_XOFF: - unmaskData.append(XOFF); - break; - case SUB_STX: - unmaskData.append(STX); - break; - case SUB_ETX: - unmaskData.append(ETX); - break; - case SUB_SUBST: - unmaskData.append(SUBST); - break; - default: - break; - } + switch (byte) + { + case SUB_XON: + unmaskData.append(XON); + break; + case SUB_XOFF: + unmaskData.append(XOFF); + break; + case SUB_STX: + unmaskData.append(STX); + break; + case SUB_ETX: + unmaskData.append(ETX); + break; + case SUB_SUBST: + unmaskData.append(SUBST); + break; + default: + break; } - else - unmaskData.append(byte); + } + else + unmaskData.append(byte); } return unmaskData; -} + } -static QByteArray addFrame(const QByteArray& p_data) -{ + static QByteArray addFrame(const QByteArray &p_data) + { QByteArray ret; ret.reserve(2 + p_data.size()); ret.append(STX); ret.append(p_data); ret.append(ETX); return ret; -} + } -static QByteArray removeFrame(const QByteArray& p_data) -{ + static QByteArray removeFrame(const QByteArray &p_data) + { if (p_data[0] == STX && p_data[p_data.size() - 1] == ETX) { - return p_data.mid(1, p_data.size() - 2); + return p_data.mid(1, p_data.size() - 2); } else - throw ConversionError("Framing Error"); -} + throw ConversionError("Framing Error"); + } -static void checkLength(const QByteArray& p_data) -{ + static void checkLength(const QByteArray &p_data) + { if (p_data.size() < HEADER_SIZE) - throw ConversionError("Telegram too short"); + throw ConversionError("Telegram too short"); unsigned char length = p_data[HEADER_SIZE - 1]; if (length != p_data.size() - HEADER_SIZE) - throw ConversionError("Telegram length does not match"); -} + throw ConversionError("Telegram length does not match"); + } -QByteArray byteStreamFromSfmMessage(const SfmMessage& message) -{ + QByteArray byteStreamFromSfmMessage(const SfmMessage &message) + { QByteArray byteData(getHeader(message)); byteData.append(message.payload().size()); @@ -230,12 +230,12 @@ QByteArray byteStreamFromSfmMessage(const SfmMessage& message) byteData.append(getChecksum(byteData)); return addFrame(maskData(byteData)); -} + } -SfmMessage byteStreamToSfmMessage(const QByteArray& datastream) -{ + SfmMessage byteStreamToSfmMessage(const QByteArray &datastream) + { if (datastream.size() < MINIMUM_BYTE_SIZE) - throw ConversionError("Can't convert an QByteArray that hasn't the minimum size!"); + throw ConversionError("Can't convert an QByteArray that hasn't the minimum size!"); QByteArray checkMsg; @@ -247,29 +247,29 @@ SfmMessage byteStreamToSfmMessage(const QByteArray& datastream) checkLength(checkMsg); return getSfmMessage(checkMsg); -} + } -QByteArray byteStreamFromEscMessage(const QByteArray& message) -{ + QByteArray byteStreamFromEscMessage(const QByteArray &message) + { QByteArray byteData = message; if (message.size() == 1) { - byteData.append(message); + byteData.append(message); } else - byteData.append(getChecksum(byteData)); + byteData.append(getChecksum(byteData)); byteData = maskData(byteData); byteData = addFrame(byteData); return byteData; -} + } -QByteArray byteStreamToEscMessage(const QByteArray& datastream) -{ + QByteArray byteStreamToEscMessage(const QByteArray &datastream) + { if (datastream.size() < 2) - return QByteArray("ERROR"); + return QByteArray("ERROR"); QByteArray checkMsg; @@ -278,6 +278,6 @@ QByteArray byteStreamToEscMessage(const QByteArray& datastream) checkMsg.chop(1); return checkMsg; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h index b9de5c896..505797da2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h @@ -9,64 +9,43 @@ namespace LtsUtils { -class LTSUTILSCORE_EXPORT SfmMessage -{ + class LTSUTILSCORE_EXPORT SfmMessage + { public: - unsigned int id() const - { - return m_id; - } + unsigned int id() const { return m_id; } - void setId(unsigned int id) - { - m_id = id; - } + void setId(unsigned int id) { m_id = id; } - bool rtr() const - { - return m_rtr; - } + bool rtr() const { return m_rtr; } - void setRtr(bool rtr) - { - m_rtr = rtr; - } + void setRtr(bool rtr) { m_rtr = rtr; } - QByteArray payload() const - { - return m_payload; - } + QByteArray payload() const { return m_payload; } - void setPayload(const QByteArray& payload) - { - m_payload = payload; - } + void setPayload(const QByteArray &payload) { m_payload = payload; } - bool operator==(const SfmMessage& msg) const - { - return (m_id == msg.id() && m_rtr == msg.rtr() && m_payload == msg.payload()); - } + bool operator==(const SfmMessage &msg) const { return (m_id == msg.id() && m_rtr == msg.rtr() && m_payload == msg.payload()); } protected: unsigned int m_id = 0; bool m_rtr = false; QByteArray m_payload; -}; + }; -class ConversionError : public std::runtime_error -{ + class ConversionError : public std::runtime_error + { public: using std::runtime_error::runtime_error; -}; + }; -LTSUTILSCORE_EXPORT QByteArray byteStreamFromSfmMessage(const SfmMessage& message); + LTSUTILSCORE_EXPORT QByteArray byteStreamFromSfmMessage(const SfmMessage &message); -LTSUTILSCORE_EXPORT SfmMessage byteStreamToSfmMessage(const QByteArray& datastream); + LTSUTILSCORE_EXPORT SfmMessage byteStreamToSfmMessage(const QByteArray &datastream); -LTSUTILSCORE_EXPORT QByteArray byteStreamFromEscMessage(const QByteArray& message); + LTSUTILSCORE_EXPORT QByteArray byteStreamFromEscMessage(const QByteArray &message); -LTSUTILSCORE_EXPORT QByteArray byteStreamToEscMessage(const QByteArray& datastream); + LTSUTILSCORE_EXPORT QByteArray byteStreamToEscMessage(const QByteArray &datastream); -LTSUTILSCORE_EXPORT int lenMaskedData(const QByteArray& data); + LTSUTILSCORE_EXPORT int lenMaskedData(const QByteArray &data); } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h index 8983030d9..79cf3cda3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h @@ -7,31 +7,31 @@ namespace LtsUtils { -inline bool lessThan(const QVariant& var1, const QVariant& var2) -{ + inline bool lessThan(const QVariant &var1, const QVariant &var2) + { if (var1.canConvert() && var2.canConvert()) { - QString str1(var1.toString()); - QString str2(var2.toString()); + QString str1(var1.toString()); + QString str2(var2.toString()); - bool k1 = false; - double d1 = str1.toDouble(&k1); + bool k1 = false; + double d1 = str1.toDouble(&k1); - if (!k1) - return str1 < str2; + if (!k1) + return str1 < str2; - bool k2 = false; - double d2 = str2.toDouble(&k2); + bool k2 = false; + double d2 = str2.toDouble(&k2); - if (!k2) - return str1 < str2; + if (!k2) + return str1 < str2; - return d1 < d2; + return d1 < d2; } else if (var1.canConvert() && var2.canConvert()) - return var1.toDouble() < var2.toDouble(); + return var1.toDouble() < var2.toDouble(); return false; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp index a253f437d..7fcf696ec 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp @@ -8,52 +8,58 @@ namespace LtsUtils { -int ConnectingDialog::s_waitForHistoricalDataWaitTime = 10000; + int ConnectingDialog::s_waitForHistoricalDataWaitTime = 10000; -void ConnectingDialog::reset() -{ - m_ui->label->setText(QStringLiteral("%1") - .arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); -} + void ConnectingDialog::reset() + { + m_ui->label->setText(QStringLiteral("%1").arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); + } -void ConnectingDialog::setup() -{ + void ConnectingDialog::setup() + { m_ui = new Ui::ConnectingDialog; m_ui->setupUi(this); reset(); setMinimumSize(sizeHint()); - connect(m_ui->pbRetry, &QPushButton::clicked, this, [this]() { - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setEnabled(false); + connect(m_ui->pbRetry, + &QPushButton::clicked, + this, + [this]() + { + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setEnabled(false); - reset(); - emit signalStopLoop(); - }); + reset(); + emit signalStopLoop(); + }); - connect(m_ui->pbIgnore, &QPushButton::clicked, this, [this]() { - m_ui->pbIgnore->setEnabled(false); - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setText(tr("continuing..")); + connect(m_ui->pbIgnore, + &QPushButton::clicked, + this, + [this]() + { + m_ui->pbIgnore->setEnabled(false); + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setText(tr("continuing..")); - deleteLater(); - return; - }); -} + deleteLater(); + return; + }); + } -ConnectingDialog::~ConnectingDialog() -{ + ConnectingDialog::~ConnectingDialog() + { delete m_ui; -} + } -void ConnectingDialog::failed() -{ - m_ui->label->setText(QStringLiteral("%1") - .arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); + void ConnectingDialog::failed() + { + m_ui->label->setText(QStringLiteral("%1").arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); m_ui->pbRetry->setEnabled(true); m_ui->pbIgnore->setEnabled(true); raise(); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h index f629ee383..552295d02 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h @@ -11,47 +11,52 @@ namespace Ui { -class ConnectingDialog; + class ConnectingDialog; } namespace LtsUtils { -class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialog : public LtsWidgets::LtsFramelessDialog -{ + class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialog : public LtsWidgets::LtsFramelessDialog + { Q_OBJECT public: static int s_waitForHistoricalDataWaitTime; template - explicit ConnectingDialog(DtcType dtc, WaitForHistoricalDataFunction waitForHistoricalDataFunction, - const QString& serviceName, const QString& exerciseName, QWidget* parent = nullptr) - : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_serviceName(serviceName), - m_exerciseName(exerciseName), m_ui(nullptr) + explicit ConnectingDialog(DtcType dtc, + WaitForHistoricalDataFunction waitForHistoricalDataFunction, + const QString &serviceName, + const QString &exerciseName, + QWidget *parent = nullptr) + : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) + , m_serviceName(serviceName) + , m_exerciseName(exerciseName) + , m_ui(nullptr) { - setWindowTitle(tr("Connecting ..")); - setup(); - show(); + setWindowTitle(tr("Connecting ..")); + setup(); + show(); - while (true) + while (true) + { + if ((dtc.get()->*waitForHistoricalDataFunction)(s_waitForHistoricalDataWaitTime)) { - if ((dtc.get()->*waitForHistoricalDataFunction)(s_waitForHistoricalDataWaitTime)) - { - deleteLater(); - return; - } - - if (s_waitForHistoricalDataWaitTime >= 999999) - { - deleteLater(); - return; - } - else - { - failed(); - } + deleteLater(); + return; } + + if (s_waitForHistoricalDataWaitTime >= 999999) + { + deleteLater(); + return; + } + else + { + failed(); + } + } } ~ConnectingDialog(); @@ -61,13 +66,13 @@ class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialog : public LtsWidgets::LtsF private: QString m_serviceName; QString m_exerciseName; - Ui::ConnectingDialog* m_ui; + Ui::ConnectingDialog *m_ui; void reset(); void setup(); signals: void signalStopLoop(); -}; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp index 1c0f8322e..4fa2ad4f1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp @@ -12,39 +12,50 @@ namespace LtsUtils { -ConnectingDialogNT::ConnectingDialogNT(const std::function& checkFn, const QString& serviceName, - const QString& exerciseName, QWidget* parent) - : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_serviceName(serviceName), - m_exerciseName(exerciseName), m_checkFn(checkFn), m_go(false), m_autoRetryTimer(new QTimer(this)), - m_ui(new Ui::ConnectingDialog) -{ + ConnectingDialogNT::ConnectingDialogNT(const std::function &checkFn, const QString &serviceName, const QString &exerciseName, QWidget *parent) + : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) + , m_serviceName(serviceName) + , m_exerciseName(exerciseName) + , m_checkFn(checkFn) + , m_go(false) + , m_autoRetryTimer(new QTimer(this)) + , m_ui(new Ui::ConnectingDialog) + { m_ui->setupUi(this); m_autoRetryTimer->setInterval(1000); - connect(m_autoRetryTimer, &QTimer::timeout, this, [this]() { - if (m_autoRetryTick < 1) - { - slotRetry(); - return; - } + connect(m_autoRetryTimer, + &QTimer::timeout, + this, + [this]() + { + if (m_autoRetryTick < 1) + { + slotRetry(); + return; + } - m_ui->pbRetry->setText(QStringLiteral("%1 [%2]").arg(tr("Retry")).arg(m_autoRetryTick)); - m_autoRetryTick--; - }); + m_ui->pbRetry->setText(QStringLiteral("%1 [%2]").arg(tr("Retry")).arg(m_autoRetryTick)); + m_autoRetryTick--; + }); reset(); setMinimumSize(sizeHint()); connect(m_ui->pbRetry, &QPushButton::clicked, this, &ConnectingDialogNT::slotRetry); - connect(m_ui->pbIgnore, &QPushButton::clicked, this, [this]() { - m_ui->pbIgnore->setEnabled(false); - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setText(tr("continuing..")); + connect(m_ui->pbIgnore, + &QPushButton::clicked, + this, + [this]() + { + m_ui->pbIgnore->setEnabled(false); + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setText(tr("continuing..")); - emit signalFailed(); - deleteLater(); - return; - }); + emit signalFailed(); + deleteLater(); + return; + }); show(); @@ -52,32 +63,32 @@ ConnectingDialogNT::ConnectingDialogNT(const std::function& checkFn, m_go = true; m_ui->pbRetry->setEnabled(false); -} + } -int ConnectingDialogNT::random(int min, int max) -{ + int ConnectingDialogNT::random(int min, int max) + { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) return QRandomGenerator::global()->bounded(min, max); #else return (qrand() % (((max + 1) - min) + min)); #endif -} + } -bool ConnectingDialogNT::event(QEvent* event) -{ + bool ConnectingDialogNT::event(QEvent *event) + { bool result = LtsWidgets::LtsFramelessDialog::event(event); if (event->type() == QEvent::Paint && m_go) { - m_go = false; - QTimer::singleShot(0, this, &ConnectingDialogNT::signalGo); + m_go = false; + QTimer::singleShot(0, this, &ConnectingDialogNT::signalGo); } return result; -} + } -void ConnectingDialogNT::slotRetry() -{ + void ConnectingDialogNT::slotRetry() + { m_autoRetryTimer->stop(); m_ui->pbRetry->setText(tr("Retry")); @@ -86,36 +97,34 @@ void ConnectingDialogNT::slotRetry() reset(); QTimer::singleShot(1, this, &ConnectingDialogNT::slotGo); -} + } -void ConnectingDialogNT::slotGo() -{ + void ConnectingDialogNT::slotGo() + { if (m_checkFn(ConnectingDialog::s_waitForHistoricalDataWaitTime)) { - emit signalSuccess(); - deleteLater(); - return; + emit signalSuccess(); + deleteLater(); + return; } failed(); -} + } -void ConnectingDialogNT::reset() -{ - m_ui->label->setText(QStringLiteral("%1") - .arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); -} + void ConnectingDialogNT::reset() + { + m_ui->label->setText(QStringLiteral("%1").arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); + } -ConnectingDialogNT::~ConnectingDialogNT() -{ + ConnectingDialogNT::~ConnectingDialogNT() + { delete m_ui; -} + } -void ConnectingDialogNT::failed() -{ - m_ui->label->setText(QStringLiteral("%1") - .arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); + void ConnectingDialogNT::failed() + { + m_ui->label->setText(QStringLiteral("%1").arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); m_ui->pbRetry->setEnabled(true); m_ui->pbIgnore->setEnabled(true); @@ -124,6 +133,6 @@ void ConnectingDialogNT::failed() m_autoRetryTimer->start(); raise(); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h index a9200b6ca..a5b3eda11 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h @@ -11,19 +11,18 @@ class QTimer; namespace Ui { -class ConnectingDialog; + class ConnectingDialog; } namespace LtsUtils { -class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialogNT : public LtsWidgets::LtsFramelessDialog -{ + class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialogNT : public LtsWidgets::LtsFramelessDialog + { Q_OBJECT public: - explicit ConnectingDialogNT(const std::function& checkFn, const QString& serviceName, - const QString& exerciseName, QWidget* parent); + explicit ConnectingDialogNT(const std::function &checkFn, const QString &serviceName, const QString &exerciseName, QWidget *parent); ~ConnectingDialogNT(); void failed(); @@ -43,14 +42,14 @@ class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialogNT : public LtsWidgets::Lt std::function m_checkFn; bool m_go; - QTimer* m_autoRetryTimer; + QTimer *m_autoRetryTimer; int m_autoRetryTick{0}; - Ui::ConnectingDialog* m_ui; + Ui::ConnectingDialog *m_ui; int random(int min, int max); - bool event(QEvent* event) override; + bool event(QEvent *event) override; void reset(); -}; + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp index 36be661cb..eb306c713 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp @@ -13,8 +13,8 @@ namespace LtsUtils { -QIcon iconFromSvg(const QByteArray& svgData, QSize iconSize) -{ + QIcon iconFromSvg(const QByteArray &svgData, QSize iconSize) + { QSvgRenderer renderer(svgData); QPixmap p(iconSize); p.fill(Qt::transparent); @@ -23,60 +23,60 @@ QIcon iconFromSvg(const QByteArray& svgData, QSize iconSize) painter.end(); return {p}; -} + } -QIcon iconFromSvg(const QString& svgFilename, QSize iconSize) -{ + QIcon iconFromSvg(const QString &svgFilename, QSize iconSize) + { QFile f(svgFilename); if (!f.open(QIODevice::ReadOnly)) - return {}; + return {}; return iconFromSvg(f.readAll(), iconSize); -} + } -QPixmap pixmapFromIcon(const QIcon& icon, QSize iconSize) -{ + QPixmap pixmapFromIcon(const QIcon &icon, QSize iconSize) + { return icon.pixmap(iconSize).scaled(100, 100, Qt::AspectRatioMode::IgnoreAspectRatio); -} + } -QPixmap pixmapFromSvg(const QString& svgFilename, QSize iconSize) -{ + QPixmap pixmapFromSvg(const QString &svgFilename, QSize iconSize) + { return pixmapFromIcon(iconFromSvg(svgFilename, iconSize), iconSize); -} + } -QPixmap getPixmap(const std::vector& data) -{ + QPixmap getPixmap(const std::vector &data) + { if (data.size() == 0) - return QPixmap(); + return QPixmap(); - return getPixmap(QByteArray(reinterpret_cast(&data.at(0)), data.size())); -} + return getPixmap(QByteArray(reinterpret_cast(&data.at(0)), data.size())); + } -QPixmap getPixmap(const QByteArray& data) -{ + QPixmap getPixmap(const QByteArray &data) + { return QPixmap::fromImage(QImage::fromData(data)); -} + } -QImage getImage(const std::vector& data) -{ + QImage getImage(const std::vector &data) + { if (data.size() == 0) - return QImage(); + return QImage(); - return getImage(QByteArray(reinterpret_cast(&data.at(0)), data.size())); -} + return getImage(QByteArray(reinterpret_cast(&data.at(0)), data.size())); + } -QImage getImage(const QByteArray& data) -{ + QImage getImage(const QByteArray &data) + { return QImage::fromData(data); -} + } -static inline void setIf(bool* boolPtr, bool val) -{ + static inline void setIf(bool *boolPtr, bool val) + { if (boolPtr) - *boolPtr = val; -} + *boolPtr = val; + } -std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng) -{ + std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng) + { QBuffer buf; buf.open(QIODevice::WriteOnly); pixmap.save(&buf, "PNG"); @@ -87,22 +87,22 @@ std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng) if (ba.size() > 10240 && !pixmap.hasAlpha() && !pixmap.hasAlphaChannel()) { - QBuffer buf2; - buf2.open(QIODevice::WriteOnly); - pixmap.save(&buf2, "JPG"); - buf2.close(); - if (buf2.buffer().size() < buf.buffer().size()) - { - setIf(bIsPng, false); - ba = buf2.buffer(); - } + QBuffer buf2; + buf2.open(QIODevice::WriteOnly); + pixmap.save(&buf2, "JPG"); + buf2.close(); + if (buf2.buffer().size() < buf.buffer().size()) + { + setIf(bIsPng, false); + ba = buf2.buffer(); + } } return convert>(ba); -} + } -std::vector fromImage(const QImage& image, bool* bIsPng) -{ + std::vector fromImage(const QImage &image, bool *bIsPng) + { QBuffer buf; buf.open(QIODevice::WriteOnly); image.save(&buf, "PNG"); @@ -112,18 +112,18 @@ std::vector fromImage(const QImage& image, bool* bIsPng) setIf(bIsPng, true); if ((ba.size() > 10240 && !image.hasAlphaChannel()) || ba.size() > 1024 * 1024) { - QBuffer buf2; - buf2.open(QIODevice::WriteOnly); - image.save(&buf2, "JPG"); - buf2.close(); - if (buf2.buffer().size() < buf.buffer().size()) - { - setIf(bIsPng, false); - ba = buf2.buffer(); - } + QBuffer buf2; + buf2.open(QIODevice::WriteOnly); + image.save(&buf2, "JPG"); + buf2.close(); + if (buf2.buffer().size() < buf.buffer().size()) + { + setIf(bIsPng, false); + ba = buf2.buffer(); + } } return convert>(ba); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h index 04028956a..dc29a4034 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h @@ -17,15 +17,15 @@ class QIcon; namespace LtsUtils { -LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector& data); -LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray& data); -LTSUTILSCORE_EXPORT QImage getImage(const std::vector& data); -LTSUTILSCORE_EXPORT QImage getImage(const QByteArray& data); -LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QByteArray& svgData, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QString& svgFilename, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QPixmap pixmapFromIcon(const QIcon& icon, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QPixmap pixmapFromSvg(const QString& svgFilename, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng = nullptr); -LTSUTILSCORE_EXPORT std::vector fromImage(const QImage& image, bool* bIsPng = nullptr); + LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector &data); + LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray &data); + LTSUTILSCORE_EXPORT QImage getImage(const std::vector &data); + LTSUTILSCORE_EXPORT QImage getImage(const QByteArray &data); + LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QByteArray &svgData, QSize iconSize = QSize(100, 100)); + LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QString &svgFilename, QSize iconSize = QSize(100, 100)); + LTSUTILSCORE_EXPORT QPixmap pixmapFromIcon(const QIcon &icon, QSize iconSize = QSize(100, 100)); + LTSUTILSCORE_EXPORT QPixmap pixmapFromSvg(const QString &svgFilename, QSize iconSize = QSize(100, 100)); + LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng = nullptr); + LTSUTILSCORE_EXPORT std::vector fromImage(const QImage &image, bool *bIsPng = nullptr); } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/ltsutilsdds_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/ltsutilsdds_export.h index b7f7294bd..9e7c0c6d7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/ltsutilsdds_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/ltsutilsdds_export.h @@ -9,4 +9,4 @@ #define LTSUTILSGUIDDS_EXPORT #define LTSUTILSGUIDDS_NO_EXPORT -#endif // LTSUTILSDDS_EXPORT_H \ No newline at end of file +#endif // LTSUTILSDDS_EXPORT_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp index 2141663a7..94699f9d2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp @@ -18,72 +18,76 @@ namespace LtsUtils { -bool RequestHelper::s_debug = false; + bool RequestHelper::s_debug = false; -RequestHelper::RequestHelper(QObject* parent, bool quiet, + RequestHelper::RequestHelper(QObject *parent, + bool quiet, - const std::function& success, const std::function& failure) - : QObject(parent), m_failed(false), m_repliedId(-1), m_quiet(quiet), m_blockingCall(true), m_successFn(success), - m_failureFn(failure) -{ + const std::function &success, + const std::function &failure) + : QObject(parent) + , m_failed(false) + , m_repliedId(-1) + , m_quiet(quiet) + , m_blockingCall(true) + , m_successFn(success) + , m_failureFn(failure) + { connect(this, &RequestHelper::signalSuccess, this, m_successFn, Qt::QueuedConnection); connect(this, &RequestHelper::signalFailed, this, m_failureFn, Qt::QueuedConnection); if (s_debug) { - QTimer* t = new QTimer(this); - t->setInterval(2000); - t->setSingleShot(true); - connect(this, &RequestHelper::signalNextRequest, t, static_cast(&QTimer::start)); - connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); + QTimer *t = new QTimer(this); + t->setInterval(2000); + t->setSingleShot(true); + connect(this, &RequestHelper::signalNextRequest, t, static_cast(&QTimer::start)); + connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); } else { - connect(this, &RequestHelper::signalNextRequest, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection + connect(this, &RequestHelper::signalNextRequest, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection - ); + ); } -} + } -void RequestHelper::addRequest(const std::function& requestFunction, - const std::function& baseReplyHandler) -{ + void RequestHelper::addRequest(const std::function &requestFunction, const std::function &baseReplyHandler) + { m_requestFunctions.append(RequestFunctionContainer(requestFunction, baseReplyHandler)); -} + } -bool RequestHelper::requestReply(const Core::FunctionReply& baseReply) -{ + bool RequestHelper::requestReply(const Core::FunctionReply &baseReply) + { // rtiddsgen 7.7 generates plain public members (no getters/setters) const Core::FunctionReplyObject fro(baseReply.id, baseReply.errorString, baseReply.errorParams); return _requestReply(fro, &baseReply); -} + } -bool RequestHelper::requestReply(const Core::FunctionReplyObject& replyObject) -{ + bool RequestHelper::requestReply(const Core::FunctionReplyObject &replyObject) + { return _requestReply(replyObject, nullptr); -} + } -bool RequestHelper::_requestReply(const Core::FunctionReplyObject& fro, const Core::FunctionReply* baseReply) -{ + bool RequestHelper::_requestReply(const Core::FunctionReplyObject &fro, const Core::FunctionReply *baseReply) + { m_errorString = fro.translated(); #ifdef REQUEST_HELPER_WITH_GUI if (fro.error()) { - if (!m_quiet) + if (!m_quiet) + { + if (m_blockingCall) { - if (m_blockingCall) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), m_errorString, - tr("Request failed")); - } - else - { - new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), m_errorString, - tr("Request failed")); - } + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), m_errorString, tr("Request failed")); } + else + { + new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), m_errorString, tr("Request failed")); + } + } } #endif @@ -91,67 +95,65 @@ bool RequestHelper::_requestReply(const Core::FunctionReplyObject& fro, const Co if (m_singleRequestCustomFunctionReply != nullptr) { - if (baseReply) - m_singleRequestCustomFunctionReply(*baseReply); - else - m_singleRequestCustomFunctionReply( - Core::FunctionReply(fro.id(), fro.str(), fro.args(), fro.additionalInfo())); + if (baseReply) + m_singleRequestCustomFunctionReply(*baseReply); + else + m_singleRequestCustomFunctionReply(Core::FunctionReply(fro.id(), fro.str(), fro.args(), fro.additionalInfo())); } if (fro.error()) { - failure(); - return false; + failure(); + return false; } emit signalNextRequest(); return true; -} + } -bool RequestHelper::startSingleRequest( - const std::function& requestFunction, - const std::function& baseReplyHandler) -{ + bool RequestHelper::startSingleRequest(const std::function &requestFunction, + const std::function &baseReplyHandler) + { addRequest(requestFunction, baseReplyHandler); return startRequests(); -} + } -void RequestHelper::failure() -{ + void RequestHelper::failure() + { m_failed = true; emit signalFailed(); done(); -} + } -void RequestHelper::done() -{ + void RequestHelper::done() + { #ifdef REQUEST_HELPER_WITH_GUI if (!m_quiet) - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); #endif m_requestFunctions.clear(); m_singleRequestCustomFunctionReply = nullptr; if (m_blockingCall) - emit signalQuitLoop(); + emit signalQuitLoop(); m_blockingCall = true; if (!m_blockingCall) - deleteLater(); -} + deleteLater(); + } -void RequestHelper::slotNextRequest() -{ + void RequestHelper::slotNextRequest() + { if (m_requestFunctions.isEmpty()) { - if (!m_blockingCall) - emit signalSuccess(); + if (!m_blockingCall) + emit signalSuccess(); - done(); + done(); - return; + return; } const RequestFunctionContainer rfc = m_requestFunctions.takeFirst(); @@ -162,59 +164,60 @@ void RequestHelper::slotNextRequest() if (result == 0) { #ifdef REQUEST_HELPER_WITH_GUI - if (!m_quiet) + if (!m_quiet) + { + if (m_blockingCall) { - if (m_blockingCall) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Request failed")); - } - else - { - connect(new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), tr("Request failed")), - &LtsWidgets::LtsMessageDialogNew::destroyed, this, [this]() { failure(); }); - - return; - } + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Request failed")); } -#endif - failure(); - } -} + else + { + connect(new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), tr("Request failed")), + &LtsWidgets::LtsMessageDialogNew::destroyed, + this, + [this]() { failure(); }); -void RequestHelper::startSingleBackgroundRequest( - const std::function& requestFunction, - const std::function& baseReplyHandler) -{ + return; + } + } +#endif + failure(); + } + } + + void RequestHelper::startSingleBackgroundRequest(const std::function &requestFunction, + const std::function &baseReplyHandler) + { m_blockingCall = false; startSingleRequest(requestFunction, baseReplyHandler); -} + } -void RequestHelper::startBackgroundRequests() -{ + void RequestHelper::startBackgroundRequests() + { m_blockingCall = false; startRequests(); -} + } -void RequestHelper::setCustomWaitMessage(const QString& customWaitMessage) -{ + void RequestHelper::setCustomWaitMessage(const QString &customWaitMessage) + { m_customWaitMessage = (customWaitMessage + QStringLiteral(" ...")); -} + } -bool RequestHelper::startRequests() -{ + bool RequestHelper::startRequests() + { if (m_requestFunctions.isEmpty()) { #ifdef LTS_DEBUG - qWarning("RequestHelper: started request helper without requests!"); + qWarning("RequestHelper: started request helper without requests!"); #endif - return true; + return true; } m_failed = false; #ifdef REQUEST_HELPER_WITH_GUI if (!m_quiet) - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(m_customWaitMessage); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(m_customWaitMessage); m_customWaitMessage.clear(); #endif @@ -223,25 +226,25 @@ bool RequestHelper::startRequests() if (s_debug) { - QTimer* t = new QTimer(this); - t->setInterval(2000); - connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); - connect(t, &QTimer::timeout, t, &QTimer::deleteLater); - t->start(); + QTimer *t = new QTimer(this); + t->setInterval(2000); + connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); + connect(t, &QTimer::timeout, t, &QTimer::deleteLater); + t->start(); } else { - slotNextRequest(); + slotNextRequest(); - if (m_blockingCall) - { - QEventLoop loop; - connect(this, &RequestHelper::signalQuitLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); - loop.exec(); - } + if (m_blockingCall) + { + QEventLoop loop; + connect(this, &RequestHelper::signalQuitLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); + loop.exec(); + } } return (!m_failed); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h index 719fda9d7..8708e759d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h @@ -27,114 +27,113 @@ namespace LtsUtils { -template -dds::core::optional toOptional(T inVal) -{ - return inVal != T() ? dds::core::optional(inVal) : dds::core::optional(); -} + template dds::core::optional toOptional(T inVal) + { + return inVal != T() ? dds::core::optional(inVal) : dds::core::optional(); + } -template -dds::core::optional optional() -{ - return dds::core::optional(); -} + template dds::core::optional optional() + { + return dds::core::optional(); + } -class LTSUTILSGUIDDS_INTERNAL_EXPORT RequestHelper : public QObject // TODO: DOC !!! -{ - Q_OBJECT + class LTSUTILSGUIDDS_INTERNAL_EXPORT RequestHelper : public QObject // TODO: DOC !!! + { + Q_OBJECT -public: - static bool s_debug; + public: + static bool s_debug; - explicit RequestHelper(QObject *parent = nullptr, bool quiet = false, - // for non-blocking - const std::function &success = [](){}, - const std::function &failure = [](){}); - ~RequestHelper() = default; + explicit RequestHelper( + QObject *parent = nullptr, + bool quiet = false, + // for non-blocking + const std::function &success = []() {}, + const std::function &failure = []() {}); + ~RequestHelper() = default; - bool quiet() const { return m_quiet; } - void setQuiet(bool quiet) { m_quiet = quiet; } - void addRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr); - bool startRequests(); // blocks! + bool quiet() const { return m_quiet; } + void setQuiet(bool quiet) { m_quiet = quiet; } + void addRequest(const std::function &requestFunction, const std::function &baseReplyHandler = nullptr); + bool startRequests(); // blocks! - // do not throw a message if this method fails, as this method does this already // blocks! - bool startSingleRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr // for replies that return a custom FunctionReply, which has to be handled >>after successful execution<< - ); + // do not throw a message if this method fails, as this method does this already // blocks! + bool startSingleRequest(const std::function &requestFunction, + const std::function &baseReplyHandler = + nullptr // for replies that return a custom FunctionReply, which has to be handled >>after successful execution<< + ); - // non-blocking ! - /** + // non-blocking ! + /** * @brief startSingleBackgroundRequest << you cannot reuse this request helper after using background requests! Only use if your REALLY need it. * @param requestFunction * @param baseReplyHandler */ - void startSingleBackgroundRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr); - /** + void startSingleBackgroundRequest(const std::function &requestFunction, + const std::function &baseReplyHandler = nullptr); + /** * @brief startBackgroundRequests << you cannot reuse this request helper after using background requests! Only use if your REALLY need it. */ - void startBackgroundRequests(); // non-blocking ! + void startBackgroundRequests(); // non-blocking ! - bool requestReply(const Core::FunctionReply &baseReply); // if you have a custom FunctionReply, pass the base ptr - bool requestReply(const Core::FunctionReplyObject &replyObject); + bool requestReply(const Core::FunctionReply &baseReply); // if you have a custom FunctionReply, pass the base ptr + bool requestReply(const Core::FunctionReplyObject &replyObject); - /** + /** * @brief hasRequests are requests is added? * @return True if a request is added, otherwise false */ - bool hasRequests() const { return !m_requestFunctions.isEmpty(); } + bool hasRequests() const { return !m_requestFunctions.isEmpty(); } - /** + /** * @brief getRepliedId returns the Return-ID of the ReplyObject you gave to the method 'requestReply' - which is mostly the ID for the new Table Entry (Unique ID) * @return the Return-ID or -1 on error (not set) */ - int getRepliedId() const { return m_repliedId; } + int getRepliedId() const { return m_repliedId; } - /** + /** * @brief getErrorString returns the error string set by an ftc reply * @return */ - QString getErrorString() const { return m_errorString; } + QString getErrorString() const { return m_errorString; } - /** + /** * @brief setCustomWaitMessage changes the default 'Waiting for server reply ...' message with a custom one (NOTE: " ..." is automagically added to the custom text) * After a request was started, the custom wait message is immediately reset, so that the next call to start a request, shows the default message again * @param customWaitMessage the wait message to replace the default message with (note that " ..." is added to the text) */ - void setCustomWaitMessage(const QString &customWaitMessage); + void setCustomWaitMessage(const QString &customWaitMessage); - bool failed() const { return m_failed; } - void failure(); + bool failed() const { return m_failed; } + void failure(); -private: - using RequestFunctionContainer = QPair, std::function>; + private: + using RequestFunctionContainer = QPair, std::function>; - QVector m_requestFunctions; - bool m_failed; - int m_repliedId; - std::function m_singleRequestCustomFunctionReply; - bool m_quiet; - bool m_blockingCall; - std::function m_successFn; - std::function m_failureFn; - QString m_errorString; - QString m_customWaitMessage; + QVector m_requestFunctions; + bool m_failed; + int m_repliedId; + std::function m_singleRequestCustomFunctionReply; + bool m_quiet; + bool m_blockingCall; + std::function m_successFn; + std::function m_failureFn; + QString m_errorString; + QString m_customWaitMessage; - void done(); - bool _requestReply(const Core::FunctionReplyObject &fro, const Core::FunctionReply *baseReply); + void done(); + bool _requestReply(const Core::FunctionReplyObject &fro, const Core::FunctionReply *baseReply); -signals: - void signalNextRequest(); - void signalQuitLoop(); - void signalSuccess(); - void signalFailed(); + signals: + void signalNextRequest(); + void signalQuitLoop(); + void signalSuccess(); + void signalFailed(); -private slots: - void slotNextRequest(); - -}; + private slots: + void slotNextRequest(); + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp index 8ff5eafa2..5ec022ea2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp @@ -10,82 +10,79 @@ namespace LtsUtils { -struct StyleManagerHandler -{ + struct StyleManagerHandler + { StyleManager styleManager; -}; -Q_GLOBAL_STATIC(StyleManagerHandler, s_styleManagerHandler) + }; + Q_GLOBAL_STATIC(StyleManagerHandler, s_styleManagerHandler) -StyleManager* StyleManager::getInstance() -{ + StyleManager *StyleManager::getInstance() + { return &s_styleManagerHandler->styleManager; -} + } -bool StyleManager::loadStyle(const QString& stylePluginName, bool highDpi) -{ + bool StyleManager::loadStyle(const QString &stylePluginName, bool highDpi) + { if (m_currentStylePluginLoader != nullptr) { - QObject* pluginInstance = m_currentStylePluginLoader->instance(); - StylePlugin::Plugin* sp = qobject_cast(pluginInstance); + QObject *pluginInstance = m_currentStylePluginLoader->instance(); + StylePlugin::Plugin *sp = qobject_cast(pluginInstance); - if (sp == nullptr) - { - qWarning() << "StyleManager::loadStyle: could not unload style plugin - wrong type (" - << pluginInstance->metaObject()->className() << ") - new style not loaded"; - return false; - } + if (sp == nullptr) + { + qWarning() << "StyleManager::loadStyle: could not unload style plugin - wrong type (" << pluginInstance->metaObject()->className() << ") - new style not loaded"; + return false; + } - sp->unloadStyle(); + sp->unloadStyle(); - m_currentStylePluginLoader = nullptr; + m_currentStylePluginLoader = nullptr; } - LtsPluginManager::LtsPluginLoader* pluginLoader = LtsPluginManager::LtsPluginLoader::getInstance(); + LtsPluginManager::LtsPluginLoader *pluginLoader = LtsPluginManager::LtsPluginLoader::getInstance(); - QPluginLoader* stylePluginLoader = nullptr; + QPluginLoader *stylePluginLoader = nullptr; int pluginsLoaded = 0; - std::function loadPluginFn = - [&stylePluginLoader, &pluginsLoaded](const LtsPluginManager::PluginInstance& pi) { - stylePluginLoader = pi.pluginLoader; - pluginsLoaded++; - return true; - }; + std::function loadPluginFn = [&stylePluginLoader, &pluginsLoaded](const LtsPluginManager::PluginInstance &pi) + { + stylePluginLoader = pi.pluginLoader; + pluginsLoaded++; + return true; + }; if (!pluginLoader->loadPlugins(LtsPluginManager::PluginType::STYLE, loadPluginFn, QStringList() << stylePluginName)) { - qWarning() << "StyleManager::loadStyle: Error loading Style Plugin - using default Qt style"; - return false; + qWarning() << "StyleManager::loadStyle: Error loading Style Plugin - using default Qt style"; + return false; } if (pluginsLoaded == 0) { - qWarning() << "StyleManager::loadStyle: Could not find Style Plugin" << stylePluginName - << "- using default Qt style"; - return false; + qWarning() << "StyleManager::loadStyle: Could not find Style Plugin" << stylePluginName << "- using default Qt style"; + return false; } if (pluginsLoaded > 1) { - qWarning() << "StyleManager::loadStyle: Style Plugin" << stylePluginName - << " is ambiguous - using default Qt style"; - return false; + qWarning() << "StyleManager::loadStyle: Style Plugin" << stylePluginName << " is ambiguous - using default Qt style"; + return false; } if (stylePluginLoader == nullptr) { - qWarning() << "StyleManager::loadStyle: No Style Plugin loader available - using default Qt style"; - return false; + qWarning() << "StyleManager::loadStyle: No Style Plugin loader available - using default Qt style"; + return false; } - StylePlugin::Plugin* sp = qobject_cast(stylePluginLoader->instance()); + StylePlugin::Plugin *sp = qobject_cast(stylePluginLoader->instance()); if (sp == nullptr) { - qWarning() << "StyleManager::loadStyle: could not load style plugin - wrong type (" - << stylePluginLoader->instance()->metaObject()->className() << ") - new style not loaded"; - return false; + qWarning() << "StyleManager::loadStyle: could not load style plugin - wrong type (" << stylePluginLoader->instance()->metaObject()->className() + << ") - new style not loaded"; + return false; } sp->loadStyle(highDpi); @@ -95,6 +92,6 @@ bool StyleManager::loadStyle(const QString& stylePluginName, bool highDpi) emit signalStyleChanged(stylePluginName); return true; -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h index 20e34f67f..17a0f28ea 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h @@ -10,29 +10,26 @@ class QPluginLoader; namespace LtsUtils { -class LTSUTILSGUISTYLEMANAGER_EXPORT StyleManager : public QObject -{ + class LTSUTILSGUISTYLEMANAGER_EXPORT StyleManager : public QObject + { Q_OBJECT using QObject::QObject; ~StyleManager() = default; public: - static StyleManager* getInstance(); + static StyleManager *getInstance(); - bool loadStyle(const QString& stylePluginName, bool highDpi = false); + bool loadStyle(const QString &stylePluginName, bool highDpi = false); - const QString& currentStyleName() const - { - return m_stylePluginName; - } + const QString ¤tStyleName() const { return m_stylePluginName; } private: friend struct StyleManagerHandler; - QPluginLoader* m_currentStylePluginLoader = nullptr; + QPluginLoader *m_currentStylePluginLoader = nullptr; QString m_stylePluginName; signals: - void signalStyleChanged(const QString& stylePluginName); -}; + void signalStyleChanged(const QString &stylePluginName); + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp index 62e4d6829..dd3366240 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp @@ -16,233 +16,234 @@ namespace LtsUtils { -enum class SettingType { + enum class SettingType + { String = 1, StringList = 2, Json = 3, FunctionKeys = 4, Boolean = 5, -}; + }; -QString typeToString(SettingType t) -{ + QString typeToString(SettingType t) + { switch (t) { - case SettingType::String: - return QStringLiteral("String"); - case SettingType::StringList: - return QStringLiteral("StringList"); - case SettingType::Json: - return QStringLiteral("Json"); - case SettingType::FunctionKeys: - return QStringLiteral("FunctionKeys"); - case SettingType::Boolean: - return QStringLiteral("Boolean"); + case SettingType::String: + return QStringLiteral("String"); + case SettingType::StringList: + return QStringLiteral("StringList"); + case SettingType::Json: + return QStringLiteral("Json"); + case SettingType::FunctionKeys: + return QStringLiteral("FunctionKeys"); + case SettingType::Boolean: + return QStringLiteral("Boolean"); } Q_ASSERT(false); return QStringLiteral("Unknown SettingType (%1)").arg(int(t)); -} + } -SettingType stringToType(const QString& s) -{ + SettingType stringToType(const QString &s) + { if (s == typeToString(SettingType::String)) - return SettingType::String; + return SettingType::String; if (s == typeToString(SettingType::StringList)) - return SettingType::StringList; + return SettingType::StringList; if (s == typeToString(SettingType::Json)) - return SettingType::Json; + return SettingType::Json; if (s == typeToString(SettingType::FunctionKeys)) - return SettingType::FunctionKeys; + return SettingType::FunctionKeys; if (s == typeToString(SettingType::Boolean)) - return SettingType::Boolean; + return SettingType::Boolean; Q_ASSERT(false); return SettingType::String; -} + } -static QString craftKey(const QString& group, const QString& identifier) -{ + static QString craftKey(const QString &group, const QString &identifier) + { return group + QLatin1Char('.') + identifier; -} + } -static OperatorSettings* s_operatorSettings = nullptr; + static OperatorSettings *s_operatorSettings = nullptr; -static void cleanupOperatorSettings() -{ + static void cleanupOperatorSettings() + { delete s_operatorSettings; s_operatorSettings = nullptr; -} + } -OperatorSettings* OperatorSettings::getInstance() -{ + OperatorSettings *OperatorSettings::getInstance() + { if (!s_operatorSettings) { - s_operatorSettings = new OperatorSettings; - qAddPostRoutine(&cleanupOperatorSettings); + s_operatorSettings = new OperatorSettings; + qAddPostRoutine(&cleanupOperatorSettings); } return s_operatorSettings; -} + } -static ProjectSettings* s_projectSettings = nullptr; + static ProjectSettings *s_projectSettings = nullptr; -static void cleanupProjectSettings() -{ + static void cleanupProjectSettings() + { delete s_projectSettings; s_projectSettings = nullptr; -} + } -ProjectSettings* ProjectSettings::getInstance() -{ + ProjectSettings *ProjectSettings::getInstance() + { if (!s_projectSettings) { - s_projectSettings = new ProjectSettings; - qAddPostRoutine(&cleanupProjectSettings); + s_projectSettings = new ProjectSettings; + qAddPostRoutine(&cleanupProjectSettings); } return s_projectSettings; -} + } -bool ProjectSettings::initFromFile(const QString& filename) -{ + bool ProjectSettings::initFromFile(const QString &filename) + { QFile f(filename); if (!f.open(QIODevice::ReadOnly)) - return false; + return false; QJsonParseError jErr; const QJsonObject settings = QJsonDocument::fromJson(f.readAll(), &jErr).object(); if (jErr.error != QJsonParseError::NoError) - return false; + return false; const QJsonObject psObj = settings[QStringLiteral("ProjectSettings")].toObject(); if (psObj.isEmpty()) - return false; + return false; QHash newData; - const QStringList& groupKeys(psObj.keys()); - for (const auto& gKey : groupKeys) + const QStringList &groupKeys(psObj.keys()); + for (const auto &gKey : groupKeys) { - const QJsonObject objGroup(psObj[gKey].toObject()); - const QStringList& itemKeys(objGroup.keys()); - for (const auto& key : itemKeys) + const QJsonObject objGroup(psObj[gKey].toObject()); + const QStringList &itemKeys(objGroup.keys()); + for (const auto &key : itemKeys) + { + const QJsonObject obj(objGroup[key].toObject()); + const auto strType(obj[QStringLiteral("Type")].toString()); + const auto type = stringToType(strType); + const QJsonValue jVal(obj[QStringLiteral("Default")]); + QVariant val; + switch (type) { - const QJsonObject obj(objGroup[key].toObject()); - const auto strType(obj[QStringLiteral("Type")].toString()); - const auto type = stringToType(strType); - const QJsonValue jVal(obj[QStringLiteral("Default")]); - QVariant val; - switch (type) - { - case SettingType::Json: - val = QJsonDocument(jVal.toObject()).toJson(); - break; - case SettingType::StringList: { - const QJsonArray arr(jVal.toArray()); - QStringList sl; - sl.reserve(arr.size()); - for (const auto& ele : arr) - sl.push_back(ele.toString()); - val = sl; - break; - } - case SettingType::FunctionKeys: - val = jVal.toVariant(); - break; - case SettingType::String: - val = jVal.toString(); - break; - case SettingType::Boolean: - val = jVal.toBool(); - break; - } - newData[craftKey(gKey, key)] = val; + case SettingType::Json: + val = QJsonDocument(jVal.toObject()).toJson(); + break; + case SettingType::StringList: + { + const QJsonArray arr(jVal.toArray()); + QStringList sl; + sl.reserve(arr.size()); + for (const auto &ele : arr) + sl.push_back(ele.toString()); + val = sl; + break; + } + case SettingType::FunctionKeys: + val = jVal.toVariant(); + break; + case SettingType::String: + val = jVal.toString(); + break; + case SettingType::Boolean: + val = jVal.toBool(); + break; } + newData[craftKey(gKey, key)] = val; + } } getInstance()->m_data = newData; return true; -} + } -bool ProjectSettings::isFunctionEnabled(const QString& group, const QString& function) -{ - const QStringList functionNames = - getInstance()->value(QStringLiteral("Functionalities"), QStringLiteral("IdentifierList")).toStringList(); + bool ProjectSettings::isFunctionEnabled(const QString &group, const QString &function) + { + const QStringList functionNames = getInstance()->value(QStringLiteral("Functionalities"), QStringLiteral("IdentifierList")).toStringList(); return functionNames.contains(group + QLatin1Char(':') + function); -} + } -void Settings::init(const QByteArray& settings) -{ + void Settings::init(const QByteArray &settings) + { QByteArray uncompressed; try { - uncompressed = qUncompress(settings); + uncompressed = qUncompress(settings); } catch (...) { } if (uncompressed.isEmpty()) - uncompressed = settings; + uncompressed = settings; QDataStream stream(uncompressed); stream >> m_data; -} + } -QByteArray Settings::exportSettings() const -{ + QByteArray Settings::exportSettings() const + { if (m_data.isEmpty()) - return QByteArray(); + return QByteArray(); QByteArray ba; QDataStream stream(&ba, QIODevice::WriteOnly); stream << m_data; return qCompress(ba); -} + } -void Settings::clear() -{ + void Settings::clear() + { m_data.clear(); -} + } -void Settings::dump() -{ + void Settings::dump() + { qWarning() << "Settings::m_data: keys=" << m_data.keys(); QHashIterator it(m_data); int i = 0; while (it.hasNext()) { - it.next(); - qWarning() << i++ << ":" - << " - key='" << it.key() << "' value -> '" << it.value() << "'"; + it.next(); + qWarning() << i++ << ":" + << " - key='" << it.key() << "' value -> '" << it.value() << "'"; } qWarning() << "Settings::m_data: ------------------"; -} + } -void Settings::setValue(const QString& group, const QString& identifier, const QVariant& value) -{ + void Settings::setValue(const QString &group, const QString &identifier, const QVariant &value) + { m_data.insert(craftKey(group, identifier), value); emit valueChanged(group, identifier, value); -} + } -void Settings::removeValue(const QString& group, const QString& identifier) -{ + void Settings::removeValue(const QString &group, const QString &identifier) + { if (m_data.remove(craftKey(group, identifier))) - emit valueRemoved(group, identifier); -} + emit valueRemoved(group, identifier); + } -QStringList Settings::identifiers(const QString& group) const -{ + QStringList Settings::identifiers(const QString &group) const + { QStringList result; for (auto it = m_data.begin(); it != m_data.end(); ++it) { - const QStringList decrafted = QString(it.key()).split(QLatin1Char('.')); - if (decrafted.size() > 1 && QStringView(group).compare(decrafted.at(0)) == 0) - result.append(decrafted.at(0).mid(1)); + const QStringList decrafted = QString(it.key()).split(QLatin1Char('.')); + if (decrafted.size() > 1 && QStringView(group).compare(decrafted.at(0)) == 0) + result.append(decrafted.at(0).mid(1)); } return result; -} + } -QVariant Settings::value(const QString& group, const QString& identifier, const QVariant& defaultValue) const -{ + QVariant Settings::value(const QString &group, const QString &identifier, const QVariant &defaultValue) const + { return m_data.value(craftKey(group, identifier), defaultValue); -} + } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h index d52cad490..45d15e203 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h @@ -12,22 +12,22 @@ class QJsonObject; namespace LtsUtils { -class LTSUTILSSETTINGS_EXPORT Settings : public QObject -{ + class LTSUTILSSETTINGS_EXPORT Settings : public QObject + { Q_OBJECT public: ~Settings() = default; - void setValue(const QString& group, const QString& identifier, const QVariant& value); + void setValue(const QString &group, const QString &identifier, const QVariant &value); - void removeValue(const QString& group, const QString& identifier); + void removeValue(const QString &group, const QString &identifier); - QVariant value(const QString& group, const QString& identifier, const QVariant& defaultValue = QVariant()) const; + QVariant value(const QString &group, const QString &identifier, const QVariant &defaultValue = QVariant()) const; - QStringList identifiers(const QString& group) const; + QStringList identifiers(const QString &group) const; - void init(const QByteArray& settings); + void init(const QByteArray &settings); QByteArray exportSettings() const; void clear(); @@ -37,28 +37,28 @@ class LTSUTILSSETTINGS_EXPORT Settings : public QObject Settings() = default; signals: - void valueChanged(const QString& group, const QString& identifier, const QVariant& value); - void valueRemoved(const QString& group, const QString& identifier); + void valueChanged(const QString &group, const QString &identifier, const QVariant &value); + void valueRemoved(const QString &group, const QString &identifier); protected: QHash m_data; -}; + }; -class LTSUTILSSETTINGS_EXPORT OperatorSettings : public Settings -{ + class LTSUTILSSETTINGS_EXPORT OperatorSettings : public Settings + { Q_OBJECT public: - static OperatorSettings* getInstance(); -}; + static OperatorSettings *getInstance(); + }; -class LTSUTILSSETTINGS_EXPORT ProjectSettings : public Settings -{ + class LTSUTILSSETTINGS_EXPORT ProjectSettings : public Settings + { Q_OBJECT public: - static ProjectSettings* getInstance(); + static ProjectSettings *getInstance(); - static bool initFromFile(const QString& filename); - static bool isFunctionEnabled(const QString& group, const QString& function); -}; + static bool initFromFile(const QString &filename); + static bool isFunctionEnabled(const QString &group, const QString &function); + }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp index a01cec859..edfeabf8c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp @@ -10,80 +10,80 @@ namespace LtsWebSocket { -ClientConnection::ClientConnection(QWebSocket* socket, QObject* parent) - : QThread(parent), m_logger(getLogger("LtsWebSocket.ClientConnection")), m_socket(socket ? socket : new QWebSocket) -{ -} + ClientConnection::ClientConnection(QWebSocket *socket, QObject *parent) + : QThread(parent) + , m_logger(getLogger("LtsWebSocket.ClientConnection")) + , m_socket(socket ? socket : new QWebSocket) + { + } -ClientConnection::~ClientConnection() -{ + ClientConnection::~ClientConnection() + { DEBUG_LOG(m_logger) << "Thread closed" << this; delete m_socket; qDeleteAll(m_messageQueue); -} + } #ifdef QT6_WEBSOCKETS_AVAILABLE -bool ClientConnection::init() -{ + bool ClientConnection::init() + { if (m_socket == nullptr) { - ERROR_LOG(m_logger) << "Initialisation failed due to an invalid socket"; - return false; + ERROR_LOG(m_logger) << "Initialisation failed due to an invalid socket"; + return false; } DEBUG_LOG(m_logger) << "Started new thread" << this; - connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, - Qt::DirectConnection); + connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, Qt::DirectConnection); connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue); connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect); return true; -} + } -void ClientConnection::addReply(ReplyMessage* message) -{ + void ClientConnection::addReply(ReplyMessage *message) + { if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) { - m_messageQueue.enqueue(message); - DEBUG_LOG(m_logger) << "Adding message to queue, size: " << m_messageQueue.size(); - return; + m_messageQueue.enqueue(message); + DEBUG_LOG(m_logger) << "Adding message to queue, size: " << m_messageQueue.size(); + return; } const QString msg(message->toJsonString()); DEBUG_LOG(m_logger) << "Sending message: " << msg; m_socket->sendTextMessage(msg); delete message; -} + } -void ClientConnection::onNewTextMessageFromSocket(const QString& message) -{ + void ClientConnection::onNewTextMessageFromSocket(const QString &message) + { DEBUG_LOG(m_logger) << "Recv msg: " << message << this; emit newTextMessage(this, message); -} + } -void ClientConnection::sendMessagesFromQueue() -{ + void ClientConnection::sendMessagesFromQueue() + { INFO_LOG(m_logger) << "Client connected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); if (m_socket->state() != QAbstractSocket::ConnectedState) - return; + return; while (!m_messageQueue.isEmpty()) { - ReplyMessage* message = m_messageQueue.dequeue(); - const QString msg(message->toJsonString()); - TRACE_LOG(m_logger) << "Send msg: " << msg; - m_socket->sendTextMessage(msg); - delete message; - DEBUG_LOG(m_logger) << "Sent message from queue, new size: " << m_messageQueue.size(); + ReplyMessage *message = m_messageQueue.dequeue(); + const QString msg(message->toJsonString()); + TRACE_LOG(m_logger) << "Send msg: " << msg; + m_socket->sendTextMessage(msg); + delete message; + DEBUG_LOG(m_logger) << "Sent message from queue, new size: " << m_messageQueue.size(); } -} + } -void ClientConnection::onSocketDisconnect() -{ - DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" - << m_socket->peerPort(); + void ClientConnection::onSocketDisconnect() + { + DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); exit(0); emit disconnected(this); -} + } #endif } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h index ccba1273e..cbb3a0dce 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h @@ -12,68 +12,70 @@ #ifdef QT6_WEBSOCKETS_AVAILABLE class QWebSocket; #else -namespace LtsWebSocket { class QWebSocketStub; } +namespace LtsWebSocket +{ + class QWebSocketStub; +} using QWebSocket = LtsWebSocket::QWebSocketStub; namespace LtsWebSocket { -class QWebSocketStub -{ + class QWebSocketStub + { public: - QWebSocketStub(QObject* parent = nullptr) { Q_UNUSED(parent); } + QWebSocketStub(QObject *parent = nullptr) { Q_UNUSED(parent); } virtual ~QWebSocketStub() = default; - void sendTextMessage(const QString& /*message*/) {} + void sendTextMessage(const QString & /*message*/) {} void close() {} bool isValid() const { return false; } QString errorString() const { return QString(); } -}; + }; } // namespace LtsWebSocket #endif namespace LtsWebSocket { -class LTSWEBSOCKETSERVER_EXPORT ClientConnection : public QThread, public ReplyHandler -{ + class LTSWEBSOCKETSERVER_EXPORT ClientConnection + : public QThread + , public ReplyHandler + { Q_OBJECT public: - explicit ClientConnection(QWebSocket* socket, QObject* parent = nullptr); + explicit ClientConnection(QWebSocket *socket, QObject *parent = nullptr); ~ClientConnection(); #ifdef QT6_WEBSOCKETS_AVAILABLE bool init(); - void addReply(ReplyMessage* message) override; + void addReply(ReplyMessage *message) override; - QWebSocket* webSocket() - { - return m_socket; - } + QWebSocket *webSocket() { return m_socket; } #else bool init() { return false; } - void addReply(ReplyMessage* /*message*/) override {} - QWebSocket* webSocket() { return nullptr; } + void addReply(ReplyMessage * /*message*/) override {} + QWebSocket *webSocket() { return nullptr; } #endif signals: - void newTextMessage(ClientConnection* client, const QString& message); + void newTextMessage(ClientConnection *client, const QString &message); - void disconnected(ClientConnection* client); + void disconnected(ClientConnection *client); private slots: #ifdef QT6_WEBSOCKETS_AVAILABLE - void onNewTextMessageFromSocket(const QString& message); + void onNewTextMessageFromSocket(const QString &message); void sendMessagesFromQueue(); void onSocketDisconnect(); #endif private: - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; #ifdef QT6_WEBSOCKETS_AVAILABLE void sendMessages(); #endif - QWebSocket* m_socket; - QQueue m_messageQueue; -}; + QWebSocket *m_socket; + QQueue m_messageQueue; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp index 993af8a2b..e11557acd 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp @@ -9,13 +9,14 @@ namespace LtsWebSocket { -InvalidMessage::InvalidMessage(ReplyHandler* client, const QString& uuid, const QString& errorText) - : AbstractClientMessage(client, QString(), 1, uuid), m_errorText(errorText) -{ -} + InvalidMessage::InvalidMessage(ReplyHandler *client, const QString &uuid, const QString &errorText) + : AbstractClientMessage(client, QString(), 1, uuid) + , m_errorText(errorText) + { + } -void InvalidMessage::process() -{ + void InvalidMessage::process() + { ErrorMessage::ErrorData errorData; errorData.errorClass = 1; @@ -23,12 +24,12 @@ void InvalidMessage::process() errorData.uuid = m_uuid; m_client->addReply(new ErrorMessage(errorData)); -} + } -bool InvalidMessage::hasValidData() const -{ + bool InvalidMessage::hasValidData() const + { return true; -} + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h index fb73396ed..47dc94f98 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h @@ -11,12 +11,15 @@ namespace LtsWebSocket { -class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessage -{ + class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessage + { public: - AbstractClientMessage(ReplyHandler* client, const QString& type, const int typeId, const QString& uuid, - const QJsonValue& data = QJsonValue()) - : m_type(type), m_typeId(typeId), m_uuid(uuid), m_data(data), m_client(client) + AbstractClientMessage(ReplyHandler *client, const QString &type, const int typeId, const QString &uuid, const QJsonValue &data = QJsonValue()) + : m_type(type) + , m_typeId(typeId) + , m_uuid(uuid) + , m_data(data) + , m_client(client) { } @@ -26,29 +29,26 @@ class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessage virtual bool hasValidData() const = 0; - void reply(ReplyMessage* reply) - { - m_client->addReply(reply); - } + void reply(ReplyMessage *reply) { m_client->addReply(reply); } protected: const QString m_type; const int m_typeId; const QString m_uuid; const QJsonValue m_data; - ReplyHandler* m_client; -}; + ReplyHandler *m_client; + }; -class LTSWEBSOCKETCOMMON_EXPORT InvalidMessage final : public AbstractClientMessage -{ + class LTSWEBSOCKETCOMMON_EXPORT InvalidMessage final : public AbstractClientMessage + { public: - explicit InvalidMessage(ReplyHandler* client, const QString& uuid, const QString& errorText); + explicit InvalidMessage(ReplyHandler *client, const QString &uuid, const QString &errorText); void process() override; bool hasValidData() const override; private: QString m_errorText; -}; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp index e6aecf65d..269023415 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp @@ -10,13 +10,13 @@ namespace LtsWebSocket { -QJsonParseError AbstractClientMessageFactory::parseMessage(const QString& message) -{ + QJsonParseError AbstractClientMessageFactory::parseMessage(const QString &message) + { QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error); if (error.error != QJsonParseError::NoError) - return error; + return error; QJsonObject obj = doc.object(); @@ -26,38 +26,37 @@ QJsonParseError AbstractClientMessageFactory::parseMessage(const QString& messag m_uuid = obj.value(JsonKeys::UUID_()).toString(); return error; -} + } -AbstractClientMessage* AbstractClientMessageFactory::checkAttributes(ReplyHandler* client, const QString& message) const -{ + AbstractClientMessage *AbstractClientMessageFactory::checkAttributes(ReplyHandler *client, const QString &message) const + { if (!m_uuid.isEmpty() && !m_type.isEmpty()) - return nullptr; + return nullptr; if (m_uuid.isEmpty()) { - WARNING_LOG(m_logger) << "Got message without uuid: " << message << "'"; - return new LtsWebSocket::InvalidMessage(client, QString(), QStringLiteral("Got message without uuid")); + WARNING_LOG(m_logger) << "Got message without uuid: " << message << "'"; + return new LtsWebSocket::InvalidMessage(client, QString(), QStringLiteral("Got message without uuid")); } WARNING_LOG(m_logger) << "Got message no type: " << message << "'"; return new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Message has no type")); -} + } -AbstractClientMessage* AbstractClientMessageFactory::checkResult(ReplyHandler* client, const QString& message, - AbstractClientMessage* result) const -{ + AbstractClientMessage *AbstractClientMessageFactory::checkResult(ReplyHandler *client, const QString &message, AbstractClientMessage *result) const + { if (result == nullptr) { - WARNING_LOG(m_logger) << "Could not parse message: " << message; - result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Invalid type")); + WARNING_LOG(m_logger) << "Could not parse message: " << message; + result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Invalid type")); } if (!result->hasValidData()) { - WARNING_LOG(m_logger) << "Resulting JSon message has invalid data... " << message; - delete result; - result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Has invalid data part")); + WARNING_LOG(m_logger) << "Resulting JSon message has invalid data... " << message; + delete result; + result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Has invalid data part")); } return result; -} + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h index a843e5964..35cfcde04 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h @@ -11,58 +11,55 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } namespace LtsWebSocket { -class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory -{ + class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory + { public: - explicit AbstractClientMessageFactory(NGL::INGLLogger& logger) : m_logger(logger) {} + explicit AbstractClientMessageFactory(NGL::INGLLogger &logger) + : m_logger(logger) + { + } virtual ~AbstractClientMessageFactory() {} - QJsonParseError parseMessage(const QString& message); + QJsonParseError parseMessage(const QString &message); - virtual AbstractClientMessage* createMessage(ReplyHandler* client, const QString& message) = 0; + virtual AbstractClientMessage *createMessage(ReplyHandler *client, const QString &message) = 0; protected: - AbstractClientMessage* checkAttributes(ReplyHandler* client, const QString& message) const; - AbstractClientMessage* checkResult(ReplyHandler* client, const QString& message, - AbstractClientMessage* result) const; + AbstractClientMessage *checkAttributes(ReplyHandler *client, const QString &message) const; + AbstractClientMessage *checkResult(ReplyHandler *client, const QString &message, AbstractClientMessage *result) const; protected: - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; QString m_type; int m_typeId; QString m_uuid; QJsonValue m_data; -}; + }; -class PongMessage final : public ReplyMessage -{ + class PongMessage final : public ReplyMessage + { public: - static QString strPong() + static QString strPong() { return QStringLiteral("pong"); } + + static int idPong() { return 2; } + + explicit PongMessage(const QString &payload) + : ReplyMessage(strPong(), idPong(), QString()) + , m_payload(payload) { - return QStringLiteral("pong"); } - static int idPong() - { - return 2; - } - - explicit PongMessage(const QString& payload) : ReplyMessage(strPong(), idPong(), QString()), m_payload(payload) {} - - QString toJsonString() const override - { - return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload); - } + QString toJsonString() const override { return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload); } private: QString m_payload; -}; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp index c94a9bd1d..575065a76 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp @@ -12,84 +12,84 @@ using namespace LtsWebSocket; -ConnectionHandler::ConnectionHandler(QObject* parent) - : QObject(parent), m_logger(getLogger("LtsWebSocket.ConnectionHandler")), m_server(nullptr) +ConnectionHandler::ConnectionHandler(QObject *parent) + : QObject(parent) + , m_logger(getLogger("LtsWebSocket.ConnectionHandler")) + , m_server(nullptr) { } ConnectionHandler::~ConnectionHandler() { #ifdef QT6_WEBSOCKETS_AVAILABLE - for (auto connection : std::as_const(m_connections)) - connection->disconnect(this); + for (auto connection : std::as_const(m_connections)) + connection->disconnect(this); #endif } #ifdef QT6_WEBSOCKETS_AVAILABLE -bool ConnectionHandler::init(const QString& serviceName, unsigned short port) +bool ConnectionHandler::init(const QString &serviceName, unsigned short port) { - if (m_server != nullptr) - { - m_server->disconnect(); - delete m_server; - } + if (m_server != nullptr) + { + m_server->disconnect(); + delete m_server; + } - m_server = new QWebSocketServer(QStringLiteral("RME-") + serviceName, QWebSocketServer::NonSecureMode, this); + m_server = new QWebSocketServer(QStringLiteral("RME-") + serviceName, QWebSocketServer::NonSecureMode, this); - connect(m_server, &QWebSocketServer::newConnection, this, &ConnectionHandler::onNewConnection); - connect(m_server, &QWebSocketServer::serverError, this, &ConnectionHandler::onServerError); + connect(m_server, &QWebSocketServer::newConnection, this, &ConnectionHandler::onNewConnection); + connect(m_server, &QWebSocketServer::serverError, this, &ConnectionHandler::onServerError); - DEBUG_LOG(m_logger) << "Trying to listen "; - if (!m_server->listen(QHostAddress::Any, port)) - { - ERROR_LOG(m_logger) << "Not possible to listen to port " << port; - return false; - } - DEBUG_LOG(m_logger) << "... ok, port " << m_server->serverPort(); + DEBUG_LOG(m_logger) << "Trying to listen "; + if (!m_server->listen(QHostAddress::Any, port)) + { + ERROR_LOG(m_logger) << "Not possible to listen to port " << port; + return false; + } + DEBUG_LOG(m_logger) << "... ok, port " << m_server->serverPort(); - return true; + return true; } -void ConnectionHandler::sendToAllClients(ReplyMessage* message) +void ConnectionHandler::sendToAllClients(ReplyMessage *message) { - for (auto connection : std::as_const(m_connections)) - connection->addReply(new ReplyMessage(*message)); + for (auto connection : std::as_const(m_connections)) + connection->addReply(new ReplyMessage(*message)); - delete message; + delete message; } void ConnectionHandler::onServerError(QWebSocketProtocol::CloseCode closeCode) { - ERROR_LOG(m_logger) << "Got server error with close code " << closeCode; + ERROR_LOG(m_logger) << "Got server error with close code " << closeCode; } void ConnectionHandler::onNewConnection() { - while (m_server->hasPendingConnections()) + while (m_server->hasPendingConnections()) + { + QWebSocket *socket = m_server->nextPendingConnection(); + + ClientConnection *newConnection = new ClientConnection(socket, this); + connect(newConnection, &ClientConnection::destroyed, this, [this](QObject *o) { m_connections.remove(static_cast(o)); }); + + if (!newConnection->init()) { - QWebSocket* socket = m_server->nextPendingConnection(); - - ClientConnection* newConnection = new ClientConnection(socket, this); - connect(newConnection, &ClientConnection::destroyed, this, - [this](QObject* o) { m_connections.remove(static_cast(o)); }); - - if (!newConnection->init()) - { - ERROR_LOG(m_logger) << "Failed to initialise new client"; - delete newConnection; - newConnection = nullptr; - continue; - } - newConnection->start(); - - connect(newConnection, &ClientConnection::newTextMessage, this, &ConnectionHandler::newTextMessageFromClient); - connect(newConnection, &ClientConnection::disconnected, this, &ConnectionHandler::clientDisconnected); - connect(newConnection, &ClientConnection::finished, newConnection, &ClientConnection::deleteLater); - - m_connections.insert(newConnection); - emit clientConnected(newConnection); - INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" - << socket->localPort(); + ERROR_LOG(m_logger) << "Failed to initialise new client"; + delete newConnection; + newConnection = nullptr; + continue; } + newConnection->start(); + + connect(newConnection, &ClientConnection::newTextMessage, this, &ConnectionHandler::newTextMessageFromClient); + connect(newConnection, &ClientConnection::disconnected, this, &ConnectionHandler::clientDisconnected); + connect(newConnection, &ClientConnection::finished, newConnection, &ClientConnection::deleteLater); + + m_connections.insert(newConnection); + emit clientConnected(newConnection); + INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" << socket->localPort(); + } } #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h index 3181fcb6f..9156edecc 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h @@ -11,46 +11,52 @@ #include #include #else -namespace LtsWebSocket { class QWebSocketServerStub; } +namespace LtsWebSocket +{ + class QWebSocketServerStub; +} using QWebSocketServer = LtsWebSocket::QWebSocketServerStub; -namespace QWebSocketProtocol { enum class CloseCode { NormalClosure = 1000 }; } +namespace QWebSocketProtocol +{ + enum class CloseCode + { + NormalClosure = 1000 + }; +} #endif namespace LtsWebSocket { -class MessageHandler; -class ClientConnection; -class ReplyMessage; + class MessageHandler; + class ClientConnection; + class ReplyMessage; -class ConnectionHandler : public QObject -{ + class ConnectionHandler : public QObject + { Q_OBJECT public: - explicit ConnectionHandler(QObject* parent = nullptr); + explicit ConnectionHandler(QObject *parent = nullptr); ~ConnectionHandler(); #ifdef QT6_WEBSOCKETS_AVAILABLE - bool init(const QString& serviceName, unsigned short port); + bool init(const QString &serviceName, unsigned short port); - void sendToAllClients(ReplyMessage* message); + void sendToAllClients(ReplyMessage *message); - unsigned short webSocketPort() - { - return m_server->serverPort(); - } + unsigned short webSocketPort() { return m_server->serverPort(); } #else - bool init(const QString& /*serviceName*/, unsigned short /*port*/) { return false; } - void sendToAllClients(ReplyMessage* /*message*/) {} + bool init(const QString & /*serviceName*/, unsigned short /*port*/) { return false; } + void sendToAllClients(ReplyMessage * /*message*/) {} unsigned short webSocketPort() { return 0; } #endif signals: - void newTextMessageFromClient(ClientConnection* client, const QString& message); + void newTextMessageFromClient(ClientConnection *client, const QString &message); - void clientDisconnected(ClientConnection* client); + void clientDisconnected(ClientConnection *client); - void clientConnected(ClientConnection* client); + void clientConnected(ClientConnection *client); private slots: #ifdef QT6_WEBSOCKETS_AVAILABLE @@ -59,12 +65,12 @@ class ConnectionHandler : public QObject #endif private: - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; #ifdef QT6_WEBSOCKETS_AVAILABLE - QWebSocketServer* m_server; + QWebSocketServer *m_server; #else - void* m_server; + void *m_server; #endif - QSet m_connections; -}; + QSet m_connections; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h index 18318dd10..e03acb561 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h @@ -9,33 +9,34 @@ namespace LtsWebSocket { -template class DataManagerBaseDl -{ + template class DataManagerBaseDl + { protected: - explicit DataManagerBaseDl(const std::shared_ptr& dbInterface, NGL::INGLLogger& logger) - : m_logger(logger), m_dbInterface(dbInterface) + explicit DataManagerBaseDl(const std::shared_ptr &dbInterface, NGL::INGLLogger &logger) + : m_logger(logger) + , m_dbInterface(dbInterface) { } - template ReplyMessage* toBaseDataMessageFromDb(const QString& uuid) const + template ReplyMessage *toBaseDataMessageFromDb(const QString &uuid) const { - QVector dataVec; + QVector dataVec; - if (!m_dbInterface->select(dataVec)) - { - const QString errorMessage = QStringLiteral("Error reading data from database!"); - ERROR_LOG(m_logger) << errorMessage; - ErrorMessage::ErrorData errData; - errData.errorMessage = errorMessage; - errData.uuid = uuid; - return new ErrorMessage(errData); - } + if (!m_dbInterface->select(dataVec)) + { + const QString errorMessage = QStringLiteral("Error reading data from database!"); + ERROR_LOG(m_logger) << errorMessage; + ErrorMessage::ErrorData errData; + errData.errorMessage = errorMessage; + errData.uuid = uuid; + return new ErrorMessage(errData); + } - return new MessageType(m_dbInterface->template toJson(dataVec), uuid); + return new MessageType(m_dbInterface->template toJson(dataVec), uuid); } protected: NGL::INGLLogger &m_logger; std::shared_ptr m_dbInterface; -}; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h index 2aa992813..02ce30271 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h @@ -7,42 +7,42 @@ namespace LtsWebSocket { -namespace JsonKeys -{ + namespace JsonKeys + { -inline QString DATA() -{ - return QStringLiteral("data"); -} + inline QString DATA() + { + return QStringLiteral("data"); + } -inline QString UUID_() -{ - return QStringLiteral("uuid"); -} + inline QString UUID_() + { + return QStringLiteral("uuid"); + } -inline QString TYPE() -{ - return QStringLiteral("type"); -} + inline QString TYPE() + { + return QStringLiteral("type"); + } -inline QString TYPEID() -{ - return QStringLiteral("typeId"); -} + inline QString TYPEID() + { + return QStringLiteral("typeId"); + } -inline QString ERROR_() -{ - return QStringLiteral("error"); -} + inline QString ERROR_() + { + return QStringLiteral("error"); + } -inline QString ERROR_MESSAGE() -{ - return QStringLiteral("errorMessage"); -} + inline QString ERROR_MESSAGE() + { + return QStringLiteral("errorMessage"); + } -inline QString ERROR_CLASS() -{ - return QStringLiteral("errorClass"); -} -} // namespace JsonKeys + inline QString ERROR_CLASS() + { + return QStringLiteral("errorClass"); + } + } // namespace JsonKeys } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp index a90b01bbf..e9e585866 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp @@ -7,8 +7,8 @@ namespace LtsWebSocket { -LOGGER_T getLogger(const char* name) -{ + LOGGER_T getLogger(const char *name) + { static const char ns[] = "Lts.WebSocket."; std::string loggerName; const size_t len = strlen(name); @@ -18,13 +18,13 @@ LOGGER_T getLogger(const char* name) try { - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); } - catch (const std::exception& ex) + catch (const std::exception &ex) { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); } -} + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h index 11afe3543..3c53f2064 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h @@ -8,12 +8,12 @@ namespace LtsWebSocket { -typedef NGL::INGLLogger& LOGGER_T; + typedef NGL::INGLLogger &LOGGER_T; -LTSWEBSOCKETCOMMON_EXPORT LOGGER_T getLogger(const char* name); + LTSWEBSOCKETCOMMON_EXPORT LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString& loggerName) -{ + inline LOGGER_T getLogger(const QString &loggerName) + { return getLogger(loggerName.toUtf8().constData()); -} + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp index bc70d3950..0f9cbdf8d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp @@ -10,138 +10,137 @@ namespace LtsWebSocket { -class WebSocketHelper : public QObject -{ + class WebSocketHelper : public QObject + { Q_OBJECT public: - WebSocketHelper(AbstractClientMessageFactory* messageFactory, LtsWebSocketClient* webSocketClient, - NGL::INGLLogger& logger); + WebSocketHelper(AbstractClientMessageFactory *messageFactory, LtsWebSocketClient *webSocketClient, NGL::INGLLogger &logger); ~WebSocketHelper(); public Q_SLOTS: - void doOpen(const QString& hostname, const unsigned short port); + void doOpen(const QString &hostname, const unsigned short port); void doClose(); - void doSendTextMessage(const QString& msg); + void doSendTextMessage(const QString &msg); void onConnected(); void onDisconnected(); void onError(QAbstractSocket::SocketError error); - void parseMessage(const QString& message); + void parseMessage(const QString &message); Q_SIGNALS: - void messageParsed(AbstractClientMessage* clientMessage); + void messageParsed(AbstractClientMessage *clientMessage); void connected(); void disconnected(); void dataReceived(); void error(QAbstractSocket::SocketError); private: - AbstractClientMessageFactory* m_messageFactory; - LtsWebSocketClient* m_webSocketClient; - QWebSocket* m_socket; - NGL::INGLLogger& m_logger; -}; + AbstractClientMessageFactory *m_messageFactory; + LtsWebSocketClient *m_webSocketClient; + QWebSocket *m_socket; + NGL::INGLLogger &m_logger; + }; -WebSocketHelper::WebSocketHelper(AbstractClientMessageFactory* messageFactory, LtsWebSocketClient* webSocketClient, - NGL::INGLLogger& logger) - : QObject(), m_messageFactory(messageFactory), m_webSocketClient(webSocketClient), - m_socket(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)), m_logger(logger) -{ + WebSocketHelper::WebSocketHelper(AbstractClientMessageFactory *messageFactory, LtsWebSocketClient *webSocketClient, NGL::INGLLogger &logger) + : QObject() + , m_messageFactory(messageFactory) + , m_webSocketClient(webSocketClient) + , m_socket(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)) + , m_logger(logger) + { connect(m_socket, &QWebSocket::textMessageReceived, this, &WebSocketHelper::parseMessage); connect(m_socket, &QWebSocket::textFrameReceived, this, &WebSocketHelper::dataReceived); connect(m_socket, &QWebSocket::connected, this, &WebSocketHelper::onConnected); connect(m_socket, &QWebSocket::disconnected, this, &WebSocketHelper::onDisconnected); connect(m_socket, &QWebSocket::errorOccurred, this, &WebSocketHelper::error); -} + } -WebSocketHelper::~WebSocketHelper() -{ + WebSocketHelper::~WebSocketHelper() + { m_socket->close(); delete m_socket; -} + } -void WebSocketHelper::doOpen(const QString& hostname, const unsigned short port) -{ + void WebSocketHelper::doOpen(const QString &hostname, const unsigned short port) + { const QUrl url(QStringLiteral("ws://%1:%2/").arg(hostname).arg(port)); if (m_socket->state() == QAbstractSocket::SocketState::ConnectedState) { - if (m_socket->requestUrl() != url) - doClose(); - else - { - INFO_LOG(m_logger) << "Web socket to url: " << url.toDisplayString() << " is already open."; - return; - } + if (m_socket->requestUrl() != url) + doClose(); + else + { + INFO_LOG(m_logger) << "Web socket to url: " << url.toDisplayString() << " is already open."; + return; + } } INFO_LOG(m_logger) << "Opening web socket to url: " << url.toDisplayString(); m_socket->open(url); -} + } -void WebSocketHelper::doClose() -{ + void WebSocketHelper::doClose() + { INFO_LOG(m_logger) << "Closing web socket to url:" << m_socket->requestUrl().toDisplayString(); m_socket->close(); -} + } -void WebSocketHelper::doSendTextMessage(const QString& msg) -{ + void WebSocketHelper::doSendTextMessage(const QString &msg) + { if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) { - ERROR_LOG(m_logger) << "Message could not be send, socket is not connected."; - return; + ERROR_LOG(m_logger) << "Message could not be send, socket is not connected."; + return; } DEBUG_LOG(m_logger) << "Sending message: " << msg; m_socket->sendTextMessage(msg); -} + } -void WebSocketHelper::onConnected() -{ - INFO_LOG(m_logger) << "Connected to server url: " << m_socket->requestUrl().toDisplayString() - << " using local port: " << m_socket->localPort(); + void WebSocketHelper::onConnected() + { + INFO_LOG(m_logger) << "Connected to server url: " << m_socket->requestUrl().toDisplayString() << " using local port: " << m_socket->localPort(); emit connected(); -} + } -void WebSocketHelper::onDisconnected() -{ + void WebSocketHelper::onDisconnected() + { INFO_LOG(m_logger) << "Disconnected from server url: " << m_socket->requestUrl().toDisplayString(); emit disconnected(); -} + } -void WebSocketHelper::onError(QAbstractSocket::SocketError error) -{ + void WebSocketHelper::onError(QAbstractSocket::SocketError error) + { ERROR_LOG(m_logger) << "Error occured: " << error << " closing socket."; m_socket->close(); -} + } -void WebSocketHelper::parseMessage(const QString& message) -{ + void WebSocketHelper::parseMessage(const QString &message) + { const QString pingMsg(QStringLiteral("ping")); if (message.startsWith(pingMsg)) { - doSendTextMessage(PongMessage(message.mid(pingMsg.size())).toJsonString()); - return; + doSendTextMessage(PongMessage(message.mid(pingMsg.size())).toJsonString()); + return; } - AbstractClientMessage* clientMessage = nullptr; + AbstractClientMessage *clientMessage = nullptr; auto result = m_messageFactory->parseMessage(message); if (QJsonParseError::NoError == result.error) - clientMessage = m_messageFactory->createMessage(m_webSocketClient, message); + clientMessage = m_messageFactory->createMessage(m_webSocketClient, message); else { - WARNING_LOG(m_logger) << "Could not parse incoming message: '" << message - << "', error: " << result.errorString(); - clientMessage = - new InvalidMessage(m_webSocketClient, QString(), - QStringLiteral("Got message which is not JSON conform (%1)").arg(result.errorString())); + WARNING_LOG(m_logger) << "Could not parse incoming message: '" << message << "', error: " << result.errorString(); + clientMessage = new InvalidMessage(m_webSocketClient, QString(), QStringLiteral("Got message which is not JSON conform (%1)").arg(result.errorString())); } if (clientMessage) - emit messageParsed(clientMessage); -} + emit messageParsed(clientMessage); + } -LtsWebSocketClient::LtsWebSocketClient(AbstractClientMessageFactory* messageFactory, QObject* parent) - : QObject(parent), m_logger(getLogger("LtsWebSocketClient")), m_messageFactory(messageFactory), - m_webSocketHelperThread(new QThread(this)) -{ + LtsWebSocketClient::LtsWebSocketClient(AbstractClientMessageFactory *messageFactory, QObject *parent) + : QObject(parent) + , m_logger(getLogger("LtsWebSocketClient")) + , m_messageFactory(messageFactory) + , m_webSocketHelperThread(new QThread(this)) + { m_webSocketHelper = new WebSocketHelper(m_messageFactory, this, m_logger); m_webSocketHelper->moveToThread(m_webSocketHelperThread); m_webSocketHelperThread->start(); @@ -154,40 +153,40 @@ LtsWebSocketClient::LtsWebSocketClient(AbstractClientMessageFactory* messageFact connect(this, &LtsWebSocketClient::onOpen, m_webSocketHelper, &WebSocketHelper::doOpen); connect(this, &LtsWebSocketClient::onClose, m_webSocketHelper, &WebSocketHelper::doClose); connect(this, &LtsWebSocketClient::onSendTextMessage, m_webSocketHelper, &WebSocketHelper::doSendTextMessage); -} + } -LtsWebSocketClient::~LtsWebSocketClient() -{ + LtsWebSocketClient::~LtsWebSocketClient() + { m_webSocketHelper->disconnect(this); m_webSocketHelperThread->quit(); m_webSocketHelperThread->wait(); delete m_webSocketHelper; -} + } -void LtsWebSocketClient::open(const QString& hostname, const unsigned short port) -{ + void LtsWebSocketClient::open(const QString &hostname, const unsigned short port) + { emit onOpen(hostname, port); -} + } -void LtsWebSocketClient::close() -{ + void LtsWebSocketClient::close() + { emit onClose(); -} + } -void LtsWebSocketClient::addReply(ReplyMessage* message) -{ + void LtsWebSocketClient::addReply(ReplyMessage *message) + { const QString msg(message->toJsonString()); emit onSendTextMessage(msg); delete message; -} + } -void LtsWebSocketClient::onNewClientMessage(AbstractClientMessage* clientMessage) -{ + void LtsWebSocketClient::onNewClientMessage(AbstractClientMessage *clientMessage) + { if (!clientMessage) - return; + return; clientMessage->process(); delete clientMessage; -} + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h index edbcf4896..f223cd9c5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h @@ -13,20 +13,22 @@ class QThread; namespace LtsWebSocket { -class WebSocketHelper; + class WebSocketHelper; -class LTSWEBSOCKETCLIENT_EXPORT LtsWebSocketClient : public QObject, public ReplyHandler -{ + class LTSWEBSOCKETCLIENT_EXPORT LtsWebSocketClient + : public QObject + , public ReplyHandler + { Q_OBJECT public: - explicit LtsWebSocketClient(AbstractClientMessageFactory* messageFactory, QObject* parent = nullptr); + explicit LtsWebSocketClient(AbstractClientMessageFactory *messageFactory, QObject *parent = nullptr); ~LtsWebSocketClient(); - void open(const QString& hostname, const unsigned short port); + void open(const QString &hostname, const unsigned short port); void close(); - void addReply(ReplyMessage* message) override; + void addReply(ReplyMessage *message) override; signals: void connected(); @@ -35,18 +37,18 @@ class LTSWEBSOCKETCLIENT_EXPORT LtsWebSocketClient : public QObject, public Repl private slots: - void onNewClientMessage(AbstractClientMessage* clientMessage); + void onNewClientMessage(AbstractClientMessage *clientMessage); signals: - void onOpen(const QString& hostname, const unsigned short port); + void onOpen(const QString &hostname, const unsigned short port); void onClose(); - void onSendTextMessage(const QString& msg); + void onSendTextMessage(const QString &msg); private: - NGL::INGLLogger& m_logger; - AbstractClientMessageFactory* m_messageFactory; + NGL::INGLLogger &m_logger; + AbstractClientMessageFactory *m_messageFactory; - QThread* m_webSocketHelperThread; - WebSocketHelper* m_webSocketHelper; -}; + QThread *m_webSocketHelperThread; + WebSocketHelper *m_webSocketHelper; + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp index bfcbe0b8c..247a4e75c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp @@ -11,114 +11,112 @@ namespace LtsWebSocket { -LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory* messageFactory, QObject* parent) - : QObject(parent), m_queueTimer(new QTimer(this)), m_messageFactory(messageFactory), m_connectionHandler(nullptr), - m_logger(getLogger("LtsWebSocket.Server")) -{ + LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory *messageFactory, QObject *parent) + : QObject(parent) + , m_queueTimer(new QTimer(this)) + , m_messageFactory(messageFactory) + , m_connectionHandler(nullptr) + , m_logger(getLogger("LtsWebSocket.Server")) + { connect(m_queueTimer, &QTimer::timeout, this, &LtsWebSocketServer::onQueueTimerTimeout); m_queueTimer->setSingleShot(true); -} + } -LtsWebSocketServer::~LtsWebSocketServer() = default; + LtsWebSocketServer::~LtsWebSocketServer() = default; -bool LtsWebSocketServer::init(const QString& serviceName, const unsigned short port) -{ + bool LtsWebSocketServer::init(const QString &serviceName, const unsigned short port) + { m_connectionHandler.reset(new ConnectionHandler(this)); if (!m_connectionHandler->init(serviceName, port)) { - ERROR_LOG(m_logger) << "Could not init m_connectionHandler with servicename: " << serviceName - << ((port == 0) ? QStringLiteral(" random port") - : QStringLiteral(" port: ") + QString::number(port)); - m_connectionHandler.reset(); - return false; + ERROR_LOG(m_logger) << "Could not init m_connectionHandler with servicename: " << serviceName + << ((port == 0) ? QStringLiteral(" random port") : QStringLiteral(" port: ") + QString::number(port)); + m_connectionHandler.reset(); + return false; } - connect(m_connectionHandler.get(), &ConnectionHandler::newTextMessageFromClient, this, - &LtsWebSocketServer::onNewTextMessage); - connect(m_connectionHandler.get(), &ConnectionHandler::clientDisconnected, this, - &LtsWebSocketServer::clientDisconnected); + connect(m_connectionHandler.get(), &ConnectionHandler::newTextMessageFromClient, this, &LtsWebSocketServer::onNewTextMessage); + connect(m_connectionHandler.get(), &ConnectionHandler::clientDisconnected, this, &LtsWebSocketServer::clientDisconnected); connect(m_connectionHandler.get(), &ConnectionHandler::clientConnected, this, &LtsWebSocketServer::clientConnected); m_queueTimer->start(m_messageDelay); return true; -} + } -bool LtsWebSocketServer::init(const QString& serviceName, const QPair& portRange) -{ + bool LtsWebSocketServer::init(const QString &serviceName, const QPair &portRange) + { if (portRange.first < 1025 || portRange.first > portRange.second) - return init(serviceName); + return init(serviceName); for (quint16 currentPort = portRange.first; currentPort <= portRange.second; ++currentPort) { - if (init(serviceName, currentPort)) - return true; + if (init(serviceName, currentPort)) + return true; } return init(serviceName); -} + } -void LtsWebSocketServer::sendToAllClients(ReplyMessage* message) -{ + void LtsWebSocketServer::sendToAllClients(ReplyMessage *message) + { DEBUG_LOG(m_logger) << "Sending message to all clients: " << message->toJsonString(); m_connectionHandler->sendToAllClients(message); -} + } -unsigned short LtsWebSocketServer::webSocketPort() const -{ + unsigned short LtsWebSocketServer::webSocketPort() const + { return m_connectionHandler->webSocketPort(); -} + } -void LtsWebSocketServer::setMessageDelay(qint32 delay) -{ + void LtsWebSocketServer::setMessageDelay(qint32 delay) + { m_messageDelay = delay; -} + } -void LtsWebSocketServer::onNewTextMessage(ReplyHandler* client, const QString& message) -{ + void LtsWebSocketServer::onNewTextMessage(ReplyHandler *client, const QString &message) + { const QString pingMsg(QStringLiteral("ping")); if (message.startsWith(pingMsg)) { - client->addReply(new PongMessage(message.mid(pingMsg.size()))); - return; + client->addReply(new PongMessage(message.mid(pingMsg.size()))); + return; } DEBUG_LOG(m_logger) << "Got new message: " << message; m_messageQueue.append({client, message}); if (!m_queueTimer->isActive()) - m_queueTimer->start(m_messageDelay); -} + m_queueTimer->start(m_messageDelay); + } -void LtsWebSocketServer::onQueueTimerTimeout() -{ + void LtsWebSocketServer::onQueueTimerTimeout() + { if (m_messageQueue.isEmpty()) - return; + return; MessageCredentials credentials = m_messageQueue.takeFirst(); - AbstractClientMessage* clientMessage = nullptr; + AbstractClientMessage *clientMessage = nullptr; auto result = m_messageFactory->parseMessage(credentials.message); if (QJsonParseError::NoError == result.error) - clientMessage = m_messageFactory->createMessage(credentials.client, credentials.message); + clientMessage = m_messageFactory->createMessage(credentials.client, credentials.message); else { - WARNING_LOG(m_logger) << "Could not parse incoming message: '" << credentials.message - << "', error: " << result.errorString(); + WARNING_LOG(m_logger) << "Could not parse incoming message: '" << credentials.message << "', error: " << result.errorString(); - clientMessage = - new InvalidMessage(credentials.client, QString(), QStringLiteral("Got message which is not JSON conform")); + clientMessage = new InvalidMessage(credentials.client, QString(), QStringLiteral("Got message which is not JSON conform")); } if (clientMessage) - clientMessage->process(); + clientMessage->process(); delete clientMessage; m_queueTimer->start(m_messageDelay); -} + } } // namespace LtsWebSocket #else @@ -126,12 +124,14 @@ void LtsWebSocketServer::onQueueTimerTimeout() namespace LtsWebSocket { -LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory* /*messageFactory*/, QObject* parent) - : QObject(parent), m_queueTimer(new QTimer(this)), m_logger(getLogger("LtsWebSocket.Server")) -{ -} + LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory * /*messageFactory*/, QObject *parent) + : QObject(parent) + , m_queueTimer(new QTimer(this)) + , m_logger(getLogger("LtsWebSocket.Server")) + { + } -LtsWebSocketServer::~LtsWebSocketServer() = default; + LtsWebSocketServer::~LtsWebSocketServer() = default; } // namespace LtsWebSocket #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h index 1852fafd8..52cd4a11f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h @@ -15,83 +15,87 @@ class QTimer; #ifdef QT6_WEBSOCKETS_AVAILABLE namespace LtsWebSocket { -class ConnectionHandler; -class ClientConnection; + class ConnectionHandler; + class ClientConnection; -class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer : public QObject -{ + class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer : public QObject + { Q_OBJECT public: - explicit LtsWebSocketServer(AbstractClientMessageFactory* messageFactory, QObject* parent = nullptr); + explicit LtsWebSocketServer(AbstractClientMessageFactory *messageFactory, QObject *parent = nullptr); virtual ~LtsWebSocketServer(); - bool init(const QString& serviceName, const unsigned short port = 0); + bool init(const QString &serviceName, const unsigned short port = 0); - bool init(const QString& serviceName, const QPair& portRange); + bool init(const QString &serviceName, const QPair &portRange); - void sendToAllClients(ReplyMessage* message); + void sendToAllClients(ReplyMessage *message); unsigned short webSocketPort() const; void setMessageDelay(qint32 delay); signals: - void clientDisconnected(ClientConnection* client); + void clientDisconnected(ClientConnection *client); - void clientConnected(ClientConnection* client); + void clientConnected(ClientConnection *client); private slots: - void onNewTextMessage(ReplyHandler* client, const QString& message); + void onNewTextMessage(ReplyHandler *client, const QString &message); void onQueueTimerTimeout(); private: struct MessageCredentials { - ReplyHandler* client{nullptr}; - QString message; + ReplyHandler *client{nullptr}; + QString message; - MessageCredentials(ReplyHandler* client, const QString& message) : client(client), message(message) {} + MessageCredentials(ReplyHandler *client, const QString &message) + : client(client) + , message(message) + { + } }; QQueue m_messageQueue; - QTimer* m_queueTimer{nullptr}; - AbstractClientMessageFactory* m_messageFactory{nullptr}; + QTimer *m_queueTimer{nullptr}; + AbstractClientMessageFactory *m_messageFactory{nullptr}; std::unique_ptr m_connectionHandler; qint32 m_messageDelay{0}; LOGGER_T m_logger; -}; + }; } // namespace LtsWebSocket #else #include namespace LtsWebSocket { -class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer : public QObject -{ + class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer : public QObject + { Q_OBJECT public: - explicit LtsWebSocketServer(AbstractClientMessageFactory* /*messageFactory*/, QObject* parent = nullptr); + explicit LtsWebSocketServer(AbstractClientMessageFactory * /*messageFactory*/, QObject *parent = nullptr); virtual ~LtsWebSocketServer(); - bool init(const QString& /*serviceName*/, const unsigned short /*port*/ = 0) { return false; } - bool init(const QString& /*serviceName*/, const QPair& /*portRange*/) { return false; } - void sendToAllClients(ReplyMessage* /*message*/) {} + bool init(const QString & /*serviceName*/, const unsigned short /*port*/ = 0) { return false; } + bool init(const QString & /*serviceName*/, const QPair & /*portRange*/) { return false; } + void sendToAllClients(ReplyMessage * /*message*/) {} unsigned short webSocketPort() const { return 0; } void setMessageDelay(qint32 /*delay*/) {} signals: - void clientDisconnected(void* /*client*/); - void clientConnected(void* /*client*/); + void clientDisconnected(void * /*client*/); + void clientConnected(void * /*client*/); private slots: - void onNewTextMessage(void* /*client*/, const QString& /*message*/) {} + void onNewTextMessage(void * /*client*/, const QString & /*message*/) {} void onQueueTimerTimeout() {} private: - QTimer* m_queueTimer{nullptr}; + QTimer *m_queueTimer{nullptr}; LOGGER_T m_logger; -}; + }; } // namespace LtsWebSocket #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketcommon_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketcommon_export.h index fff22153e..a3de205d8 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketcommon_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketcommon_export.h @@ -5,9 +5,9 @@ #include #if defined(LTSWEBSOCKETCOMMON_LIBRARY) - #define LTSWEBSOCKETCOMMON_EXPORT Q_DECL_EXPORT +#define LTSWEBSOCKETCOMMON_EXPORT Q_DECL_EXPORT #else - #define LTSWEBSOCKETCOMMON_EXPORT Q_DECL_IMPORT +#define LTSWEBSOCKETCOMMON_EXPORT Q_DECL_IMPORT #endif -#endif // LTSWEBSOCKETCOMMON_EXPORT_H \ No newline at end of file +#endif // LTSWEBSOCKETCOMMON_EXPORT_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketserver_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketserver_export.h index 099b1f887..fc82574d3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketserver_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/ltswebsocketserver_export.h @@ -4,9 +4,9 @@ #include #if defined(LTSWEBSOCKETSERVER_LIBRARY) -# define LTSWEBSOCKETSERVER_EXPORT Q_DECL_EXPORT +#define LTSWEBSOCKETSERVER_EXPORT Q_DECL_EXPORT #else -# define LTSWEBSOCKETSERVER_EXPORT Q_DECL_IMPORT +#define LTSWEBSOCKETSERVER_EXPORT Q_DECL_IMPORT #endif -#endif // LTSWEBSOCKETSERVER_EXPORT_H \ No newline at end of file +#endif // LTSWEBSOCKETSERVER_EXPORT_H diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h index 67aa3bf06..8cacd3aa5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h @@ -2,11 +2,11 @@ namespace LtsWebSocketServer { -class ReplyMessage; + class ReplyMessage; -class MessageHandler -{ + class MessageHandler + { public: - virtual void addMessage(ReplyMessage* message) = 0; -}; + virtual void addMessage(ReplyMessage *message) = 0; + }; } // namespace LtsWebSocketServer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp index d1ab498af..9c07785ea 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp @@ -9,26 +9,26 @@ namespace LtsWebSocket { -QString ReplyMessage::toJsonString() const -{ + QString ReplyMessage::toJsonString() const + { return QString::fromUtf8(QJsonDocument(m_jsonRepresentation).toJson(QJsonDocument::Compact)); -} + } -ReplyMessage::ReplyMessage(const QString& type, const int typeId, const QString& uuid) -{ + ReplyMessage::ReplyMessage(const QString &type, const int typeId, const QString &uuid) + { m_jsonRepresentation.insert(JsonKeys::TYPE(), type); m_jsonRepresentation.insert(JsonKeys::TYPEID(), typeId); if (!uuid.isEmpty()) - m_jsonRepresentation.insert(JsonKeys::UUID_(), uuid); -} + m_jsonRepresentation.insert(JsonKeys::UUID_(), uuid); + } -ErrorMessage::ErrorMessage(const ErrorMessage::ErrorData& data) - : ReplyMessage(JsonKeys::ERROR_(), -1, QUuid::createUuid().toString()) -{ - m_jsonRepresentation.insert(JsonKeys::DATA(), QJsonObject({{JsonKeys::UUID_(), data.uuid}, - {JsonKeys::ERROR_CLASS(), data.errorClass}, - {JsonKeys::ERROR_MESSAGE(), data.errorMessage}})); -} + ErrorMessage::ErrorMessage(const ErrorMessage::ErrorData &data) + : ReplyMessage(JsonKeys::ERROR_(), -1, QUuid::createUuid().toString()) + { + m_jsonRepresentation.insert(JsonKeys::DATA(), + QJsonObject( + {{JsonKeys::UUID_(), data.uuid}, {JsonKeys::ERROR_CLASS(), data.errorClass}, {JsonKeys::ERROR_MESSAGE(), data.errorMessage}})); + } } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h index 2a6edc5f0..ffb954711 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h @@ -11,45 +11,42 @@ namespace LtsWebSocket { -class LTSWEBSOCKETCOMMON_EXPORT ReplyMessage -{ + class LTSWEBSOCKETCOMMON_EXPORT ReplyMessage + { public: virtual ~ReplyMessage() = default; virtual QString toJsonString() const; - QJsonObject json() const - { - return m_jsonRepresentation; - } + QJsonObject json() const { return m_jsonRepresentation; } protected: ReplyMessage() = default; - ReplyMessage(const QString& type, const int typeId, const QString& uuid); + ReplyMessage(const QString &type, const int typeId, const QString &uuid); protected: QJsonObject m_jsonRepresentation; -}; + }; -class LTSWEBSOCKETCOMMON_EXPORT ReplyHandler -{ + class LTSWEBSOCKETCOMMON_EXPORT ReplyHandler + { public: virtual ~ReplyHandler() = default; - virtual void addReply(ReplyMessage* message) = 0; -}; + virtual void addReply(ReplyMessage *message) = 0; + }; -class LTSWEBSOCKETCOMMON_EXPORT ErrorMessage final : public ReplyMessage -{ + class LTSWEBSOCKETCOMMON_EXPORT ErrorMessage final : public ReplyMessage + { public: struct ErrorData { - int errorClass = 0; - QString uuid; - QString errorMessage; + int errorClass = 0; + QString uuid; + QString errorMessage; }; - explicit ErrorMessage(const ErrorData& data); -}; + explicit ErrorMessage(const ErrorData &data); + }; } // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h index af5341276..8d39bb83f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h @@ -8,35 +8,35 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } namespace LtsSession { -class LtsSessionDataDds; + class LtsSessionDataDds; } namespace DataPluginBase { -class Interface -{ -public: + class Interface + { + public: virtual ~Interface() = default; -}; + }; -class Plugin : public QObject -{ - Q_OBJECT + class Plugin : public QObject + { + Q_OBJECT public: Plugin() = default; virtual ~Plugin() = default; virtual QString pluginName() const = 0; - virtual std::shared_ptr createDataInterface(LtsSession::LtsSessionDataDds* session) = 0; + virtual std::shared_ptr createDataInterface(LtsSession::LtsSessionDataDds *session) = 0; virtual bool availableInPartition(IDL::PartitionType partition) const = 0; -}; + }; } // namespace DataPluginBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h index 00387ca36..4d7f045bf 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h @@ -13,132 +13,99 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } namespace LtsWidgets { -class LtsBackgroundWidget; -class LtsBaseLayoutWidget; + class LtsBackgroundWidget; + class LtsBaseLayoutWidget; } // namespace LtsWidgets namespace LtsSession { -class LtsSession; + class LtsSession; } namespace GuiPluginBase { -class Interface; + class Interface; + + class Plugin + { + Q_GADGET -class Plugin -{ - Q_GADGET - public: virtual ~Plugin() = default; virtual QString pluginName() = 0; - virtual std::shared_ptr createGuiInterface(LtsSession::LtsSession* session) = 0; + virtual std::shared_ptr createGuiInterface(LtsSession::LtsSession *session) = 0; virtual bool availableInPartition(IDL::PartitionType partition) const = 0; -}; + }; -class Interface -{ + class Interface + { public: - Interface(LtsSession::LtsSession* session, NGL::INGLLogger& logger) - : m_hasInit(true), m_session(session), m_appId(LtsAppDescriptor::App::Login), m_logger(logger) + Interface(LtsSession::LtsSession *session, NGL::INGLLogger &logger) + : m_hasInit(true) + , m_session(session) + , m_appId(LtsAppDescriptor::App::Login) + , m_logger(logger) { } virtual ~Interface() = default; - void setFlags(const QFlags& flags) - { - m_flags = flags; - } + void setFlags(const QFlags &flags) { m_flags = flags; } - const QFlags& getFlags() const - { - return m_flags; - } + const QFlags &getFlags() const { return m_flags; } - void setOptions(const QStringList& options) - { - m_options = options; - } + void setOptions(const QStringList &options) { m_options = options; } - const QStringList& getOptions() const - { - return m_options; - } + const QStringList &getOptions() const { return m_options; } - void setAppId(LtsAppDescriptor::App appId) - { - m_appId = appId; - } + void setAppId(LtsAppDescriptor::App appId) { m_appId = appId; } - LtsAppDescriptor::App appId() const - { - return m_appId; - } + LtsAppDescriptor::App appId() const { return m_appId; } - virtual QVector getActions() - { - return QVector(); - } + virtual QVector getActions() { return QVector(); } - virtual bool fetchInterfaces() - { - return true; - } + virtual bool fetchInterfaces() { return true; } virtual void clearInterfaces() {} - virtual QString menuGroup() const - { - return {}; - } + virtual QString menuGroup() const { return {}; } virtual LtsUtils::LtsTranslatableIdentifier menuGroupIdentifier() const { - m_hasMenuGroupIdentifier = false; - return {}; + m_hasMenuGroupIdentifier = false; + return {}; } virtual bool availableInPartition(IDL::PartitionType partition) const { - Q_UNUSED(partition); - return true; + Q_UNUSED(partition); + return true; } - virtual void init() - { - m_hasInit = false; - } + virtual void init() { m_hasInit = false; } - virtual void executePayload(LtsWidgets::LtsBackgroundWidget* mainBackground) - { - (void)mainBackground; - } + virtual void executePayload(LtsWidgets::LtsBackgroundWidget *mainBackground) { (void)mainBackground; } - virtual int executionPriority() const - { - return -1; - } + virtual int executionPriority() const { return -1; } bool m_hasInit; mutable bool m_hasMenuGroupIdentifier = true; protected: - LtsSession::LtsSession* m_session; + LtsSession::LtsSession *m_session; private: QFlags m_flags; QStringList m_options; LtsAppDescriptor::App m_appId; - NGL::INGLLogger& m_logger; -}; + NGL::INGLLogger &m_logger; + }; } // namespace GuiPluginBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h index 481a22fb3..a9eb4f788 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h @@ -7,13 +7,13 @@ namespace ProjectPlugin { -class Plugin -{ + class Plugin + { Q_GADGET - -public: + + public: virtual ~Plugin() = default; -}; + }; } // namespace ProjectPlugin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h index 27e15a10f..e8791fcf7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h @@ -10,71 +10,72 @@ namespace DDSConnector { -class DdsConnector; + class DdsConnector; } class NSqlQuery; namespace RecordReplay { -class RecordReplayPlugin -{ - Q_GADGET - + class RecordReplayPlugin + { + Q_GADGET + public: virtual ~RecordReplayPlugin() = default; virtual QString pluginName() const = 0; - virtual bool initDtc(const std::shared_ptr& ddsConnector, int exerciseId) = 0; + virtual bool initDtc(const std::shared_ptr &ddsConnector, int exerciseId) = 0; - virtual bool initDts(const std::shared_ptr& ddsConnector, int exerciseId, - bool bCanHandleSchemas, NSqlQuery& query) = 0; + virtual bool initDts(const std::shared_ptr &ddsConnector, int exerciseId, bool bCanHandleSchemas, NSqlQuery &query) = 0; virtual bool initCopy(int exerciseId, bool bCanHandleSchemasRead, bool bCanHandleSchemasWrite) = 0; - virtual bool copyData(NSqlQuery& queryFrom, NSqlQuery& queryTo, qint64 fromTime, qint64 toTime) = 0; + virtual bool copyData(NSqlQuery &queryFrom, NSqlQuery &queryTo, qint64 fromTime, qint64 toTime) = 0; virtual QString svcShortName() const = 0; - virtual bool ddsTopicsToDatabase(NSqlQuery& query, QHash& minRecordSampleTimes) = 0; + virtual bool ddsTopicsToDatabase(NSqlQuery &query, QHash &minRecordSampleTimes) = 0; - virtual bool setReplayStartTime(NSqlQuery& query, qint64 startTime) = 0; + virtual bool setReplayStartTime(NSqlQuery &query, qint64 startTime) = 0; - virtual bool ddsTopicsFromDatabase(NSqlQuery& query, qint64 fromTime, qint64 toTime) = 0; + virtual bool ddsTopicsFromDatabase(NSqlQuery &query, qint64 fromTime, qint64 toTime) = 0; virtual bool publishData(qint64 desiredTime) = 0; virtual bool waitForAsyncOperations(qint64 desiredTime) { - Q_UNUSED(desiredTime); - return true; + Q_UNUSED(desiredTime); + return true; } virtual void clearData() = 0; struct RecSnapshot { - qint64 timeStamp = 0; - std::map recIdArray; - RecSnapshot() = default; + qint64 timeStamp = 0; + std::map recIdArray; + RecSnapshot() = default; - RecSnapshot(qint64 timeStamp_, const std::map& recIdArray_) - : timeStamp(timeStamp_), recIdArray(recIdArray_) - { - } + RecSnapshot(qint64 timeStamp_, const std::map &recIdArray_) + : timeStamp(timeStamp_) + , recIdArray(recIdArray_) + { + } }; - virtual std::map> - getSnapshotTimes(NSqlQuery& query, qint64 toTime, qint64 interval, - const QHash& minRecordedSampleTimes) = 0; + virtual std::map> getSnapshotTimes(NSqlQuery &query, + qint64 toTime, + qint64 interval, + const QHash &minRecordedSampleTimes) = 0; virtual QVector getRecordTopicNames() const = 0; virtual QVector getRecordTableNames() const = 0; - virtual qint64 getMinimumSampleTime(NSqlQuery& q, const QString& topicName, qint64 defaultValue) const = 0; -}; + virtual qint64 getMinimumSampleTime(NSqlQuery &q, const QString &topicName, qint64 defaultValue) const = 0; + }; } // namespace RecordReplay Q_DECLARE_INTERFACE(RecordReplay::RecordReplayPlugin, "special:3:recordreplay") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h index 93c1798dd..6c955833b 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h @@ -6,16 +6,16 @@ namespace StylePlugin { -class Plugin -{ - Q_GADGET - + class Plugin + { + Q_GADGET + public: virtual ~Plugin() = default; virtual void loadStyle(bool highDpi) = 0; virtual void unloadStyle() = 0; -}; + }; } // namespace StylePlugin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h index 414142726..0fea44d43 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h @@ -10,122 +10,104 @@ class QWidget; namespace TopicEditorBase { -class ExportNotifier; + class ExportNotifier; } namespace TopicReplay { -class Interface -{ + class Interface + { public: - static QJsonObject timeRange(qint64 start, qint64 end) - { - return {{QStringLiteral("start"), start}, {QStringLiteral("end"), end}}; - } + static QJsonObject timeRange(qint64 start, qint64 end) { return {{QStringLiteral("start"), start}, {QStringLiteral("end"), end}}; } struct SituationReplayTime { - int id = 0; + int id = 0; - qint64 topicStart_s = -1; - qint64 topicEnd_s = -1; + qint64 topicStart_s = -1; + qint64 topicEnd_s = -1; - qint64 replayStart_ms = -1; - qint64 replayEnd_ms = -1; - double replaySpeedFactor = 1; + qint64 replayStart_ms = -1; + qint64 replayEnd_ms = -1; + double replaySpeedFactor = 1; - QJsonObject toReplayInformation() const - { - return { - {QStringLiteral("id"), id}, - {QStringLiteral("timeInPresentation"), timeRange(topicStart_s * 1000, topicEnd_s * 1000)}, - }; - } + QJsonObject toReplayInformation() const + { + return { + {QStringLiteral("id"), id}, + {QStringLiteral("timeInPresentation"), timeRange(topicStart_s * 1000, topicEnd_s * 1000)}, + }; + } - QJsonObject toPlaybackTime(double max) const - { - QJsonObject ret = timeRange(replayStart_ms, std::min(replayEnd_ms * replaySpeedFactor, max)); - ret[QStringLiteral("replaySpeedFactor")] = replaySpeedFactor; - return ret; - } + QJsonObject toPlaybackTime(double max) const + { + QJsonObject ret = timeRange(replayStart_ms, std::min(replayEnd_ms * replaySpeedFactor, max)); + ret[QStringLiteral("replaySpeedFactor")] = replaySpeedFactor; + return ret; + } - QJsonObject toJson(double maxReplayEndMs) const - { - return { - {QStringLiteral("playbackTime"), toPlaybackTime(maxReplayEndMs)}, - {QStringLiteral("replayInformation"), toReplayInformation()}, - }; - } + QJsonObject toJson(double maxReplayEndMs) const + { + return { + {QStringLiteral("playbackTime"), toPlaybackTime(maxReplayEndMs)}, + {QStringLiteral("replayInformation"), toReplayInformation()}, + }; + } }; Interface() = default; virtual ~Interface() = default; - virtual QWidget* createWidget() - { - return nullptr; - } + virtual QWidget *createWidget() { return nullptr; } - virtual bool playbackInit(const QJsonObject& attributes) + virtual bool playbackInit(const QJsonObject &attributes) { - Q_UNUSED(attributes); - return true; + Q_UNUSED(attributes); + return true; } virtual bool playbackStart(int secondsOffset) { - Q_UNUSED(secondsOffset); - return true; + Q_UNUSED(secondsOffset); + return true; } - virtual bool playbackPause() + virtual bool playbackPause() { return true; } + + virtual bool playbackStop() { return true; } + + virtual void setExportPlaybackTimes(qint64 startTimeSec, qint64 durationSec, const QVector &sitReplayTimes) { - return true; + Q_UNUSED(startTimeSec); + Q_UNUSED(durationSec); + Q_UNUSED(sitReplayTimes); } - virtual bool playbackStop() + virtual bool exportTopic(const QJsonObject &attributes, const QString &strFolderPath, TopicEditorBase::ExportNotifier *pExportNotifier) = 0; + + virtual QVector additionalTrackEntries(const QJsonObject &attributes) const { - return true; + Q_UNUSED(attributes); + return {}; } - virtual void setExportPlaybackTimes(qint64 startTimeSec, qint64 durationSec, - const QVector& sitReplayTimes) + virtual QVector additionalTrackEntries(const QJsonObject &attributes, bool &keepOriginalTopic) const { - Q_UNUSED(startTimeSec); - Q_UNUSED(durationSec); - Q_UNUSED(sitReplayTimes); + keepOriginalTopic = true; + return additionalTrackEntries(attributes); } - virtual bool exportTopic(const QJsonObject& attributes, const QString& strFolderPath, - TopicEditorBase::ExportNotifier* pExportNotifier) = 0; + virtual void setBasePath(const QString &basePath) { Q_UNUSED(basePath); } + }; - virtual QVector additionalTrackEntries(const QJsonObject& attributes) const - { - Q_UNUSED(attributes); - return {}; - } - - virtual QVector additionalTrackEntries(const QJsonObject& attributes, - bool& keepOriginalTopic) const - { - keepOriginalTopic = true; - return additionalTrackEntries(attributes); - } - - virtual void setBasePath(const QString& basePath) - { - Q_UNUSED(basePath); - } -}; - -class Factory -{ + class Factory + { public: virtual ~Factory() = default; - virtual Interface* createInterface(TopicEditorBase::TopicType topicType) = 0; -}; + virtual Interface *createInterface(TopicEditorBase::TopicType topicType) = 0; + }; } // namespace TopicReplay diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h b/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h index c92e810c5..8878c101f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h @@ -10,61 +10,62 @@ namespace IDL { -enum class PartitionType { + enum class PartitionType + { Any, Global, Exercise, AllExercises, Replay, -}; + }; -inline std::string toStdString(PartitionType pt) -{ + inline std::string toStdString(PartitionType pt) + { switch (pt) { - case PartitionType::Any: - return "Any"; - case PartitionType::Global: - return "Global"; - case PartitionType::Exercise: - return "Exercise"; - case PartitionType::AllExercises: - return "AllExercises"; - case PartitionType::Replay: - return "Replay"; + case PartitionType::Any: + return "Any"; + case PartitionType::Global: + return "Global"; + case PartitionType::Exercise: + return "Exercise"; + case PartitionType::AllExercises: + return "AllExercises"; + case PartitionType::Replay: + return "Replay"; } return std::string("invalid:") + std::to_string(static_cast(pt)); -} + } -inline std::ostream& operator<<(std::ostream& o, PartitionType pt) -{ + inline std::ostream &operator<<(std::ostream &o, PartitionType pt) + { switch (pt) { - case PartitionType::Any: - case PartitionType::Global: - case PartitionType::Exercise: - case PartitionType::AllExercises: - case PartitionType::Replay: - return o << std::string("PartitionType::") + toStdString(pt); - default: - return o << std::to_string(static_cast(pt)); + case PartitionType::Any: + case PartitionType::Global: + case PartitionType::Exercise: + case PartitionType::AllExercises: + case PartitionType::Replay: + return o << std::string("PartitionType::") + toStdString(pt); + default: + return o << std::to_string(static_cast(pt)); } -} + } -inline std::string exercisePartition(int exerciseId) -{ + inline std::string exercisePartition(int exerciseId) + { if (exerciseId < 0) - return {"ex_*"}; + return {"ex_*"}; return std::string("ex_") + std::to_string(exerciseId); -} + } -inline std::string replayPartition(int partitionId) -{ + inline std::string replayPartition(int partitionId) + { if (partitionId < 0) - return {"srp_*"}; + return {"srp_*"}; return std::string("srp_") + std::to_string(partitionId); -} + } } // namespace IDL diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp index 8f13c191b..5b51e35c5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp @@ -9,72 +9,83 @@ namespace httq { -AbstractServer::AbstractServer(QObject* parent) - : QObject(parent), mSvr(new QTcpServer(this)), mLoggerFactory(nullptr), mLogger(nullptr) -{ -} + AbstractServer::AbstractServer(QObject *parent) + : QObject(parent) + , mSvr(new QTcpServer(this)) + , mLoggerFactory(nullptr) + , mLogger(nullptr) + { + } -LoggerFactory* AbstractServer::createLoggerFactory() -{ + LoggerFactory *AbstractServer::createLoggerFactory() + { return new LoggerFactory(this); -} + } -LoggerFactory* AbstractServer::getLoggerFactory() -{ + LoggerFactory *AbstractServer::getLoggerFactory() + { if (mLoggerFactory == nullptr) - mLoggerFactory = createLoggerFactory(); + mLoggerFactory = createLoggerFactory(); return mLoggerFactory; -} + } -void AbstractServer::slotNewConnection() -{ + void AbstractServer::slotNewConnection() + { mLogger->debug(QStringLiteral("newConnection")); - while (QTcpSocket* cli = mSvr->nextPendingConnection()) + while (QTcpSocket *cli = mSvr->nextPendingConnection()) { - mLogger->debug(QStringLiteral("nextPendingConnection")); + mLogger->debug(QStringLiteral("nextPendingConnection")); - if (cli == nullptr) - { - mLogger->debug(QStringLiteral("invalid tcp client")); - return; - } + if (cli == nullptr) + { + mLogger->debug(QStringLiteral("invalid tcp client")); + return; + } - HttpRequest* req = new HttpRequest(cli, this); + HttpRequest *req = new HttpRequest(cli, this); - connect(req, &HttpRequest::signalUpgrade, this, [this, req](QTcpSocket* sock) { - mLogger->debug(QStringLiteral("signalUpgrade")); + connect(req, + &HttpRequest::signalUpgrade, + this, + [this, req](QTcpSocket *sock) + { + mLogger->debug(QStringLiteral("signalUpgrade")); #ifdef QT6_WEBSOCKETS_AVAILABLE - QWebSocketServer* wsSvr = webSocketServer(); + QWebSocketServer *wsSvr = webSocketServer(); - if (wsSvr == nullptr) - { - mLogger->debug(QStringLiteral("no websocket server available for websocket upgrade")); - sock->close(); - sock->deleteLater(); - return; - } + if (wsSvr == nullptr) + { + mLogger->debug(QStringLiteral("no websocket server available for websocket upgrade")); + sock->close(); + sock->deleteLater(); + return; + } - wsSvr->handleConnection(sock); + wsSvr->handleConnection(sock); #else mLogger->debug(QStringLiteral("websocket support not available")); sock->close(); sock->deleteLater(); return; #endif - emit sock->readyRead(); - }); + emit sock->readyRead(); + }); - connect(req, &HttpRequest::signalReady, this, [this, req]() { - mLogger->debug(QStringLiteral("signalReady")); - newHttpConnection(req); - }); + connect(req, + &HttpRequest::signalReady, + this, + [this, req]() + { + mLogger->debug(QStringLiteral("signalReady")); + newHttpConnection(req); + }); } -} + } -bool AbstractServer::listen(qint16 port, const QHostAddress& host) -{ + bool AbstractServer::listen(qint16 port, const QHostAddress &host) + { mLoggerFactory = createLoggerFactory(); mLogger = mLoggerFactory->createLogger(this); @@ -83,5 +94,5 @@ bool AbstractServer::listen(qint16 port, const QHostAddress& host) connect(mSvr, &QTcpServer::newConnection, this, &AbstractServer::slotNewConnection); return mSvr->listen(host, port); -} + } } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp index 5ddb4cc6a..330cdb30c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp @@ -13,67 +13,87 @@ namespace httq { -DataStream::DataStream(QIODevice* from, QIODevice* to, const QByteArray& bodyPartial, qint64 fileLength, - size_t bufferSize, LoggerFactory* loggerFactory, QObject* parent) - : QObject(parent), mBodyPartial(bodyPartial), mFrom(from), mTo(to), mBufferSize(bufferSize), - mFileLength(fileLength), mLogger(loggerFactory->createLogger(this)) -{ + DataStream::DataStream(QIODevice *from, + QIODevice *to, + const QByteArray &bodyPartial, + qint64 fileLength, + size_t bufferSize, + LoggerFactory *loggerFactory, + QObject *parent) + : QObject(parent) + , mBodyPartial(bodyPartial) + , mFrom(from) + , mTo(to) + , mBufferSize(bufferSize) + , mFileLength(fileLength) + , mLogger(loggerFactory->createLogger(this)) + { #ifdef SAVE_PARTIAL_BODY { - QTemporaryFile f; - f.open(); - f.write(mBodyPartial); - f.setAutoRemove(false); - qWarning() << "partial:" << f.fileName(); + QTemporaryFile f; + f.open(); + f.write(mBodyPartial); + f.setAutoRemove(false); + qWarning() << "partial:" << f.fileName(); } #endif if (mFileLength == 0) { - mLogger->warning(QStringLiteral("file size = 0 - done")); - QTimer::singleShot(1, this, [this]() { - emit signalDone(); - deleteLater(); - }); - return; + mLogger->warning(QStringLiteral("file size = 0 - done")); + QTimer::singleShot(1, + this, + [this]() + { + emit signalDone(); + deleteLater(); + }); + return; } mLogger->debug(QStringLiteral("DataStream c_tor")); mBuffer.reserve(bufferSize); - mFromSupportsSignals = (qobject_cast(mFrom) == nullptr); - mToSupportsSignals = (qobject_cast(mTo) == nullptr); - mLogger->debug( - QStringLiteral("signal support - from: %1 - to: %2").arg(mFromSupportsSignals).arg(mToSupportsSignals)); + mFromSupportsSignals = (qobject_cast(mFrom) == nullptr); + mToSupportsSignals = (qobject_cast(mTo) == nullptr); + mLogger->debug(QStringLiteral("signal support - from: %1 - to: %2").arg(mFromSupportsSignals).arg(mToSupportsSignals)); - auto sock = qobject_cast(mFrom); + auto sock = qobject_cast(mFrom); qWarning() << "######################### SOCK" << sock; - connect(sock, &QTcpSocket::readyRead, this, [this]() { - mLogger->debug(QStringLiteral(">> DataStream readyRead")); + connect(sock, + &QTcpSocket::readyRead, + this, + [this]() + { + mLogger->debug(QStringLiteral(">> DataStream readyRead")); - QTimer::singleShot(1, this, [this]() { readNext(); }); - }); + QTimer::singleShot(1, this, [this]() { readNext(); }); + }); if (mToSupportsSignals) - connect(mTo, &QIODevice::bytesWritten, this, [this]() { - mLogger->debug(QStringLiteral(">> DataStream write")); + connect(mTo, + &QIODevice::bytesWritten, + this, + [this]() + { + mLogger->debug(QStringLiteral(">> DataStream write")); - mReadyWrite = true; - QTimer::singleShot(1, this, [this]() { readNext(); }); - }); + mReadyWrite = true; + QTimer::singleShot(1, this, [this]() { readNext(); }); + }); QTimer::singleShot(1, this, [this]() { readNext(); }); -} + } -DataStream::~DataStream() -{ + DataStream::~DataStream() + { mLogger->debug(QStringLiteral("~DataStream")); -} + } -void DataStream::readNext() -{ + void DataStream::readNext() + { #if defined(DEBUG_SLOW) && defined(Q_OS_UNIX) mLogger->debug(QStringLiteral("read: slowing down.....")); usleep(2 * 1000 * 1000); @@ -83,38 +103,38 @@ void DataStream::readNext() if (mBuffer.size() > 0) { - mLogger->debug(QStringLiteral("read: ignoring read until buffer was written")); - return; + mLogger->debug(QStringLiteral("read: ignoring read until buffer was written")); + return; } if (mToSupportsSignals && !mReadyWrite) { - mLogger->debug(QStringLiteral("read: won't read until write is ready!")); - return; + mLogger->debug(QStringLiteral("read: won't read until write is ready!")); + return; } if (!mBodyPartial.isEmpty()) { - mBuffer = mBodyPartial; + mBuffer = mBodyPartial; - alreadyRead += mBuffer.size(); - mLogger->debug(QStringLiteral("read: prebody size: %1").arg(mBuffer.size())); + alreadyRead += mBuffer.size(); + mLogger->debug(QStringLiteral("read: prebody size: %1").arg(mBuffer.size())); - mBodyPartial.clear(); + mBodyPartial.clear(); - mLogger->debug(QStringLiteral("read: queueing writeNext after prebody read")); - QTimer::singleShot(1, this, [this]() { writeNext(); }); - return; + mLogger->debug(QStringLiteral("read: queueing writeNext after prebody read")); + QTimer::singleShot(1, this, [this]() { writeNext(); }); + return; } if ((mFrom->bytesAvailable() < 1)) { - mLogger->debug(QStringLiteral("read: no bytes available and not ready read")); + mLogger->debug(QStringLiteral("read: no bytes available and not ready read")); - QTimer::singleShot(1000, this, [this]() { readNext(); }); + QTimer::singleShot(1000, this, [this]() { readNext(); }); - return; + return; } mBuffer = mFrom->read(mBufferSize); @@ -125,57 +145,53 @@ void DataStream::readNext() if (mBuffer.size() < 1) { - mLogger->debug(QStringLiteral("read: cannot read anything")); - deleteLater(); - return; + mLogger->debug(QStringLiteral("read: cannot read anything")); + deleteLater(); + return; } mLogger->debug(QStringLiteral("read: queueing writeNext")); QTimer::singleShot(1, this, [this]() { writeNext(); }); -} + } -void DataStream::writeNext() -{ + void DataStream::writeNext() + { mLogger->debug(QStringLiteral("write: writeNext: %1").arg(mBuffer.size())); if (mBuffer.size() < 1) { - mLogger->debug(QStringLiteral("write: nothing to write")); - QTimer::singleShot(1, this, [this]() { readNext(); }); - return; + mLogger->debug(QStringLiteral("write: nothing to write")); + QTimer::singleShot(1, this, [this]() { readNext(); }); + return; } if (!mTo->isOpen() || !mTo->isWritable()) { - mLogger->debug( - QStringLiteral("write: file error: open? %1 - writable? %2").arg(mTo->isOpen()).arg(mTo->isWritable())); - deleteLater(); - return; + mLogger->debug(QStringLiteral("write: file error: open? %1 - writable? %2").arg(mTo->isOpen()).arg(mTo->isWritable())); + deleteLater(); + return; } if (mToSupportsSignals && !mReadyWrite) { - mLogger->debug(QStringLiteral("write: !mReadyWrite")); + mLogger->debug(QStringLiteral("write: !mReadyWrite")); - return; + return; } if (mToSupportsSignals) - mReadyWrite = false; + mReadyWrite = false; const qint64 size = mTo->write(mBuffer); mLogger->debug(QStringLiteral("write: wrote to buffer %1 bytes").arg(size)); - mLogger->debug(QStringLiteral("write: %1 / %2 bytes done (%3 bytes left until DataStream done)") - .arg(alreadyRead) - .arg(mFileLength) - .arg(mFileLength - alreadyRead)); + mLogger->debug(QStringLiteral("write: %1 / %2 bytes done (%3 bytes left until DataStream done)").arg(alreadyRead).arg(mFileLength).arg(mFileLength - alreadyRead)); if (size < mBuffer.size()) { - mLogger->warning(QStringLiteral("write: cannot write all bytes: %1 / %2 bytes").arg(mBuffer.size()).arg(size)); - deleteLater(); - return; + mLogger->warning(QStringLiteral("write: cannot write all bytes: %1 / %2 bytes").arg(mBuffer.size()).arg(size)); + deleteLater(); + return; } mLogger->debug(QStringLiteral("write: mPos is now %1 and was set to zero now!!").arg(mBuffer.size())); @@ -183,27 +199,27 @@ void DataStream::writeNext() if (alreadyRead == mFileLength) { - mLogger->debug(QStringLiteral("write: DONE!")); - emit signalDone(); - deleteLater(); - return; + mLogger->debug(QStringLiteral("write: DONE!")); + emit signalDone(); + deleteLater(); + return; } if (alreadyRead > mFileLength) { - mLogger->debug(QStringLiteral("write: oops... we read too much!! data may be corrupt!! already read %1 bytes, " - "but content length is only %2 (%1 / %2)") - .arg(alreadyRead) - .arg(mFileLength)); - emit signalDone(); - deleteLater(); - return; + mLogger->debug(QStringLiteral("write: oops... we read too much!! data may be corrupt!! already read %1 bytes, " + "but content length is only %2 (%1 / %2)") + .arg(alreadyRead) + .arg(mFileLength)); + emit signalDone(); + deleteLater(); + return; } if (mToSupportsSignals) - mLogger->debug(QStringLiteral("write: waiting for bytes written to be triggered...")); + mLogger->debug(QStringLiteral("write: waiting for bytes written to be triggered...")); mLogger->debug(QStringLiteral("write: queueing writeNext again")); QTimer::singleShot(1, this, [this]() { writeNext(); }); -} + } } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp index 3aae18fe3..7accbd593 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp @@ -13,14 +13,16 @@ namespace httq { -HttpRequest::HttpRequest(QTcpSocket* cli, AbstractServer* parent) - : QObject(parent), mCli(cli), mLogger(parent->getLoggerFactory()->createLogger(this)) -{ + HttpRequest::HttpRequest(QTcpSocket *cli, AbstractServer *parent) + : QObject(parent) + , mCli(cli) + , mLogger(parent->getLoggerFactory()->createLogger(this)) + { mLogger->debug(QStringLiteral("HttpRequest c_tor")); http_parser_init(&mParser, HTTP_REQUEST); mData.mHttpRquest = this; - mParser.data = static_cast(&mData); + mParser.data = static_cast(&mData); connect(cli, &QTcpSocket::readyRead, this, &HttpRequest::slotReadyRead); connect(cli, &QTcpSocket::disconnected, this, [this]() { qWarning() << "Client disconnected himself!!"; }); @@ -36,110 +38,108 @@ HttpRequest::HttpRequest(QTcpSocket* cli, AbstractServer* parent) mParserSettings.on_message_complete = &HttpRequest::on_message_complete; mParserSettings.on_chunk_header = &HttpRequest::on_chunk_header; mParserSettings.on_chunk_complete = &HttpRequest::on_chunk_complete; -} + } -HttpRequest::~HttpRequest() -{ + HttpRequest::~HttpRequest() + { mLogger->debug(QStringLiteral("~HttpRequest")); if (mCli == nullptr) - return; + return; mLogger->debug(QStringLiteral("mCli flush & close")); mCli->flush(); -} + } -QString HttpRequest::toString() const -{ + QString HttpRequest::toString() const + { return QStringLiteral("HttpRequest(url = '%1', method = %2)").arg(url().toString()).arg(methodString()); -} + } -int HttpRequest::on_message_begin(http_parser* parser) -{ + int HttpRequest::on_message_begin(http_parser *parser) + { dataLogger(parser)->debug(QStringLiteral("on_message_begin")); return 0; -} + } -int HttpRequest::on_url(http_parser* parser, const char* at, size_t length) -{ + int HttpRequest::on_url(http_parser *parser, const char *at, size_t length) + { dataLogger(parser)->debug(QStringLiteral("on_url '%1'").arg(QString::fromUtf8(at, length))); http_parser_url parserUrl; if (http_parser_parse_url(at, length, false, &parserUrl) != 0) { - dataLogger(parser)->debug(QStringLiteral("could not determine url! %1").arg(QString::fromUtf8(at, length))); - return 1; + dataLogger(parser)->debug(QStringLiteral("could not determine url! %1").arg(QString::fromUtf8(at, length))); + return 1; } QUrl url; -#define isUrlFieldSet(field) parserUrl.field_set&(1 << field) +#define isUrlFieldSet(field) parserUrl.field_set & (1 << field) if (isUrlFieldSet(UF_SCHEMA)) - url.setScheme(QString::fromUtf8(at + parserUrl.field_data[UF_SCHEMA].off, parserUrl.field_data[UF_SCHEMA].len)); + url.setScheme(QString::fromUtf8(at + parserUrl.field_data[UF_SCHEMA].off, parserUrl.field_data[UF_SCHEMA].len)); if (parserUrl.field_set & (1 << UF_HOST)) - url.setHost(QString::fromUtf8(at + parserUrl.field_data[UF_HOST].off, parserUrl.field_data[UF_HOST].len)); + url.setHost(QString::fromUtf8(at + parserUrl.field_data[UF_HOST].off, parserUrl.field_data[UF_HOST].len)); if (parserUrl.field_set & (1 << UF_PORT)) { - bool k = false; - QString portString( - QString::fromUtf8(at + parserUrl.field_data[UF_PORT].off, parserUrl.field_data[UF_PORT].len)); - qint16 port = portString.toShort(&k); + bool k = false; + QString portString(QString::fromUtf8(at + parserUrl.field_data[UF_PORT].off, parserUrl.field_data[UF_PORT].len)); + qint16 port = portString.toShort(&k); - if (!k) - { - dataLogger(parser)->warning(QStringLiteral("could not determine port! %1").arg(portString)); - return 1; - } + if (!k) + { + dataLogger(parser)->warning(QStringLiteral("could not determine port! %1").arg(portString)); + return 1; + } - url.setPort(static_cast(port)); + url.setPort(static_cast(port)); } if (parserUrl.field_set & (1 << UF_PATH)) - url.setPath(QString::fromUtf8(at + parserUrl.field_data[UF_PATH].off, parserUrl.field_data[UF_PATH].len)); + url.setPath(QString::fromUtf8(at + parserUrl.field_data[UF_PATH].off, parserUrl.field_data[UF_PATH].len)); - HttpRequestData* reqData = data(parser); + HttpRequestData *reqData = data(parser); if (isUrlFieldSet(UF_QUERY)) { - QUrlQuery q(QString::fromUtf8(at + parserUrl.field_data[UF_QUERY].off, parserUrl.field_data[UF_QUERY].len)); - url.setQuery(q); - reqData->mQuery = q; + QUrlQuery q(QString::fromUtf8(at + parserUrl.field_data[UF_QUERY].off, parserUrl.field_data[UF_QUERY].len)); + url.setQuery(q); + reqData->mQuery = q; } if (isUrlFieldSet(UF_USERINFO)) - url.setUserInfo( - QString::fromUtf8(at + parserUrl.field_data[UF_USERINFO].off, parserUrl.field_data[UF_USERINFO].len)); + url.setUserInfo(QString::fromUtf8(at + parserUrl.field_data[UF_USERINFO].off, parserUrl.field_data[UF_USERINFO].len)); #undef isUrlFieldSet dataLogger(parser)->debug(QStringLiteral("final url = %1").arg(url.toString())); reqData->mUrl = url; return 0; -} + } -int HttpRequest::on_status(http_parser* parser, const char*, size_t) -{ + int HttpRequest::on_status(http_parser *parser, const char *, size_t) + { dataLogger(parser)->debug(QStringLiteral("on_status")); return 0; -} + } -int HttpRequest::on_header_field(http_parser* parser, const char* at, size_t length) -{ + int HttpRequest::on_header_field(http_parser *parser, const char *at, size_t length) + { dataLogger(parser)->debug(QStringLiteral("on_header_field")); data(parser)->mCurrentHeaderField = QString::fromUtf8(at, length); return 0; -} + } -int HttpRequest::on_header_value(http_parser* parser, const char* at, size_t length) -{ + int HttpRequest::on_header_value(http_parser *parser, const char *at, size_t length) + { dataLogger(parser)->debug(QStringLiteral("on_header_value")); QString value(QString::fromUtf8(at, length)); - HttpRequestData* reqdata = data(parser); + HttpRequestData *reqdata = data(parser); reqdata->mHeaders.insert(reqdata->mCurrentHeaderField, value); @@ -148,53 +148,52 @@ int HttpRequest::on_header_value(http_parser* parser, const char* at, size_t len reqdata->mCurrentHeaderField.clear(); return 0; -} + } -int HttpRequest::on_headers_complete(http_parser* parser) -{ + int HttpRequest::on_headers_complete(http_parser *parser) + { dataLogger(parser)->debug(QStringLiteral("on_headers_complete")); return 0; -} + } -int HttpRequest::on_body(http_parser* parser, const char* at, size_t length) -{ + int HttpRequest::on_body(http_parser *parser, const char *at, size_t length) + { dataLogger(parser)->debug(QStringLiteral("on_body")); data(parser)->mBodyPartial = QByteArray(at, length); data(parser)->mDone = true; return 0; -} + } -int HttpRequest::on_message_complete(http_parser* parser) -{ + int HttpRequest::on_message_complete(http_parser *parser) + { dataLogger(parser)->debug(QStringLiteral("on_message_complete")); data(parser)->mDone = true; return 0; -} + } -int HttpRequest::on_chunk_header(http_parser* parser) -{ + int HttpRequest::on_chunk_header(http_parser *parser) + { dataLogger(parser)->debug(QStringLiteral("on_chunk_header")); return 0; -} + } -int HttpRequest::on_chunk_complete(http_parser* parser) -{ + int HttpRequest::on_chunk_complete(http_parser *parser) + { dataLogger(parser)->debug(QStringLiteral("on_chunk_complete")); return 0; -} + } -qint64 HttpRequest::availableBytes() const -{ + qint64 HttpRequest::availableBytes() const + { return (mContentLength - alreadyRead); -} + } -DataStream* HttpRequest::createDataStreamToClient(int status, const QString& contentType, QIODevice* from, - qint64 fileSize, qint64 bufferSize) -{ + DataStream *HttpRequest::createDataStreamToClient(int status, const QString &contentType, QIODevice *from, qint64 fileSize, qint64 bufferSize) + { mLogger->debug(QStringLiteral("createDataStreamToClient")); writeStatusHeader(status); @@ -204,33 +203,30 @@ DataStream* HttpRequest::createDataStreamToClient(int status, const QString& con mCli->write("\r\n"); return new DataStream(from, mCli, {}, fileSize, bufferSize, mLogger->getLoggerFactory(), this); -} + } -DataStream* HttpRequest::createDataStreamFromClient(QIODevice* to, qint64 fileSize, qint64 bufferSize) -{ + DataStream *HttpRequest::createDataStreamFromClient(QIODevice *to, qint64 fileSize, qint64 bufferSize) + { mLogger->debug(QStringLiteral("createDataStreamFromClient")); return new DataStream(mCli, to, mData.mBodyPartial, fileSize, bufferSize, mLogger->getLoggerFactory(), this); -} + } -void HttpRequest::write(int status, const QJsonValue& jsonValue) -{ + void HttpRequest::write(int status, const QJsonValue &jsonValue) + { QJsonDocument doc; if (jsonValue.isArray()) - doc = QJsonDocument(jsonValue.toArray()); + doc = QJsonDocument(jsonValue.toArray()); else - doc = QJsonDocument(jsonValue.toObject()); + doc = QJsonDocument(jsonValue.toObject()); write(status, doc.toJson(), QStringLiteral("application/json")); -} + } -void HttpRequest::write(int status, const QByteArray& data, const QString& contentType) -{ - mLogger->debug(QStringLiteral("write to client: status = %1, data (size) = %2, contentType = %3") - .arg(status) - .arg(data.size()) - .arg(contentType)); + void HttpRequest::write(int status, const QByteArray &data, const QString &contentType) + { + mLogger->debug(QStringLiteral("write to client: status = %1, data (size) = %2, contentType = %3").arg(status).arg(data.size()).arg(contentType)); writeStatusHeader(status); addHeader(QStringLiteral("Content-Type"), contentType); @@ -240,118 +236,116 @@ void HttpRequest::write(int status, const QByteArray& data, const QString& conte mCli->write("\r\n"); mCli->write(data); -} + } -void HttpRequest::writeStatusHeader(int status) -{ + void HttpRequest::writeStatusHeader(int status) + { QString header(QStringLiteral("HTTP/1.1 %1 %2\r\n").arg(status).arg(QStringLiteral("OK"))); mLogger->debug(QStringLiteral("write to client: header = %1").arg(header)); mCli->write(header.toUtf8()); -} + } -void HttpRequest::addHeader(const QString& key, const QString& value) -{ + void HttpRequest::addHeader(const QString &key, const QString &value) + { mHeaders.insert(key, value); -} + } -void HttpRequest::writeHeaders() -{ + void HttpRequest::writeHeaders() + { QString headers; QMapIterator it(mHeaders); while (it.hasNext()) { - it.next(); - headers += QStringLiteral("%1: %2\r\n").arg(it.key(), it.value()); + it.next(); + headers += QStringLiteral("%1: %2\r\n").arg(it.key(), it.value()); } mLogger->debug(QStringLiteral("write to client: headers = %1").arg(headers)); mCli->write(headers.toUtf8()); -} + } -void HttpRequest::slotReadyRead() -{ + void HttpRequest::slotReadyRead() + { mLogger->debug(QStringLiteral("slotReadyRead")); if (mDone) { - mLogger->debug(QStringLiteral("slotReadyRead: already marked as done")); - return; + mLogger->debug(QStringLiteral("slotReadyRead: already marked as done")); + return; } mCli->startTransaction(); while (mCli->bytesAvailable() && !mData.mDone) { - mLogger->debug(QStringLiteral("slotReadyRead: bytes available")); - const QByteArray data(mCli->read(10000)); + mLogger->debug(QStringLiteral("slotReadyRead: bytes available")); + const QByteArray data(mCli->read(10000)); - int dataSize = data.size(); + int dataSize = data.size(); - size_t size = http_parser_execute(&mParser, &mParserSettings, data.constData(), static_cast(dataSize)); + size_t size = http_parser_execute(&mParser, &mParserSettings, data.constData(), static_cast(dataSize)); - if (size < static_cast(dataSize)) - { - mLogger->error(QStringLiteral("http parser error: %1") - .arg(QString::fromUtf8(http_errno_name(HTTP_PARSER_ERRNO(&mParser))))); - mCli->commitTransaction(); - deleteLater(); - return; - } + if (size < static_cast(dataSize)) + { + mLogger->error(QStringLiteral("http parser error: %1").arg(QString::fromUtf8(http_errno_name(HTTP_PARSER_ERRNO(&mParser))))); + mCli->commitTransaction(); + deleteLater(); + return; + } } if (mData.mDone) { - mLogger->debug(QStringLiteral("slotReadyRead: now marked as done")); + mLogger->debug(QStringLiteral("slotReadyRead: now marked as done")); - mDone = true; + mDone = true; - mLogger->debug(QStringLiteral("slotReadyRead: method = %1").arg(methodString())); + mLogger->debug(QStringLiteral("slotReadyRead: method = %1").arg(methodString())); - auto it = mData.mHeaders.constFind(QStringLiteral("Upgrade")); + auto it = mData.mHeaders.constFind(QStringLiteral("Upgrade")); - if (it != mData.mHeaders.constEnd() && (*it).toLower() == QStringLiteral("websocket")) - { - mLogger->debug(QStringLiteral("slotReadyRead: Upgrade: %1").arg(*it)); - disconnect(mCli, &QTcpSocket::readyRead, nullptr, nullptr); + if (it != mData.mHeaders.constEnd() && (*it).toLower() == QStringLiteral("websocket")) + { + mLogger->debug(QStringLiteral("slotReadyRead: Upgrade: %1").arg(*it)); + disconnect(mCli, &QTcpSocket::readyRead, nullptr, nullptr); - mCli->rollbackTransaction(); - mCli->setParent(nullptr); - auto cli = mCli; - mCli = nullptr; - emit signalUpgrade(cli); + mCli->rollbackTransaction(); + mCli->setParent(nullptr); + auto cli = mCli; + mCli = nullptr; + emit signalUpgrade(cli); - deleteLater(); - return; - } - - it = mData.mHeaders.constFind(QStringLiteral("Content-Length")); - - if (it != mData.mHeaders.constEnd()) - { - bool k = false; - mContentLength = (*it).toLongLong(&k); - - if (!k) - { - mLogger->error(QStringLiteral("slotReadyRead: invalid content length: ").arg(*it)); - deleteLater(); - return; - } - } - - alreadyRead = mData.mBodyPartial.size(); - - mLogger->debug( - QStringLiteral("slotReadyRead: already read %1 / %2 bytes").arg(alreadyRead).arg(contentLength())); - - mCli->commitTransaction(); - emit signalReady(); + deleteLater(); return; + } + + it = mData.mHeaders.constFind(QStringLiteral("Content-Length")); + + if (it != mData.mHeaders.constEnd()) + { + bool k = false; + mContentLength = (*it).toLongLong(&k); + + if (!k) + { + mLogger->error(QStringLiteral("slotReadyRead: invalid content length: ").arg(*it)); + deleteLater(); + return; + } + } + + alreadyRead = mData.mBodyPartial.size(); + + mLogger->debug(QStringLiteral("slotReadyRead: already read %1 / %2 bytes").arg(alreadyRead).arg(contentLength())); + + mCli->commitTransaction(); + emit signalReady(); + return; } mLogger->debug(QStringLiteral("slotReadyRead: commit transaction")); mCli->commitTransaction(); -} + } } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp index ba1f1ae46..a43821fce 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp @@ -5,44 +5,46 @@ namespace httq { -Logger* LoggerFactory::createLogger(QObject* parent) -{ + Logger *LoggerFactory::createLogger(QObject *parent) + { return new Logger(this, parent); -} + } -Logger::Logger(LoggerFactory* loggerFactory, QObject* parent) : QObject(parent), mLoggerFactory(loggerFactory) -{ + Logger::Logger(LoggerFactory *loggerFactory, QObject *parent) + : QObject(parent) + , mLoggerFactory(loggerFactory) + { if (parent == nullptr) { - mPath = QStringLiteral("Global"); + mPath = QStringLiteral("Global"); } else { - mPath = QString::fromUtf8(parent->metaObject()->className()); + mPath = QString::fromUtf8(parent->metaObject()->className()); } -} + } -void Logger::debug(const QString& message) -{ + void Logger::debug(const QString &message) + { qtLogger(QStringLiteral("DEBUG"), qWarning()) << message; -} + } -void Logger::warning(const QString& message) -{ + void Logger::warning(const QString &message) + { qtLogger(QStringLiteral("WARNING"), qWarning()) << message; -} + } -void Logger::error(const QString& message) -{ + void Logger::error(const QString &message) + { qtLogger(QStringLiteral("ERROR"), qCritical()) << message; -} + } -QDebug Logger::qtLogger(const QString& type, QDebug logger) -{ + QDebug Logger::qtLogger(const QString &type, QDebug logger) + { QDebug d(logger.noquote()); d << type << mPath << ":"; return d; -} + } } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h index 040a72554..a4ef0a8c7 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h @@ -31,141 +31,150 @@ typedef unsigned __int64 uint64_t; #endif #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -/* Forward declarations */ -struct http_parser; -struct http_parser_settings; + /* Forward declarations */ + struct http_parser; + struct http_parser_settings; -typedef struct http_parser http_parser; -typedef struct http_parser_settings http_parser_settings; + typedef struct http_parser http_parser; + typedef struct http_parser_settings http_parser_settings; -typedef int (*http_data_cb)(http_parser*, const char*, size_t); -typedef int (*http_cb)(http_parser*); + typedef int (*http_data_cb)(http_parser *, const char *, size_t); + typedef int (*http_cb)(http_parser *); -#define HTTP_STATUS_MAP(XX) \ - XX(100, CONTINUE, Continue) \ - XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ - XX(102, PROCESSING, Processing) \ - XX(200, OK, OK) \ - XX(201, CREATED, Created) \ - XX(202, ACCEPTED, Accepted) \ - XX(203, NON_AUTHORITATIVE_INFORMATION, Non - Authoritative Information) \ - XX(204, NO_CONTENT, No Content) \ - XX(205, RESET_CONTENT, Reset Content) \ - XX(206, PARTIAL_CONTENT, Partial Content) \ - XX(207, MULTI_STATUS, Multi - Status) \ - XX(208, ALREADY_REPORTED, Already Reported) \ - XX(226, IM_USED, IM Used) \ - XX(300, MULTIPLE_CHOICES, Multiple Choices) \ - XX(301, MOVED_PERMANENTLY, Moved Permanently) \ - XX(302, FOUND, Found) \ - XX(303, SEE_OTHER, See Other) \ - XX(304, NOT_MODIFIED, Not Modified) \ - XX(305, USE_PROXY, Use Proxy) \ - XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ - XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ - XX(400, BAD_REQUEST, Bad Request) \ - XX(401, UNAUTHORIZED, Unauthorized) \ - XX(402, PAYMENT_REQUIRED, Payment Required) \ - XX(403, FORBIDDEN, Forbidden) \ - XX(404, NOT_FOUND, Not Found) \ - XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ - XX(406, NOT_ACCEPTABLE, Not Acceptable) \ - XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ - XX(408, REQUEST_TIMEOUT, Request Timeout) \ - XX(409, CONFLICT, Conflict) \ - XX(410, GONE, Gone) \ - XX(411, LENGTH_REQUIRED, Length Required) \ - XX(412, PRECONDITION_FAILED, Precondition Failed) \ - XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ - XX(414, URI_TOO_LONG, URI Too Long) \ - XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ - XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ - XX(417, EXPECTATION_FAILED, Expectation Failed) \ - XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ - XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ - XX(423, LOCKED, Locked) \ - XX(424, FAILED_DEPENDENCY, Failed Dependency) \ - XX(426, UPGRADE_REQUIRED, Upgrade Required) \ - XX(428, PRECONDITION_REQUIRED, Precondition Required) \ - XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ - XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ - XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ - XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ - XX(501, NOT_IMPLEMENTED, Not Implemented) \ - XX(502, BAD_GATEWAY, Bad Gateway) \ - XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ - XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ - XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ - XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ - XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ - XX(508, LOOP_DETECTED, Loop Detected) \ - XX(510, NOT_EXTENDED, Not Extended) \ - XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) +#define HTTP_STATUS_MAP(XX) \ + XX(100, CONTINUE, Continue) \ + XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ + XX(102, PROCESSING, Processing) \ + XX(200, OK, OK) \ + XX(201, CREATED, Created) \ + XX(202, ACCEPTED, Accepted) \ + XX(203, NON_AUTHORITATIVE_INFORMATION, Non - Authoritative Information) \ + XX(204, NO_CONTENT, No Content) \ + XX(205, RESET_CONTENT, Reset Content) \ + XX(206, PARTIAL_CONTENT, Partial Content) \ + XX(207, MULTI_STATUS, Multi - Status) \ + XX(208, ALREADY_REPORTED, Already Reported) \ + XX(226, IM_USED, IM Used) \ + XX(300, MULTIPLE_CHOICES, Multiple Choices) \ + XX(301, MOVED_PERMANENTLY, Moved Permanently) \ + XX(302, FOUND, Found) \ + XX(303, SEE_OTHER, See Other) \ + XX(304, NOT_MODIFIED, Not Modified) \ + XX(305, USE_PROXY, Use Proxy) \ + XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ + XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ + XX(400, BAD_REQUEST, Bad Request) \ + XX(401, UNAUTHORIZED, Unauthorized) \ + XX(402, PAYMENT_REQUIRED, Payment Required) \ + XX(403, FORBIDDEN, Forbidden) \ + XX(404, NOT_FOUND, Not Found) \ + XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ + XX(406, NOT_ACCEPTABLE, Not Acceptable) \ + XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ + XX(408, REQUEST_TIMEOUT, Request Timeout) \ + XX(409, CONFLICT, Conflict) \ + XX(410, GONE, Gone) \ + XX(411, LENGTH_REQUIRED, Length Required) \ + XX(412, PRECONDITION_FAILED, Precondition Failed) \ + XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ + XX(414, URI_TOO_LONG, URI Too Long) \ + XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ + XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ + XX(417, EXPECTATION_FAILED, Expectation Failed) \ + XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ + XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ + XX(423, LOCKED, Locked) \ + XX(424, FAILED_DEPENDENCY, Failed Dependency) \ + XX(426, UPGRADE_REQUIRED, Upgrade Required) \ + XX(428, PRECONDITION_REQUIRED, Precondition Required) \ + XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ + XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ + XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ + XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ + XX(501, NOT_IMPLEMENTED, Not Implemented) \ + XX(502, BAD_GATEWAY, Bad Gateway) \ + XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ + XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ + XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ + XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ + XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ + XX(508, LOOP_DETECTED, Loop Detected) \ + XX(510, NOT_EXTENDED, Not Extended) \ + XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) -enum http_status { + enum http_status + { #define XX(num, name, string) HTTP_STATUS_##name = num, HTTP_STATUS_MAP(XX) #undef XX -}; + }; -#define HTTP_METHOD_MAP(XX) \ - XX(0, DELETE, DELETE) \ - XX(1, GET, GET) \ - XX(2, HEAD, HEAD) \ - XX(3, POST, POST) \ - XX(4, PUT, PUT) \ - \ - XX(5, CONNECT, CONNECT) \ - XX(6, OPTIONS, OPTIONS) \ - XX(7, TRACE, TRACE) \ - \ - XX(8, COPY, COPY) \ - XX(9, LOCK, LOCK) \ - XX(10, MKCOL, MKCOL) \ - XX(11, MOVE, MOVE) \ - XX(12, PROPFIND, PROPFIND) \ - XX(13, PROPPATCH, PROPPATCH) \ - XX(14, SEARCH, SEARCH) \ - XX(15, UNLOCK, UNLOCK) \ - XX(16, BIND, BIND) \ - XX(17, REBIND, REBIND) \ - XX(18, UNBIND, UNBIND) \ - XX(19, ACL, ACL) \ - \ - XX(20, REPORT, REPORT) \ - XX(21, MKACTIVITY, MKACTIVITY) \ - XX(22, CHECKOUT, CHECKOUT) \ - XX(23, MERGE, MERGE) \ - \ - XX(24, MSEARCH, M - SEARCH) \ - XX(25, NOTIFY, NOTIFY) \ - XX(26, SUBSCRIBE, SUBSCRIBE) \ - XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ - \ - XX(28, PATCH, PATCH) \ - XX(29, PURGE, PURGE) \ - \ - XX(30, MKCALENDAR, MKCALENDAR) \ - \ - XX(31, LINK, LINK) \ - XX(32, UNLINK, UNLINK) \ - \ - XX(33, SOURCE, SOURCE) +#define HTTP_METHOD_MAP(XX) \ + XX(0, DELETE, DELETE) \ + XX(1, GET, GET) \ + XX(2, HEAD, HEAD) \ + XX(3, POST, POST) \ + XX(4, PUT, PUT) \ + \ + XX(5, CONNECT, CONNECT) \ + XX(6, OPTIONS, OPTIONS) \ + XX(7, TRACE, TRACE) \ + \ + XX(8, COPY, COPY) \ + XX(9, LOCK, LOCK) \ + XX(10, MKCOL, MKCOL) \ + XX(11, MOVE, MOVE) \ + XX(12, PROPFIND, PROPFIND) \ + XX(13, PROPPATCH, PROPPATCH) \ + XX(14, SEARCH, SEARCH) \ + XX(15, UNLOCK, UNLOCK) \ + XX(16, BIND, BIND) \ + XX(17, REBIND, REBIND) \ + XX(18, UNBIND, UNBIND) \ + XX(19, ACL, ACL) \ + \ + XX(20, REPORT, REPORT) \ + XX(21, MKACTIVITY, MKACTIVITY) \ + XX(22, CHECKOUT, CHECKOUT) \ + XX(23, MERGE, MERGE) \ + \ + XX(24, MSEARCH, M - SEARCH) \ + XX(25, NOTIFY, NOTIFY) \ + XX(26, SUBSCRIBE, SUBSCRIBE) \ + XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ + \ + XX(28, PATCH, PATCH) \ + XX(29, PURGE, PURGE) \ + \ + XX(30, MKCALENDAR, MKCALENDAR) \ + \ + XX(31, LINK, LINK) \ + XX(32, UNLINK, UNLINK) \ + \ + XX(33, SOURCE, SOURCE) -enum http_method { + enum http_method + { #define XX(num, name, string) HTTP_##name = num, HTTP_METHOD_MAP(XX) #undef XX -}; + }; -enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; + enum http_parser_type + { + HTTP_REQUEST, + HTTP_RESPONSE, + HTTP_BOTH + }; -enum flags { + enum flags + { F_CHUNKED = 1 << 0, F_CONNECTION_KEEP_ALIVE = 1 << 1, F_CONNECTION_CLOSE = 1 << 2, @@ -175,57 +184,60 @@ enum flags { F_SKIPBODY = 1 << 6, F_CONTENTLENGTH = 1 << 7, F_TRANSFER_ENCODING = 1 << 8 -}; + }; -#define HTTP_ERRNO_MAP(XX) \ - \ - XX(OK, "success") \ - \ - XX(CB_message_begin, "the on_message_begin callback failed") \ - XX(CB_url, "the on_url callback failed") \ - XX(CB_header_field, "the on_header_field callback failed") \ - XX(CB_header_value, "the on_header_value callback failed") \ - XX(CB_headers_complete, "the on_headers_complete callback failed") \ - XX(CB_body, "the on_body callback failed") \ - XX(CB_message_complete, "the on_message_complete callback failed") \ - XX(CB_status, "the on_status callback failed") \ - XX(CB_chunk_header, "the on_chunk_header callback failed") \ - XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ - \ - XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ - XX(HEADER_OVERFLOW, "too many header bytes seen; overflow detected") \ - XX(CLOSED_CONNECTION, "data received after completed connection: close message") \ - XX(INVALID_VERSION, "invalid HTTP version") \ - XX(INVALID_STATUS, "invalid HTTP status code") \ - XX(INVALID_METHOD, "invalid HTTP method") \ - XX(INVALID_URL, "invalid URL") \ - XX(INVALID_HOST, "invalid host") \ - XX(INVALID_PORT, "invalid port") \ - XX(INVALID_PATH, "invalid path") \ - XX(INVALID_QUERY_STRING, "invalid query string") \ - XX(INVALID_FRAGMENT, "invalid fragment") \ - XX(LF_EXPECTED, "LF character expected") \ - XX(INVALID_HEADER_TOKEN, "invalid character in header") \ - XX(INVALID_CONTENT_LENGTH, "invalid character in content-length header") \ - XX(UNEXPECTED_CONTENT_LENGTH, "unexpected content-length header") \ - XX(INVALID_CHUNK_SIZE, "invalid character in chunk size header") \ - XX(INVALID_CONSTANT, "invalid constant string") \ - XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state") \ - XX(STRICT, "strict mode assertion failed") \ - XX(PAUSED, "parser is paused") \ - XX(UNKNOWN, "an unknown error occurred") \ - XX(INVALID_TRANSFER_ENCODING, "request has invalid transfer-encoding") +#define HTTP_ERRNO_MAP(XX) \ + \ + XX(OK, "success") \ + \ + XX(CB_message_begin, "the on_message_begin callback failed") \ + XX(CB_url, "the on_url callback failed") \ + XX(CB_header_field, "the on_header_field callback failed") \ + XX(CB_header_value, "the on_header_value callback failed") \ + XX(CB_headers_complete, "the on_headers_complete callback failed") \ + XX(CB_body, "the on_body callback failed") \ + XX(CB_message_complete, "the on_message_complete callback failed") \ + XX(CB_status, "the on_status callback failed") \ + XX(CB_chunk_header, "the on_chunk_header callback failed") \ + XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ + \ + XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ + XX(HEADER_OVERFLOW, "too many header bytes seen; overflow detected") \ + XX(CLOSED_CONNECTION, "data received after completed connection: close message") \ + XX(INVALID_VERSION, "invalid HTTP version") \ + XX(INVALID_STATUS, "invalid HTTP status code") \ + XX(INVALID_METHOD, "invalid HTTP method") \ + XX(INVALID_URL, "invalid URL") \ + XX(INVALID_HOST, "invalid host") \ + XX(INVALID_PORT, "invalid port") \ + XX(INVALID_PATH, "invalid path") \ + XX(INVALID_QUERY_STRING, "invalid query string") \ + XX(INVALID_FRAGMENT, "invalid fragment") \ + XX(LF_EXPECTED, "LF character expected") \ + XX(INVALID_HEADER_TOKEN, "invalid character in header") \ + XX(INVALID_CONTENT_LENGTH, "invalid character in content-length header") \ + XX(UNEXPECTED_CONTENT_LENGTH, "unexpected content-length header") \ + XX(INVALID_CHUNK_SIZE, "invalid character in chunk size header") \ + XX(INVALID_CONSTANT, "invalid constant string") \ + XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state") \ + XX(STRICT, "strict mode assertion failed") \ + XX(PAUSED, "parser is paused") \ + XX(UNKNOWN, "an unknown error occurred") \ + XX(INVALID_TRANSFER_ENCODING, "request has invalid transfer-encoding") #define HTTP_ERRNO_GEN(n, s) HPE_##n, -enum http_errno { HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) }; + enum http_errno + { + HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) + }; #undef HTTP_ERRNO_GEN #define HTTP_PARSER_ERRNO(p) ((enum http_errno)(p)->http_errno) -struct http_parser -{ + struct http_parser + { unsigned int type : 2; unsigned int flags : 8; @@ -246,11 +258,11 @@ struct http_parser unsigned int upgrade : 1; - void* data; -}; + void *data; + }; -struct http_parser_settings -{ + struct http_parser_settings + { http_cb on_message_begin; http_data_cb on_url; http_data_cb on_status; @@ -262,9 +274,10 @@ struct http_parser_settings http_cb on_chunk_header; http_cb on_chunk_complete; -}; + }; -enum http_parser_url_fields { + enum http_parser_url_fields + { UF_SCHEMA = 0, UF_HOST = 1, UF_PORT = 2, @@ -273,47 +286,47 @@ enum http_parser_url_fields { UF_FRAGMENT = 5, UF_USERINFO = 6, UF_MAX = 7 -}; + }; -struct http_parser_url -{ + struct http_parser_url + { uint16_t field_set; uint16_t port; struct { - uint16_t off; - uint16_t len; + uint16_t off; + uint16_t len; } field_data[UF_MAX]; -}; + }; -unsigned long http_parser_version(void); + unsigned long http_parser_version(void); -void http_parser_init(http_parser* parser, enum http_parser_type type); + void http_parser_init(http_parser *parser, enum http_parser_type type); -void http_parser_settings_init(http_parser_settings* settings); + void http_parser_settings_init(http_parser_settings *settings); -size_t http_parser_execute(http_parser* parser, const http_parser_settings* settings, const char* data, size_t len); + size_t http_parser_execute(http_parser *parser, const http_parser_settings *settings, const char *data, size_t len); -int http_should_keep_alive(const http_parser* parser); + int http_should_keep_alive(const http_parser *parser); -const char* http_method_str(enum http_method m); + const char *http_method_str(enum http_method m); -const char* http_status_str(enum http_status s); + const char *http_status_str(enum http_status s); -const char* http_errno_name(enum http_errno err); + const char *http_errno_name(enum http_errno err); -const char* http_errno_description(enum http_errno err); + const char *http_errno_description(enum http_errno err); -void http_parser_url_init(struct http_parser_url* u); + void http_parser_url_init(struct http_parser_url *u); -int http_parser_parse_url(const char* buf, size_t buflen, int is_connect, struct http_parser_url* u); + int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, struct http_parser_url *u); -void http_parser_pause(http_parser* parser, int paused); + void http_parser_pause(http_parser *parser, int paused); -int http_body_is_final(const http_parser* parser); + int http_body_is_final(const http_parser *parser); -void http_parser_set_max_header_size(uint32_t size); + void http_parser_set_max_header_size(uint32_t size); #ifdef __cplusplus } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h index cffdfbf2f..7e57b061c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h @@ -12,35 +12,32 @@ class QWebSocketServer; namespace httq { -class HttpRequest; -class LoggerFactory; -class Logger; + class HttpRequest; + class LoggerFactory; + class Logger; -class HTTQ_EXPORT AbstractServer : public QObject -{ + class HTTQ_EXPORT AbstractServer : public QObject + { Q_OBJECT public: - explicit AbstractServer(QObject* parent = nullptr); + explicit AbstractServer(QObject *parent = nullptr); - virtual bool newHttpConnection(HttpRequest* request) = 0; + virtual bool newHttpConnection(HttpRequest *request) = 0; - #ifdef QT6_WEBSOCKETS_AVAILABLE - virtual QWebSocketServer* webSocketServer() const - { - return nullptr; - } +#ifdef QT6_WEBSOCKETS_AVAILABLE + virtual QWebSocketServer *webSocketServer() const { return nullptr; } #endif - virtual LoggerFactory* createLoggerFactory(); - LoggerFactory* getLoggerFactory(); - bool listen(qint16 port, const QHostAddress& host = QHostAddress::Any); + virtual LoggerFactory *createLoggerFactory(); + LoggerFactory *getLoggerFactory(); + bool listen(qint16 port, const QHostAddress &host = QHostAddress::Any); private slots: void slotNewConnection(); private: - QTcpServer* mSvr; - LoggerFactory* mLoggerFactory{nullptr}; - Logger* mLogger; -}; + QTcpServer *mSvr; + LoggerFactory *mLoggerFactory{nullptr}; + Logger *mLogger; + }; } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h index 044bd0473..682fbc9e9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h @@ -10,15 +10,20 @@ class QIODevice; namespace httq { -class HttpRequest; + class HttpRequest; -class HTTQ_EXPORT DataStream : public QObject -{ + class HTTQ_EXPORT DataStream : public QObject + { Q_OBJECT private: - explicit DataStream(QIODevice* from, QIODevice* to, const QByteArray& bodyPartial, qint64 fileLength, - size_t bufferSize, LoggerFactory* loggerFactory, QObject* parent = nullptr); + explicit DataStream(QIODevice *from, + QIODevice *to, + const QByteArray &bodyPartial, + qint64 fileLength, + size_t bufferSize, + LoggerFactory *loggerFactory, + QObject *parent = nullptr); public: ~DataStream(); @@ -33,8 +38,8 @@ class HTTQ_EXPORT DataStream : public QObject QByteArray mBuffer; QByteArray mBodyPartial; - QIODevice* mFrom; - QIODevice* mTo; + QIODevice *mFrom; + QIODevice *mTo; qint64 mBufferSize; qint64 alreadyRead{0}; @@ -45,5 +50,5 @@ class HTTQ_EXPORT DataStream : public QObject signals: void signalDone(); -}; + }; } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h index 47bf1ec43..99f1bb3e0 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h @@ -15,13 +15,13 @@ class QIODevice; namespace httq { -class AbstractServer; -class Logger; -class DataStream; -class HttpRequest; + class AbstractServer; + class Logger; + class DataStream; + class HttpRequest; -struct HttpRequestData -{ + struct HttpRequestData + { QByteArray mData; QUrl mUrl; QString mCurrentHeaderField; @@ -29,64 +29,42 @@ struct HttpRequestData bool mDone{false}; QByteArray mBodyPartial; QUrlQuery mQuery; - HttpRequest* mHttpRquest; -}; + HttpRequest *mHttpRquest; + }; -class HTTQ_EXPORT HttpRequest : public QObject -{ + class HTTQ_EXPORT HttpRequest : public QObject + { Q_OBJECT private: - explicit HttpRequest(QTcpSocket* cli, AbstractServer* parent = nullptr); + explicit HttpRequest(QTcpSocket *cli, AbstractServer *parent = nullptr); public: ~HttpRequest(); qint64 availableBytes() const; - http_method method() const - { - return (enum http_method)mParser.method; - } + http_method method() const { return (enum http_method)mParser.method; } - QString methodString() const - { - return QString::fromUtf8(http_method_str(method())); - } + QString methodString() const { return QString::fromUtf8(http_method_str(method())); } - const QUrl& url() const - { - return mData.mUrl; - } + const QUrl &url() const { return mData.mUrl; } - const QUrlQuery& query() const - { - return mData.mQuery; - } + const QUrlQuery &query() const { return mData.mQuery; } - qint64 contentLength() const - { - return mContentLength; - } + qint64 contentLength() const { return mContentLength; } - const QMap& requestHeaders() const - { - return mData.mHeaders; - } + const QMap &requestHeaders() const { return mData.mHeaders; } - Logger* logger() - { - return mLogger; - } + Logger *logger() { return mLogger; } QString toString() const; - void addHeader(const QString& key, const QString& value); - void write(int status, const QByteArray& data, const QString& contentType); - void write(int status, const QJsonValue& jsonValue); - DataStream* createDataStreamFromClient(QIODevice* to, qint64 fileSize, qint64 bufferSize = 1024 * 1024); - DataStream* createDataStreamToClient(int status, const QString& contentType, QIODevice* from, qint64 fileSize, - qint64 bufferSize = 1024 * 1024); + void addHeader(const QString &key, const QString &value); + void write(int status, const QByteArray &data, const QString &contentType); + void write(int status, const QJsonValue &jsonValue); + DataStream *createDataStreamFromClient(QIODevice *to, qint64 fileSize, qint64 bufferSize = 1024 * 1024); + DataStream *createDataStreamToClient(int status, const QString &contentType, QIODevice *from, qint64 fileSize, qint64 bufferSize = 1024 * 1024); friend class DataStream; @@ -96,28 +74,22 @@ class HTTQ_EXPORT HttpRequest : public QObject void writeStatusHeader(int status); void writeHeaders(); - static int on_message_begin(http_parser* parser); - static int on_url(http_parser* parser, const char* at, size_t length); - static int on_status(http_parser* parser, const char* at, size_t length); - static int on_header_field(http_parser* parser, const char* at, size_t length); - static int on_header_value(http_parser* parser, const char* at, size_t length); - static int on_headers_complete(http_parser* parser); - static int on_body(http_parser* parser, const char* at, size_t length); - static int on_message_complete(http_parser* parser); - static int on_chunk_header(http_parser* parser); - static int on_chunk_complete(http_parser* parser); + static int on_message_begin(http_parser *parser); + static int on_url(http_parser *parser, const char *at, size_t length); + static int on_status(http_parser *parser, const char *at, size_t length); + static int on_header_field(http_parser *parser, const char *at, size_t length); + static int on_header_value(http_parser *parser, const char *at, size_t length); + static int on_headers_complete(http_parser *parser); + static int on_body(http_parser *parser, const char *at, size_t length); + static int on_message_complete(http_parser *parser); + static int on_chunk_header(http_parser *parser); + static int on_chunk_complete(http_parser *parser); - static HttpRequestData* data(http_parser* parser) - { - return static_cast(parser->data); - } + static HttpRequestData *data(http_parser *parser) { return static_cast(parser->data); } - static Logger* dataLogger(http_parser* parser) - { - return static_cast(parser->data)->mHttpRquest->logger(); - } + static Logger *dataLogger(http_parser *parser) { return static_cast(parser->data)->mHttpRquest->logger(); } - QTcpSocket* mCli; + QTcpSocket *mCli; http_parser mParser; http_parser_settings mParserSettings; HttpRequestData mData; @@ -125,13 +97,13 @@ class HTTQ_EXPORT HttpRequest : public QObject qint64 mContentLength{0}; qint64 alreadyRead{0}; QMap mHeaders; - Logger* mLogger; + Logger *mLogger; private slots: void slotReadyRead(); signals: - void signalUpgrade(QTcpSocket* sock); + void signalUpgrade(QTcpSocket *sock); void signalReady(); -}; + }; } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h index 1ed8bb377..ea9aa1f6f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h @@ -8,40 +8,43 @@ namespace httq { -class Logger; + class Logger; -class HTTQ_EXPORT LoggerFactory : public QObject -{ + class HTTQ_EXPORT LoggerFactory : public QObject + { Q_OBJECT public: - LoggerFactory(QObject* parent) : QObject(parent) {} - - virtual Logger* createLogger(QObject* parent); -}; - -class HTTQ_EXPORT Logger : public QObject -{ - Q_OBJECT - public: - Logger(LoggerFactory* loggerFactory, QObject* parent); - - virtual void debug(const QString& message); - virtual void warning(const QString& message); - virtual void error(const QString& message); - - virtual LoggerFactory* getLoggerFactory() const + LoggerFactory(QObject *parent) + : QObject(parent) { - Q_ASSERT(mLoggerFactory); - return mLoggerFactory; + } + + virtual Logger *createLogger(QObject *parent); + }; + + class HTTQ_EXPORT Logger : public QObject + { + Q_OBJECT + public: + Logger(LoggerFactory *loggerFactory, QObject *parent); + + virtual void debug(const QString &message); + virtual void warning(const QString &message); + virtual void error(const QString &message); + + virtual LoggerFactory *getLoggerFactory() const + { + Q_ASSERT(mLoggerFactory); + return mLoggerFactory; } protected: QPointer mLoggerFactory; private: - QDebug qtLogger(const QString& type, QDebug debug); + QDebug qtLogger(const QString &type, QDebug debug); QString mPath; -}; + }; } // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.cpp old mode 100755 new mode 100644 index d2b387b89..47cfbed8b --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.cpp @@ -11,183 +11,183 @@ namespace TetraRadio { -ConvertFromJson::ConvertFromJson(const std::shared_ptr &rxHandler, - const char *loggerName) : m_rxHandler(rxHandler) - , m_bWarnedOnce(false) - , m_logger(N_LogView::getLogger(loggerName)) {} - -bool ConvertFromJson::handleTelegram(const QByteArray &baJson, int &recvCounter) -{ - using namespace TrainingAreaBase::TetraIcd; - - if (baJson.isEmpty()) - return false; - const QJsonObject obj = QJsonDocument::fromJson(baJson).object(); - const QJsonValue sendCounter = obj.value(QStringLiteral("counter")); - if (!sendCounter.isUndefined()) + ConvertFromJson::ConvertFromJson(const std::shared_ptr &rxHandler, const char *loggerName) + : m_rxHandler(rxHandler) + , m_bWarnedOnce(false) + , m_logger(N_LogView::getLogger(loggerName)) { - if (!sendCounter.isDouble()) - return false; - recvCounter = sendCounter.toInt(-1); - DEBUG_LOG(m_logger) << "Incoming telegram with Id " << obj.value(QStringLiteral("type")).toString(); - if (recvCounter < 0) - return false; } - const QJsonValue typeId = obj.value(QStringLiteral("typeId")); - if (!typeId.isDouble()) + + bool ConvertFromJson::handleTelegram(const QByteArray &baJson, int &recvCounter) { - ERROR_LOG(m_logger) << "Can not read type id: " << baJson; - return false; - } - const QJsonObject data = obj.value(QStringLiteral("data")).toObject(); - try - { - switch (typeId.toInt()) + using namespace TrainingAreaBase::TetraIcd; + + if (baJson.isEmpty()) + return false; + const QJsonObject obj = QJsonDocument::fromJson(baJson).object(); + const QJsonValue sendCounter = obj.value(QStringLiteral("counter")); + if (!sendCounter.isUndefined()) { - case Constraints::id(): - { - auto ack = TrainingAreaBase::TetraIcd::Acknowledge::fromJson(data); - handleAcknowledge(ack.timeStamp, ack.ackCounter); - break; + if (!sendCounter.isDouble()) + return false; + recvCounter = sendCounter.toInt(-1); + DEBUG_LOG(m_logger) << "Incoming telegram with Id " << obj.value(QStringLiteral("type")).toString(); + if (recvCounter < 0) + return false; } - case Constraints::id(): - rxData(ManipulationReport::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentOperationalState::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentConfigurationReport::fromJson(data)); - break; - case Constraints::id(): - rxData(CtaDataError::fromJson(data)); - break; - case Constraints::id(): - rxData(RestoreRadioReadiness::fromJson(data)); - break; - case Constraints::id(): - rxData(PositionReport::fromJson(data)); - break; - case Constraints::id(): - rxData(PositionReportWithMountedEquipments::fromJson(data)); - break; - case Constraints::id(): - rxData(MineTriggered::fromJson(data)); - break; - case Constraints::id(): - rxData(DefinitionIed::fromJson(data)); - break; - case Constraints::id(): - rxData(StateIed::fromJson(data)); - break; - case Constraints::id(): - rxData(DusSingleMineState::fromJson(data)); - break; - case Constraints::id(): - rxData(StateChangeDirect::fromJson(data)); - break; - case Constraints::id(): - rxData(StateChangeIndirect::fromJson(data)); - break; - case Constraints::id(): - rxData(OperatorAction::fromJson(data)); - break; - case Constraints::id(): - rxData(SelectiveReammunition::fromJson(data)); - break; - case Constraints::id(): - rxData(StateChange::fromJson(data)); - break; - case Constraints::id(): - rxData(FunctionalAreaEntry::fromJson(data)); - break; - case Constraints::id(): - rxData(OpaquePayloadDataIn::fromJson(data)); - break; - case Constraints::id(): - rxData(SpecialSensorData::fromJson(data)); - break; - case Constraints::id(): - rxData(MinelayerTrailerData::fromJson(data)); - break; - case Constraints::id(): - rxData(MinelayerThrowerData::fromJson(data)); - break; - case Constraints::id(): - rxData(MinelayerTrailerPosition::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentEvent::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentGearAssignment::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentGearChargeState::fromJson(data)); - break; - case Constraints::id(): - rxData(BiteReport::fromJson(data)); - break; - case Constraints::id(): - rxData(EquipmentGearEvent::fromJson(data)); - break; - case Constraints::id(): - rxData(ParticipantSwVersions::fromJson(data)); - break; - case Constraints::id(): - rxData(ParticipantModeReport::fromJson(data)); - break; - case Constraints::id(): - rxData(ParticipantConfigurationReport::fromJson(data)); - break; - case Constraints::id(): - rxData(SanitationRepair::fromJson(data)); - break; - case Constraints::id(): - rxData(SanitaryMaterialStockReport::fromJson(data)); - break; - case Constraints::id(): - rxData(Sanitation::fromJson(data)); - break; - case Constraints::id(): - rxData(EmergencyCall::fromJson(data)); - break; - case Constraints::id(): - rxData(ApacheLaserDesignation::fromJson(data)); - break; - case Constraints::id(): - handleTetraConnectionChanged(ProxyConnectionState::fromJson(data).connectedToSystem); - break; - case Constraints::id(): - - break; - default: - WARNING_LOG(m_logger) << "Handler for telegram Id " << typeId.toInt() - << " not yet implemented (" << baJson << ")"; + const QJsonValue typeId = obj.value(QStringLiteral("typeId")); + if (!typeId.isDouble()) + { + ERROR_LOG(m_logger) << "Can not read type id: " << baJson; return false; } + const QJsonObject data = obj.value(QStringLiteral("data")).toObject(); + try + { + switch (typeId.toInt()) + { + case Constraints::id(): + { + auto ack = TrainingAreaBase::TetraIcd::Acknowledge::fromJson(data); + handleAcknowledge(ack.timeStamp, ack.ackCounter); + break; + } + case Constraints::id(): + rxData(ManipulationReport::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentOperationalState::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentConfigurationReport::fromJson(data)); + break; + case Constraints::id(): + rxData(CtaDataError::fromJson(data)); + break; + case Constraints::id(): + rxData(RestoreRadioReadiness::fromJson(data)); + break; + case Constraints::id(): + rxData(PositionReport::fromJson(data)); + break; + case Constraints::id(): + rxData(PositionReportWithMountedEquipments::fromJson(data)); + break; + case Constraints::id(): + rxData(MineTriggered::fromJson(data)); + break; + case Constraints::id(): + rxData(DefinitionIed::fromJson(data)); + break; + case Constraints::id(): + rxData(StateIed::fromJson(data)); + break; + case Constraints::id(): + rxData(DusSingleMineState::fromJson(data)); + break; + case Constraints::id(): + rxData(StateChangeDirect::fromJson(data)); + break; + case Constraints::id(): + rxData(StateChangeIndirect::fromJson(data)); + break; + case Constraints::id(): + rxData(OperatorAction::fromJson(data)); + break; + case Constraints::id(): + rxData(SelectiveReammunition::fromJson(data)); + break; + case Constraints::id(): + rxData(StateChange::fromJson(data)); + break; + case Constraints::id(): + rxData(FunctionalAreaEntry::fromJson(data)); + break; + case Constraints::id(): + rxData(OpaquePayloadDataIn::fromJson(data)); + break; + case Constraints::id(): + rxData(SpecialSensorData::fromJson(data)); + break; + case Constraints::id(): + rxData(MinelayerTrailerData::fromJson(data)); + break; + case Constraints::id(): + rxData(MinelayerThrowerData::fromJson(data)); + break; + case Constraints::id(): + rxData(MinelayerTrailerPosition::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentEvent::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentGearAssignment::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentGearChargeState::fromJson(data)); + break; + case Constraints::id(): + rxData(BiteReport::fromJson(data)); + break; + case Constraints::id(): + rxData(EquipmentGearEvent::fromJson(data)); + break; + case Constraints::id(): + rxData(ParticipantSwVersions::fromJson(data)); + break; + case Constraints::id(): + rxData(ParticipantModeReport::fromJson(data)); + break; + case Constraints::id(): + rxData(ParticipantConfigurationReport::fromJson(data)); + break; + case Constraints::id(): + rxData(SanitationRepair::fromJson(data)); + break; + case Constraints::id(): + rxData(SanitaryMaterialStockReport::fromJson(data)); + break; + case Constraints::id(): + rxData(Sanitation::fromJson(data)); + break; + case Constraints::id(): + rxData(EmergencyCall::fromJson(data)); + break; + case Constraints::id(): + rxData(ApacheLaserDesignation::fromJson(data)); + break; + case Constraints::id(): + handleTetraConnectionChanged(ProxyConnectionState::fromJson(data).connectedToSystem); + break; + case Constraints::id(): + + break; + default: + WARNING_LOG(m_logger) << "Handler for telegram Id " << typeId.toInt() << " not yet implemented (" << baJson << ")"; + return false; + } + } + catch (const std::exception &e) + { + WARNING_LOG(m_logger) << "Could not parse json: " << e.what() << " (" << baJson << ")"; + return false; + } + return true; } - catch (const std::exception &e) + + template void ConvertFromJson::rxData(const T &data) { - WARNING_LOG(m_logger) << "Could not parse json: " << e.what() << " (" << baJson << ")"; - return false; + if (!m_rxHandler) + { + if (!m_bWarnedOnce) + { + ERROR_LOG(m_logger) << "No RecvFromTab available"; + m_bWarnedOnce = true; + } + return; + } + return m_rxHandler->rxData(data); } - return true; + } - -template -void ConvertFromJson::rxData(const T &data) -{ - if (!m_rxHandler) - { - if (!m_bWarnedOnce) - { - ERROR_LOG(m_logger) << "No RecvFromTab available"; - m_bWarnedOnce = true; - } - return; - } - return m_rxHandler->rxData(data); -} - -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.h old mode 100755 new mode 100644 index 5c927b4b6..4ed614d8c --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_from_json.h @@ -9,27 +9,27 @@ class XDR_Wrapper_it; namespace TetraRadio { -class ConvertFromJson -{ -public: - explicit ConvertFromJson(const std::shared_ptr &rxHandler, const char *loggerName); - virtual ~ConvertFromJson() = default; + class ConvertFromJson + { + public: + explicit ConvertFromJson(const std::shared_ptr &rxHandler, const char *loggerName); + virtual ~ConvertFromJson() = default; -protected: - bool handleTelegram(const QByteArray &baJson, int &recvCounter); - virtual void handleAcknowledge(qint64 timeStamp, int counter) = 0; - virtual void handleTetraConnectionChanged(bool bConnected) = 0; -private: - template - void rxData(const T &data); + protected: + bool handleTelegram(const QByteArray &baJson, int &recvCounter); + virtual void handleAcknowledge(qint64 timeStamp, int counter) = 0; + virtual void handleTetraConnectionChanged(bool bConnected) = 0; -private: - - static TrainingAreaBase::TetraIcd::BiteError convertBiteError(const QJsonObject &obj); - std::shared_ptr m_rxHandler; -protected: - NGL::INGLLogger &m_logger; - bool m_bWarnedOnce; -}; + private: + template void rxData(const T &data); -} + private: + static TrainingAreaBase::TetraIcd::BiteError convertBiteError(const QJsonObject &obj); + std::shared_ptr m_rxHandler; + + protected: + NGL::INGLLogger &m_logger; + bool m_bWarnedOnce; + }; + +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.cpp old mode 100755 new mode 100644 index 0fd9dd096..ee81aeeb9 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.cpp @@ -9,281 +9,279 @@ namespace TetraRadio { -ConvertToJson::ConvertToJson(const char *loggerName) - : QObject() - , SendToTab() - , m_bConnected(false) - , m_logger(N_LogView::getLogger(loggerName)) -{ - resetSendCounter(); -} - -ConvertToJson::~ConvertToJson() -{} - -TrainingAreaBase::SendToTab::HandleState ConvertToJson::canHandleTelegram(int equipmentNumber, int telegramId) const -{ - if (!m_bConnected) - return HandleState::No; - - using namespace TrainingAreaBase::TetraIcd; - if (telegramId == Constraints::id() || - telegramId == Constraints::id()) - return HandleState::YesShare; - - Q_UNUSED(equipmentNumber) - return HandleState::YesFallback; -} - -void ConvertToJson::resetSendCounter() -{ - m_sendCounter = 1; -} - -bool ConvertToJson::sendTele(const QByteArray &ba) -{ - const QJsonDocument doc(QJsonDocument::fromJson(ba)); - QJsonObject obj = doc.object(); - const QJsonValue typeId = obj[QStringLiteral("typeId")]; - if (typeId.toInt() == TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) + ConvertToJson::ConvertToJson(const char *loggerName) + : QObject() + , SendToTab() + , m_bConnected(false) + , m_logger(N_LogView::getLogger(loggerName)) { - NOTICE_LOG(m_logger) << "Outgoing ack"; + resetSendCounter(); + } + + ConvertToJson::~ConvertToJson() {} + + TrainingAreaBase::SendToTab::HandleState ConvertToJson::canHandleTelegram(int equipmentNumber, int telegramId) const + { + if (!m_bConnected) + return HandleState::No; + + using namespace TrainingAreaBase::TetraIcd; + if (telegramId == Constraints::id() || telegramId == Constraints::id()) + return HandleState::YesShare; + + Q_UNUSED(equipmentNumber) + return HandleState::YesFallback; + } + + void ConvertToJson::resetSendCounter() + { + m_sendCounter = 1; + } + + bool ConvertToJson::sendTele(const QByteArray &ba) + { + const QJsonDocument doc(QJsonDocument::fromJson(ba)); + QJsonObject obj = doc.object(); + const QJsonValue typeId = obj[QStringLiteral("typeId")]; + if (typeId.toInt() == TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) + { + NOTICE_LOG(m_logger) << "Outgoing ack"; + emit outgoingMessage(ba); + return true; + } + + obj[QStringLiteral("counter")] = m_sendCounter++; + const QByteArray baToSend = QJsonDocument(obj).toJson(QJsonDocument::Compact); + NOTICE_LOG(m_logger) << "Outgoing message: " << typeId.toInt(); + emit outgoingMessage(baToSend); + return true; + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Acknowledge &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandBite &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Init &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SetVulnerabilityModel &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandEquipmentConfigurationReport &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandVulnerabilityStateChange &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::LanguageSelection &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::EquipmentMessage &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::EquipmentMessageOC &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateSingleExplosion &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateAreaExplosion &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateMineArea &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::MineAreaSingleMineState &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateNContamination &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateCContamination &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DeactivateEffectSimulation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ModifyAreaEffectSimulationName &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::PauseEffectSimulation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ResumeEffectSimulation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::MineTriggered &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DusMineReactivation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateFunctionalArea &data) + { + return sendToTx(&data); + } + + bool TetraRadio::ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateDusSingleMine &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseEnvironmentData &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseStateData &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantSwVersionsRequest &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::OpaquePayloadDataOut &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::TechnicalArea &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CesHitInformation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CesHitRequest &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantMode &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandParticipantMode &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantConfiguration &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandParticipantConfiguration &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Sanitation &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SelectiveReammunition &data) + { + DEBUG_LOG(m_logger) << "ConvertToJson::txData SelectiveReammunition"; + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SetDevicePowerRequest &data) + { + return sendToTx(&data); + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::OcCommand &data) + { + DEBUG_LOG(m_logger) << "ConvertToJson::txData OcCommand"; + return sendToTx(&data); + } + + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::UAVPerformMission &data) + { + Q_UNUSED(data); + return false; + } + + bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::UAVChangeState &data) + { + Q_UNUSED(data); + return false; + } + + bool ConvertToJson::sendToTx(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data) + { + if (!m_bConnected) + return false; + QJsonObject obj; + obj[QStringLiteral("data")] = data->toJson(); + obj[QStringLiteral("type")] = data->type(); + obj[QStringLiteral("typeId")] = data->id(); + if (data->id() != TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) + obj[QStringLiteral("counter")] = m_sendCounter++; + const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); + if (data->id() != TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) + DEBUG_LOG(m_logger) << "Sending tele: " << ba; emit outgoingMessage(ba); return true; } - obj[QStringLiteral("counter")] = m_sendCounter++; - const QByteArray baToSend = QJsonDocument(obj).toJson(QJsonDocument::Compact); - NOTICE_LOG(m_logger) << "Outgoing message: " << typeId.toInt(); - emit outgoingMessage(baToSend); - return true; } - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Acknowledge &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandBite &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Init &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SetVulnerabilityModel &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandEquipmentConfigurationReport &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandVulnerabilityStateChange &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::LanguageSelection &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::EquipmentMessage &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::EquipmentMessageOC &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateSingleExplosion &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateAreaExplosion &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateMineArea &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::MineAreaSingleMineState &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateNContamination &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateCContamination &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DeactivateEffectSimulation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ModifyAreaEffectSimulationName &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::PauseEffectSimulation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ResumeEffectSimulation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::MineTriggered &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DusMineReactivation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateFunctionalArea &data) -{ - return sendToTx(&data); -} - -bool TetraRadio::ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CreateDusSingleMine &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseEnvironmentData &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseStateData &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantSwVersionsRequest &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::OpaquePayloadDataOut &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::TechnicalArea &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CesHitInformation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::CesHitRequest &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantMode &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandParticipantMode &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ParticipantConfiguration &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::DemandParticipantConfiguration &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::Sanitation &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SelectiveReammunition &data) -{ - DEBUG_LOG(m_logger) << "ConvertToJson::txData SelectiveReammunition"; - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::SetDevicePowerRequest &data) -{ - return sendToTx(&data); -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::OcCommand &data) -{ - DEBUG_LOG(m_logger) << "ConvertToJson::txData OcCommand"; - return sendToTx(&data); -} - - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::UAVPerformMission &data) -{ - Q_UNUSED(data); - return false; -} - -bool ConvertToJson::txData(const TrainingAreaBase::TetraIcd::UAVChangeState &data) -{ - Q_UNUSED(data); - return false; -} - -bool ConvertToJson::sendToTx(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data) -{ - if (!m_bConnected) - return false; - QJsonObject obj; - obj[QStringLiteral("data")] = data->toJson(); - obj[QStringLiteral("type")] = data->type(); - obj[QStringLiteral("typeId")] = data->id(); - if (data->id() != TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) - obj[QStringLiteral("counter")] = m_sendCounter++; - const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); - if (data->id() != TrainingAreaBase::TetraIcd::TelegramId::BESTAETIGUNG) - DEBUG_LOG(m_logger) << "Sending tele: " << ba; - emit outgoingMessage(ba); - return true; -} - -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.h old mode 100755 new mode 100644 index 500e97ebd..696231637 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/convert_to_json.h @@ -9,74 +9,78 @@ namespace TetraRadio { -class ConvertToJson final : public QObject, public TrainingAreaBase::SendToTab -{ - Q_OBJECT -public: - explicit ConvertToJson(const char *loggerName); - ~ConvertToJson(); + class ConvertToJson final + : public QObject + , public TrainingAreaBase::SendToTab + { + Q_OBJECT + public: + explicit ConvertToJson(const char *loggerName); + ~ConvertToJson(); - const char *name() const override { return "Tetra"; } - HandleState canHandleTelegram(int equipmentNumber, int telegramId) const override; - void resetSendCounter() override; - bool sendTele(const QByteArray &ba); + const char *name() const override { return "Tetra"; } + HandleState canHandleTelegram(int equipmentNumber, int telegramId) const override; + void resetSendCounter() override; + bool sendTele(const QByteArray &ba); - void setConnected(bool bConnected) { m_bConnected = bConnected; } -public: - bool txData(const TrainingAreaBase::TetraIcd::Acknowledge &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DemandBite &data) override; - bool txData(const TrainingAreaBase::TetraIcd::Init &data) override; - bool txData(const TrainingAreaBase::TetraIcd::SetVulnerabilityModel &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DemandEquipmentConfigurationReport &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DemandVulnerabilityStateChange &data) override; - bool txData(const TrainingAreaBase::TetraIcd::LanguageSelection &data) override; - bool txData(const TrainingAreaBase::TetraIcd::EquipmentMessage &data) override; - bool txData(const TrainingAreaBase::TetraIcd::EquipmentMessageOC &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateSingleExplosion &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateAreaExplosion &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateMineArea &data) override; - bool txData(const TrainingAreaBase::TetraIcd::MineAreaSingleMineState &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateNContamination &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateCContamination &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DeactivateEffectSimulation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ModifyAreaEffectSimulationName &data) override; - bool txData(const TrainingAreaBase::TetraIcd::PauseEffectSimulation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ResumeEffectSimulation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::MineTriggered &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DusMineReactivation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateFunctionalArea &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CreateDusSingleMine &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ExerciseEnvironmentData &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ExerciseStateData &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ParticipantSwVersionsRequest &data) override; - bool txData(const TrainingAreaBase::TetraIcd::OpaquePayloadDataOut &data) override; - bool txData(const TrainingAreaBase::TetraIcd::TechnicalArea &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CesHitInformation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::CesHitRequest &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ParticipantMode &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DemandParticipantMode &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ParticipantConfiguration &data) override; - bool txData(const TrainingAreaBase::TetraIcd::DemandParticipantConfiguration &data) override; - bool txData(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) override; - bool txData(const TrainingAreaBase::TetraIcd::Sanitation &data) override; - bool txData(const TrainingAreaBase::TetraIcd::SelectiveReammunition &data) override; - bool txData(const TrainingAreaBase::TetraIcd::SetDevicePowerRequest &data) override; - bool txData(const TrainingAreaBase::TetraIcd::OcCommand &data) override; - bool txData(const TrainingAreaBase::TetraIcd::UAVPerformMission &data) override; - bool txData(const TrainingAreaBase::TetraIcd::UAVChangeState &) override ; - bool txData(const TrainingAreaBase::TetraIcd::ExFireReadiness &) override { return false; }; - bool txData(const TrainingAreaBase::TetraIcd::ExFiredReport &) override { return false; }; - bool txData(const TrainingAreaBase::TetraIcd::ExConfirmationReport &) override { return false; }; + void setConnected(bool bConnected) { m_bConnected = bConnected; } - bool sendToTx(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data); -Q_SIGNALS: - void outgoingMessage(const QByteArray &msg); -protected: -protected: - NGL::INGLLogger &m_logger; - int m_sendCounter; - bool m_bConnected; -}; + public: + bool txData(const TrainingAreaBase::TetraIcd::Acknowledge &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DemandBite &data) override; + bool txData(const TrainingAreaBase::TetraIcd::Init &data) override; + bool txData(const TrainingAreaBase::TetraIcd::SetVulnerabilityModel &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DemandEquipmentConfigurationReport &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DemandVulnerabilityStateChange &data) override; + bool txData(const TrainingAreaBase::TetraIcd::LanguageSelection &data) override; + bool txData(const TrainingAreaBase::TetraIcd::EquipmentMessage &data) override; + bool txData(const TrainingAreaBase::TetraIcd::EquipmentMessageOC &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateSingleExplosion &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateAreaExplosion &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateMineArea &data) override; + bool txData(const TrainingAreaBase::TetraIcd::MineAreaSingleMineState &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateNContamination &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateCContamination &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DeactivateEffectSimulation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ModifyAreaEffectSimulationName &data) override; + bool txData(const TrainingAreaBase::TetraIcd::PauseEffectSimulation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ResumeEffectSimulation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::MineTriggered &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DusMineReactivation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateFunctionalArea &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CreateDusSingleMine &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ExerciseEnvironmentData &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ExerciseStateData &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ParticipantSwVersionsRequest &data) override; + bool txData(const TrainingAreaBase::TetraIcd::OpaquePayloadDataOut &data) override; + bool txData(const TrainingAreaBase::TetraIcd::TechnicalArea &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CesHitInformation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::CesHitRequest &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ParticipantMode &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DemandParticipantMode &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ParticipantConfiguration &data) override; + bool txData(const TrainingAreaBase::TetraIcd::DemandParticipantConfiguration &data) override; + bool txData(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) override; + bool txData(const TrainingAreaBase::TetraIcd::Sanitation &data) override; + bool txData(const TrainingAreaBase::TetraIcd::SelectiveReammunition &data) override; + bool txData(const TrainingAreaBase::TetraIcd::SetDevicePowerRequest &data) override; + bool txData(const TrainingAreaBase::TetraIcd::OcCommand &data) override; + bool txData(const TrainingAreaBase::TetraIcd::UAVPerformMission &data) override; + bool txData(const TrainingAreaBase::TetraIcd::UAVChangeState &) override; + bool txData(const TrainingAreaBase::TetraIcd::ExFireReadiness &) override { return false; }; + bool txData(const TrainingAreaBase::TetraIcd::ExFiredReport &) override { return false; }; + bool txData(const TrainingAreaBase::TetraIcd::ExConfirmationReport &) override { return false; }; + + bool sendToTx(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data); + Q_SIGNALS: + void outgoingMessage(const QByteArray &msg); + + protected: + protected: + NGL::INGLLogger &m_logger; + int m_sendCounter; + bool m_bConnected; + }; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.cpp old mode 100755 new mode 100644 index 29a4b491f..6321fcf54 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.cpp @@ -21,211 +21,199 @@ namespace TetraRadio { - - -std::shared_ptr TetraJsonPlugin::createInterface(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb, - const std::shared_ptr &, - const std::shared_ptr &, - NGL::Settings *settings) -{ - return std::make_shared(pdp, recvFromTabCb, settings); -} - -TetraJsonInterfaceImpl::TetraJsonInterfaceImpl(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb, - NGL::Settings *settings) - : m_logger(N_LogView::getLogger("TAB.Plugin.TetraJsonInterfaceImpl")) - , m_socketDispatcher(new SocketDispatcher(pdp, recvFromTabCb)) - , m_pdp(pdp) - , m_prtCnvApp(nullptr) - , m_exerciseId(0) - , m_radioGrpId(0) -{ - Q_UNUSED(settings); - N_CoPrtCnv::CoPrtCnvTelegramConverter::setUse2BytesForSingleFireDiameter( - settings->settings()->value(QLatin1String("AES/use2BytesForSingleFireDiameter"), true).toBool()); - N_CoPrtCnv::CoPrtCnvTelegramConverter::setUsePvSan( - settings->settings()->value(QLatin1String("TrainingAreaBase/UsePvSan"), false).toBool()); - ERROR_LOG(m_logger) << "hello i got this!"; -} - -TetraJsonInterfaceImpl::~TetraJsonInterfaceImpl() -{ - cleanupProcess(); -} - -bool TetraJsonInterfaceImpl::init() -{ - m_exerciseId = m_pdp->exerciseId(); - NOTICE_LOG(m_logger) << "Our exercise id is " << m_exerciseId; - - if (m_exerciseId == 0) - if (!checkConfigTemplates()) - return false; - - return updatePrtCnv(); -} - -void TetraJsonInterfaceImpl::exerciseChanged() -{ - NOTICE_LOG(m_logger) << "TetraJsonInterfaceImpl::exerciseChanged"; - if (m_pdp->exerciseRadioGroup().id() != m_radioGrpId) - if (!updatePrtCnv()) - ERROR_LOG(m_logger) << "Error changing PrtCnv state from radio grp id: " - << m_radioGrpId - << " to " << m_pdp->exerciseRadioGroup().id(); -} - -bool TetraJsonInterfaceImpl::updatePrtCnv() -{ - int newRadioGrpId = m_pdp->exerciseRadioGroup().id(); - - if (newRadioGrpId == m_radioGrpId) + std::shared_ptr TetraJsonPlugin::createInterface(TrainingAreaBase::Plugin::DataProvider *pdp, + const std::shared_ptr &recvFromTabCb, + const std::shared_ptr &, + const std::shared_ptr &, + NGL::Settings *settings) { - NOTICE_LOG(m_logger) << "No need to update PrtCnv configuration - radio group did not change: " << m_radioGrpId; + return std::make_shared(pdp, recvFromTabCb, settings); + } + + TetraJsonInterfaceImpl::TetraJsonInterfaceImpl(TrainingAreaBase::Plugin::DataProvider *pdp, + const std::shared_ptr &recvFromTabCb, + NGL::Settings *settings) + : m_logger(N_LogView::getLogger("TAB.Plugin.TetraJsonInterfaceImpl")) + , m_socketDispatcher(new SocketDispatcher(pdp, recvFromTabCb)) + , m_pdp(pdp) + , m_prtCnvApp(nullptr) + , m_exerciseId(0) + , m_radioGrpId(0) + { + Q_UNUSED(settings); + N_CoPrtCnv::CoPrtCnvTelegramConverter::setUse2BytesForSingleFireDiameter( + settings->settings()->value(QLatin1String("AES/use2BytesForSingleFireDiameter"), true).toBool()); + N_CoPrtCnv::CoPrtCnvTelegramConverter::setUsePvSan(settings->settings()->value(QLatin1String("TrainingAreaBase/UsePvSan"), false).toBool()); + ERROR_LOG(m_logger) << "hello i got this!"; + } + + TetraJsonInterfaceImpl::~TetraJsonInterfaceImpl() + { + cleanupProcess(); + } + + bool TetraJsonInterfaceImpl::init() + { + m_exerciseId = m_pdp->exerciseId(); + NOTICE_LOG(m_logger) << "Our exercise id is " << m_exerciseId; + + if (m_exerciseId == 0) + if (!checkConfigTemplates()) + return false; + + return updatePrtCnv(); + } + + void TetraJsonInterfaceImpl::exerciseChanged() + { + NOTICE_LOG(m_logger) << "TetraJsonInterfaceImpl::exerciseChanged"; + if (m_pdp->exerciseRadioGroup().id() != m_radioGrpId) + if (!updatePrtCnv()) + ERROR_LOG(m_logger) << "Error changing PrtCnv state from radio grp id: " << m_radioGrpId << " to " << m_pdp->exerciseRadioGroup().id(); + } + + bool TetraJsonInterfaceImpl::updatePrtCnv() + { + int newRadioGrpId = m_pdp->exerciseRadioGroup().id(); + + if (newRadioGrpId == m_radioGrpId) + { + NOTICE_LOG(m_logger) << "No need to update PrtCnv configuration - radio group did not change: " << m_radioGrpId; + return true; + } + + NOTICE_LOG(m_logger) << "Our radio group id is " << newRadioGrpId; + if (newRadioGrpId > 0) + { + + QFile::remove(iniFileOut()); + if (!QFile::copy(iniFileIn(), iniFileOut())) + { + ERROR_LOG(m_logger) << "Error creating ini file for PrtCnv: " << iniFileOut(); + return false; + } + + ProjectDataManagement::RadioGroup radioGrp = m_pdp->exerciseRadioGroup(); + Q_UNUSED(radioGrp); + + { + QSettings s(iniFileOut(), QSettings::IniFormat); + s.setValue(QStringLiteral("Common/LogTelegramPath"), QStringLiteral("logdata/ex_%1").arg(m_exerciseId)); + s.setValue(QStringLiteral("Common/LogTelegramPrefix"), QStringLiteral("PrtCnv_ex_%1").arg(m_exerciseId)); + s.setValue(QStringLiteral("Central/HostName"), QStringLiteral("directConnection")); + // RadioGroup API simplified - radio configuration members removed + s.setValue(QStringLiteral("Radio/UseScrambling"), m_pdp->useTetraScrambling() ? 1 : 0); + s.setValue(QStringLiteral("Injection/Port"), m_socketDispatcher->randomListenPort()); + NOTICE_LOG(m_logger) << "TetraJson Injection/Port = " << s.value(QStringLiteral("Injection/Port")).toInt(); + s.sync(); + } + + + if (!startPrtCnv()) + return false; + } + else + cleanupProcess(); + + + m_radioGrpId = newRadioGrpId; + return true; } - NOTICE_LOG(m_logger) << "Our radio group id is " << newRadioGrpId; - if (newRadioGrpId > 0) + bool TetraJsonInterfaceImpl::checkConfigTemplates() { - - QFile::remove(iniFileOut()); - if (!QFile::copy(iniFileIn(), iniFileOut())) + if (!QFile::exists(iniFileIn())) { - ERROR_LOG(m_logger) << "Error creating ini file for PrtCnv: " << iniFileOut(); - return false; + INFO_LOG(m_logger) << "Creating " << iniFileIn(); + if (!QFile::copy(QStringLiteral(":/PrtCnv.dat"), iniFileIn())) + { + ERROR_LOG(m_logger) << "Error creating " << iniFileIn(); + return false; + } + else + QFile(iniFileIn()).setPermissions(QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner); } - ProjectDataManagement::RadioGroup radioGrp = m_pdp->exerciseRadioGroup(); - Q_UNUSED(radioGrp); - + if (!QFile::exists(playerIdsFile())) { - QSettings s(iniFileOut(), QSettings::IniFormat); - s.setValue(QStringLiteral("Common/LogTelegramPath"), QStringLiteral("logdata/ex_%1").arg(m_exerciseId)); - s.setValue(QStringLiteral("Common/LogTelegramPrefix"), QStringLiteral("PrtCnv_ex_%1").arg(m_exerciseId)); - s.setValue(QStringLiteral("Central/HostName"), QStringLiteral("directConnection")); - // RadioGroup API simplified - radio configuration members removed - s.setValue(QStringLiteral("Radio/UseScrambling"), m_pdp->useTetraScrambling() ? 1 : 0); - s.setValue(QStringLiteral("Injection/Port"), m_socketDispatcher->randomListenPort()); - NOTICE_LOG(m_logger) << "TetraJson Injection/Port = " << s.value(QStringLiteral("Injection/Port")).toInt(); - s.sync(); + INFO_LOG(m_logger) << "Creating " << playerIdsFile(); + if (!QFile::copy(QStringLiteral(":/playerIds.dat"), playerIdsFile())) + { + ERROR_LOG(m_logger) << "Error creating " << playerIdsFile(); + return false; + } + else + QFile(playerIdsFile()).setPermissions(QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner); } - - if (!startPrtCnv()) - return false; - } - else - cleanupProcess(); - - - m_radioGrpId = newRadioGrpId; - - return true; -} - -bool TetraJsonInterfaceImpl::checkConfigTemplates() -{ - if (!QFile::exists(iniFileIn())) - { - INFO_LOG(m_logger) << "Creating " << iniFileIn(); - if (!QFile::copy(QStringLiteral(":/PrtCnv.dat"), iniFileIn())) - { - ERROR_LOG(m_logger) << "Error creating " << iniFileIn(); - return false; - } - else - QFile(iniFileIn()).setPermissions(QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner); + return true; } - if (!QFile::exists(playerIdsFile())) + bool TetraJsonInterfaceImpl::startPrtCnv() { - INFO_LOG(m_logger) << "Creating " << playerIdsFile(); - if (!QFile::copy(QStringLiteral(":/playerIds.dat"), playerIdsFile())) - { - ERROR_LOG(m_logger) << "Error creating " << playerIdsFile(); - return false; - } - else - QFile(playerIdsFile()).setPermissions(QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner); + NOTICE_LOG(m_logger) << "Starting PrtCnv (intern)"; + cleanupProcess(); + m_prtCnvApp = new PrtCnv::PrtCnvApplication; + const QSqlDatabase db = m_pdp->databaseConnection(); + m_prtCnvApp->setDatabaseConnectionParams(db.driverName(), db.hostName(), db.databaseName(), m_pdp->databaseSchemaName(), db.userName(), db.password()); + m_prtCnvApp->setExerciseId(m_pdp->exerciseId()); + m_prtCnvApp->setConfigFile(iniFileOut()); + m_prtCnvApp->startApp(); + m_socketDispatcher->init(m_prtCnvApp); + + onTetraConnectionChanged(false); + connect(m_socketDispatcher.get(), &SocketDispatcher::tetraConnectionChanged, this, &TetraJsonInterfaceImpl::onTetraConnectionChanged); + + connect(m_socketDispatcher.get(), &SocketDispatcher::warehouseMessage, this, &TetraJsonInterfaceImpl::directMessage); + + return true; } - return true; -} + std::shared_ptr TetraJsonInterfaceImpl::sendToTab() + { + return m_socketDispatcher->sendToTab(); + } -bool TetraJsonInterfaceImpl::startPrtCnv() -{ - NOTICE_LOG(m_logger) << "Starting PrtCnv (intern)"; - cleanupProcess(); - m_prtCnvApp = new PrtCnv::PrtCnvApplication; - const QSqlDatabase db = m_pdp->databaseConnection(); - m_prtCnvApp->setDatabaseConnectionParams(db.driverName(), - db.hostName(), - db.databaseName(), - m_pdp->databaseSchemaName(), - db.userName(), - db.password()); - m_prtCnvApp->setExerciseId(m_pdp->exerciseId()); - m_prtCnvApp->setConfigFile(iniFileOut()); - m_prtCnvApp->startApp(); - m_socketDispatcher->init(m_prtCnvApp); + bool TetraJsonInterfaceImpl::canSendData() const + { + return m_socketDispatcher->canSendData() && m_prtCnvApp != nullptr; + } - onTetraConnectionChanged(false); - connect(m_socketDispatcher.get(), &SocketDispatcher::tetraConnectionChanged, - this, &TetraJsonInterfaceImpl::onTetraConnectionChanged); - - connect(m_socketDispatcher.get(), &SocketDispatcher::warehouseMessage, - this, &TetraJsonInterfaceImpl::directMessage); - - return true; -} - -std::shared_ptr TetraJsonInterfaceImpl::sendToTab() -{ - return m_socketDispatcher->sendToTab(); -} - -bool TetraJsonInterfaceImpl::canSendData() const -{ - return m_socketDispatcher->canSendData() && m_prtCnvApp != nullptr; -} - -void TetraJsonInterfaceImpl::onTetraConnectionChanged(bool bConnected) -{ + void TetraJsonInterfaceImpl::onTetraConnectionChanged(bool bConnected) + { emit connectionState(QString::fromUtf8(name()), bConnected); -} + } -void TetraJsonInterfaceImpl::cleanupProcess() -{ - m_socketDispatcher->init(nullptr); - if (!m_prtCnvApp) - return; - m_prtCnvApp->shutdownApp(); - delete m_prtCnvApp; - m_prtCnvApp = nullptr; - onTetraConnectionChanged(false); -} + void TetraJsonInterfaceImpl::cleanupProcess() + { + m_socketDispatcher->init(nullptr); + if (!m_prtCnvApp) + return; + m_prtCnvApp->shutdownApp(); + delete m_prtCnvApp; + m_prtCnvApp = nullptr; + onTetraConnectionChanged(false); + } -QString TetraJsonInterfaceImpl::iniFileIn() -{ - return iniPath() + QStringLiteral("/PrtCnv.dat"); -} + QString TetraJsonInterfaceImpl::iniFileIn() + { + return iniPath() + QStringLiteral("/PrtCnv.dat"); + } -QString TetraJsonInterfaceImpl::iniFileOut() const -{ - return iniPath() + QStringLiteral("/PrtCnv_ex_%1.dat").arg(m_exerciseId); -} + QString TetraJsonInterfaceImpl::iniFileOut() const + { + return iniPath() + QStringLiteral("/PrtCnv_ex_%1.dat").arg(m_exerciseId); + } -QString TetraJsonInterfaceImpl::iniPath() -{ - return QCoreApplication::applicationDirPath() + QLatin1Char('/'); -} + QString TetraJsonInterfaceImpl::iniPath() + { + return QCoreApplication::applicationDirPath() + QLatin1Char('/'); + } -QString TetraJsonInterfaceImpl::playerIdsFile() -{ - return iniPath() + QStringLiteral("/playerIds.dat"); -} + QString TetraJsonInterfaceImpl::playerIdsFile() + { + return iniPath() + QStringLiteral("/playerIds.dat"); + } -} +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.h old mode 100755 new mode 100644 index e735d31e6..a536b12c0 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/plugin.h @@ -11,58 +11,56 @@ namespace TetraRadio { -class TetraJsonPlugin : public QObject, public TrainingAreaBase::Plugin::Plugin -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "special:3:tab.jsonsocket") - Q_INTERFACES(TrainingAreaBase::Plugin::Plugin) -public: - TetraJsonPlugin() = default; - ~TetraJsonPlugin() = default; - std::shared_ptr createInterface(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb, - const std::shared_ptr &sendToTabCb, - const std::shared_ptr &, - NGL::Settings *settings) override; -}; - -class SocketDispatcher; -class TetraJsonInterfaceImpl final : public TrainingAreaBase::Plugin::Interface -{ - Q_OBJECT -public: - TetraJsonInterfaceImpl(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb, - NGL::Settings *settings); - ~TetraJsonInterfaceImpl(); - - bool init() override; - std::shared_ptr sendToTab() override; - bool isDebugInterface() const override + class TetraJsonPlugin + : public QObject + , public TrainingAreaBase::Plugin::Plugin { - return false; - } - bool canSendData() const override; - void exerciseChanged() override; - const char *name() const override { return "TETRA"; } -private Q_SLOTS: - void onTetraConnectionChanged(bool bConnected); -private: -NGL::INGLLogger &m_logger; - void cleanupProcess(); - static QString iniFileIn(); - QString iniFileOut() const; - static QString iniPath(); - static QString playerIdsFile(); - bool updatePrtCnv(); - bool checkConfigTemplates(); - bool startPrtCnv(); + Q_OBJECT + Q_PLUGIN_METADATA(IID "special:3:tab.jsonsocket") + Q_INTERFACES(TrainingAreaBase::Plugin::Plugin) + public: + TetraJsonPlugin() = default; + ~TetraJsonPlugin() = default; + std::shared_ptr createInterface(TrainingAreaBase::Plugin::DataProvider *pdp, + const std::shared_ptr &recvFromTabCb, + const std::shared_ptr &sendToTabCb, + const std::shared_ptr &, + NGL::Settings *settings) override; + }; -private: - std::unique_ptr m_socketDispatcher; - TrainingAreaBase::Plugin::DataProvider *m_pdp; - PrtCnv::PrtCnvApplication *m_prtCnvApp; - int m_exerciseId; - int m_radioGrpId; -}; -} + class SocketDispatcher; + class TetraJsonInterfaceImpl final : public TrainingAreaBase::Plugin::Interface + { + Q_OBJECT + public: + TetraJsonInterfaceImpl(TrainingAreaBase::Plugin::DataProvider *pdp, const std::shared_ptr &recvFromTabCb, NGL::Settings *settings); + ~TetraJsonInterfaceImpl(); + + bool init() override; + std::shared_ptr sendToTab() override; + bool isDebugInterface() const override { return false; } + bool canSendData() const override; + void exerciseChanged() override; + const char *name() const override { return "TETRA"; } + private Q_SLOTS: + void onTetraConnectionChanged(bool bConnected); + + private: + NGL::INGLLogger &m_logger; + void cleanupProcess(); + static QString iniFileIn(); + QString iniFileOut() const; + static QString iniPath(); + static QString playerIdsFile(); + bool updatePrtCnv(); + bool checkConfigTemplates(); + bool startPrtCnv(); + + private: + std::unique_ptr m_socketDispatcher; + TrainingAreaBase::Plugin::DataProvider *m_pdp; + PrtCnv::PrtCnvApplication *m_prtCnvApp; + int m_exerciseId; + int m_radioGrpId; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.cpp old mode 100755 new mode 100644 index a016c2630..ef6a86f43 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.cpp @@ -10,128 +10,117 @@ namespace TetraRadio { - - -SocketDispatcher::SocketDispatcher(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb) - : QObject() - , ConvertFromJson(recvFromTabCb, "TAB.Plugin.SocketDispatcher") - , m_txHandler(std::make_shared("TxSocketHandler")) - , m_dataProvider(pdp) - , m_prtCnvApp(nullptr) - , m_ackTimer(new QTimer(this)) - , m_bInitialAck(false) - , m_receiveCounter(0) -{ - m_ackTimer->setInterval(1000); - m_ackTimer->setSingleShot(false); - connect(m_ackTimer, &QTimer::timeout, - this, &SocketDispatcher::onAckTimeout); -} - -SocketDispatcher::~SocketDispatcher() -{ - delete m_ackTimer; -} - -bool SocketDispatcher::init(PrtCnv::PrtCnvApplication *prtCnvApp) -{ - if (m_prtCnvApp == prtCnvApp) - return true; - if (m_prtCnvApp) - m_prtCnvApp->disconnect(this); - m_prtCnvApp = prtCnvApp; - if (m_prtCnvApp) + SocketDispatcher::SocketDispatcher(TrainingAreaBase::Plugin::DataProvider *pdp, const std::shared_ptr &recvFromTabCb) + : QObject() + , ConvertFromJson(recvFromTabCb, "TAB.Plugin.SocketDispatcher") + , m_txHandler(std::make_shared("TxSocketHandler")) + , m_dataProvider(pdp) + , m_prtCnvApp(nullptr) + , m_ackTimer(new QTimer(this)) + , m_bInitialAck(false) + , m_receiveCounter(0) { - connect(m_txHandler.get(), &ConvertToJson::outgoingMessage, - m_prtCnvApp, &PrtCnv::PrtCnvApplication::textMessageFromCentralToPrtCnv); - connect(m_prtCnvApp, &PrtCnv::PrtCnvApplication::textMessageFromPrtCnvToCentral, - this, &SocketDispatcher::onTextMessageReceived); - connect(m_prtCnvApp, &PrtCnv::PrtCnvApplication::warehouseMessageFromPtrCnv, - this, &SocketDispatcher::warehouseMessage); - - m_ackTimer->start(); - m_bInitialAck = true; + m_ackTimer->setInterval(1000); + m_ackTimer->setSingleShot(false); + connect(m_ackTimer, &QTimer::timeout, this, &SocketDispatcher::onAckTimeout); } - else + + SocketDispatcher::~SocketDispatcher() { - m_bInitialAck = false; - m_ackTimer->stop(); + delete m_ackTimer; } - return true; -} -quint16 SocketDispatcher::randomListenPort() const -{ - QTcpServer *s = new QTcpServer; - s->listen(QHostAddress::Any, 0); - while (!s->isListening()) - QCoreApplication::processEvents(); - quint16 port = s->serverPort(); - delete s; - return port; -} - -std::shared_ptr SocketDispatcher::sendToTab() -{ - return std::static_pointer_cast(m_txHandler); -} - -void SocketDispatcher::onTextMessageReceived(const QByteArray &message) -{ - DEBUG_LOG(m_logger) << "TetraJson onTextMessageReceived: '" << message << "'"; - int newRecvCounter = 0; - if (!handleTelegram(message, newRecvCounter)) - return; - m_receiveCounter = newRecvCounter; -} - -void SocketDispatcher::handleTetraConnectionChanged(bool bConnected) -{ - emit tetraConnectionChanged(bConnected); -} - -void SocketDispatcher::handleAcknowledge(qint64 timeStamp, int counter) -{ - TRACE_LOG(m_logger) << "Ack from Socket for time " << timeStamp - << " with counter " << counter - << ", initial: " << m_bInitialAck; - if (m_bInitialAck) + bool SocketDispatcher::init(PrtCnv::PrtCnvApplication *prtCnvApp) { - m_txHandler->setConnected(true); - m_bInitialAck = false; - onSendInitialData(); - } - -} - -void SocketDispatcher::onAckTimeout() -{ - TrainingAreaBase::TetraIcd::Acknowledge ack; - ack.timeStamp = time(nullptr) * 1000; - ack.ackCounter = m_receiveCounter; - m_txHandler->txData(ack); -} - -void SocketDispatcher::onSendInitialData() -{ - if (m_dataProvider) - { - NOTICE_LOG(m_logger) << "sending initial data exerciseId=" << m_dataProvider->exerciseId(); - - if (m_dataProvider->exerciseId() > 0) + if (m_prtCnvApp == prtCnvApp) + return true; + if (m_prtCnvApp) + m_prtCnvApp->disconnect(this); + m_prtCnvApp = prtCnvApp; + if (m_prtCnvApp) { - - m_txHandler->txData(m_dataProvider->exerciseEnvironmentData()); + connect(m_txHandler.get(), &ConvertToJson::outgoingMessage, m_prtCnvApp, &PrtCnv::PrtCnvApplication::textMessageFromCentralToPrtCnv); + connect(m_prtCnvApp, &PrtCnv::PrtCnvApplication::textMessageFromPrtCnvToCentral, this, &SocketDispatcher::onTextMessageReceived); + connect(m_prtCnvApp, &PrtCnv::PrtCnvApplication::warehouseMessageFromPtrCnv, this, &SocketDispatcher::warehouseMessage); + + m_ackTimer->start(); + m_bInitialAck = true; } - - m_txHandler->txData(m_dataProvider->exerciseStateData()); - m_txHandler->txData(m_dataProvider->exerciseEquipmentAssignment()); - const auto &aesTeles = m_dataProvider->aesTelegrams(); - for (TrainingAreaBase::TetraIcd::TrainingAreaTelegram *aesTele : aesTeles) - m_txHandler->sendToTx(aesTele); - + else + { + m_bInitialAck = false; + m_ackTimer->stop(); + } + return true; } -} -} + quint16 SocketDispatcher::randomListenPort() const + { + QTcpServer *s = new QTcpServer; + s->listen(QHostAddress::Any, 0); + while (!s->isListening()) + QCoreApplication::processEvents(); + quint16 port = s->serverPort(); + delete s; + return port; + } + + std::shared_ptr SocketDispatcher::sendToTab() + { + return std::static_pointer_cast(m_txHandler); + } + + void SocketDispatcher::onTextMessageReceived(const QByteArray &message) + { + DEBUG_LOG(m_logger) << "TetraJson onTextMessageReceived: '" << message << "'"; + int newRecvCounter = 0; + if (!handleTelegram(message, newRecvCounter)) + return; + m_receiveCounter = newRecvCounter; + } + + void SocketDispatcher::handleTetraConnectionChanged(bool bConnected) + { + emit tetraConnectionChanged(bConnected); + } + + void SocketDispatcher::handleAcknowledge(qint64 timeStamp, int counter) + { + TRACE_LOG(m_logger) << "Ack from Socket for time " << timeStamp << " with counter " << counter << ", initial: " << m_bInitialAck; + if (m_bInitialAck) + { + m_txHandler->setConnected(true); + m_bInitialAck = false; + onSendInitialData(); + } + } + + void SocketDispatcher::onAckTimeout() + { + TrainingAreaBase::TetraIcd::Acknowledge ack; + ack.timeStamp = time(nullptr) * 1000; + ack.ackCounter = m_receiveCounter; + m_txHandler->txData(ack); + } + + void SocketDispatcher::onSendInitialData() + { + if (m_dataProvider) + { + NOTICE_LOG(m_logger) << "sending initial data exerciseId=" << m_dataProvider->exerciseId(); + + if (m_dataProvider->exerciseId() > 0) + { + + m_txHandler->txData(m_dataProvider->exerciseEnvironmentData()); + } + + m_txHandler->txData(m_dataProvider->exerciseStateData()); + m_txHandler->txData(m_dataProvider->exerciseEquipmentAssignment()); + const auto &aesTeles = m_dataProvider->aesTelegrams(); + for (TrainingAreaBase::TetraIcd::TrainingAreaTelegram *aesTele : aesTeles) + m_txHandler->sendToTx(aesTele); + } + } + +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.h old mode 100755 new mode 100644 index 3a078ec4a..f1e29c8a9 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/Plugins/TetraJson/socket_dispatcher_json.h @@ -14,36 +14,39 @@ namespace TetraRadio { -class SocketDispatcher final : public QObject, protected ConvertFromJson -{ - Q_OBJECT -public: - explicit SocketDispatcher(TrainingAreaBase::Plugin::DataProvider *pdp, - const std::shared_ptr &recvFromTabCb); - ~SocketDispatcher(); + class SocketDispatcher final + : public QObject + , protected ConvertFromJson + { + Q_OBJECT + public: + explicit SocketDispatcher(TrainingAreaBase::Plugin::DataProvider *pdp, const std::shared_ptr &recvFromTabCb); + ~SocketDispatcher(); - bool init(PrtCnv::PrtCnvApplication *prtCnvApp); - std::shared_ptr sendToTab(); - quint16 randomListenPort() const; - bool canSendData() const { return m_prtCnvApp != nullptr; } -Q_SIGNALS: - void tetraConnectionChanged(bool bConnected); - void warehouseMessage(const QByteArray &jsonData); -private Q_SLOTS: - void onTextMessageReceived(const QByteArray &message); - void onAckTimeout(); - void onSendInitialData(); -private: - void disconnectSocket(QWebSocket *s); - void handleTetraConnectionChanged(bool bConnected) override; - void handleAcknowledge(qint64 timeStamp, int counter) override; -private: - std::shared_ptr m_txHandler; - TrainingAreaBase::Plugin::DataProvider *m_dataProvider; - PrtCnv::PrtCnvApplication *m_prtCnvApp; - QTimer *m_ackTimer; - bool m_bInitialAck; - int m_receiveCounter; -}; + bool init(PrtCnv::PrtCnvApplication *prtCnvApp); + std::shared_ptr sendToTab(); + quint16 randomListenPort() const; + bool canSendData() const { return m_prtCnvApp != nullptr; } + Q_SIGNALS: + void tetraConnectionChanged(bool bConnected); + void warehouseMessage(const QByteArray &jsonData); + private Q_SLOTS: + void onTextMessageReceived(const QByteArray &message); + void onAckTimeout(); + void onSendInitialData(); -} + private: + void disconnectSocket(QWebSocket *s); + void handleTetraConnectionChanged(bool bConnected) override; + void handleAcknowledge(qint64 timeStamp, int counter) override; + + private: + std::shared_ptr m_txHandler; + TrainingAreaBase::Plugin::DataProvider *m_dataProvider; + PrtCnv::PrtCnvApplication *m_prtCnvApp; + QTimer *m_ackTimer; + bool m_bInitialAck; + int m_receiveCounter; + }; + +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.cpp old mode 100755 new mode 100644 index 670cb43fb..db48b646f --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.cpp @@ -8,25 +8,24 @@ namespace TrainingAreaBase { -LOGGER_T getLogger(const char *name) -{ - static const char ns[] = "TAB."; - std::string loggerName; - const size_t len = strlen(name); - loggerName.reserve(sizeof(ns) + len); - loggerName.append(ns, sizeof(ns) - 1); - loggerName.append(name, len); + LOGGER_T getLogger(const char *name) + { + static const char ns[] = "TAB."; + std::string loggerName; + const size_t len = strlen(name); + loggerName.reserve(sizeof(ns) + len); + loggerName.append(ns, sizeof(ns) - 1); + loggerName.append(name, len); - try - { - return NGL::NGLLoggerBootstrap::getNGLRootLogger(). - getNGLLogger(loggerName); - } - catch (const std::exception &ex) - { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception &ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } + } - -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.h old mode 100755 new mode 100644 index 45e0504f7..a478e6bfd --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/logger.h @@ -8,11 +8,11 @@ namespace TrainingAreaBase { -using LOGGER_T = NGL::INGLLogger &; + using LOGGER_T = NGL::INGLLogger &; -SVCTABCOMMON_EXPORT LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) -{ - return getLogger(loggerName.toUtf8().constData()); + SVCTABCOMMON_EXPORT LOGGER_T getLogger(const char *name); + inline LOGGER_T getLogger(const QString &loggerName) + { + return getLogger(loggerName.toUtf8().constData()); + } } -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/recv_from_tab.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/recv_from_tab.h old mode 100755 new mode 100644 index 7fbf41613..deace40e0 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/recv_from_tab.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/recv_from_tab.h @@ -6,53 +6,53 @@ namespace TrainingAreaBase { -class RecvFromTab -{ -public: - RecvFromTab() = default; - virtual ~RecvFromTab() = default; + class RecvFromTab + { + public: + RecvFromTab() = default; + virtual ~RecvFromTab() = default; - virtual void rxData(const TetraIcd::ManipulationReport &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentOperationalState &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentConfigurationReport &inData) = 0; - virtual void rxData(const TetraIcd::CtaDataError &inData) = 0; - virtual void rxData(const TetraIcd::PositionReport &inData) = 0; - virtual void rxData(const TetraIcd::PositionReportWithMountedEquipments &inData) = 0; - virtual void rxData(const TetraIcd::MineTriggered &inData) = 0; - virtual void rxData(const TetraIcd::DefinitionIed &inData) = 0; - virtual void rxData(const TetraIcd::StateIed &inData) = 0; - virtual void rxData(const TetraIcd::DusSingleMineState &inData) = 0; - virtual void rxData(const TetraIcd::StateChangeDirect &inData) = 0; - virtual void rxData(const TetraIcd::StateChangeIndirect &inData) = 0; - virtual void rxData(const TetraIcd::OperatorAction &inData) = 0; - virtual void rxData(const TetraIcd::StateChange &inData) = 0; - virtual void rxData(const TetraIcd::FunctionalAreaEntry &inData) = 0; - virtual void rxData(const TetraIcd::SpecialSensorData &inData) = 0; - virtual void rxData(const TetraIcd::MinelayerTrailerData &indata) = 0; - virtual void rxData(const TetraIcd::MinelayerThrowerData &inData) = 0; - virtual void rxData(const TetraIcd::MinelayerTrailerPosition &indata) = 0; - virtual void rxData(const TetraIcd::BiteReport &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentEvent &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentGearAssignment &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentGearChargeState &inData) = 0; - virtual void rxData(const TetraIcd::EquipmentGearEvent &inData) = 0; - virtual void rxData(const TetraIcd::ParticipantSwVersions &data) = 0; - virtual void rxData(const TetraIcd::EquipmentMessageOC &inData) = 0; - virtual void rxData(const TetraIcd::OpaquePayloadDataIn &inData) = 0; - virtual void rxData(const TetraIcd::ParticipantModeReport &inData) = 0; - virtual void rxData(const TetraIcd::ParticipantConfigurationReport & inData) = 0; - virtual void rxData(const TetraIcd::EmergencyCall &inData) = 0; - virtual void rxData(const TetraIcd::SanitationRepair &inData) = 0; - virtual void rxData(const TetraIcd::SanitaryMaterialStockReport &inData) = 0; - virtual void rxData(const TetraIcd::Sanitation &inData) = 0; - virtual void rxData(const TetraIcd::ApacheLaserDesignation &inData) = 0; - virtual void rxData(const TetraIcd::SelectiveReammunition &inData) = 0; - virtual void rxData(const TetraIcd::BatteryInfo &inData) {Q_UNUSED(inData)} - virtual void rxData(const TetraIcd::BatteryAlarm &inData){Q_UNUSED(inData)} - virtual void rxData(const TetraIcd::ServiceControl &inData){Q_UNUSED(inData)} - virtual void rxData(const TetraIcd::RestoreRadioReadiness &inData) = 0; - virtual void rxData(const TetraIcd::UAVStatus &inData) = 0; - virtual void rxData(const TetraIcd::UAVRadioLinkConnectionStatus &inData) = 0; - virtual void rxData(const TetraIcd::UAVMissionStatus &inData) = 0; -}; -} + virtual void rxData(const TetraIcd::ManipulationReport &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentOperationalState &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentConfigurationReport &inData) = 0; + virtual void rxData(const TetraIcd::CtaDataError &inData) = 0; + virtual void rxData(const TetraIcd::PositionReport &inData) = 0; + virtual void rxData(const TetraIcd::PositionReportWithMountedEquipments &inData) = 0; + virtual void rxData(const TetraIcd::MineTriggered &inData) = 0; + virtual void rxData(const TetraIcd::DefinitionIed &inData) = 0; + virtual void rxData(const TetraIcd::StateIed &inData) = 0; + virtual void rxData(const TetraIcd::DusSingleMineState &inData) = 0; + virtual void rxData(const TetraIcd::StateChangeDirect &inData) = 0; + virtual void rxData(const TetraIcd::StateChangeIndirect &inData) = 0; + virtual void rxData(const TetraIcd::OperatorAction &inData) = 0; + virtual void rxData(const TetraIcd::StateChange &inData) = 0; + virtual void rxData(const TetraIcd::FunctionalAreaEntry &inData) = 0; + virtual void rxData(const TetraIcd::SpecialSensorData &inData) = 0; + virtual void rxData(const TetraIcd::MinelayerTrailerData &indata) = 0; + virtual void rxData(const TetraIcd::MinelayerThrowerData &inData) = 0; + virtual void rxData(const TetraIcd::MinelayerTrailerPosition &indata) = 0; + virtual void rxData(const TetraIcd::BiteReport &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentEvent &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentGearAssignment &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentGearChargeState &inData) = 0; + virtual void rxData(const TetraIcd::EquipmentGearEvent &inData) = 0; + virtual void rxData(const TetraIcd::ParticipantSwVersions &data) = 0; + virtual void rxData(const TetraIcd::EquipmentMessageOC &inData) = 0; + virtual void rxData(const TetraIcd::OpaquePayloadDataIn &inData) = 0; + virtual void rxData(const TetraIcd::ParticipantModeReport &inData) = 0; + virtual void rxData(const TetraIcd::ParticipantConfigurationReport &inData) = 0; + virtual void rxData(const TetraIcd::EmergencyCall &inData) = 0; + virtual void rxData(const TetraIcd::SanitationRepair &inData) = 0; + virtual void rxData(const TetraIcd::SanitaryMaterialStockReport &inData) = 0; + virtual void rxData(const TetraIcd::Sanitation &inData) = 0; + virtual void rxData(const TetraIcd::ApacheLaserDesignation &inData) = 0; + virtual void rxData(const TetraIcd::SelectiveReammunition &inData) = 0; + virtual void rxData(const TetraIcd::BatteryInfo &inData) { Q_UNUSED(inData) } + virtual void rxData(const TetraIcd::BatteryAlarm &inData) { Q_UNUSED(inData) } + virtual void rxData(const TetraIcd::ServiceControl &inData) { Q_UNUSED(inData) } + virtual void rxData(const TetraIcd::RestoreRadioReadiness &inData) = 0; + virtual void rxData(const TetraIcd::UAVStatus &inData) = 0; + virtual void rxData(const TetraIcd::UAVRadioLinkConnectionStatus &inData) = 0; + virtual void rxData(const TetraIcd::UAVMissionStatus &inData) = 0; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/send_to_tab.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/send_to_tab.h old mode 100755 new mode 100644 index a815bcb1a..a5563e12d --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/send_to_tab.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/send_to_tab.h @@ -6,70 +6,70 @@ namespace TrainingAreaBase { -class SendToTab -{ -protected: - SendToTab() = default; - virtual ~SendToTab() = default; -public: - virtual const char *name() const = 0; - enum class HandleState + class SendToTab { - No, - YesFallback, - YesShare, - Debug, - YesConsume + protected: + SendToTab() = default; + virtual ~SendToTab() = default; + + public: + virtual const char *name() const = 0; + enum class HandleState + { + No, + YesFallback, + YesShare, + Debug, + YesConsume + }; + virtual HandleState canHandleTelegram(int equipmentNumber, int telegramId) const = 0; + virtual void resetSendCounter() = 0; + virtual bool txData(const TetraIcd::Acknowledge &data) = 0; + virtual bool txData(const TetraIcd::DemandBite &data) = 0; + virtual bool txData(const TetraIcd::Init &data) = 0; + virtual bool txData(const TetraIcd::SetVulnerabilityModel &data) = 0; + virtual bool txData(const TetraIcd::DemandEquipmentConfigurationReport &data) = 0; + virtual bool txData(const TetraIcd::DemandVulnerabilityStateChange &data) = 0; + virtual bool txData(const TetraIcd::LanguageSelection &data) = 0; + virtual bool txData(const TetraIcd::EquipmentMessage &data) = 0; + virtual bool txData(const TetraIcd::EquipmentMessageOC &data) = 0; + virtual bool txData(const TetraIcd::CreateSingleExplosion &data) = 0; + virtual bool txData(const TetraIcd::CreateAreaExplosion &data) = 0; + virtual bool txData(const TetraIcd::CreateMineArea &data) = 0; + virtual bool txData(const TetraIcd::MineAreaSingleMineState &data) = 0; + virtual bool txData(const TetraIcd::CreateNContamination &data) = 0; + virtual bool txData(const TetraIcd::CreateCContamination &data) = 0; + virtual bool txData(const TetraIcd::DeactivateEffectSimulation &data) = 0; + virtual bool txData(const TetraIcd::ModifyAreaEffectSimulationName &data) = 0; + virtual bool txData(const TetraIcd::PauseEffectSimulation &data) = 0; + virtual bool txData(const TetraIcd::ResumeEffectSimulation &data) = 0; + virtual bool txData(const TetraIcd::MineTriggered &data) = 0; + virtual bool txData(const TetraIcd::DusMineReactivation &data) = 0; + virtual bool txData(const TetraIcd::CreateFunctionalArea &data) = 0; + virtual bool txData(const TetraIcd::CreateDusSingleMine &data) = 0; + virtual bool txData(const TetraIcd::ExerciseEnvironmentData &data) = 0; + virtual bool txData(const TetraIcd::ExerciseStateData &data) = 0; + virtual bool txData(const TetraIcd::ParticipantSwVersionsRequest &data) = 0; + virtual bool txData(const TetraIcd::OpaquePayloadDataOut &data) = 0; + virtual bool txData(const TetraIcd::TechnicalArea &data) = 0; + virtual bool txData(const TetraIcd::CesHitInformation &data) = 0; + virtual bool txData(const TetraIcd::CesHitRequest &data) = 0; + virtual bool txData(const TetraIcd::ParticipantMode &data) = 0; + virtual bool txData(const TetraIcd::DemandParticipantMode &data) = 0; + virtual bool txData(const TetraIcd::ParticipantConfiguration &data) = 0; + virtual bool txData(const TetraIcd::DemandParticipantConfiguration &data) = 0; + virtual bool txData(const TetraIcd::ExerciseEquipmentAssignmentComplete &data) = 0; + virtual bool txData(const TetraIcd::Sanitation &data) = 0; + virtual bool txData(const TetraIcd::SelectiveReammunition &data) = 0; + virtual bool txData(const TetraIcd::SetDevicePowerRequest &data) = 0; + virtual bool txData(const TetraIcd::OcCommand &data) = 0; + + virtual bool txData(const TrainingAreaBase::TetraIcd::ExFireReadiness &data) = 0; + virtual bool txData(const TrainingAreaBase::TetraIcd::ExFiredReport &data) = 0; + virtual bool txData(const TrainingAreaBase::TetraIcd::ExConfirmationReport &data) = 0; + + + virtual bool txData(const TetraIcd::UAVPerformMission &data) = 0; + virtual bool txData(const TetraIcd::UAVChangeState &data) = 0; }; - virtual HandleState canHandleTelegram(int equipmentNumber, int telegramId) const = 0; - virtual void resetSendCounter() = 0; - virtual bool txData(const TetraIcd::Acknowledge &data) = 0; - virtual bool txData(const TetraIcd::DemandBite &data) = 0; - virtual bool txData(const TetraIcd::Init &data) = 0; - virtual bool txData(const TetraIcd::SetVulnerabilityModel &data) = 0; - virtual bool txData(const TetraIcd::DemandEquipmentConfigurationReport & data) = 0; - virtual bool txData(const TetraIcd::DemandVulnerabilityStateChange &data) = 0; - virtual bool txData(const TetraIcd::LanguageSelection &data) = 0; - virtual bool txData(const TetraIcd::EquipmentMessage &data) = 0; - virtual bool txData(const TetraIcd::EquipmentMessageOC &data) = 0; - virtual bool txData(const TetraIcd::CreateSingleExplosion &data) = 0; - virtual bool txData(const TetraIcd::CreateAreaExplosion &data) = 0; - virtual bool txData(const TetraIcd::CreateMineArea &data) = 0; - virtual bool txData(const TetraIcd::MineAreaSingleMineState &data) = 0; - virtual bool txData(const TetraIcd::CreateNContamination &data) = 0; - virtual bool txData(const TetraIcd::CreateCContamination &data) = 0; - virtual bool txData(const TetraIcd::DeactivateEffectSimulation &data) = 0; - virtual bool txData(const TetraIcd::ModifyAreaEffectSimulationName &data) = 0; - virtual bool txData(const TetraIcd::PauseEffectSimulation &data) = 0; - virtual bool txData(const TetraIcd::ResumeEffectSimulation &data) = 0; - virtual bool txData(const TetraIcd::MineTriggered &data) = 0; - virtual bool txData(const TetraIcd::DusMineReactivation &data) = 0; - virtual bool txData(const TetraIcd::CreateFunctionalArea &data) = 0; - virtual bool txData(const TetraIcd::CreateDusSingleMine &data) = 0; - virtual bool txData(const TetraIcd::ExerciseEnvironmentData &data) = 0; - virtual bool txData(const TetraIcd::ExerciseStateData &data) = 0; - virtual bool txData(const TetraIcd::ParticipantSwVersionsRequest &data) = 0; - virtual bool txData(const TetraIcd::OpaquePayloadDataOut &data) = 0; - virtual bool txData(const TetraIcd::TechnicalArea &data) = 0; - virtual bool txData(const TetraIcd::CesHitInformation &data) = 0; - virtual bool txData(const TetraIcd::CesHitRequest &data) = 0; - virtual bool txData(const TetraIcd::ParticipantMode &data) = 0; - virtual bool txData(const TetraIcd::DemandParticipantMode & data) = 0; - virtual bool txData(const TetraIcd::ParticipantConfiguration &data) = 0; - virtual bool txData(const TetraIcd::DemandParticipantConfiguration &data) = 0; - virtual bool txData(const TetraIcd::ExerciseEquipmentAssignmentComplete &data) = 0; - virtual bool txData(const TetraIcd::Sanitation &data) = 0; - virtual bool txData(const TetraIcd::SelectiveReammunition &data) = 0; - virtual bool txData(const TetraIcd::SetDevicePowerRequest &data) = 0; - virtual bool txData(const TetraIcd::OcCommand &data) = 0; - - virtual bool txData(const TrainingAreaBase::TetraIcd::ExFireReadiness &data) = 0; - virtual bool txData(const TrainingAreaBase::TetraIcd::ExFiredReport&data) = 0; - virtual bool txData(const TrainingAreaBase::TetraIcd::ExConfirmationReport &data) = 0; - - - virtual bool txData(const TetraIcd::UAVPerformMission &data) = 0; - virtual bool txData(const TetraIcd::UAVChangeState &data) = 0; - -}; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_db_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_db_stub.hpp index e2dff77b5..4567dfad1 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_db_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_db_stub.hpp @@ -6,16 +6,19 @@ #include "tab_enums_stub.hpp" -namespace tab { -namespace db { +namespace tab +{ + namespace db + { -// Stub class to replace RTI IDL-generated database types -class TrainingDatabase { -public: - virtual ~TrainingDatabase() = default; -}; + // Stub class to replace RTI IDL-generated database types + class TrainingDatabase + { + public: + virtual ~TrainingDatabase() = default; + }; -} // namespace db + } // namespace db } // namespace tab -#endif // TAB_DB_STUB_HPP \ No newline at end of file +#endif // TAB_DB_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_enums_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_enums_stub.hpp index da25eefa3..8da12a92c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_enums_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_enums_stub.hpp @@ -4,21 +4,24 @@ #ifndef TAB_ENUMS_STUB_HPP #define TAB_ENUMS_STUB_HPP -namespace tab { +namespace tab +{ -// Stub enums to replace RTI IDL-generated enums -enum class TrainingAreaType { + // Stub enums to replace RTI IDL-generated enums + enum class TrainingAreaType + { Unknown = 0, Standard = 1, Advanced = 2 -}; + }; -enum class TrainingStatus { + enum class TrainingStatus + { Inactive = 0, Active = 1, Completed = 2 -}; + }; } // namespace tab -#endif // TAB_ENUMS_STUB_HPP \ No newline at end of file +#endif // TAB_ENUMS_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_stub.hpp index 43e9c1475..8536b32af 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_stub.hpp @@ -7,38 +7,41 @@ #include "tab_enums_stub.hpp" #include -namespace tab { +namespace tab +{ -// Stub class to replace RTI IDL-generated TrainingArea type -class TrainingArea { -public: + // Stub class to replace RTI IDL-generated TrainingArea type + class TrainingArea + { + public: TrainingArea() = default; virtual ~TrainingArea() = default; - + std::string getName() const { return m_name; } - void setName(const std::string& name) { m_name = name; } - + void setName(const std::string &name) { m_name = name; } + TrainingAreaType getType() const { return m_type; } void setType(TrainingAreaType type) { m_type = type; } - -private: + + private: std::string m_name; TrainingAreaType m_type = TrainingAreaType::Unknown; -}; + }; -// Stub class to replace RTI IDL-generated TrainingSession type -class TrainingSession { -public: + // Stub class to replace RTI IDL-generated TrainingSession type + class TrainingSession + { + public: TrainingSession() = default; virtual ~TrainingSession() = default; - + TrainingStatus getStatus() const { return m_status; } void setStatus(TrainingStatus status) { m_status = status; } - -private: + + private: TrainingStatus m_status = TrainingStatus::Inactive; -}; + }; } // namespace tab -#endif // TAB_STUB_HPP \ No newline at end of file +#endif // TAB_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_topic_type_plugin_stub.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_topic_type_plugin_stub.cpp index 73534295b..9534d7cf4 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_topic_type_plugin_stub.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/stubs/tab_topic_type_plugin_stub.cpp @@ -3,25 +3,30 @@ #include "tab_enums_stub.hpp" -namespace tab { -namespace plugin { +namespace tab +{ + namespace plugin + { -// Stub class to replace RTI IDL-generated topic type plugin -class TopicTypePlugin { -public: - virtual ~TopicTypePlugin() = default; - - virtual bool initialize() { return true; } - virtual void shutdown() {} -}; + // Stub class to replace RTI IDL-generated topic type plugin + class TopicTypePlugin + { + public: + virtual ~TopicTypePlugin() = default; -} // namespace plugin + virtual bool initialize() { return true; } + virtual void shutdown() {} + }; + + } // namespace plugin } // namespace tab // Export stub function -extern "C" { - tab::plugin::TopicTypePlugin* createTopicTypePlugin() { - static tab::plugin::TopicTypePlugin instance; - return &instance; - } -} \ No newline at end of file +extern "C" +{ + tab::plugin::TopicTypePlugin *createTopicTypePlugin() + { + static tab::plugin::TopicTypePlugin instance; + return &instance; + } +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_export.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_export.h old mode 100755 new mode 100644 index f8b0f51e2..8717f96f4 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_export.h @@ -5,43 +5,43 @@ #include #ifndef TAB_COMMON_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define TAB_COMMON_EXPORT -# else -# if defined(MAKE_SVCTABCOMMON_LIB) -# define TAB_COMMON_EXPORT Q_DECL_EXPORT -# ifndef WIN32 -# ifdef NDDSUSERDllExport -# undef NDDSUSERDllExport -# endif -# define NDDSUSERDllExport Q_DECL_EXPORT -# endif -# else -# define TAB_COMMON_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define TAB_COMMON_EXPORT +#else +#if defined(MAKE_SVCTABCOMMON_LIB) +#define TAB_COMMON_EXPORT Q_DECL_EXPORT +#ifndef WIN32 +#ifdef NDDSUSERDllExport +#undef NDDSUSERDllExport +#endif +#define NDDSUSERDllExport Q_DECL_EXPORT +#endif +#else +#define TAB_COMMON_EXPORT Q_DECL_IMPORT +#endif +#endif #endif #ifndef TAB_CLIENT_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define TAB_CLIENT_EXPORT -# else -# if defined(MAKE_SVCTABCLIENT_LIB) -# define TAB_CLIENT_EXPORT Q_DECL_EXPORT -# else -# define TAB_CLIENT_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define TAB_CLIENT_EXPORT +#else +#if defined(MAKE_SVCTABCLIENT_LIB) +#define TAB_CLIENT_EXPORT Q_DECL_EXPORT +#else +#define TAB_CLIENT_EXPORT Q_DECL_IMPORT +#endif +#endif #endif #ifndef TAB_SERVER_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define TAB_SERVER_EXPORT -# else -# if defined(MAKE_SVCTABSERVER_LIB) -# define TAB_SERVER_EXPORT Q_DECL_EXPORT -# else -# define TAB_SERVER_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define TAB_SERVER_EXPORT +#else +#if defined(MAKE_SVCTABSERVER_LIB) +#define TAB_SERVER_EXPORT Q_DECL_EXPORT +#else +#define TAB_SERVER_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_plugin_interface.h old mode 100755 new mode 100644 index 64c694ad2..36330e9bb --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/tab_plugin_interface.h @@ -12,71 +12,75 @@ class QSqlDatabase; namespace NGL { -class Settings; + class Settings; } namespace TrainingAreaBase { -class DdsHandler; -class SendToTab; -class TxMixin; + class DdsHandler; + class SendToTab; + class TxMixin; -class RecvFromTab; -namespace Plugin -{ -class Interface; -class DataProvider -{ -public: - DataProvider() = default; - virtual ~DataProvider() = default; + class RecvFromTab; + namespace Plugin + { + class Interface; + class DataProvider + { + public: + DataProvider() = default; + virtual ~DataProvider() = default; - virtual int exerciseId() const = 0; - virtual bool useTetraScrambling() const = 0; - virtual ProjectDataManagement::RadioGroup exerciseRadioGroup() const = 0; - virtual TetraIcd::ExerciseEnvironmentData exerciseEnvironmentData() const = 0; - virtual TetraIcd::ExerciseStateData exerciseStateData() const = 0; - - virtual TetraIcd::ExerciseEquipmentAssignmentComplete exerciseEquipmentAssignment() const = 0; - virtual QVector aesTelegrams() const = 0; - virtual QSqlDatabase databaseConnection() const = 0; - virtual QString databaseSchemaName() const = 0; - virtual int domainId() const = 0; -}; + virtual int exerciseId() const = 0; + virtual bool useTetraScrambling() const = 0; + virtual ProjectDataManagement::RadioGroup exerciseRadioGroup() const = 0; + virtual TetraIcd::ExerciseEnvironmentData exerciseEnvironmentData() const = 0; + virtual TetraIcd::ExerciseStateData exerciseStateData() const = 0; -class Plugin -{ - Q_GADGET -public: - Plugin() = default; - virtual ~Plugin() = default; - - virtual std::shared_ptr createInterface(DataProvider *pdp, - const std::shared_ptr &recvFromTabCb, - const std::shared_ptr &sendToTabCb, - const std::shared_ptr &ddsHandler, - NGL::Settings *settings) = 0; -}; + virtual TetraIcd::ExerciseEquipmentAssignmentComplete exerciseEquipmentAssignment() const = 0; + virtual QVector aesTelegrams() const = 0; + virtual QSqlDatabase databaseConnection() const = 0; + virtual QString databaseSchemaName() const = 0; + virtual int domainId() const = 0; + }; -class Interface : public QObject -{ - Q_OBJECT -public: - Interface() = default; - virtual ~Interface() = default; + class Plugin + { + Q_GADGET + public: + Plugin() = default; + virtual ~Plugin() = default; - virtual bool init() = 0; - virtual std::shared_ptr sendToTab() = 0; - virtual bool isDebugInterface() const = 0; - virtual bool canSendData() const = 0; - virtual void exerciseChanged () = 0; - virtual const char *name() const = 0; + virtual std::shared_ptr createInterface(DataProvider *pdp, + const std::shared_ptr &recvFromTabCb, + const std::shared_ptr &sendToTabCb, + const std::shared_ptr &ddsHandler, + NGL::Settings *settings) = 0; + }; - virtual bool turnOn(bool turnOn) { Q_UNUSED(turnOn); return false; } + class Interface : public QObject + { + Q_OBJECT + public: + Interface() = default; + virtual ~Interface() = default; -signals: - void connectionState(const QString &name, bool connectionState); - void directMessage(const QByteArray &jsonMessage); -}; -} -} + virtual bool init() = 0; + virtual std::shared_ptr sendToTab() = 0; + virtual bool isDebugInterface() const = 0; + virtual bool canSendData() const = 0; + virtual void exerciseChanged() = 0; + virtual const char *name() const = 0; + + virtual bool turnOn(bool turnOn) + { + Q_UNUSED(turnOn); + return false; + } + + signals: + void connectionState(const QString &name, bool connectionState); + void directMessage(const QByteArray &jsonMessage); + }; + } +} Q_DECLARE_INTERFACE(TrainingAreaBase::Plugin::Plugin, "special:3:tetra") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.cpp b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.cpp index 53797392b..69a3d1265 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.cpp @@ -10,3401 +10,3207 @@ namespace TrainingAreaBase { -namespace TetraIcd -{ - -JsonException::JsonException(const QJsonObject &obj, const QString &key) - : m_obj(obj) - , m_key(key) - , m_what("Could not find key '" + key.toUtf8() + "' in json ('" + QJsonDocument(obj).toJson(QJsonDocument::Compact) + "')") -{} - -template -QJsonValue enumToJson(E e) -{ - static_assert(std::is_enum::value, "Only useable with enumerations"); - return static_cast(e); -} - -template -QJsonValue arrayToJson(const std::vector &cont) -{ - QJsonArray arr; - for (const A &s : cont) - arr += s.toJson(); - return arr; -} - -template <> -QJsonValue arrayToJson(const std::vector &cont) -{ - QJsonArray arr; - for (const int i : cont) - arr += i; - return arr; -} - -template <> -QJsonValue arrayToJson(const std::vector &cont) -{ - - return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast(cont.data()), cont.size()).toHex()); -} - -template -bool get(const QJsonObject &obj, const QString &key, T &val, bool bOptional = false) -{ - if (bOptional) + namespace TetraIcd { - try + + JsonException::JsonException(const QJsonObject &obj, const QString &key) + : m_obj(obj) + , m_key(key) + , m_what("Could not find key '" + key.toUtf8() + "' in json ('" + QJsonDocument(obj).toJson(QJsonDocument::Compact) + "')") { - val = T::fromJson(obj[key].toObject()); } - catch (const JsonException &e) + + template QJsonValue enumToJson(E e) { - Q_UNUSED(e); - return false; + static_assert(std::is_enum::value, "Only useable with enumerations"); + return static_cast(e); } - } - else - val = T::fromJson(obj[key].toObject()); - return true; -} -template <> -bool get(const QJsonObject &obj, const QString &key, QJsonArray &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isArray()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toArray(); - return true; -} + template QJsonValue arrayToJson(const std::vector &cont) + { + QJsonArray arr; + for (const A &s : cont) + arr += s.toJson(); + return arr; + } -template <> -bool get(const QJsonObject &obj, const QString &key, bool &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isBool()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toBool(); - return true; -} + template <> QJsonValue arrayToJson(const std::vector &cont) + { + QJsonArray arr; + for (const int i : cont) + arr += i; + return arr; + } -template <> -bool get(const QJsonObject &obj, const QString &key, qint32 &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isDouble()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toInt(); - return true; -} + template <> QJsonValue arrayToJson(const std::vector &cont) + { -template <> -bool get(const QJsonObject &obj, const QString &key, quint32 &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isDouble()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = uint32_t(jVal.toDouble()); - return true; -} + return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast(cont.data()), cont.size()).toHex()); + } -template <> -bool get(const QJsonObject &obj, const QString &key, qint64 &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isDouble()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = int64_t(jVal.toDouble()); - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, double &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isDouble()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toDouble(); - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, QString &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isString()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toString(); - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, std::string &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isString()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - val = jVal.toString().toStdString(); - return true; -} - -template -bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional = false) -{ - const QJsonValue jVal = obj[key]; - if (!jVal.isNull() && !jVal.isArray()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - if (jVal.isNull()) - return false; - const QJsonArray arr = jVal.toArray(); - val.clear(); - val.reserve(arr.size()); - for (const auto &ele : arr) - val.push_back(T::fromJson(ele.toObject())); - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional) -{ - const auto jVal = obj[key]; - if (!jVal.isArray()) - { - if (bOptional) - return false; - throw JsonException(obj, key); - } - const QJsonArray arr = jVal.toArray(); - val.clear(); - val.reserve(arr.size()); - for (const auto &v : arr) - { - if (!v.isDouble()) - throw JsonException(obj, key); - val.push_back(v.toInt()); - } - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional) -{ - QString sPayload; - if (!get(obj, key, sPayload, bOptional)) - return false; - const QByteArray ba = QByteArray::fromHex(sPayload.toLatin1()); - val.clear(); - val.reserve(ba.size()); - std::copy(ba.begin(), ba.end(), std::back_inserter(val)); - return true; -} - -template <> -bool get(const QJsonObject &obj, const QString &key, VulnerabilityState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - - val = static_cast(iVal); - return true; - - -} - -template <> -bool get(const QJsonObject &obj, const QString &key, OriginatorType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case OriginatorType::Initialisation: - case OriginatorType::ObserverController: - case OriginatorType::ExerciseControl: - case OriginatorType::FunctionalArea: - case OriginatorType::MedicTimeout: - case OriginatorType::Sanitation: - case OriginatorType::MedicDecontamination: - case OriginatorType::MaintainanceRepair: - case OriginatorType::MaintainanceDecontamination: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, FunctionalAreaOperatingMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case FunctionalAreaOperatingMode::NotUsed: - case FunctionalAreaOperatingMode::OperatedByOC: - case FunctionalAreaOperatingMode::WaitForTimeout: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, Language &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case Language::NoChange: - case Language::German: - case Language::English: - case Language::French: - case Language::Arabic: - case Language::Spanish: - case Language::Russian: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantLicenseState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantLicenseState::Unknown: - case ParticipantLicenseState::Licensed: - case ParticipantLicenseState::Rejected: - case ParticipantLicenseState::Unlicense: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::MineHandgrenadeSensorMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::MineHandgrenadeSensorMode::PersonellMode: - case EquipmentConfigurationReport::MineHandgrenadeSensorMode::NormalVehicleMode: - case EquipmentConfigurationReport::MineHandgrenadeSensorMode::OcVehicleMode: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::FirMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::FirMode::NoFir: - case EquipmentConfigurationReport::FirMode::Fir: - case EquipmentConfigurationReport::FirMode::FirSpzMarder: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::MineLayerMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::MineLayerMode::NoMineLayerDevice: - case EquipmentConfigurationReport::MineLayerMode::MinLayerTrailer: - case EquipmentConfigurationReport::MineLayerMode::MineLayerThrower: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::SpecialSensorStandardMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::SpecialSensorStandardMode::NoSpecialSensorStandard: - case EquipmentConfigurationReport::SpecialSensorStandardMode::ZABC: - case EquipmentConfigurationReport::SpecialSensorStandardMode::CSF: - case EquipmentConfigurationReport::SpecialSensorStandardMode::PzBr: - case EquipmentConfigurationReport::SpecialSensorStandardMode::MRF: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::AgdusHwMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::AgdusHwMode::WithoutHelmetWithoutVest: - case EquipmentConfigurationReport::AgdusHwMode::WithHelmetWithoutVest: - case EquipmentConfigurationReport::AgdusHwMode::WithHelmetWithVest: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::PositionUpdateInterval &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case EquipmentConfigurationReport::PositionUpdateInterval::Vehicle: - case EquipmentConfigurationReport::PositionUpdateInterval::Personnell: - case EquipmentConfigurationReport::PositionUpdateInterval::Aircraft: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, CtaDataError::Reason &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case CtaDataError::Reason::WrongParameter: - case CtaDataError::Reason::TelegramOutdated: - case CtaDataError::Reason::InvalidByteCount: - case CtaDataError::Reason::InvalidData: - case CtaDataError::Reason::FragmentationError: - case CtaDataError::Reason::Unknown: - case CtaDataError::Reason::AdditionalDemandTimeout: - case CtaDataError::Reason::ErrorLoginEquipmentNumber: - case CtaDataError::Reason::ErrorLoginTetraId: - case CtaDataError::Reason::InfoLoginMasteringFlag: - case CtaDataError::Reason::ErrorSendingNamelist: - case CtaDataError::Reason::ErrorSendingToExerciseControl: - case CtaDataError::Reason::ErrorNotLoggedIn: - case CtaDataError::Reason::ErrorNotLicensed: - case CtaDataError::Reason::ErrorConfigSelfTest: - case CtaDataError::Reason::JsonDecodeFailure: - case CtaDataError::Reason::WrongCrc: - case CtaDataError::Reason::BroadcastCounterOverflow: - case CtaDataError::Reason::InvalidTime: - case CtaDataError::Reason::InvalidPosition: - case CtaDataError::Reason::InvalidTacticalState: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, CreateCContamination::Volatiliy &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case CreateCContamination::Volatiliy::Floating: - case CreateCContamination::Volatiliy::Resident: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, AreaEffectSimulationType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case AreaEffectSimulationType::Unknown: - case AreaEffectSimulationType::MineArea: - case AreaEffectSimulationType::ExplosionArea: - case AreaEffectSimulationType::ExplosionSingle: - case AreaEffectSimulationType::NContamination: - case AreaEffectSimulationType::CContamination: - case AreaEffectSimulationType::FunctionalArea: - case AreaEffectSimulationType::TechnicalArea: - case AreaEffectSimulationType::DusSingleMineSimulator: - case AreaEffectSimulationType::GasPipeDetonation: - case AreaEffectSimulationType::SpecialArea: - case AreaEffectSimulationType::BeStillWarning: - case AreaEffectSimulationType::DangerZoneExplosion: - case AreaEffectSimulationType::AirSupport: - - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, IedType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case IedType::SuicideIed: - case IedType::IedSmallPyro: - case IedType::IedBigPyro: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, IedPairingState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case IedPairingState::NotPaired: - case IedPairingState::PairedToParticipant: - case IedPairingState::PairedToOps: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, IedTacticalState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case IedTacticalState::NotActive: - case IedTacticalState::Active: - case IedTacticalState::Defused: - case IedTacticalState::TriggeredBySwitch: - case IedTacticalState::TriggeredByRemote: - case IedTacticalState::TriggeredByLightBarrier: - case IedTacticalState::TriggeredByTautWire: - case IedTacticalState::TriggeredByControlDevice: - case IedTacticalState::Unknown: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, IedError &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case IedError::NoError: - case IedError::DeviceMissing: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, MinelayerThrowerData::ThrowingType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case MinelayerThrowerData::ThrowingType::Straight: - case MinelayerThrowerData::ThrowingType::Right: - case MinelayerThrowerData::ThrowingType::Left: - case MinelayerThrowerData::ThrowingType::LeftAndRight: - case MinelayerThrowerData::ThrowingType::SingleRight: - case MinelayerThrowerData::ThrowingType::SingleLeft: - case MinelayerThrowerData::ThrowingType::SingleLeftAndRight: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, OpaquePayloadDataBase::Type &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case OpaquePayloadDataBase::Type::FireSmokeMarker: - case OpaquePayloadDataBase::Type::Geopairing: - case OpaquePayloadDataBase::Type::Target: - case OpaquePayloadDataBase::Type::OC: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, TechnicalArea::Type &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case TechnicalArea::Type::Reserved: - case TechnicalArea::Type::RemoveArea: - case TechnicalArea::Type::MoutArea: - case TechnicalArea::Type::RestingAreaPersonnel: - case TechnicalArea::Type::RestingAreaVehicle: - case TechnicalArea::Type::RestingAreaPersonnelAndVehicle: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::OperationMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::OperationMode::NoChange: - case ParticipantModeBase::OperationMode::Normal: - case ParticipantModeBase::OperationMode::BeStill: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, BiteReport::LoginType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case BiteReport::LoginType::NoLogin: - case BiteReport::LoginType::NewLogin: - case BiteReport::LoginType::Relogin: - case BiteReport::LoginType::InvalidLogin: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::WphMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::WphMode::NoChange: - case ParticipantModeBase::WphMode::Without: - case ParticipantModeBase::WphMode::With: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::PersonellProtection &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::PersonellProtection::NoChange: - case ParticipantModeBase::PersonellProtection::Without: - case ParticipantModeBase::PersonellProtection::Suit: - case ParticipantModeBase::PersonellProtection::SuitAndGloves: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::ProtectionLevel &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::ProtectionLevel::NoChange: - case ParticipantModeBase::ProtectionLevel::IdzBs: - case ParticipantModeBase::ProtectionLevel::IdzEs: - case ParticipantModeBase::ProtectionLevel::Ksk: - case ParticipantModeBase::ProtectionLevel::SoldierWithBodyArmor: - case ParticipantModeBase::ProtectionLevel::SoldierActor: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::HandgrenadeSearchMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::HandgrenadeSearchMode::NoChange: - case ParticipantModeBase::HandgrenadeSearchMode::On: - case ParticipantModeBase::HandgrenadeSearchMode::Off: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::InternationalMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::InternationalMode::NoChange: - case ParticipantModeBase::InternationalMode::On: - case ParticipantModeBase::InternationalMode::Off: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::ABCProtectionMode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantModeBase::ABCProtectionMode::NoChange: - case ParticipantModeBase::ABCProtectionMode::On: - case ParticipantModeBase::ABCProtectionMode::Off: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::FaultPositionHandling &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantConfigurationBase::FaultPositionHandling::NoChange: - case ParticipantConfigurationBase::FaultPositionHandling::NoPositions: - case ParticipantConfigurationBase::FaultPositionHandling::InvalidPositionValue: - case ParticipantConfigurationBase::FaultPositionHandling::EstimatedPosition: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::SwitchingPositionIntervall &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantConfigurationBase::SwitchingPositionIntervall::NoChange: - case ParticipantConfigurationBase::SwitchingPositionIntervall::On: - case ParticipantConfigurationBase::SwitchingPositionIntervall::Off: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::OpticalCode &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ParticipantConfigurationBase::OpticalCode::NoChange: - case ParticipantConfigurationBase::OpticalCode::Osag10: - case ParticipantConfigurationBase::OpticalCode::Osag20Basic: - case ParticipantConfigurationBase::OpticalCode::SisoStandard: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, SanitationResult &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case SanitationResult::NoEffect: - case SanitationResult::Unhandled: - case SanitationResult::Insufficient: - case SanitationResult::Sufficient: - case SanitationResult::Optimal: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, SanitationEvaluation &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case SanitationEvaluation::NotApplicable: - case SanitationEvaluation::Okay: - case SanitationEvaluation::PartlyWrong: - case SanitationEvaluation::Wrong: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, Qualification &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case Qualification::NotDefined: - case Qualification::SANPers: - case Qualification::FAB: - case Qualification::FAA: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, SanitationRepair::TreatmentResult &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case SanitationRepair::TreatmentResult::None: - case SanitationRepair::TreatmentResult::Success: - case SanitationRepair::TreatmentResult::Failure: - case SanitationRepair::TreatmentResult::Stabilized: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ExerciseStateData::ExerciseState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ExerciseStateData::ExerciseState::Unknown: - case ExerciseStateData::ExerciseState::Created: - case ExerciseStateData::ExerciseState::Started: - case ExerciseStateData::ExerciseState::Paused: - case ExerciseStateData::ExerciseState::Stopped: - case ExerciseStateData::ExerciseState::Terminated: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, ServiceControlEnum &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case ServiceControlEnum::PRESHUTDOWN: - case ServiceControlEnum::SHUTDOWN: - case ServiceControlEnum::STOP: - - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, PowerMethod &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case PowerMethod::Unknown: - case PowerMethod::PowerOn: - case PowerMethod::PowerOff: - - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, UAVActionTask &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case UAVActionTask::Undefined: - case UAVActionTask::Disarm: - case UAVActionTask::Arm: - case UAVActionTask::Takeoff: - case UAVActionTask::Connect: - case UAVActionTask::Loiter: - case UAVActionTask::Return: - case UAVActionTask::Observe: - val = static_cast(iVal); + template bool get(const QJsonObject &obj, const QString &key, T &val, bool bOptional = false) + { + if (bOptional) + { + try + { + val = T::fromJson(obj[key].toObject()); + } + catch (const JsonException &e) + { + Q_UNUSED(e); + return false; + } + } + else + val = T::fromJson(obj[key].toObject()); return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, UAVRadioLinkConnectionStatusType &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case UAVRadioLinkConnectionStatusType::Connected: - case UAVRadioLinkConnectionStatusType::Disconnected: - case UAVRadioLinkConnectionStatusType::Connecting: - case UAVRadioLinkConnectionStatusType::Error: - case UAVRadioLinkConnectionStatusType::Undefined: - case UAVRadioLinkConnectionStatusType::Diconnecting: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - -template <> -bool get(const QJsonObject &obj, const QString &key, UAVState &val, bool bOptional) -{ - int iVal = 0; - get(obj, key, iVal, bOptional); - switch (static_cast(iVal)) - { - case UAVState::Auto: - case UAVState::Calibrating: - case UAVState::Init: - case UAVState::Maintenance: - case UAVState::Undefined: - case UAVState::Manual: - case UAVState::Normal: - case UAVState::Off: - case UAVState::On: - case UAVState::Shutdown: - case UAVState::Standby: - val = static_cast(iVal); - return true; - } - throw JsonException(obj, key); -} - - - -Header Header::fromJson(const QJsonObject &obj) -{ - Header ret; - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("timeStamp"), ret.timeStamp); - return ret; -} - -QJsonObject Header::toJson() const -{ - return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, - {QStringLiteral("timeStamp"), timeStamp} - }; -} - - -RelativePosition RelativePosition::fromJson(const QJsonObject &obj) -{ - RelativePosition ret; - get(obj, QStringLiteral("offsetX"), ret.offsetX); - get(obj, QStringLiteral("offsetY"), ret.offsetY); - get(obj, QStringLiteral("offsetZ"), ret.offsetZ); - return ret; -} - -QJsonObject RelativePosition::toJson() const -{ - return QJsonObject{{QStringLiteral("offsetX"), offsetX}, - {QStringLiteral("offsetY"), offsetY}, - {QStringLiteral("offsetZ"), offsetZ} - }; -} - - -AbsolutePosition AbsolutePosition::fromJson(const QJsonObject &obj) -{ - AbsolutePosition ret; - get(obj, QStringLiteral("lon"), ret.lon); - get(obj, QStringLiteral("lat"), ret.lat); - get(obj, QStringLiteral("z"), ret.z); - return ret; -} - -QJsonObject AbsolutePosition::toJson() const -{ - return QJsonObject{{QStringLiteral("lon"), lon}, - {QStringLiteral("lat"), lat}, - {QStringLiteral("z"), z} - }; -} - - -OpsPosition OpsPosition::fromJson(const QJsonObject &obj) -{ - OpsPosition ret; - get(obj, QStringLiteral("opsId"), ret.opsId); - get(obj, QStringLiteral("moutObjectId"), ret.moutObjectId, true); - get(obj, QStringLiteral("moutRoomId"), ret.moutRoomId, true); - return ret; -} - -QJsonObject OpsPosition::toJson() const -{ - return QJsonObject{{QStringLiteral("opsId"), opsId}, - {QStringLiteral("moutObjectId"), moutObjectId}, - {QStringLiteral("moutRoomId"), moutRoomId} - }; -} - - -GpsQuality GpsQuality::fromJson(const QJsonObject &obj) -{ - GpsQuality ret; - get(obj, QStringLiteral("moreThan4SatellitesAvailable"), ret.moreThan4SatellitesAvailable); - get(obj, QStringLiteral("dgpsModeAvailable"), ret.dgpsModeAvailable); - get(obj, QStringLiteral("pdopValue"), ret.pdopValue); - return ret; -} - -QJsonObject GpsQuality::toJson() const -{ - return QJsonObject{{QStringLiteral("moreThan4SatellitesAvailable"), moreThan4SatellitesAvailable}, - {QStringLiteral("dgpsModeAvailable"), dgpsModeAvailable}, - {QStringLiteral("pdopValue"), pdopValue} - }; -} - - -Gear Gear::fromJson(const QJsonObject &obj) -{ - Gear ret; - get(obj, QStringLiteral("gearTasCode"), ret.gearTasCode); - get(obj, QStringLiteral("gearSerialNumber"), ret.gearSerialNumber); - get(obj, QStringLiteral("chargeCounting"), ret.chargeCounting); - return ret; -} - -QJsonObject Gear::toJson() const -{ - return QJsonObject{{QStringLiteral("gearTasCode"), gearTasCode}, - {QStringLiteral("gearSerialNumber"), gearSerialNumber}, - {QStringLiteral("chargeCounting"), chargeCounting} - }; -} - - -GearCharge GearCharge::fromJson(const QJsonObject &obj) -{ - GearCharge ret; - get(obj, QStringLiteral("gearTasCode"), ret.gearTasCode); - get(obj, QStringLiteral("gearSerialNumber"), ret.gearSerialNumber); - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - get(obj, QStringLiteral("remain"), ret.remain); - get(obj, QStringLiteral("location"), ret.location); - return ret; -} - -QJsonObject GearCharge::toJson() const -{ - return QJsonObject{{QStringLiteral("gearTasCode"), gearTasCode}, - {QStringLiteral("gearSerialNumber"), gearSerialNumber}, - {QStringLiteral("chargeTypeId"), chargeTypeId}, - {QStringLiteral("remain"), remain}, - {QStringLiteral("location"), location} - }; -} - - -WlsPosition WlsPosition::fromJson(const QJsonObject &obj) -{ - WlsPosition ret; - get(obj, QStringLiteral("x"), ret.x); - get(obj, QStringLiteral("y"), ret.y); - get(obj, QStringLiteral("z"), ret.z); - get(obj, QStringLiteral("wlsAreaId"), ret.wlsAreaId); - get(obj, QStringLiteral("wlsZone"), ret.wlsZone); - get(obj, QStringLiteral("wlsBuildingId"), ret.wlsBuildingId); - get(obj, QStringLiteral("wlsRoomNumber"), ret.wlsRoomNumber); - get(obj, QStringLiteral("playerOrientation"), ret.playerOrientation); - get(obj, QStringLiteral("weaponOrientation"), ret.weaponOrientation); - get(obj, QStringLiteral("isValid"), ret.isValid); - return ret; -} - -QJsonObject WlsPosition::toJson() const -{ - return QJsonObject{{QStringLiteral("x"), x}, - {QStringLiteral("y"), y}, - {QStringLiteral("z"), z}, - {QStringLiteral("wlsAreaId"), wlsAreaId}, - {QStringLiteral("wlsZone"), wlsZone}, - {QStringLiteral("wlsBuildingId"), wlsBuildingId}, - {QStringLiteral("wlsRoomNumber"), wlsRoomNumber}, - {QStringLiteral("playerOrientation"), playerOrientation}, - {QStringLiteral("weaponOrientation"), weaponOrientation}, - {QStringLiteral("isValid"), isValid} - }; -} - - -WlsParticipantState WlsParticipantState::fromJson(const QJsonObject &obj) -{ - WlsParticipantState ret; - get(obj, QStringLiteral("tagId"), ret.tagId); - get(obj, QStringLiteral("lastSeen"), ret.lastSeen); - get(obj, QStringLiteral("voltage"), ret.voltage); - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("tacticalState"), ret.tacticalState); - get(obj, QStringLiteral("gpsOn"), ret.gpsOn); - get(obj, QStringLiteral("inBlockedArea"), ret.inBlockedArea); - get(obj, QStringLiteral("relativePosition"), ret.relativePosition); - return ret; -} - -QJsonObject WlsParticipantState::toJson() const -{ - return QJsonObject{{QStringLiteral("tagId"), tagId}, - {QStringLiteral("lastSeen"), lastSeen}, - {QStringLiteral("voltage"), voltage}, - {QStringLiteral("equipmentNumber"), equipmentNumber}, - {QStringLiteral("tacticalState"), tacticalState}, - {QStringLiteral("gpsOn"), gpsOn}, - {QStringLiteral("inBlockedArea"), inBlockedArea}, - {QStringLiteral("relativePosition"), relativePosition.toJson()} - }; -} - - -BatteryState BatteryState::fromJson(const QJsonObject &obj) -{ - BatteryState ret; - get(obj, QStringLiteral("batteryPort"), ret.m_batteryPort); - get(obj, QStringLiteral("battery"), ret.m_batteryPercent); - get(obj, QStringLiteral("voltage"), ret.m_voltage); - get(obj, QStringLiteral("temperature"), ret.m_temperature); - get(obj, QStringLiteral("frequency"), ret.m_frequency); - get(obj, QStringLiteral("generic"), ret.m_generic); - get(obj, QStringLiteral("current"), ret.m_current); - get(obj, QStringLiteral("switchOrValue"), ret.m_switchOrValue); - get(obj, QStringLiteral("serialNumber"), ret.m_serialNumber); - return ret; -} - -QJsonObject BatteryState::toJson() const -{ - return QJsonObject{{QStringLiteral("batteryPort"), batteryPort()}, - {QStringLiteral("battery"), batteryPercent()}, - {QStringLiteral("voltage"), voltage()}, - {QStringLiteral("temperature"), temperature()}, - {QStringLiteral("frequency"), frequency()}, - {QStringLiteral("generic"), generic()}, - {QStringLiteral("current"), current()}, - {QStringLiteral("switchOrValue"), switchOrValue()}, - {QStringLiteral("serialNumber"), serialNumber()} - }; -} - - -Acknowledge Acknowledge::fromJson(const QJsonObject &obj) -{ - Acknowledge ret; - get(obj, QStringLiteral("timeStamp"), ret.timeStamp); - get(obj, QStringLiteral("ackCounter"), ret.ackCounter); - return ret; -} - -QJsonObject Acknowledge::toJson() const -{ - return QJsonObject{{QStringLiteral("timeStamp"), timeStamp}, - {QStringLiteral("ackCounter"), ackCounter} - }; -} - - -Init Init::fromJson(const QJsonObject &obj) -{ - Init ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("workstationId"), ret.workstationId); - get(obj, QStringLiteral("restockCharges"), ret.restockCharges); - get(obj, QStringLiteral("resetManipulation"), ret.resetManipulation); - get(obj, QStringLiteral("resetVulnerabilityState"), ret.resetVulnerabilityState); - get(obj, QStringLiteral("restockSanitationMaterial"), ret.restockSanitationMaterial); - return ret; -} - -QJsonObject Init::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("workstationId"), workstationId}, - {QStringLiteral("restockCharges"), restockCharges}, - {QStringLiteral("resetManipulation"), resetManipulation}, - {QStringLiteral("resetVulnerabilityState"), resetVulnerabilityState}, - {QStringLiteral("restockSanitationMaterial"), restockSanitationMaterial} - }; -} - - -ManipulationReport ManipulationReport::fromJson(const QJsonObject &obj) -{ - ManipulationReport ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("isManipulation"), ret.isManipulation); - get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); - return ret; -} - -QJsonObject ManipulationReport::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("isManipulation"), isManipulation}, - {QStringLiteral("equipmentFunctionId"), equipmentFunctionId} - }; -} - - -DemandBite DemandBite::fromJson(const QJsonObject &obj) -{ - DemandBite ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("withSelfTest"), ret.withSelfTest); - return ret; -} - -QJsonObject DemandBite::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("withSelfTest"), withSelfTest} - }; -} - - -EquipmentOperationalState EquipmentOperationalState::fromJson(const QJsonObject &obj) -{ - EquipmentOperationalState ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("nbcProtectionActive"), ret.nbcProtectionActive); - return ret; -} - -QJsonObject EquipmentOperationalState::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("nbcProtectionActive"), nbcProtectionActive} - }; -} - - -void VulnerabilityModelBase::fromJson(const QJsonObject &obj, VulnerabilityModelBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("vulnerabilityModelMineIed"), ret.vulnerabilityModelMineIed); - get(obj, QStringLiteral("vulnerabilityModelAreaFire"), ret.vulnerabilityModelAreaFire); - get(obj, QStringLiteral("vulnerabilityModelOperatingResource"), ret.vulnerabilityModelOperatingResource); - get(obj, QStringLiteral("vulnerabilityModelAcWeaponry"), ret.vulnerabilityModelAcWeaponry); -} - -QJsonObject VulnerabilityModelBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("vulnerabilityModelMineIed"), vulnerabilityModelMineIed}, - {QStringLiteral("vulnerabilityModelAreaFire"), vulnerabilityModelAreaFire}, - {QStringLiteral("vulnerabilityModelOperatingResource"), vulnerabilityModelOperatingResource}, - {QStringLiteral("vulnerabilityModelAcWeaponry"), vulnerabilityModelAcWeaponry} - }; -} - - -SetVulnerabilityModel SetVulnerabilityModel::fromJson(const QJsonObject &obj) -{ - SetVulnerabilityModel ret; - VulnerabilityModelBase::fromJson(obj, ret); - return ret; -} - -QJsonObject SetVulnerabilityModel::toJson() const -{ - return VulnerabilityModelBase::toJson(); -} - - -DemandEquipmentConfigurationReport DemandEquipmentConfigurationReport::fromJson(const QJsonObject &obj) -{ - DemandEquipmentConfigurationReport ret; - get(obj, QStringLiteral("header"), ret.header); - return ret; -} - -QJsonObject DemandEquipmentConfigurationReport::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}}; -} - - -EquipmentConfigurationReport EquipmentConfigurationReport::fromJson(const QJsonObject &obj) -{ - EquipmentConfigurationReport ret; - VulnerabilityModelBase::fromJson(obj, ret); - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("canStartUpTime"), ret.canStartUpTime); - get(obj, QStringLiteral("equipmentType"), ret.equipmentType); - get(obj, QStringLiteral("loginWaittimeBitweenTrys"), ret.loginWaittimeBitweenTrys); - get(obj, QStringLiteral("loginMaxRetryCnt"), ret.loginMaxRetryCnt); - get(obj, QStringLiteral("loginMasteringFlag"), ret.loginMasteringFlag); - get(obj, QStringLiteral("canDeviceConfiguration"), ret.canDeviceConfiguration); - get(obj, QStringLiteral("displayDeviceVoiceOutput"), ret.displayDeviceVoiceOutput); - get(obj, QStringLiteral("displayDeviceLanguage"), ret.displayDeviceLanguage); - get(obj, QStringLiteral("pyrotechnics"), ret.pyrotechnics); - get(obj, QStringLiteral("mhgrsMode"), ret.mhgrsMode); - get(obj, QStringLiteral("mhgrsEnergySaving"), ret.mhgrsEnergySaving); - get(obj, QStringLiteral("specialSensorFir"), ret.specialSensorFir); - get(obj, QStringLiteral("specialSensorMinelayer"), ret.specialSensorMinelayer); - get(obj, QStringLiteral("specialSensorStandard"), ret.specialSensorStandard); - get(obj, QStringLiteral("agdusHwMode"), ret.agdusHwMode); - get(obj, QStringLiteral("positionUpdateInterval"), ret.positionUpdateInterval); - get(obj, QStringLiteral("displayTextMainGroup"), ret.displayTextMainGroup); - get(obj, QStringLiteral("displayTextSubGroup"), ret.displayTextSubGroup); - get(obj, QStringLiteral("vulnerabilityModelAgdus"), ret.vulnerabilityModelAgdus); - return ret; -} - -QJsonObject EquipmentConfigurationReport::toJson() const -{ - QJsonObject obj = VulnerabilityModelBase::toJson(); - obj[QStringLiteral("header")] = header.toJson(); - obj[QStringLiteral("equipmentNumber")] = equipmentNumber; - obj[QStringLiteral("canStartUpTime")] = canStartUpTime; - obj[QStringLiteral("equipmentType")] = equipmentType; - obj[QStringLiteral("loginWaittimeBitweenTrys")] = loginWaittimeBitweenTrys; - obj[QStringLiteral("loginMaxRetryCnt")] = loginMaxRetryCnt; - obj[QStringLiteral("loginMasteringFlag")] = loginMasteringFlag; - obj[QStringLiteral("canDeviceConfiguration")] = canDeviceConfiguration; - obj[QStringLiteral("displayDeviceVoiceOutput")] = displayDeviceVoiceOutput; - obj[QStringLiteral("displayDeviceLanguage")] = enumToJson(displayDeviceLanguage); - obj[QStringLiteral("pyrotechnics")] = pyrotechnics; - obj[QStringLiteral("mhgrsMode")] = enumToJson(mhgrsMode); - obj[QStringLiteral("mhgrsEnergySaving")] = mhgrsEnergySaving; - obj[QStringLiteral("specialSensorFir")] = enumToJson(specialSensorFir); - obj[QStringLiteral("specialSensorMinelayer")] = enumToJson(specialSensorMinelayer); - obj[QStringLiteral("specialSensorStandard")] = enumToJson(specialSensorStandard); - obj[QStringLiteral("agdusHwMode")] = enumToJson(agdusHwMode); - obj[QStringLiteral("positionUpdateInterval")] = enumToJson(positionUpdateInterval); - obj[QStringLiteral("displayTextMainGroup")] = displayTextMainGroup; - obj[QStringLiteral("displayTextSubGroup")] = displayTextSubGroup; - obj[QStringLiteral("vulnerabilityModelAgdus")] = vulnerabilityModelAgdus; - return obj; -} - - -CtaDataError CtaDataError::fromJson(const QJsonObject &obj) -{ - CtaDataError ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("reason"), ret.reason); - get(obj, QStringLiteral("originTelegramId"), ret.originTelegramId); - return ret; -} - -QJsonObject CtaDataError::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("reason"), enumToJson(reason)}, - {QStringLiteral("originTelegramId"), originTelegramId} - }; -} - - -void PositionReportBase::fromJson(const QJsonObject &obj, PositionReportBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - bool bAtLeastOneFound = false; - if (get(obj, QStringLiteral("relPosition"), ret.relPosition, true)) - bAtLeastOneFound = true; - if (get(obj, QStringLiteral("geoPosition"), ret.geoPosition, true)) - bAtLeastOneFound = true; - - get(obj, QStringLiteral("opsPosition"), ret.opsPosition, bAtLeastOneFound); - get(obj, QStringLiteral("gpsQuality"), ret.gpsQuality, true); -} - -QJsonObject PositionReportBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("geoPosition"), geoPosition.toJson()}, - {QStringLiteral("opsPosition"), opsPosition.toJson()}, - {QStringLiteral("gpsQuality"), gpsQuality.toJson()} - }; -} - - -PositionReport PositionReport::fromJson(const QJsonObject &obj) -{ - PositionReport ret; - PositionReportBase::fromJson(obj, ret); - return ret; -} - -QJsonObject PositionReport::toJson() const -{ - return PositionReportBase::toJson(); -} - - -PositionReportWithMountedEquipments PositionReportWithMountedEquipments::fromJson(const QJsonObject &obj) -{ - PositionReportWithMountedEquipments ret; - PositionReportBase::fromJson(obj, ret); - get(obj, QStringLiteral("mountedEquipments"), ret.mountedEquipments); - return ret; -} - -QJsonObject PositionReportWithMountedEquipments::toJson() const -{ - QJsonObject obj = PositionReportBase::toJson(); - obj[QStringLiteral("mountedEquipments")] = arrayToJson(mountedEquipments); - return obj; -} - - -void CreateAreaEffectSimulationBase::fromJson(const QJsonObject &obj, CreateAreaEffectSimulationBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("name"), ret.name); - get(obj, QStringLiteral("partyId"), ret.partyId); - get(obj, QStringLiteral("relEffectPosition"), ret.relEffectPosition); -} - -QJsonObject CreateAreaEffectSimulationBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("name"), QString::fromStdString(name)}, - {QStringLiteral("partyId"), partyId}, - {QStringLiteral("relEffectPosition"), relEffectPosition.toJson()} - }; -} - - -void CreateCombatAreaEffectSimulationBase::fromJson(const QJsonObject &obj, CreateCombatAreaEffectSimulationBase &ret) -{ - CreateAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - get(obj, QStringLiteral("effectStart"), ret.effectStart); - get(obj, QStringLiteral("effectDuration"), ret.effectDuration); -} - -QJsonObject CreateCombatAreaEffectSimulationBase::toJson() const -{ - QJsonObject obj = CreateAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("chargeTypeId")] = chargeTypeId; - obj[QStringLiteral("effectStart")] = effectStart; - obj[QStringLiteral("effectDuration")] = effectDuration; - return obj; -} - - -OcCommand OcCommand::fromJson(const QJsonObject &obj) -{ - OcCommand ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("action"), ret.action); - return ret; -} - -QJsonObject OcCommand::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("action"), action} - }; -} - - -CreateSingleExplosion CreateSingleExplosion::fromJson(const QJsonObject &obj) -{ - CreateSingleExplosion ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("effectDiameter"), ret.effectDiameter); - return ret; -} - -QJsonObject CreateSingleExplosion::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("effectDiameter")] = effectDiameter; - return obj; -} - - -CreateAreaExplosion CreateAreaExplosion::fromJson(const QJsonObject &obj) -{ - CreateAreaExplosion ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("relCorner"), ret.relCorner); - get(obj, QStringLiteral("height"), ret.height); - get(obj, QStringLiteral("width"), ret.width); - get(obj, QStringLiteral("rotationAngle"), ret.rotationAngle); - get(obj, QStringLiteral("impactCount"), ret.impactCount); - get(obj, QStringLiteral("impactEdgeLength"), ret.impactEdgeLength); - get(obj, QStringLiteral("impactRadius"), ret.impactRadius); - get(obj, QStringLiteral("hazardDistance"), ret.hazardDistance); - - get(obj, QStringLiteral("mhpLength"), ret.mhpLength); - get(obj, QStringLiteral("mhpWidth"), ret.mhpWidth); - get(obj, QStringLiteral("mhpRotation"), ret.mhpRotation); - get(obj, QStringLiteral("mhPoints"), ret.mhPoints); - - - return ret; -} - -QJsonObject CreateAreaExplosion::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("relCorner")] = relCorner.toJson(); - obj[QStringLiteral("height")] = height; - obj[QStringLiteral("width")] = width; - obj[QStringLiteral("rotationAngle")] = rotationAngle; - obj[QStringLiteral("impactCount")] = impactCount; - obj[QStringLiteral("impactEdgeLength")] = impactEdgeLength; - obj[QStringLiteral("impactRadius")] = impactRadius; - - obj[QStringLiteral("hazardDistance")] = hazardDistance; - - obj[QStringLiteral("mhpLength")] = mhpLength; - obj[QStringLiteral("mhpWidth")] = mhpWidth; - obj[QStringLiteral("mhpRotation")] = mhpRotation; - obj[QStringLiteral("mhPoints")] = arrayToJson(mhPoints); - return obj; -} - - -PauseEffectSimulation PauseEffectSimulation::fromJson(const QJsonObject &obj) -{ - PauseEffectSimulation ret; - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - return ret; -} - -QJsonObject PauseEffectSimulation::toJson() const -{ - return QJsonObject{{QStringLiteral("aesDdsId"), aesDdsId}}; -} - - -ResumeEffectSimulation ResumeEffectSimulation::fromJson(const QJsonObject &obj) -{ - ResumeEffectSimulation ret; - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("sequelNumber"), ret.sequelNumber); - get(obj, QStringLiteral("nextImpact"), ret.nextImpact); - get(obj, QStringLiteral("resumeTime"), ret.resumeTime); - get(obj, QStringLiteral("remainDuration"), ret.remainDuration); - return ret; -} - -QJsonObject ResumeEffectSimulation::toJson() const -{ - return QJsonObject{{QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("sequelNumber"), sequelNumber}, - {QStringLiteral("nextImpact"), nextImpact}, - {QStringLiteral("resumeTime"), resumeTime}, - {QStringLiteral("remainDuration"), remainDuration} - }; -} - - -MineAreaSegment MineAreaSegment::fromJson(const QJsonObject &obj) -{ - MineAreaSegment ret; - get(obj, QStringLiteral("relStart"), ret.relStart); - get(obj, QStringLiteral("relEnd"), ret.relEnd); - return ret; -} - -QJsonObject MineAreaSegment::toJson() const -{ - return QJsonObject{{QStringLiteral("relStart"), relStart.toJson()}, - {QStringLiteral("relEnd"), relEnd.toJson()} - }; -} - - -CreateMineArea CreateMineArea::fromJson(const QJsonObject &obj) -{ - CreateMineArea ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - - - get(obj, QStringLiteral("layingDepth"), ret.layingDepth); - get(obj, QStringLiteral("layingDensity"), ret.layingDensity); - get(obj, QStringLiteral("segments"), ret.segments); - return ret; -} - -QJsonObject CreateMineArea::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - - - obj[QStringLiteral("layingDepth")] = layingDepth; - obj[QStringLiteral("layingDensity")] = layingDensity; - obj[QStringLiteral("segments")] = arrayToJson(segments); - return obj; -} - - -MineAreaSingleMineState MineAreaSingleMineState::fromJson(const QJsonObject &obj) -{ - MineAreaSingleMineState ret; - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("mineCount"), ret.mineCount); - get(obj, QStringLiteral("mineState"), ret.mineState); - return ret; -} - -QJsonObject MineAreaSingleMineState::toJson() const -{ - return QJsonObject{{QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("mineCount"), mineCount}, - {QStringLiteral("mineState"), arrayToJson(mineState)}, - }; -} - - -CreateNContamination CreateNContamination::fromJson(const QJsonObject &obj) -{ - CreateNContamination ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("innerRadius"), ret.innerRadius); - get(obj, QStringLiteral("borderLengthInner"), ret.borderLengthInner); - get(obj, QStringLiteral("borderLengthOuter"), ret.borderLengthOuter); - get(obj, QStringLiteral("spanAngle"), ret.spanAngle); - get(obj, QStringLiteral("rotationAngle"), ret.rotationAngle); - return ret; -} - -QJsonObject CreateNContamination::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("innerRadius")] = innerRadius; - obj[QStringLiteral("borderLengthInner")] = borderLengthInner; - obj[QStringLiteral("borderLengthOuter")] = borderLengthOuter; - obj[QStringLiteral("spanAngle")] = spanAngle; - obj[QStringLiteral("rotationAngle")] = rotationAngle; - return obj; -} - - -CreateCContamination CreateCContamination::fromJson(const QJsonObject &obj) -{ - CreateCContamination ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("effectRadius"), ret.effectRadius); - get(obj, QStringLiteral("expansionFactor"), ret.expansionFactor); - get(obj, QStringLiteral("propagationDirection"), ret.propagationDirection); - get(obj, QStringLiteral("windSpeed"), ret.windSpeed); - get(obj, QStringLiteral("validityTimeWind"), ret.validityTimeWind); - get(obj, QStringLiteral("relPositionValidityTimeWind"), ret.relPositionValidityTimeWind); - get(obj, QStringLiteral("volatility"), ret.volatility); - return ret; -} - -QJsonObject CreateCContamination::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("effectRadius")] = effectRadius; - obj[QStringLiteral("expansionFactor")] = expansionFactor; - obj[QStringLiteral("propagationDirection")] = propagationDirection; - obj[QStringLiteral("windSpeed")] = windSpeed; - obj[QStringLiteral("validityTimeWind")] = validityTimeWind; - obj[QStringLiteral("relPositionValidityTimeWind")] = relPositionValidityTimeWind.toJson(); - obj[QStringLiteral("volatility")] = enumToJson(volatility); - return obj; -} - - -DeactivateEffectSimulation DeactivateEffectSimulation::fromJson(const QJsonObject &obj) -{ - DeactivateEffectSimulation ret; - get(obj, QStringLiteral("aesType"), ret.aesType); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - return ret; -} - -QJsonObject DeactivateEffectSimulation::toJson() const -{ - return QJsonObject{{QStringLiteral("aesType"), enumToJson(aesType)}, - {QStringLiteral("aesDdsId"), aesDdsId} - }; -} - - -ModifyAreaEffectSimulationName ModifyAreaEffectSimulationName::fromJson(const QJsonObject &obj) -{ - ModifyAreaEffectSimulationName ret; - get(obj, QStringLiteral("aesType"), ret.aesType); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("name"), ret.name); - return ret; -} - -QJsonObject ModifyAreaEffectSimulationName::toJson() const -{ - return QJsonObject{{QStringLiteral("aesType"), enumToJson(aesType)}, - {QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("name"), QString::fromStdString(name)} - }; -} - - -MineTriggered MineTriggered::fromJson(const QJsonObject &obj) -{ - MineTriggered ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("mineAreaId"), ret.mineAreaId); - get(obj, QStringLiteral("mineIndex"), ret.mineIndex); - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("relPositionValid"), ret.relPositionValid); - return ret; -} - -QJsonObject MineTriggered::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("mineAreaId"), mineAreaId}, - {QStringLiteral("mineIndex"), mineIndex}, - {QStringLiteral("chargeTypeId"), chargeTypeId}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("relPositionValid"), relPositionValid} - }; -} - - -DusMineReactivation DusMineReactivation::fromJson(const QJsonObject &obj) -{ - DusMineReactivation ret; - get(obj, QStringLiteral("dusSerialNumbers"), ret.dusSerialNumbers); - return ret; -} - -QJsonObject DusMineReactivation::toJson() const -{ - return QJsonObject{{QStringLiteral("dusSerialNumbers"), arrayToJson(dusSerialNumbers)}}; -} - - -void IedBaseData::fromJson(const QJsonObject &obj, IedBaseData &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("iedId"), ret.iedId); - get(obj, QStringLiteral("tacticalState"), ret.tacticalState); - get(obj, QStringLiteral("statePyrotechnics"), ret.statePyrotechnics); -} - -QJsonObject IedBaseData::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("iedId"), iedId}, - {QStringLiteral("tacticalState"), enumToJson(tacticalState)}, - {QStringLiteral("statePyrotechnics"), statePyrotechnics} - }; -} - - -DefinitionIed DefinitionIed::fromJson(const QJsonObject &obj) -{ - DefinitionIed ret; - IedBaseData::fromJson(obj, ret); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("iedType"), ret.iedType); - get(obj, QStringLiteral("trigger"), ret.trigger); - get(obj, QStringLiteral("explosiveForce"), ret.explosiveForce); - get(obj, QStringLiteral("pairingState"), ret.pairingState); - get(obj, QStringLiteral("pairedId"), ret.pairedId); - get(obj, QStringLiteral("partyId"), ret.partyId); - return ret; -} - -QJsonObject DefinitionIed::toJson() const -{ - QJsonObject obj = IedBaseData::toJson(); - obj[QStringLiteral("relPosition")] = relPosition.toJson(); - obj[QStringLiteral("iedType")] = enumToJson(iedType); - obj[QStringLiteral("trigger")] = trigger; - obj[QStringLiteral("explosiveForce")] = explosiveForce; - obj[QStringLiteral("pairingState")] = enumToJson(pairingState); - obj[QStringLiteral("pairedId")] = pairedId; - obj[QStringLiteral("partyId")] = partyId; - return obj; -} - - -StateIed StateIed::fromJson(const QJsonObject &obj) -{ - StateIed ret; - IedBaseData::fromJson(obj, ret); - get(obj, QStringLiteral("batteryWarnings"), ret.batteryWarnings); - get(obj, QStringLiteral("errorStateElectronics"), ret.errorStateElectronics); - get(obj, QStringLiteral("errorStatePyrotechnics1"), ret.errorStatePyrotechnics1); - get(obj, QStringLiteral("errorStatePyrotechnics2"), ret.errorStatePyrotechnics2); - get(obj, QStringLiteral("errorStatePyrotechnics3"), ret.errorStatePyrotechnics3); - return ret; -} - -QJsonObject StateIed::toJson() const -{ - QJsonObject obj = IedBaseData::toJson(); - obj[QStringLiteral("batteryWarnings")] = batteryWarnings; - obj[QStringLiteral("errorStateElectronics")] = enumToJson(errorStateElectronics); - obj[QStringLiteral("errorStatePyrotechnics1")] = enumToJson(errorStatePyrotechnics1); - obj[QStringLiteral("errorStatePyrotechnics2")] = enumToJson(errorStatePyrotechnics2); - obj[QStringLiteral("errorStatePyrotechnics3")] = enumToJson(errorStatePyrotechnics3); - return obj; -} - - -DusSingleMineState DusSingleMineState::fromJson(const QJsonObject &obj) -{ - DusSingleMineState ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("mineId"), ret.mineId); - get(obj, QStringLiteral("effectStart"), ret.effectStart); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - get(obj, QStringLiteral("state"), ret.state); - return ret; -} - -QJsonObject DusSingleMineState::toJson() const -{ - QJsonObject obj; - obj[QStringLiteral("header")] = header.toJson(); - obj[QStringLiteral("mineId")] = mineId; - obj[QStringLiteral("effectStart")] = effectStart; - obj[QStringLiteral("relPosition")] = relPosition.toJson(); - obj[QStringLiteral("chargeTypeId")] = chargeTypeId; - obj[QStringLiteral("state")] = state; - return obj; -} - - -CreateDusSingleMine CreateDusSingleMine::fromJson(const QJsonObject &obj) -{ - CreateDusSingleMine ret; - CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("mineId"), ret.mineId); - return ret; -} - -QJsonObject CreateDusSingleMine::toJson() const -{ - QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("mineId")] = mineId; - return obj; -} - - -void StateChangeBase::fromJson(const QJsonObject &obj, StateChangeBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - - bool bAtLeastOneFound = false; - if (get(obj, QStringLiteral("relPosition"), ret.relPosition, true)) - bAtLeastOneFound = true; - if (get(obj, QStringLiteral("geoPosition"), ret.geoPosition, true)) - bAtLeastOneFound = true; - - get(obj, QStringLiteral("opsPosition"), ret.opsPosition, bAtLeastOneFound); - - get(obj, QStringLiteral("vulnerabilityState"), ret.vulnerabilityState); - get(obj, QStringLiteral("tasVulnerabilityKindId"), ret.tasVulnerabilityKindId); - get(obj, QStringLiteral("tasVitality"), ret.tasVitality, true); - get(obj, QStringLiteral("vulnerabilityBits"), ret.vulnerabilityBits); - - get(obj, QStringLiteral("originatorId"), ret.originatorId); -} - -QJsonObject StateChangeBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("geoPosition"), geoPosition.toJson()}, - {QStringLiteral("opsPosition"), opsPosition.toJson()}, - {QStringLiteral("vulnerabilityState"), enumToJson(vulnerabilityState)}, - {QStringLiteral("tasVulnerabilityKindId"), tasVulnerabilityKindId}, - {QStringLiteral("tasVitality"), tasVitality}, - {QStringLiteral("vulnerabilityBits"), vulnerabilityBits}, - {QStringLiteral("originatorId"), originatorId} - }; -} - - -StateChangeDirect StateChangeDirect::fromJson(const QJsonObject &obj) -{ - StateChangeDirect ret; - StateChangeBase::fromJson(obj, ret); - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - return ret; -} - -QJsonObject StateChangeDirect::toJson() const -{ - QJsonObject obj = StateChangeBase::toJson(); - obj[QStringLiteral("chargeTypeId")] = chargeTypeId; - return obj; -} - - -StateChangeIndirect StateChangeIndirect::fromJson(const QJsonObject &obj) -{ - StateChangeIndirect ret; - StateChangeBase::fromJson(obj, ret); - get(obj, QStringLiteral("isSecondaryEffect"), ret.isSecondaryEffect); - return ret; -} - -QJsonObject StateChangeIndirect::toJson() const -{ - QJsonObject obj = StateChangeBase::toJson(); - obj[QStringLiteral("isSecondaryEffect")] = isSecondaryEffect; - return obj; -} - - -DemandVulnerabilityStateChange DemandVulnerabilityStateChange::fromJson(const QJsonObject &obj) -{ - DemandVulnerabilityStateChange ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("workstationId"), ret.workstationId); - get(obj, QStringLiteral("reqestedState"), ret.reqestedState); - get(obj, QStringLiteral("vulnerabilityVitalityIndex"), ret.vulnerabilityVitalityIndex); - return ret; -} - -QJsonObject DemandVulnerabilityStateChange::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("workstationId"), workstationId}, - {QStringLiteral("reqestedState"), enumToJson(reqestedState)}, - {QStringLiteral("vulnerabilityVitalityIndex"), vulnerabilityVitalityIndex} - }; -} - - -OperatorAction OperatorAction::fromJson(const QJsonObject &obj) -{ - OperatorAction ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("operatorId"), ret.operatorId); - get(obj, QStringLiteral("action"), ret.action); - return ret; -} - -QJsonObject OperatorAction::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("operatorId"), operatorId}, - {QStringLiteral("action"), action} - }; -} - - -Reammunition Reammunition::fromJson(const QJsonObject &obj) -{ - Reammunition ret; - get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); - get(obj, QStringLiteral("newStock"), ret.newStock); - get(obj, QStringLiteral("newDefaultStock"), ret.newDefaultStock); - get(obj, QStringLiteral("tracerRatio"), ret.tracerRatio); - return ret; -} - -QJsonObject Reammunition::toJson() const -{ - return QJsonObject{{QStringLiteral("chargeTypeId"), chargeTypeId}, - {QStringLiteral("newStock"), newStock}, - {QStringLiteral("newDefaultStock"), newDefaultStock}, - {QStringLiteral("tracerRatio"), tracerRatio} - }; -} - - -SelectiveReammunition SelectiveReammunition::fromJson(const QJsonObject &obj) -{ - SelectiveReammunition ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("gearId"), ret.gearId); - get(obj, QStringLiteral("reammunitions"), ret.reammunitions); - - return ret; -} - -QJsonObject SelectiveReammunition::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("gearId"), gearId}, - {QStringLiteral("reammunitions"), arrayToJson(reammunitions)} - }; -} - - -StateChange StateChange::fromJson(const QJsonObject &obj) -{ - StateChange ret; - StateChangeBase::fromJson(obj, ret); - get(obj, QStringLiteral("originatorType"), ret.originatorType); - return ret; -} - -QJsonObject StateChange::toJson() const -{ - QJsonObject obj = StateChangeBase::toJson(); - obj[QStringLiteral("originatorType")] = enumToJson(originatorType); - return obj; -} - - -CreateFunctionalArea CreateFunctionalArea::fromJson(const QJsonObject &obj) -{ - CreateFunctionalArea ret; - CreateAreaEffectSimulationBase::fromJson(obj, ret); - get(obj, QStringLiteral("relEffectPosition"), ret.relEffectPosition); - get(obj, QStringLiteral("width"), ret.width); - get(obj, QStringLiteral("height"), ret.height); - get(obj, QStringLiteral("deconTimeout"), ret.deconTimeout); - get(obj, QStringLiteral("maintenanceTimeout"), ret.maintenanceTimeout); - get(obj, QStringLiteral("medicalTimeout"), ret.medicalTimeout); - get(obj, QStringLiteral("deconMode"), ret.deconMode); - get(obj, QStringLiteral("maintenanceMode"), ret.maintenanceMode); - get(obj, QStringLiteral("medicalMode"), ret.medicalMode); - return ret; -} - -QJsonObject CreateFunctionalArea::toJson() const -{ - QJsonObject obj = CreateAreaEffectSimulationBase::toJson(); - obj[QStringLiteral("relEffectPosition")] = relEffectPosition.toJson(); - obj[QStringLiteral("width")] = width; - obj[QStringLiteral("height")] = height; - obj[QStringLiteral("deconTimeout")] = qint64(deconTimeout); - obj[QStringLiteral("maintenanceTimeout")] = qint64(maintenanceTimeout); - obj[QStringLiteral("medicalTimeout")] = qint64(medicalTimeout); - obj[QStringLiteral("deconMode")] = enumToJson(deconMode); - obj[QStringLiteral("maintenanceMode")] = enumToJson(maintenanceMode); - obj[QStringLiteral("medicalMode")] = enumToJson(medicalMode); - return obj; -} - - -FunctionalAreaEntry FunctionalAreaEntry::fromJson(const QJsonObject &obj) -{ - FunctionalAreaEntry ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - return ret; -} - -QJsonObject FunctionalAreaEntry::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("aesDdsId"), aesDdsId} - }; -} - - -RequestBroadcastTelegrams RequestBroadcastTelegrams::fromJson(const QJsonObject &obj) -{ - RequestBroadcastTelegrams ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("resetCounter"), ret.resetCounter); - get(obj, QStringLiteral("broadcastIndex"), ret.broadcastIndex); - return ret; -} - -QJsonObject RequestBroadcastTelegrams::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("resetCounter"), resetCounter}, - {QStringLiteral("broadcastIndex"), broadcastIndex} - }; -} - - -SpecialSensorData SpecialSensorData::fromJson(const QJsonObject &obj) -{ - SpecialSensorData ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("operationalState"), ret.operationalState); - get(obj, QStringLiteral("airSensor"), ret.airSensor); - get(obj, QStringLiteral("tireSensor"), ret.tireSensor); - get(obj, QStringLiteral("pointSensor"), ret.pointSensor); - get(obj, QStringLiteral("solidMatterSampleExtractor"), ret.solidMatterSampleExtractor); - get(obj, QStringLiteral("type"), ret.type); - get(obj, QStringLiteral("nbcType"), ret.nbcType); - return ret; -} - -QJsonObject SpecialSensorData::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("operationalState"), operationalState}, - {QStringLiteral("airSensor"), airSensor}, - {QStringLiteral("tireSensor"), tireSensor}, - {QStringLiteral("pointSensor"), pointSensor}, - {QStringLiteral("solidMatterSampleExtractor"), solidMatterSampleExtractor}, - {QStringLiteral("type"), type}, - {QStringLiteral("nbcType"), nbcType} - }; -} - - -void MinelayerTrailerDataBase::fromJson(const QJsonObject &obj, MinelayerTrailerDataBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("barrierId"), ret.barrierId); - get(obj, QStringLiteral("layingDensity"), ret.layingDensity); - get(obj, QStringLiteral("effectStart"), ret.effectStart); - get(obj, QStringLiteral("effectDuration"), ret.effectDuration); - get(obj, QStringLiteral("indirectChargeTasCode"), ret.indirectChargeTasCode); - get(obj, QStringLiteral("mineCount"), ret.mineCount); -} - -QJsonObject MinelayerTrailerDataBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("barrierId"), barrierId}, - {QStringLiteral("layingDensity"), layingDensity}, - {QStringLiteral("effectStart"), qint64(effectStart)}, - {QStringLiteral("effectDuration"), effectDuration}, - {QStringLiteral("indirectChargeTasCode"), indirectChargeTasCode}, - {QStringLiteral("mineCount"), mineCount} - }; -} - - -MinelayerTrailerData MinelayerTrailerData::fromJson(const QJsonObject &obj) -{ - MinelayerTrailerData ret; - MinelayerTrailerDataBase::fromJson(obj, ret); - return ret; -} - -QJsonObject MinelayerTrailerData::toJson() const -{ - return MinelayerTrailerDataBase::toJson(); -} - - -MinelayerThrowerData MinelayerThrowerData::fromJson(const QJsonObject &obj) -{ - MinelayerThrowerData ret; - MinelayerTrailerDataBase::fromJson(obj, ret); - get(obj, QStringLiteral("throwingType"), ret.throwingType); - return ret; -} - -QJsonObject MinelayerThrowerData::toJson() const -{ - QJsonObject obj = MinelayerTrailerDataBase::toJson(); - obj[QStringLiteral("throwingType")] = enumToJson(throwingType); - return obj; -} -MinelayerTrailerPosition MinelayerTrailerPosition::fromJson(const QJsonObject &obj) -{ - MinelayerTrailerPosition ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("indirectChargeTasCode"), ret.indirectChargeTasCode); - get(obj, QStringLiteral("dusSerialNo"), ret.dusSerialNo); - return ret; -} - -QJsonObject MinelayerTrailerPosition::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("indirectChargeTasCode"), indirectChargeTasCode}, - {QStringLiteral("dusSerialNo"), qint64(dusSerialNo)} - }; -} - - -LanguageSelection LanguageSelection::fromJson(const QJsonObject &obj) -{ - LanguageSelection ret; - get(obj, QStringLiteral("aesDdsId"), ret.header); - get(obj, QStringLiteral("languageSelection"), ret.languageSelection); - return ret; -} - -QJsonObject LanguageSelection::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("languageSelection"), enumToJson(languageSelection)} - }; -} - - -EquipmentMessage EquipmentMessage::fromJson(const QJsonObject &obj) -{ - EquipmentMessage ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("message"), ret.message); - get(obj, QStringLiteral("msgId"), ret.msgId); - return ret; -} - -QJsonObject EquipmentMessage::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("message"), QString::fromStdString(message)}, - {QStringLiteral("msgId"), msgId} - }; -} - - -EquipmentMessageOC EquipmentMessageOC::fromJson(const QJsonObject &obj) -{ - EquipmentMessageOC ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("subject"), ret.subject); - get(obj, QStringLiteral("message"), ret.message); - get(obj, QStringLiteral("senderId"), ret.senderId); - get(obj, QStringLiteral("receiverId"), ret.receiverId); - return ret; -} - -QJsonObject EquipmentMessageOC::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("subject"), QString::fromStdString(subject)}, - {QStringLiteral("message"), QString::fromStdString(message)}, - {QStringLiteral("senderId"), senderId}, - {QStringLiteral("receiverId"), receiverId} - }; -} - - -void OpaquePayloadDataBase::fromJson(const QJsonObject &obj, OpaquePayloadDataBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("payload"), ret.payload); - get(obj, QStringLiteral("payloadType"), ret.payloadType); -} - -QJsonObject OpaquePayloadDataBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("payload"), arrayToJson(payload)}, - {QStringLiteral("payloadType"), enumToJson(payloadType)} - }; -} - - -OpaquePayloadDataOut OpaquePayloadDataOut::fromJson(const QJsonObject &obj) -{ - OpaquePayloadDataOut ret; - OpaquePayloadDataBase::fromJson(obj, ret); - get(obj, QStringLiteral("header"), ret.header); - return ret; -} - -QJsonObject OpaquePayloadDataOut::toJson() const -{ - QJsonObject obj = OpaquePayloadDataBase::toJson(); - obj[QStringLiteral("header")] = header.toJson(); - return obj; -} - - -OpaquePayloadDataIn OpaquePayloadDataIn::fromJson(const QJsonObject &obj) -{ - OpaquePayloadDataIn ret; - OpaquePayloadDataBase::fromJson(obj, ret); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - return ret; -} - -QJsonObject OpaquePayloadDataIn::toJson() const -{ - QJsonObject obj = OpaquePayloadDataBase::toJson(); - obj[QStringLiteral("relPosition")] = relPosition.toJson(); - return obj; -} - - -EquipmentEvent EquipmentEvent::fromJson(const QJsonObject &obj) -{ - EquipmentEvent ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); - get(obj, QStringLiteral("subDeviceId"), ret.subDeviceId); - get(obj, QStringLiteral("uniqueId"), ret.uniqueId); - get(obj, QStringLiteral("code"), ret.code); - get(obj, QStringLiteral("payload"), ret.payload); - return ret; -} - -QJsonObject EquipmentEvent::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("equipmentFunctionId"), equipmentFunctionId}, - {QStringLiteral("subDeviceId"), subDeviceId}, - {QStringLiteral("uniqueId"), uniqueId}, - {QStringLiteral("code"), code}, - {QStringLiteral("payload"), arrayToJson(payload)} - }; -} - - -EquipmentGearAssignment EquipmentGearAssignment::fromJson(const QJsonObject &obj) -{ - EquipmentGearAssignment ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("gears"), ret.gears, true); - return ret; -} - -QJsonObject EquipmentGearAssignment::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("gears"), arrayToJson(gears)} - }; -} - - -EquipmentGearChargeState EquipmentGearChargeState::fromJson(const QJsonObject &obj) -{ - EquipmentGearChargeState ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("charges"), ret.charges); - return ret; -} - -QJsonObject EquipmentGearChargeState::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("charges"), arrayToJson(charges)} - }; -} - - -ExerciseEnvironmentData ExerciseEnvironmentData::fromJson(const QJsonObject &obj) -{ - ExerciseEnvironmentData ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("exerciseId"), ret.exerciseId); - int tz; - get(obj, QStringLiteral("timeZone"), tz); - ret.timeZone = tz; - get(obj, QStringLiteral("utmZone"), ret.utmZone); - get(obj, QStringLiteral("utmBand"), ret.utmBand); - get(obj, QStringLiteral("grid"), ret.grid); - return ret; -} - -QJsonObject ExerciseEnvironmentData::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("exerciseId"), exerciseId}, - {QStringLiteral("timeZone"), timeZone}, - {QStringLiteral("utmZone"), utmZone}, - {QStringLiteral("utmBand"), utmBand}, - {QStringLiteral("grid"), QString::fromStdString(grid)} - }; -} - - -BiteError BiteError::fromJson(const QJsonObject &obj) -{ - BiteError ret; - get(obj, QStringLiteral("errorNumber"), ret.errorNumber); - get(obj, QStringLiteral("canDeviceNumber"), ret.canDeviceNumber); - get(obj, QStringLiteral("subdeviceNumber"), ret.subdeviceNumber); - get(obj, QStringLiteral("uniqueId"), ret.uniqueId); - return ret; -} - -QJsonObject BiteError::toJson() const -{ - return QJsonObject{{QStringLiteral("errorNumber"), errorNumber}, - {QStringLiteral("canDeviceNumber"), canDeviceNumber}, - {QStringLiteral("subdeviceNumber"), subdeviceNumber}, - {QStringLiteral("uniqueId"), uniqueId} - }; -} - - -BiteReport BiteReport::fromJson(const QJsonObject &obj) -{ - BiteReport ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("loginType"), ret.loginType); - get(obj, QStringLiteral("biteState"), ret.biteState); - get(obj, QStringLiteral("configState"), ret.configState); - get(obj, QStringLiteral("batteryState"), ret.batteryState); - get(obj, QStringLiteral("configError"), ret.configError); - get(obj, QStringLiteral("biteErrors"), ret.biteErrors, true); - return ret; -} - -QJsonObject BiteReport::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("loginType"), enumToJson(loginType)}, - {QStringLiteral("biteState"), biteState}, - {QStringLiteral("configState"), configState}, - {QStringLiteral("batteryState"), batteryState}, - {QStringLiteral("configError"), configError}, - {QStringLiteral("biteErrors"), arrayToJson(biteErrors)} - }; -} - - -EquipmentGearEvent EquipmentGearEvent::fromJson(const QJsonObject &obj) -{ - EquipmentGearEvent ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("charge"), ret.charge); - get(obj, QStringLiteral("chargeAmount"), ret.chargeAmount); - return ret; -} - -QJsonObject EquipmentGearEvent::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("charge"), charge.toJson()}, - {QStringLiteral("chargeAmount"), chargeAmount} - }; -} - - -CesHitInformation CesHitInformation::fromJson(const QJsonObject &obj) -{ - CesHitInformation ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("chargeTasCodeDirect"), ret.chargeTasCodeDirect); - get(obj, QStringLiteral("chargeTasCodeIndirect"), ret.chargeTasCodeIndirect); - get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); - get(obj, QStringLiteral("directionDegree"), ret.directionDegree); - get(obj, QStringLiteral("distance"), ret.distance); - get(obj, QStringLiteral("effectPercent"), ret.effectPercent); - return ret; -} - -QJsonObject CesHitInformation::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("chargeTasCodeDirect"), chargeTasCodeDirect}, - {QStringLiteral("chargeTasCodeIndirect"), chargeTasCodeIndirect}, - {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, - {QStringLiteral("directionDegree"), directionDegree}, - {QStringLiteral("distance"), distance}, - {QStringLiteral("effectPercent"), effectPercent} - }; -} - - -ParticipantSwVersionsRequest ParticipantSwVersionsRequest::fromJson(const QJsonObject &obj) -{ - ParticipantSwVersionsRequest ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("charge"), ret.equipmentFunctionId); - return ret; -} - -QJsonObject ParticipantSwVersionsRequest::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("chargeAmount"), equipmentFunctionId} - }; -} - - -EquipmentSwVersion EquipmentSwVersion::fromJson(const QJsonObject &obj) -{ - EquipmentSwVersion ret; - get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); - get(obj, QStringLiteral("subDeviceId"), ret.subDeviceId); - get(obj, QStringLiteral("uniqueId"), ret.uniqueId); - get(obj, QStringLiteral("swVersion"), ret.swVersion); - return ret; -} - -QJsonObject EquipmentSwVersion::toJson() const -{ - return QJsonObject{{QStringLiteral("equipmentFunctionId"), equipmentFunctionId}, - {QStringLiteral("subDeviceId"), subDeviceId}, - {QStringLiteral("uniqueId"), uniqueId}, - {QStringLiteral("swVersion"), swVersion} - }; -} - - -ParticipantSwVersions ParticipantSwVersions::fromJson(const QJsonObject &obj) -{ - ParticipantSwVersions ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("subDeviceId"), ret.equipments); - return ret; -} - -QJsonObject ParticipantSwVersions::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("subDeviceId"), arrayToJson(equipments)} - }; -} - - -CesHitRequest CesHitRequest::fromJson(const QJsonObject &obj) -{ - CesHitRequest ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("chargeTasCodeDirect"), ret.chargeTasCodeDirect); - get(obj, QStringLiteral("chargeTasCodeIndirect"), ret.chargeTasCodeIndirect); - get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("aesType"), ret.aesType); - get(obj, QStringLiteral("mineId"), ret.mineId); - get(obj, QStringLiteral("remainEffectPercent"), ret.remainEffectPercent); - get(obj, QStringLiteral("remainEffectTasCodeDirect"), ret.remainEffectTasCodeDirect); - get(obj, QStringLiteral("buildingId"), ret.buildingId); - get(obj, QStringLiteral("roomId"), ret.roomId); - get(obj, QStringLiteral("relPosition"), ret.relPosition); - get(obj, QStringLiteral("reserve1"), ret.reserve1); - get(obj, QStringLiteral("reserve2"), ret.reserve2); - - return ret; -} - -QJsonObject CesHitRequest::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("chargeTasCodeDirect"), chargeTasCodeDirect}, - {QStringLiteral("chargeTasCodeIndirect"), chargeTasCodeIndirect}, - {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, - {QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("aesType"), enumToJson(aesType)}, - {QStringLiteral("mineId"), mineId}, - {QStringLiteral("remainEffectPercent"), remainEffectPercent}, - {QStringLiteral("remainEffectTasCodeDirect"), remainEffectTasCodeDirect}, - {QStringLiteral("buildingId"), buildingId}, - {QStringLiteral("roomId"), roomId}, - {QStringLiteral("relPosition"), relPosition.toJson()}, - {QStringLiteral("reserve1"), reserve1}, - {QStringLiteral("reserve2"), reserve2} - }; -} - - -TechnicalArea TechnicalArea::fromJson(const QJsonObject &obj) -{ - TechnicalArea ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); - get(obj, QStringLiteral("taType"), ret.taType); - get(obj, QStringLiteral("name"), ret.name); - get(obj, QStringLiteral("relCorner"), ret.relCorner); - get(obj, QStringLiteral("width"), ret.width); - get(obj, QStringLiteral("height"), ret.height); - return ret; -} - -QJsonObject TechnicalArea::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("aesDdsId"), aesDdsId}, - {QStringLiteral("taType"), enumToJson(taType)}, - {QStringLiteral("name"), QString::fromStdString(name)}, - {QStringLiteral("relCorner"), relCorner.toJson()}, - {QStringLiteral("width"), width}, - {QStringLiteral("height"), height} - }; -} - - -void ParticipantModeBase::fromJson(const QJsonObject &obj, ParticipantModeBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("language"), ret.language); - get(obj, QStringLiteral("operationMode"), ret.operationMode); - get(obj, QStringLiteral("reactivationDetoxication"), ret.reactivationDetoxication); - get(obj, QStringLiteral("reactivationMaintenance"), ret.reactivationMaintenance); - get(obj, QStringLiteral("reactivationMedic"), ret.reactivationMedic); - get(obj, QStringLiteral("modeVest"), ret.modeVest); - get(obj, QStringLiteral("modeHelmet"), ret.modeHelmet); - get(obj, QStringLiteral("personellProtectionMode"), ret.personellProtectionMode); - get(obj, QStringLiteral("protectionLevel"), ret.protectionLevel); - get(obj, QStringLiteral("handgrenadeSearchMode"), ret.handgrenadeSearchMode); - get(obj, QStringLiteral("internationalMode"), ret.internationalMode); - get(obj, QStringLiteral("abcProtectionMode"), ret.abcProtectionMode); -} - -QJsonObject ParticipantModeBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("language"), enumToJson(language)}, - {QStringLiteral("operationMode"), enumToJson(operationMode)}, - {QStringLiteral("reactivationDetoxication"), reactivationDetoxication}, - {QStringLiteral("reactivationMaintenance"), reactivationMaintenance}, - {QStringLiteral("reactivationMedic"), reactivationMedic}, - {QStringLiteral("modeVest"), enumToJson(modeVest)}, - {QStringLiteral("modeHelmet"), enumToJson(modeHelmet)}, - {QStringLiteral("personellProtectionMode"), enumToJson(personellProtectionMode)}, - {QStringLiteral("protectionLevel"), enumToJson(protectionLevel)}, - {QStringLiteral("handgrenadeSearchMode"), enumToJson(handgrenadeSearchMode)}, - {QStringLiteral("internationalMode"), enumToJson(internationalMode)}, - {QStringLiteral("abcProtectionMode"), enumToJson(abcProtectionMode)} - }; -} - - -ParticipantMode ParticipantMode::fromJson(const QJsonObject &obj) -{ - ParticipantMode ret; - ParticipantModeBase::fromJson(obj, ret); - return ret; -} - -QJsonObject ParticipantMode::toJson() const -{ - return ParticipantModeBase::toJson(); -} - - -ParticipantModeReport ParticipantModeReport::fromJson(const QJsonObject &obj) -{ - ParticipantModeReport ret; - ParticipantModeBase::fromJson(obj, ret); - return ret; -} - -QJsonObject ParticipantModeReport::toJson() const -{ - return ParticipantModeBase::toJson(); -} - - -DemandParticipantMode DemandParticipantMode::fromJson(const QJsonObject &obj) -{ - DemandParticipantMode ret; - get(obj, QStringLiteral("header"), ret.header); - return ret; -} - -QJsonObject DemandParticipantMode::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}}; -} - - -void ParticipantConfigurationBase::fromJson(const QJsonObject &obj, ParticipantConfigurationBase &ret) -{ - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("positionIntervallVehicle"), ret.positionIntervallVehicle); - get(obj, QStringLiteral("positionIntervallPersonell"), ret.positionIntervallPersonell); - get(obj, QStringLiteral("positionIntervallAircraft"), ret.positionIntervallAircraft); - get(obj, QStringLiteral("positionTransmissionIntervall"), ret.positionTransmissionIntervall); - get(obj, QStringLiteral("heightbarrier"), ret.heightbarrier); - get(obj, QStringLiteral("faultPositionHandling"), ret.faultPositionHandling); - get(obj, QStringLiteral("switchingPositionIntervall"), ret.switchingPositionIntervall); - get(obj, QStringLiteral("waittimeAdditionalBroadcastDemand"), ret.waittimeAdditionalBroadcastDemand); - get(obj, QStringLiteral("factorWaittimeIncreaseAtHighload"), ret.factorWaittimeIncreaseAtHighload); - get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel1"), ret.waittimeAutomaticVulnerabilityIncreaseLevel1); - get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel2"), ret.waittimeAutomaticVulnerabilityIncreaseLevel2); - get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel3"), ret.waittimeAutomaticVulnerabilityIncreaseLevel3); - get(obj, QStringLiteral("opticalCode"), ret.opticalCode); - get(obj, QStringLiteral("vulnerabilityModel"), ret.vulnerabilityModel); - get(obj, QStringLiteral("validTimeOps"), ret.validTimeOps); -} - -QJsonObject ParticipantConfigurationBase::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("positionIntervallVehicle"), positionIntervallVehicle}, - {QStringLiteral("positionIntervallPersonell"), positionIntervallPersonell}, - {QStringLiteral("positionIntervallAircraft"), positionIntervallAircraft}, - {QStringLiteral("positionTransmissionIntervall"), positionTransmissionIntervall}, - {QStringLiteral("heightbarrier"), heightbarrier}, - {QStringLiteral("faultPositionHandling"), enumToJson(faultPositionHandling)}, - {QStringLiteral("switchingPositionIntervall"), enumToJson(switchingPositionIntervall)}, - {QStringLiteral("waittimeAdditionalBroadcastDemand"), waittimeAdditionalBroadcastDemand}, - {QStringLiteral("factorWaittimeIncreaseAtHighload"), factorWaittimeIncreaseAtHighload}, - {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel1"), waittimeAutomaticVulnerabilityIncreaseLevel1}, - {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel2"), waittimeAutomaticVulnerabilityIncreaseLevel2}, - {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel3"), waittimeAutomaticVulnerabilityIncreaseLevel3}, - {QStringLiteral("opticalCode"), enumToJson(opticalCode)}, - {QStringLiteral("vulnerabilityModel"), vulnerabilityModel}, - {QStringLiteral("validTimeOps"), validTimeOps} - }; -} - - -ParticipantConfigurationReport ParticipantConfigurationReport::fromJson(const QJsonObject &obj) -{ - ParticipantConfigurationReport ret; - ParticipantConfigurationBase::fromJson(obj, ret); - return ret; -} - -QJsonObject ParticipantConfigurationReport::toJson() const -{ - return ParticipantConfigurationBase::toJson(); -} - - -ParticipantConfiguration ParticipantConfiguration::fromJson(const QJsonObject &obj) -{ - ParticipantConfiguration ret; - ParticipantConfigurationBase::fromJson(obj, ret); - return ret; -} - -QJsonObject ParticipantConfiguration::toJson() const -{ - return ParticipantConfigurationBase::toJson(); -} - - -DemandParticipantConfiguration DemandParticipantConfiguration::fromJson(const QJsonObject &obj) -{ - DemandParticipantConfiguration ret; - get(obj, QStringLiteral("header"), ret.header); - return ret; -} - -QJsonObject DemandParticipantConfiguration::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}}; -} - - -ExerciseStateData ExerciseStateData::fromJson(const QJsonObject &obj) -{ - ExerciseStateData ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("exerciseState"), ret.exerciseState); - get(obj, QStringLiteral("exerciseId"), ret.exerciseId); - return ret; -} - -QJsonObject ExerciseStateData::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("exerciseState"), enumToJson(exerciseState)}, - {QStringLiteral("exerciseId"), exerciseId} - }; -} - - -EmergencyCall EmergencyCall::fromJson(const QJsonObject &obj) -{ - EmergencyCall ret; - get(obj, QStringLiteral("issi"), ret.issi); - get(obj, QStringLiteral("absPosition"), ret.absPosition); - get(obj, QStringLiteral("timeStamp"), ret.timeStamp); - return ret; -} - -QJsonObject EmergencyCall::toJson() const -{ - return QJsonObject{{QStringLiteral("issi"), issi}, - {QStringLiteral("absPosition"), absPosition.toJson()}, - {QStringLiteral("timeStamp"), timeStamp} - }; -} - - -RequestBroadcastStatistics RequestBroadcastStatistics::fromJson(const QJsonObject &obj) -{ - RequestBroadcastStatistics ret; - get(obj, QStringLiteral("header"), ret.header); - return ret; -} - -QJsonObject RequestBroadcastStatistics::toJson() const -{ - return QJsonObject{{QStringLiteral("issi"), header.toJson()}}; -} - - -BroadcastInformation BroadcastInformation::fromJson(const QJsonObject &obj) -{ - BroadcastInformation ret; - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("broadcastRequests"), ret.broadcastRequests); - return ret; -} - -QJsonObject BroadcastInformation::toJson() const -{ - return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, - {QStringLiteral("broadcastRequests"), broadcastRequests} - }; -} - - -BroadcastStatistics BroadcastStatistics::fromJson(const QJsonObject &obj) -{ - BroadcastStatistics ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("information"), ret.information); - return ret; -} - -QJsonObject BroadcastStatistics::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("information"), arrayToJson(information)} - }; -} - - -GroupIssiInformation GroupIssiInformation::fromJson(const QJsonObject &obj) -{ - GroupIssiInformation ret; - get(obj, QStringLiteral("exerciseId"), ret.exerciseId); - get(obj, QStringLiteral("serverIssi"), ret.serverIssi); - get(obj, QStringLiteral("broadcastIssi1"), ret.broadcastIssi1); - get(obj, QStringLiteral("broadcastIssi2"), ret.broadcastIssi2); - return ret; -} - -QJsonObject GroupIssiInformation::toJson() const -{ - return QJsonObject{{QStringLiteral("exerciseId"), exerciseId}, - {QStringLiteral("serverIssi"), serverIssi}, - {QStringLiteral("broadcastIssi1"), broadcastIssi1}, - {QStringLiteral("broadcastIssi2"), broadcastIssi2} - }; -} - - -ExerciseEquipmentAssignmentComplete ExerciseEquipmentAssignmentComplete::fromJson(const QJsonObject &obj) -{ - ExerciseEquipmentAssignmentComplete ret; - QJsonArray arrExercise; - get(obj, QStringLiteral("exerciseEquipmentAssignments"), arrExercise); - for (const auto &ele : std::as_const(arrExercise)) - { - const QJsonObject elem = ele.toObject(); - int exerciseId; - QJsonArray equipmentNumbers; - get(elem, QStringLiteral("exerciseId"), exerciseId); - get(elem, QStringLiteral("equipmentNumbers"), equipmentNumbers); - auto &cont = ret.exerciseEquipmentAssignments[exerciseId]; - for (const auto &eq : std::as_const(equipmentNumbers)) - cont.insert(eq.toInt()); - } - get(obj, QStringLiteral("groupIssiInformation"), ret.groupIssiInformation); - return ret; -} - -QJsonObject ExerciseEquipmentAssignmentComplete::toJson() const -{ - QJsonArray arrExercise; - for (const auto &it : exerciseEquipmentAssignments) - { - QJsonArray equipmentNumbers; - for (const int equipmentNumber : it.second) - equipmentNumbers += equipmentNumber; - arrExercise += QJsonObject{{QStringLiteral("exerciseId"), it.first}, - {QStringLiteral("equipmentNumbers"), equipmentNumbers} - }; - } - - return QJsonObject{{QStringLiteral("exerciseEquipmentAssignments"), arrExercise}, - {QStringLiteral("groupIssiInformation"), arrayToJson(groupIssiInformation)} - }; -} - - -ProxyConnectionState ProxyConnectionState::fromJson(const QJsonObject &obj) -{ - ProxyConnectionState ret; - get(obj, QStringLiteral("connectedToSystem"), ret.connectedToSystem); - return ret; -} - -QJsonObject ProxyConnectionState::toJson() const -{ - return QJsonObject{{QStringLiteral("connectedToSystem"), connectedToSystem}}; -} - - -ParticipantLicenseChange ParticipantLicenseChange::fromJson(const QJsonObject &obj) -{ - ParticipantLicenseChange ret; - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("licenseState"), ret.licenseState); - return ret; -} - -QJsonObject ParticipantLicenseChange::toJson() const -{ - return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, - {QStringLiteral("licenseState"), enumToJson(licenseState)} - }; -} - - -WlsParticipantsStateRequest WlsParticipantsStateRequest::fromJson(const QJsonObject &obj) -{ - Q_UNUSED(obj); - return WlsParticipantsStateRequest(); -} - -QJsonObject WlsParticipantsStateRequest::toJson() const -{ - return QJsonObject(); -} - - -WlsParticipantsStateReport WlsParticipantsStateReport::fromJson(const QJsonObject &obj) -{ - WlsParticipantsStateReport ret; - get(obj, QStringLiteral("participantStates"), ret.participantStates); - return ret; -} - -QJsonObject WlsParticipantsStateReport::toJson() const -{ - return QJsonObject{{QStringLiteral("participantStates"), arrayToJson(participantStates)}}; -} - - -WlsBinarySfmData WlsBinarySfmData::fromJson(const QJsonObject &obj) -{ - WlsBinarySfmData ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("payload"), ret.payload); - return ret; -} - -QJsonObject WlsBinarySfmData::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("payload"), arrayToJson(payload)} - }; -} - - -WlsParticipantsConnectionState WlsParticipantsConnectionState::fromJson(const QJsonObject &obj) -{ - WlsParticipantsConnectionState ret; - get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); - get(obj, QStringLiteral("dataCommunicationPossible"), ret.dataCommunicationPossible); - return ret; -} - -QJsonObject WlsParticipantsConnectionState::toJson() const -{ - return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, - {QStringLiteral("dataCommunicationPossible"), dataCommunicationPossible} - }; -} - - -SanitationRepair SanitationRepair::fromJson(const QJsonObject &obj) -{ - SanitationRepair ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("originatorType"), ret.originatorType); - get(obj, QStringLiteral("equipmentNumberOrigin"), ret.equipmentNumberOrigin); - get(obj, QStringLiteral("stateStart"), ret.stateStart); - get(obj, QStringLiteral("typeOfTreatment"), ret.typeOfTreatment); - get(obj, QStringLiteral("triage"), ret.triage); - get(obj, QStringLiteral("tyeOfDamage"), ret.tyeOfDamage); - get(obj, QStringLiteral("stateResult"), ret.stateResult); - get(obj, QStringLiteral("treatmentResult"), ret.treatmentResult); - get(obj, QStringLiteral("triagePriority"), ret.triagePriority); - get(obj, QStringLiteral("fullState"), ret.fullState); - get(obj, QStringLiteral("timeOfTreatment"), ret.timeOfTreatment); - get(obj, QStringLiteral("timeOfRecovery"), ret.timeOfRecovery); - - return ret; -} - -QJsonObject SanitationRepair::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("originatorType"), enumToJson(originatorType)}, - {QStringLiteral("equipmentNumberOrigin"), equipmentNumberOrigin}, - {QStringLiteral("stateStart"), enumToJson(stateStart)}, - {QStringLiteral("typeOfTreatment"), typeOfTreatment}, - {QStringLiteral("triage"), triage}, - {QStringLiteral("tyeOfDamage"), tyeOfDamage}, - {QStringLiteral("stateResult"), enumToJson(stateResult)}, - {QStringLiteral("treatmentResult"), enumToJson(treatmentResult)}, - {QStringLiteral("triagePriority"), triagePriority}, - {QStringLiteral("fullState"), fullState}, - {QStringLiteral("timeOfTreatment"), timeOfTreatment}, - {QStringLiteral("timeOfRecovery"), timeOfRecovery} - }; -} - -SanitaryMaterialStockReport SanitaryMaterialStockReport::fromJson(const QJsonObject &obj) -{ - SanitaryMaterialStockReport ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); - get(obj, QStringLiteral("qualification"), ret.qualification); - get(obj, QStringLiteral("uniqueId"), ret.uniqueId); - get(obj, QStringLiteral("sanitaryMaterialCount"), ret.sanitaryMaterialCount); - get(obj, QStringLiteral("sanitaryMaterialStock"), ret.sanitaryMaterialStock); - return ret; -} - -QJsonObject SanitaryMaterialStockReport::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("sanitaryMaterialCount"), sanitaryMaterialCount}, - {QStringLiteral("uniqueId"), uniqueId}, - {QStringLiteral("sanitaryMaterialStock"), arrayToJson(sanitaryMaterialStock)}, - {QStringLiteral("qualification"), enumToJson(qualification)}, - {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber} - }; -} - -ApacheLaserDesignation ApacheLaserDesignation::fromJson(const QJsonObject &obj) -{ - ApacheLaserDesignation ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("gearId"), ret.gearId); - get(obj, QStringLiteral("code"), ret.code); - get(obj, QStringLiteral("outputPower"), ret.outputPower); - get(obj, QStringLiteral("spotLocation"), ret.spotLocation); - return ret; -} - -QJsonObject ApacheLaserDesignation::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("gearId"), gearId}, - {QStringLiteral("code"), code}, - {QStringLiteral("outputPower"), outputPower}, - {QStringLiteral("spotLocation"), spotLocation.toJson()} - }; -} - -Sanitation Sanitation::fromJson(const QJsonObject &obj) -{ - Sanitation ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); - get(obj, QStringLiteral("uniqeId"), ret.uniqeId); - get(obj, QStringLiteral("proceduresTaken"), ret.proceduresTaken); - get(obj, QStringLiteral("sanitationResult"), ret.sanitationResult); - get(obj, QStringLiteral("sanitationEvaluation"), ret.sanitationEvaluation); - get(obj, QStringLiteral("qualification"), ret.qualification); - return ret; -} - -QJsonObject Sanitation::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, - {QStringLiteral("uniqeId"), uniqeId}, - {QStringLiteral("proceduresTaken"), proceduresTaken}, - {QStringLiteral("sanitationResult"), enumToJson(sanitationResult)}, - {QStringLiteral("sanitationEvaluation"), enumToJson(sanitationEvaluation)}, - {QStringLiteral("qualification"), enumToJson(qualification)} - }; -} - -BatteryInfo BatteryInfo::fromJson(const QJsonObject &obj) -{ - BatteryInfo ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("batteryStates"), ret.batteryStates); - - return ret; -} - -QJsonObject BatteryInfo::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("batteryStates"), arrayToJson(batteryStates)} - }; -} - -BatteryAlarm BatteryAlarm::fromJson(const QJsonObject &obj) -{ - BatteryAlarm ret; - get(obj, QStringLiteral("header"), ret.m_header); - get(obj, QStringLiteral("id"), ret.m_id); - get(obj, QStringLiteral("description"), ret.m_description); - get(obj, QStringLiteral("acknowledge"), ret.m_acknowledge); - get(obj, QStringLiteral("condition"), ret.m_condition); - get(obj, QStringLiteral("uniqueAlarmNumber"), ret.m_uniqueAlarmNumber); - get(obj, QStringLiteral("alarmTime"), ret.m_alarmTime); - return ret; -} - -QJsonObject BatteryAlarm::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header().toJson()}, - {QStringLiteral("id"), m_id}, - {QStringLiteral("description"), description()}, - {QStringLiteral("acknowledge"), acknowledge()}, - {QStringLiteral("condition"), condition()}, - {QStringLiteral("uniqueAlarmNumber"), uniqueAlarmNumber()}, - {QStringLiteral("alarmTime"), alarmTime()} - }; -} - -ServiceControl ServiceControl::fromJson(const QJsonObject &obj) -{ - ServiceControl ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("serviceControlState"), ret.serviceControlState); - - return ret; -} - -QJsonObject ServiceControl::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("serviceControlState"), enumToJson(serviceControlState)} - }; -} - -SetDevicePowerRequest SetDevicePowerRequest::fromJson(const QJsonObject &obj) -{ - SetDevicePowerRequest ret; - get(obj, QStringLiteral("header"), ret.header); - get(obj, QStringLiteral("powerType"), ret.powerType); - get(obj, QStringLiteral("subdeviceId"), ret.subdeviceId); - - return ret; -} - -QJsonObject SetDevicePowerRequest::toJson() const -{ - return QJsonObject{{QStringLiteral("header"), header.toJson()}, - {QStringLiteral("powerType"), enumToJson(powerType)}, - {QStringLiteral("subdeviceId"), subdeviceId} - }; -} - -RestoreRadioReadiness RestoreRadioReadiness::fromJson(const QJsonObject &obj) -{ - RestoreRadioReadiness ret; - - get(obj, HEADER(), ret.header); - get(obj, READINESS_LOSS_POSITION(), ret.readinessLossPosition); - get(obj, READINESS_LOSS_TIME(), ret.readinessLossTime); - get(obj, READINESS_RESTORE_POSITION(), ret.readinessRestorePosition); - get(obj, READINESS_RESTORE_TIME(), ret.readinessRestoreTime); - - return ret; -} - -QJsonObject RestoreRadioReadiness::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {READINESS_LOSS_POSITION(), readinessLossPosition.toJson()}, - {READINESS_LOSS_TIME(), readinessLossTime}, - {READINESS_RESTORE_POSITION(), readinessRestorePosition.toJson()}, - {READINESS_RESTORE_TIME(), readinessRestoreTime} - }; -} - - -UAVAction UAVAction::fromJson(const QJsonObject &obj) -{ - UAVAction ret; - - get(obj, TASK(), ret.task); - get(obj, POSITION(), ret.absPosition); - - return ret; -} - -QJsonObject UAVAction::toJson() const -{ - return QJsonObject{{TASK(), enumToJson(task)}, - {POSITION(), absPosition.toJson()}}; -} - - -UAVPerformMission UAVPerformMission::fromJson(const QJsonObject &obj) -{ - UAVPerformMission ret; - - get(obj, HEADER(), ret.header); - get(obj, ACTIONS(), ret.actions); - get(obj, MISSION_NAME(), ret.missionName); - get(obj, MISSION_ID(), ret.missionId); - - return ret; -} - -QJsonObject UAVPerformMission::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {ACTIONS(), arrayToJson(actions)}, - {MISSION_NAME(), missionName}, - {MISSION_ID(), missionId}}; -} - - - -UAVStatus UAVStatus::fromJson(const QJsonObject &obj) -{ - UAVStatus ret; - - get(obj, HEADER(), ret.header); - get(obj, UAVSTATE(), ret.uavState); - - return ret; -} - -QJsonObject UAVStatus::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {UAVSTATE(), enumToJson(uavState)}}; -} - - - -UAVRadioLinkConnectionStatus UAVRadioLinkConnectionStatus::fromJson(const QJsonObject &obj) -{ - UAVRadioLinkConnectionStatus ret; - - get(obj, HEADER(), ret.header); - get(obj, UAVCONNECTIONSTATE(), ret.uavConnectionState); - - return ret; -} - -QJsonObject UAVRadioLinkConnectionStatus::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {UAVCONNECTIONSTATE(), enumToJson(uavConnectionState)}}; -} - - - -UAVMissionStatus UAVMissionStatus::fromJson(const QJsonObject &obj) -{ - UAVMissionStatus ret; - - get(obj, HEADER(), ret.header); - get(obj, CURRENT_ACTION(), ret.currentAction); - get(obj, CURRENT_MISSION_NAME(), ret.currentMissionName); - get(obj, MISSION_ENDED(), ret.missionEnded); - - return ret; -} - -QJsonObject UAVMissionStatus::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {CURRENT_ACTION(), enumToJson(currentAction)}, - {CURRENT_MISSION_NAME(), currentMissionName}, - {MISSION_ENDED(), missionEnded}}; -} + } + + template <> bool get(const QJsonObject &obj, const QString &key, QJsonArray &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isArray()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toArray(); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, bool &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isBool()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toBool(); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, qint32 &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isDouble()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toInt(); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, quint32 &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isDouble()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = uint32_t(jVal.toDouble()); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, qint64 &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isDouble()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = int64_t(jVal.toDouble()); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, double &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isDouble()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toDouble(); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, QString &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isString()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toString(); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, std::string &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isString()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + val = jVal.toString().toStdString(); + return true; + } + + template bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional = false) + { + const QJsonValue jVal = obj[key]; + if (!jVal.isNull() && !jVal.isArray()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + if (jVal.isNull()) + return false; + const QJsonArray arr = jVal.toArray(); + val.clear(); + val.reserve(arr.size()); + for (const auto &ele : arr) + val.push_back(T::fromJson(ele.toObject())); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional) + { + const auto jVal = obj[key]; + if (!jVal.isArray()) + { + if (bOptional) + return false; + throw JsonException(obj, key); + } + const QJsonArray arr = jVal.toArray(); + val.clear(); + val.reserve(arr.size()); + for (const auto &v : arr) + { + if (!v.isDouble()) + throw JsonException(obj, key); + val.push_back(v.toInt()); + } + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, std::vector &val, bool bOptional) + { + QString sPayload; + if (!get(obj, key, sPayload, bOptional)) + return false; + const QByteArray ba = QByteArray::fromHex(sPayload.toLatin1()); + val.clear(); + val.reserve(ba.size()); + std::copy(ba.begin(), ba.end(), std::back_inserter(val)); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, VulnerabilityState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + + val = static_cast(iVal); + return true; + } + + template <> bool get(const QJsonObject &obj, const QString &key, OriginatorType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case OriginatorType::Initialisation: + case OriginatorType::ObserverController: + case OriginatorType::ExerciseControl: + case OriginatorType::FunctionalArea: + case OriginatorType::MedicTimeout: + case OriginatorType::Sanitation: + case OriginatorType::MedicDecontamination: + case OriginatorType::MaintainanceRepair: + case OriginatorType::MaintainanceDecontamination: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, FunctionalAreaOperatingMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case FunctionalAreaOperatingMode::NotUsed: + case FunctionalAreaOperatingMode::OperatedByOC: + case FunctionalAreaOperatingMode::WaitForTimeout: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, Language &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case Language::NoChange: + case Language::German: + case Language::English: + case Language::French: + case Language::Arabic: + case Language::Spanish: + case Language::Russian: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantLicenseState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantLicenseState::Unknown: + case ParticipantLicenseState::Licensed: + case ParticipantLicenseState::Rejected: + case ParticipantLicenseState::Unlicense: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::MineHandgrenadeSensorMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::MineHandgrenadeSensorMode::PersonellMode: + case EquipmentConfigurationReport::MineHandgrenadeSensorMode::NormalVehicleMode: + case EquipmentConfigurationReport::MineHandgrenadeSensorMode::OcVehicleMode: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::FirMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::FirMode::NoFir: + case EquipmentConfigurationReport::FirMode::Fir: + case EquipmentConfigurationReport::FirMode::FirSpzMarder: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::MineLayerMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::MineLayerMode::NoMineLayerDevice: + case EquipmentConfigurationReport::MineLayerMode::MinLayerTrailer: + case EquipmentConfigurationReport::MineLayerMode::MineLayerThrower: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::SpecialSensorStandardMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::SpecialSensorStandardMode::NoSpecialSensorStandard: + case EquipmentConfigurationReport::SpecialSensorStandardMode::ZABC: + case EquipmentConfigurationReport::SpecialSensorStandardMode::CSF: + case EquipmentConfigurationReport::SpecialSensorStandardMode::PzBr: + case EquipmentConfigurationReport::SpecialSensorStandardMode::MRF: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::AgdusHwMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::AgdusHwMode::WithoutHelmetWithoutVest: + case EquipmentConfigurationReport::AgdusHwMode::WithHelmetWithoutVest: + case EquipmentConfigurationReport::AgdusHwMode::WithHelmetWithVest: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, EquipmentConfigurationReport::PositionUpdateInterval &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case EquipmentConfigurationReport::PositionUpdateInterval::Vehicle: + case EquipmentConfigurationReport::PositionUpdateInterval::Personnell: + case EquipmentConfigurationReport::PositionUpdateInterval::Aircraft: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, CtaDataError::Reason &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case CtaDataError::Reason::WrongParameter: + case CtaDataError::Reason::TelegramOutdated: + case CtaDataError::Reason::InvalidByteCount: + case CtaDataError::Reason::InvalidData: + case CtaDataError::Reason::FragmentationError: + case CtaDataError::Reason::Unknown: + case CtaDataError::Reason::AdditionalDemandTimeout: + case CtaDataError::Reason::ErrorLoginEquipmentNumber: + case CtaDataError::Reason::ErrorLoginTetraId: + case CtaDataError::Reason::InfoLoginMasteringFlag: + case CtaDataError::Reason::ErrorSendingNamelist: + case CtaDataError::Reason::ErrorSendingToExerciseControl: + case CtaDataError::Reason::ErrorNotLoggedIn: + case CtaDataError::Reason::ErrorNotLicensed: + case CtaDataError::Reason::ErrorConfigSelfTest: + case CtaDataError::Reason::JsonDecodeFailure: + case CtaDataError::Reason::WrongCrc: + case CtaDataError::Reason::BroadcastCounterOverflow: + case CtaDataError::Reason::InvalidTime: + case CtaDataError::Reason::InvalidPosition: + case CtaDataError::Reason::InvalidTacticalState: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, CreateCContamination::Volatiliy &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case CreateCContamination::Volatiliy::Floating: + case CreateCContamination::Volatiliy::Resident: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, AreaEffectSimulationType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case AreaEffectSimulationType::Unknown: + case AreaEffectSimulationType::MineArea: + case AreaEffectSimulationType::ExplosionArea: + case AreaEffectSimulationType::ExplosionSingle: + case AreaEffectSimulationType::NContamination: + case AreaEffectSimulationType::CContamination: + case AreaEffectSimulationType::FunctionalArea: + case AreaEffectSimulationType::TechnicalArea: + case AreaEffectSimulationType::DusSingleMineSimulator: + case AreaEffectSimulationType::GasPipeDetonation: + case AreaEffectSimulationType::SpecialArea: + case AreaEffectSimulationType::BeStillWarning: + case AreaEffectSimulationType::DangerZoneExplosion: + case AreaEffectSimulationType::AirSupport: + + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, IedType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case IedType::SuicideIed: + case IedType::IedSmallPyro: + case IedType::IedBigPyro: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, IedPairingState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case IedPairingState::NotPaired: + case IedPairingState::PairedToParticipant: + case IedPairingState::PairedToOps: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, IedTacticalState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case IedTacticalState::NotActive: + case IedTacticalState::Active: + case IedTacticalState::Defused: + case IedTacticalState::TriggeredBySwitch: + case IedTacticalState::TriggeredByRemote: + case IedTacticalState::TriggeredByLightBarrier: + case IedTacticalState::TriggeredByTautWire: + case IedTacticalState::TriggeredByControlDevice: + case IedTacticalState::Unknown: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, IedError &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case IedError::NoError: + case IedError::DeviceMissing: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, MinelayerThrowerData::ThrowingType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case MinelayerThrowerData::ThrowingType::Straight: + case MinelayerThrowerData::ThrowingType::Right: + case MinelayerThrowerData::ThrowingType::Left: + case MinelayerThrowerData::ThrowingType::LeftAndRight: + case MinelayerThrowerData::ThrowingType::SingleRight: + case MinelayerThrowerData::ThrowingType::SingleLeft: + case MinelayerThrowerData::ThrowingType::SingleLeftAndRight: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, OpaquePayloadDataBase::Type &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case OpaquePayloadDataBase::Type::FireSmokeMarker: + case OpaquePayloadDataBase::Type::Geopairing: + case OpaquePayloadDataBase::Type::Target: + case OpaquePayloadDataBase::Type::OC: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, TechnicalArea::Type &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case TechnicalArea::Type::Reserved: + case TechnicalArea::Type::RemoveArea: + case TechnicalArea::Type::MoutArea: + case TechnicalArea::Type::RestingAreaPersonnel: + case TechnicalArea::Type::RestingAreaVehicle: + case TechnicalArea::Type::RestingAreaPersonnelAndVehicle: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::OperationMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::OperationMode::NoChange: + case ParticipantModeBase::OperationMode::Normal: + case ParticipantModeBase::OperationMode::BeStill: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, BiteReport::LoginType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case BiteReport::LoginType::NoLogin: + case BiteReport::LoginType::NewLogin: + case BiteReport::LoginType::Relogin: + case BiteReport::LoginType::InvalidLogin: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::WphMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::WphMode::NoChange: + case ParticipantModeBase::WphMode::Without: + case ParticipantModeBase::WphMode::With: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::PersonellProtection &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::PersonellProtection::NoChange: + case ParticipantModeBase::PersonellProtection::Without: + case ParticipantModeBase::PersonellProtection::Suit: + case ParticipantModeBase::PersonellProtection::SuitAndGloves: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::ProtectionLevel &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::ProtectionLevel::NoChange: + case ParticipantModeBase::ProtectionLevel::IdzBs: + case ParticipantModeBase::ProtectionLevel::IdzEs: + case ParticipantModeBase::ProtectionLevel::Ksk: + case ParticipantModeBase::ProtectionLevel::SoldierWithBodyArmor: + case ParticipantModeBase::ProtectionLevel::SoldierActor: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::HandgrenadeSearchMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::HandgrenadeSearchMode::NoChange: + case ParticipantModeBase::HandgrenadeSearchMode::On: + case ParticipantModeBase::HandgrenadeSearchMode::Off: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::InternationalMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::InternationalMode::NoChange: + case ParticipantModeBase::InternationalMode::On: + case ParticipantModeBase::InternationalMode::Off: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantModeBase::ABCProtectionMode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantModeBase::ABCProtectionMode::NoChange: + case ParticipantModeBase::ABCProtectionMode::On: + case ParticipantModeBase::ABCProtectionMode::Off: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::FaultPositionHandling &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantConfigurationBase::FaultPositionHandling::NoChange: + case ParticipantConfigurationBase::FaultPositionHandling::NoPositions: + case ParticipantConfigurationBase::FaultPositionHandling::InvalidPositionValue: + case ParticipantConfigurationBase::FaultPositionHandling::EstimatedPosition: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::SwitchingPositionIntervall &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantConfigurationBase::SwitchingPositionIntervall::NoChange: + case ParticipantConfigurationBase::SwitchingPositionIntervall::On: + case ParticipantConfigurationBase::SwitchingPositionIntervall::Off: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ParticipantConfigurationBase::OpticalCode &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ParticipantConfigurationBase::OpticalCode::NoChange: + case ParticipantConfigurationBase::OpticalCode::Osag10: + case ParticipantConfigurationBase::OpticalCode::Osag20Basic: + case ParticipantConfigurationBase::OpticalCode::SisoStandard: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, SanitationResult &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case SanitationResult::NoEffect: + case SanitationResult::Unhandled: + case SanitationResult::Insufficient: + case SanitationResult::Sufficient: + case SanitationResult::Optimal: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, SanitationEvaluation &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case SanitationEvaluation::NotApplicable: + case SanitationEvaluation::Okay: + case SanitationEvaluation::PartlyWrong: + case SanitationEvaluation::Wrong: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, Qualification &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case Qualification::NotDefined: + case Qualification::SANPers: + case Qualification::FAB: + case Qualification::FAA: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, SanitationRepair::TreatmentResult &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case SanitationRepair::TreatmentResult::None: + case SanitationRepair::TreatmentResult::Success: + case SanitationRepair::TreatmentResult::Failure: + case SanitationRepair::TreatmentResult::Stabilized: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ExerciseStateData::ExerciseState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ExerciseStateData::ExerciseState::Unknown: + case ExerciseStateData::ExerciseState::Created: + case ExerciseStateData::ExerciseState::Started: + case ExerciseStateData::ExerciseState::Paused: + case ExerciseStateData::ExerciseState::Stopped: + case ExerciseStateData::ExerciseState::Terminated: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, ServiceControlEnum &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case ServiceControlEnum::PRESHUTDOWN: + case ServiceControlEnum::SHUTDOWN: + case ServiceControlEnum::STOP: + + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, PowerMethod &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case PowerMethod::Unknown: + case PowerMethod::PowerOn: + case PowerMethod::PowerOff: + + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, UAVActionTask &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case UAVActionTask::Undefined: + case UAVActionTask::Disarm: + case UAVActionTask::Arm: + case UAVActionTask::Takeoff: + case UAVActionTask::Connect: + case UAVActionTask::Loiter: + case UAVActionTask::Return: + case UAVActionTask::Observe: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, UAVRadioLinkConnectionStatusType &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case UAVRadioLinkConnectionStatusType::Connected: + case UAVRadioLinkConnectionStatusType::Disconnected: + case UAVRadioLinkConnectionStatusType::Connecting: + case UAVRadioLinkConnectionStatusType::Error: + case UAVRadioLinkConnectionStatusType::Undefined: + case UAVRadioLinkConnectionStatusType::Diconnecting: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + template <> bool get(const QJsonObject &obj, const QString &key, UAVState &val, bool bOptional) + { + int iVal = 0; + get(obj, key, iVal, bOptional); + switch (static_cast(iVal)) + { + case UAVState::Auto: + case UAVState::Calibrating: + case UAVState::Init: + case UAVState::Maintenance: + case UAVState::Undefined: + case UAVState::Manual: + case UAVState::Normal: + case UAVState::Off: + case UAVState::On: + case UAVState::Shutdown: + case UAVState::Standby: + val = static_cast(iVal); + return true; + } + throw JsonException(obj, key); + } + + + Header Header::fromJson(const QJsonObject &obj) + { + Header ret; + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("timeStamp"), ret.timeStamp); + return ret; + } + + QJsonObject Header::toJson() const + { + return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, {QStringLiteral("timeStamp"), timeStamp}}; + } + + + RelativePosition RelativePosition::fromJson(const QJsonObject &obj) + { + RelativePosition ret; + get(obj, QStringLiteral("offsetX"), ret.offsetX); + get(obj, QStringLiteral("offsetY"), ret.offsetY); + get(obj, QStringLiteral("offsetZ"), ret.offsetZ); + return ret; + } + + QJsonObject RelativePosition::toJson() const + { + return QJsonObject{{QStringLiteral("offsetX"), offsetX}, {QStringLiteral("offsetY"), offsetY}, {QStringLiteral("offsetZ"), offsetZ}}; + } + + + AbsolutePosition AbsolutePosition::fromJson(const QJsonObject &obj) + { + AbsolutePosition ret; + get(obj, QStringLiteral("lon"), ret.lon); + get(obj, QStringLiteral("lat"), ret.lat); + get(obj, QStringLiteral("z"), ret.z); + return ret; + } + + QJsonObject AbsolutePosition::toJson() const + { + return QJsonObject{{QStringLiteral("lon"), lon}, {QStringLiteral("lat"), lat}, {QStringLiteral("z"), z}}; + } + + + OpsPosition OpsPosition::fromJson(const QJsonObject &obj) + { + OpsPosition ret; + get(obj, QStringLiteral("opsId"), ret.opsId); + get(obj, QStringLiteral("moutObjectId"), ret.moutObjectId, true); + get(obj, QStringLiteral("moutRoomId"), ret.moutRoomId, true); + return ret; + } + + QJsonObject OpsPosition::toJson() const + { + return QJsonObject{{QStringLiteral("opsId"), opsId}, {QStringLiteral("moutObjectId"), moutObjectId}, {QStringLiteral("moutRoomId"), moutRoomId}}; + } + + + GpsQuality GpsQuality::fromJson(const QJsonObject &obj) + { + GpsQuality ret; + get(obj, QStringLiteral("moreThan4SatellitesAvailable"), ret.moreThan4SatellitesAvailable); + get(obj, QStringLiteral("dgpsModeAvailable"), ret.dgpsModeAvailable); + get(obj, QStringLiteral("pdopValue"), ret.pdopValue); + return ret; + } + + QJsonObject GpsQuality::toJson() const + { + return QJsonObject{{QStringLiteral("moreThan4SatellitesAvailable"), moreThan4SatellitesAvailable}, + {QStringLiteral("dgpsModeAvailable"), dgpsModeAvailable}, + {QStringLiteral("pdopValue"), pdopValue}}; + } + + + Gear Gear::fromJson(const QJsonObject &obj) + { + Gear ret; + get(obj, QStringLiteral("gearTasCode"), ret.gearTasCode); + get(obj, QStringLiteral("gearSerialNumber"), ret.gearSerialNumber); + get(obj, QStringLiteral("chargeCounting"), ret.chargeCounting); + return ret; + } + + QJsonObject Gear::toJson() const + { + return QJsonObject{{QStringLiteral("gearTasCode"), gearTasCode}, + {QStringLiteral("gearSerialNumber"), gearSerialNumber}, + {QStringLiteral("chargeCounting"), chargeCounting}}; + } + + + GearCharge GearCharge::fromJson(const QJsonObject &obj) + { + GearCharge ret; + get(obj, QStringLiteral("gearTasCode"), ret.gearTasCode); + get(obj, QStringLiteral("gearSerialNumber"), ret.gearSerialNumber); + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + get(obj, QStringLiteral("remain"), ret.remain); + get(obj, QStringLiteral("location"), ret.location); + return ret; + } + + QJsonObject GearCharge::toJson() const + { + return QJsonObject{{QStringLiteral("gearTasCode"), gearTasCode}, + {QStringLiteral("gearSerialNumber"), gearSerialNumber}, + {QStringLiteral("chargeTypeId"), chargeTypeId}, + {QStringLiteral("remain"), remain}, + {QStringLiteral("location"), location}}; + } + + + WlsPosition WlsPosition::fromJson(const QJsonObject &obj) + { + WlsPosition ret; + get(obj, QStringLiteral("x"), ret.x); + get(obj, QStringLiteral("y"), ret.y); + get(obj, QStringLiteral("z"), ret.z); + get(obj, QStringLiteral("wlsAreaId"), ret.wlsAreaId); + get(obj, QStringLiteral("wlsZone"), ret.wlsZone); + get(obj, QStringLiteral("wlsBuildingId"), ret.wlsBuildingId); + get(obj, QStringLiteral("wlsRoomNumber"), ret.wlsRoomNumber); + get(obj, QStringLiteral("playerOrientation"), ret.playerOrientation); + get(obj, QStringLiteral("weaponOrientation"), ret.weaponOrientation); + get(obj, QStringLiteral("isValid"), ret.isValid); + return ret; + } + + QJsonObject WlsPosition::toJson() const + { + return QJsonObject{{QStringLiteral("x"), x}, + {QStringLiteral("y"), y}, + {QStringLiteral("z"), z}, + {QStringLiteral("wlsAreaId"), wlsAreaId}, + {QStringLiteral("wlsZone"), wlsZone}, + {QStringLiteral("wlsBuildingId"), wlsBuildingId}, + {QStringLiteral("wlsRoomNumber"), wlsRoomNumber}, + {QStringLiteral("playerOrientation"), playerOrientation}, + {QStringLiteral("weaponOrientation"), weaponOrientation}, + {QStringLiteral("isValid"), isValid}}; + } + + + WlsParticipantState WlsParticipantState::fromJson(const QJsonObject &obj) + { + WlsParticipantState ret; + get(obj, QStringLiteral("tagId"), ret.tagId); + get(obj, QStringLiteral("lastSeen"), ret.lastSeen); + get(obj, QStringLiteral("voltage"), ret.voltage); + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("tacticalState"), ret.tacticalState); + get(obj, QStringLiteral("gpsOn"), ret.gpsOn); + get(obj, QStringLiteral("inBlockedArea"), ret.inBlockedArea); + get(obj, QStringLiteral("relativePosition"), ret.relativePosition); + return ret; + } + + QJsonObject WlsParticipantState::toJson() const + { + return QJsonObject{{QStringLiteral("tagId"), tagId}, + {QStringLiteral("lastSeen"), lastSeen}, + {QStringLiteral("voltage"), voltage}, + {QStringLiteral("equipmentNumber"), equipmentNumber}, + {QStringLiteral("tacticalState"), tacticalState}, + {QStringLiteral("gpsOn"), gpsOn}, + {QStringLiteral("inBlockedArea"), inBlockedArea}, + {QStringLiteral("relativePosition"), relativePosition.toJson()}}; + } + + + BatteryState BatteryState::fromJson(const QJsonObject &obj) + { + BatteryState ret; + get(obj, QStringLiteral("batteryPort"), ret.m_batteryPort); + get(obj, QStringLiteral("battery"), ret.m_batteryPercent); + get(obj, QStringLiteral("voltage"), ret.m_voltage); + get(obj, QStringLiteral("temperature"), ret.m_temperature); + get(obj, QStringLiteral("frequency"), ret.m_frequency); + get(obj, QStringLiteral("generic"), ret.m_generic); + get(obj, QStringLiteral("current"), ret.m_current); + get(obj, QStringLiteral("switchOrValue"), ret.m_switchOrValue); + get(obj, QStringLiteral("serialNumber"), ret.m_serialNumber); + return ret; + } + + QJsonObject BatteryState::toJson() const + { + return QJsonObject{{QStringLiteral("batteryPort"), batteryPort()}, + {QStringLiteral("battery"), batteryPercent()}, + {QStringLiteral("voltage"), voltage()}, + {QStringLiteral("temperature"), temperature()}, + {QStringLiteral("frequency"), frequency()}, + {QStringLiteral("generic"), generic()}, + {QStringLiteral("current"), current()}, + {QStringLiteral("switchOrValue"), switchOrValue()}, + {QStringLiteral("serialNumber"), serialNumber()}}; + } + + + Acknowledge Acknowledge::fromJson(const QJsonObject &obj) + { + Acknowledge ret; + get(obj, QStringLiteral("timeStamp"), ret.timeStamp); + get(obj, QStringLiteral("ackCounter"), ret.ackCounter); + return ret; + } + + QJsonObject Acknowledge::toJson() const + { + return QJsonObject{{QStringLiteral("timeStamp"), timeStamp}, {QStringLiteral("ackCounter"), ackCounter}}; + } + + + Init Init::fromJson(const QJsonObject &obj) + { + Init ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("workstationId"), ret.workstationId); + get(obj, QStringLiteral("restockCharges"), ret.restockCharges); + get(obj, QStringLiteral("resetManipulation"), ret.resetManipulation); + get(obj, QStringLiteral("resetVulnerabilityState"), ret.resetVulnerabilityState); + get(obj, QStringLiteral("restockSanitationMaterial"), ret.restockSanitationMaterial); + return ret; + } + + QJsonObject Init::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("workstationId"), workstationId}, + {QStringLiteral("restockCharges"), restockCharges}, + {QStringLiteral("resetManipulation"), resetManipulation}, + {QStringLiteral("resetVulnerabilityState"), resetVulnerabilityState}, + {QStringLiteral("restockSanitationMaterial"), restockSanitationMaterial}}; + } + + + ManipulationReport ManipulationReport::fromJson(const QJsonObject &obj) + { + ManipulationReport ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("isManipulation"), ret.isManipulation); + get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); + return ret; + } + + QJsonObject ManipulationReport::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("isManipulation"), isManipulation}, + {QStringLiteral("equipmentFunctionId"), equipmentFunctionId}}; + } + + + DemandBite DemandBite::fromJson(const QJsonObject &obj) + { + DemandBite ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("withSelfTest"), ret.withSelfTest); + return ret; + } + + QJsonObject DemandBite::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("withSelfTest"), withSelfTest}}; + } + + + EquipmentOperationalState EquipmentOperationalState::fromJson(const QJsonObject &obj) + { + EquipmentOperationalState ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("nbcProtectionActive"), ret.nbcProtectionActive); + return ret; + } + + QJsonObject EquipmentOperationalState::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("nbcProtectionActive"), nbcProtectionActive}}; + } + + + void VulnerabilityModelBase::fromJson(const QJsonObject &obj, VulnerabilityModelBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("vulnerabilityModelMineIed"), ret.vulnerabilityModelMineIed); + get(obj, QStringLiteral("vulnerabilityModelAreaFire"), ret.vulnerabilityModelAreaFire); + get(obj, QStringLiteral("vulnerabilityModelOperatingResource"), ret.vulnerabilityModelOperatingResource); + get(obj, QStringLiteral("vulnerabilityModelAcWeaponry"), ret.vulnerabilityModelAcWeaponry); + } + + QJsonObject VulnerabilityModelBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("vulnerabilityModelMineIed"), vulnerabilityModelMineIed}, + {QStringLiteral("vulnerabilityModelAreaFire"), vulnerabilityModelAreaFire}, + {QStringLiteral("vulnerabilityModelOperatingResource"), vulnerabilityModelOperatingResource}, + {QStringLiteral("vulnerabilityModelAcWeaponry"), vulnerabilityModelAcWeaponry}}; + } + + + SetVulnerabilityModel SetVulnerabilityModel::fromJson(const QJsonObject &obj) + { + SetVulnerabilityModel ret; + VulnerabilityModelBase::fromJson(obj, ret); + return ret; + } + + QJsonObject SetVulnerabilityModel::toJson() const + { + return VulnerabilityModelBase::toJson(); + } + + + DemandEquipmentConfigurationReport DemandEquipmentConfigurationReport::fromJson(const QJsonObject &obj) + { + DemandEquipmentConfigurationReport ret; + get(obj, QStringLiteral("header"), ret.header); + return ret; + } + + QJsonObject DemandEquipmentConfigurationReport::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}}; + } + + + EquipmentConfigurationReport EquipmentConfigurationReport::fromJson(const QJsonObject &obj) + { + EquipmentConfigurationReport ret; + VulnerabilityModelBase::fromJson(obj, ret); + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("canStartUpTime"), ret.canStartUpTime); + get(obj, QStringLiteral("equipmentType"), ret.equipmentType); + get(obj, QStringLiteral("loginWaittimeBitweenTrys"), ret.loginWaittimeBitweenTrys); + get(obj, QStringLiteral("loginMaxRetryCnt"), ret.loginMaxRetryCnt); + get(obj, QStringLiteral("loginMasteringFlag"), ret.loginMasteringFlag); + get(obj, QStringLiteral("canDeviceConfiguration"), ret.canDeviceConfiguration); + get(obj, QStringLiteral("displayDeviceVoiceOutput"), ret.displayDeviceVoiceOutput); + get(obj, QStringLiteral("displayDeviceLanguage"), ret.displayDeviceLanguage); + get(obj, QStringLiteral("pyrotechnics"), ret.pyrotechnics); + get(obj, QStringLiteral("mhgrsMode"), ret.mhgrsMode); + get(obj, QStringLiteral("mhgrsEnergySaving"), ret.mhgrsEnergySaving); + get(obj, QStringLiteral("specialSensorFir"), ret.specialSensorFir); + get(obj, QStringLiteral("specialSensorMinelayer"), ret.specialSensorMinelayer); + get(obj, QStringLiteral("specialSensorStandard"), ret.specialSensorStandard); + get(obj, QStringLiteral("agdusHwMode"), ret.agdusHwMode); + get(obj, QStringLiteral("positionUpdateInterval"), ret.positionUpdateInterval); + get(obj, QStringLiteral("displayTextMainGroup"), ret.displayTextMainGroup); + get(obj, QStringLiteral("displayTextSubGroup"), ret.displayTextSubGroup); + get(obj, QStringLiteral("vulnerabilityModelAgdus"), ret.vulnerabilityModelAgdus); + return ret; + } + + QJsonObject EquipmentConfigurationReport::toJson() const + { + QJsonObject obj = VulnerabilityModelBase::toJson(); + obj[QStringLiteral("header")] = header.toJson(); + obj[QStringLiteral("equipmentNumber")] = equipmentNumber; + obj[QStringLiteral("canStartUpTime")] = canStartUpTime; + obj[QStringLiteral("equipmentType")] = equipmentType; + obj[QStringLiteral("loginWaittimeBitweenTrys")] = loginWaittimeBitweenTrys; + obj[QStringLiteral("loginMaxRetryCnt")] = loginMaxRetryCnt; + obj[QStringLiteral("loginMasteringFlag")] = loginMasteringFlag; + obj[QStringLiteral("canDeviceConfiguration")] = canDeviceConfiguration; + obj[QStringLiteral("displayDeviceVoiceOutput")] = displayDeviceVoiceOutput; + obj[QStringLiteral("displayDeviceLanguage")] = enumToJson(displayDeviceLanguage); + obj[QStringLiteral("pyrotechnics")] = pyrotechnics; + obj[QStringLiteral("mhgrsMode")] = enumToJson(mhgrsMode); + obj[QStringLiteral("mhgrsEnergySaving")] = mhgrsEnergySaving; + obj[QStringLiteral("specialSensorFir")] = enumToJson(specialSensorFir); + obj[QStringLiteral("specialSensorMinelayer")] = enumToJson(specialSensorMinelayer); + obj[QStringLiteral("specialSensorStandard")] = enumToJson(specialSensorStandard); + obj[QStringLiteral("agdusHwMode")] = enumToJson(agdusHwMode); + obj[QStringLiteral("positionUpdateInterval")] = enumToJson(positionUpdateInterval); + obj[QStringLiteral("displayTextMainGroup")] = displayTextMainGroup; + obj[QStringLiteral("displayTextSubGroup")] = displayTextSubGroup; + obj[QStringLiteral("vulnerabilityModelAgdus")] = vulnerabilityModelAgdus; + return obj; + } + + + CtaDataError CtaDataError::fromJson(const QJsonObject &obj) + { + CtaDataError ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("reason"), ret.reason); + get(obj, QStringLiteral("originTelegramId"), ret.originTelegramId); + return ret; + } + + QJsonObject CtaDataError::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("reason"), enumToJson(reason)}, + {QStringLiteral("originTelegramId"), originTelegramId}}; + } + + + void PositionReportBase::fromJson(const QJsonObject &obj, PositionReportBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + bool bAtLeastOneFound = false; + if (get(obj, QStringLiteral("relPosition"), ret.relPosition, true)) + bAtLeastOneFound = true; + if (get(obj, QStringLiteral("geoPosition"), ret.geoPosition, true)) + bAtLeastOneFound = true; + + get(obj, QStringLiteral("opsPosition"), ret.opsPosition, bAtLeastOneFound); + get(obj, QStringLiteral("gpsQuality"), ret.gpsQuality, true); + } + + QJsonObject PositionReportBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("geoPosition"), geoPosition.toJson()}, + {QStringLiteral("opsPosition"), opsPosition.toJson()}, + {QStringLiteral("gpsQuality"), gpsQuality.toJson()}}; + } + + + PositionReport PositionReport::fromJson(const QJsonObject &obj) + { + PositionReport ret; + PositionReportBase::fromJson(obj, ret); + return ret; + } + + QJsonObject PositionReport::toJson() const + { + return PositionReportBase::toJson(); + } + + + PositionReportWithMountedEquipments PositionReportWithMountedEquipments::fromJson(const QJsonObject &obj) + { + PositionReportWithMountedEquipments ret; + PositionReportBase::fromJson(obj, ret); + get(obj, QStringLiteral("mountedEquipments"), ret.mountedEquipments); + return ret; + } + + QJsonObject PositionReportWithMountedEquipments::toJson() const + { + QJsonObject obj = PositionReportBase::toJson(); + obj[QStringLiteral("mountedEquipments")] = arrayToJson(mountedEquipments); + return obj; + } + + + void CreateAreaEffectSimulationBase::fromJson(const QJsonObject &obj, CreateAreaEffectSimulationBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("name"), ret.name); + get(obj, QStringLiteral("partyId"), ret.partyId); + get(obj, QStringLiteral("relEffectPosition"), ret.relEffectPosition); + } + + QJsonObject CreateAreaEffectSimulationBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("name"), QString::fromStdString(name)}, + {QStringLiteral("partyId"), partyId}, + {QStringLiteral("relEffectPosition"), relEffectPosition.toJson()}}; + } + + + void CreateCombatAreaEffectSimulationBase::fromJson(const QJsonObject &obj, CreateCombatAreaEffectSimulationBase &ret) + { + CreateAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + get(obj, QStringLiteral("effectStart"), ret.effectStart); + get(obj, QStringLiteral("effectDuration"), ret.effectDuration); + } + + QJsonObject CreateCombatAreaEffectSimulationBase::toJson() const + { + QJsonObject obj = CreateAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("chargeTypeId")] = chargeTypeId; + obj[QStringLiteral("effectStart")] = effectStart; + obj[QStringLiteral("effectDuration")] = effectDuration; + return obj; + } + + + OcCommand OcCommand::fromJson(const QJsonObject &obj) + { + OcCommand ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("action"), ret.action); + return ret; + } + + QJsonObject OcCommand::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("action"), action}}; + } + + + CreateSingleExplosion CreateSingleExplosion::fromJson(const QJsonObject &obj) + { + CreateSingleExplosion ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("effectDiameter"), ret.effectDiameter); + return ret; + } + + QJsonObject CreateSingleExplosion::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("effectDiameter")] = effectDiameter; + return obj; + } + + + CreateAreaExplosion CreateAreaExplosion::fromJson(const QJsonObject &obj) + { + CreateAreaExplosion ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("relCorner"), ret.relCorner); + get(obj, QStringLiteral("height"), ret.height); + get(obj, QStringLiteral("width"), ret.width); + get(obj, QStringLiteral("rotationAngle"), ret.rotationAngle); + get(obj, QStringLiteral("impactCount"), ret.impactCount); + get(obj, QStringLiteral("impactEdgeLength"), ret.impactEdgeLength); + get(obj, QStringLiteral("impactRadius"), ret.impactRadius); + get(obj, QStringLiteral("hazardDistance"), ret.hazardDistance); + + get(obj, QStringLiteral("mhpLength"), ret.mhpLength); + get(obj, QStringLiteral("mhpWidth"), ret.mhpWidth); + get(obj, QStringLiteral("mhpRotation"), ret.mhpRotation); + get(obj, QStringLiteral("mhPoints"), ret.mhPoints); + + + return ret; + } + + QJsonObject CreateAreaExplosion::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("relCorner")] = relCorner.toJson(); + obj[QStringLiteral("height")] = height; + obj[QStringLiteral("width")] = width; + obj[QStringLiteral("rotationAngle")] = rotationAngle; + obj[QStringLiteral("impactCount")] = impactCount; + obj[QStringLiteral("impactEdgeLength")] = impactEdgeLength; + obj[QStringLiteral("impactRadius")] = impactRadius; + + obj[QStringLiteral("hazardDistance")] = hazardDistance; + + obj[QStringLiteral("mhpLength")] = mhpLength; + obj[QStringLiteral("mhpWidth")] = mhpWidth; + obj[QStringLiteral("mhpRotation")] = mhpRotation; + obj[QStringLiteral("mhPoints")] = arrayToJson(mhPoints); + return obj; + } + + + PauseEffectSimulation PauseEffectSimulation::fromJson(const QJsonObject &obj) + { + PauseEffectSimulation ret; + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + return ret; + } + + QJsonObject PauseEffectSimulation::toJson() const + { + return QJsonObject{{QStringLiteral("aesDdsId"), aesDdsId}}; + } + + + ResumeEffectSimulation ResumeEffectSimulation::fromJson(const QJsonObject &obj) + { + ResumeEffectSimulation ret; + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("sequelNumber"), ret.sequelNumber); + get(obj, QStringLiteral("nextImpact"), ret.nextImpact); + get(obj, QStringLiteral("resumeTime"), ret.resumeTime); + get(obj, QStringLiteral("remainDuration"), ret.remainDuration); + return ret; + } + + QJsonObject ResumeEffectSimulation::toJson() const + { + return QJsonObject{{QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("sequelNumber"), sequelNumber}, + {QStringLiteral("nextImpact"), nextImpact}, + {QStringLiteral("resumeTime"), resumeTime}, + {QStringLiteral("remainDuration"), remainDuration}}; + } + + + MineAreaSegment MineAreaSegment::fromJson(const QJsonObject &obj) + { + MineAreaSegment ret; + get(obj, QStringLiteral("relStart"), ret.relStart); + get(obj, QStringLiteral("relEnd"), ret.relEnd); + return ret; + } + + QJsonObject MineAreaSegment::toJson() const + { + return QJsonObject{{QStringLiteral("relStart"), relStart.toJson()}, {QStringLiteral("relEnd"), relEnd.toJson()}}; + } + + + CreateMineArea CreateMineArea::fromJson(const QJsonObject &obj) + { + CreateMineArea ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + + + get(obj, QStringLiteral("layingDepth"), ret.layingDepth); + get(obj, QStringLiteral("layingDensity"), ret.layingDensity); + get(obj, QStringLiteral("segments"), ret.segments); + return ret; + } + + QJsonObject CreateMineArea::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + + + obj[QStringLiteral("layingDepth")] = layingDepth; + obj[QStringLiteral("layingDensity")] = layingDensity; + obj[QStringLiteral("segments")] = arrayToJson(segments); + return obj; + } + + + MineAreaSingleMineState MineAreaSingleMineState::fromJson(const QJsonObject &obj) + { + MineAreaSingleMineState ret; + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("mineCount"), ret.mineCount); + get(obj, QStringLiteral("mineState"), ret.mineState); + return ret; + } + + QJsonObject MineAreaSingleMineState::toJson() const + { + return QJsonObject{ + {QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("mineCount"), mineCount}, + {QStringLiteral("mineState"), arrayToJson(mineState)}, + }; + } + + + CreateNContamination CreateNContamination::fromJson(const QJsonObject &obj) + { + CreateNContamination ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("innerRadius"), ret.innerRadius); + get(obj, QStringLiteral("borderLengthInner"), ret.borderLengthInner); + get(obj, QStringLiteral("borderLengthOuter"), ret.borderLengthOuter); + get(obj, QStringLiteral("spanAngle"), ret.spanAngle); + get(obj, QStringLiteral("rotationAngle"), ret.rotationAngle); + return ret; + } + + QJsonObject CreateNContamination::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("innerRadius")] = innerRadius; + obj[QStringLiteral("borderLengthInner")] = borderLengthInner; + obj[QStringLiteral("borderLengthOuter")] = borderLengthOuter; + obj[QStringLiteral("spanAngle")] = spanAngle; + obj[QStringLiteral("rotationAngle")] = rotationAngle; + return obj; + } + + + CreateCContamination CreateCContamination::fromJson(const QJsonObject &obj) + { + CreateCContamination ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("effectRadius"), ret.effectRadius); + get(obj, QStringLiteral("expansionFactor"), ret.expansionFactor); + get(obj, QStringLiteral("propagationDirection"), ret.propagationDirection); + get(obj, QStringLiteral("windSpeed"), ret.windSpeed); + get(obj, QStringLiteral("validityTimeWind"), ret.validityTimeWind); + get(obj, QStringLiteral("relPositionValidityTimeWind"), ret.relPositionValidityTimeWind); + get(obj, QStringLiteral("volatility"), ret.volatility); + return ret; + } + + QJsonObject CreateCContamination::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("effectRadius")] = effectRadius; + obj[QStringLiteral("expansionFactor")] = expansionFactor; + obj[QStringLiteral("propagationDirection")] = propagationDirection; + obj[QStringLiteral("windSpeed")] = windSpeed; + obj[QStringLiteral("validityTimeWind")] = validityTimeWind; + obj[QStringLiteral("relPositionValidityTimeWind")] = relPositionValidityTimeWind.toJson(); + obj[QStringLiteral("volatility")] = enumToJson(volatility); + return obj; + } + + + DeactivateEffectSimulation DeactivateEffectSimulation::fromJson(const QJsonObject &obj) + { + DeactivateEffectSimulation ret; + get(obj, QStringLiteral("aesType"), ret.aesType); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + return ret; + } + + QJsonObject DeactivateEffectSimulation::toJson() const + { + return QJsonObject{{QStringLiteral("aesType"), enumToJson(aesType)}, {QStringLiteral("aesDdsId"), aesDdsId}}; + } + + + ModifyAreaEffectSimulationName ModifyAreaEffectSimulationName::fromJson(const QJsonObject &obj) + { + ModifyAreaEffectSimulationName ret; + get(obj, QStringLiteral("aesType"), ret.aesType); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("name"), ret.name); + return ret; + } + + QJsonObject ModifyAreaEffectSimulationName::toJson() const + { + return QJsonObject{{QStringLiteral("aesType"), enumToJson(aesType)}, + {QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("name"), QString::fromStdString(name)}}; + } + + + MineTriggered MineTriggered::fromJson(const QJsonObject &obj) + { + MineTriggered ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("mineAreaId"), ret.mineAreaId); + get(obj, QStringLiteral("mineIndex"), ret.mineIndex); + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("relPositionValid"), ret.relPositionValid); + return ret; + } + + QJsonObject MineTriggered::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("mineAreaId"), mineAreaId}, + {QStringLiteral("mineIndex"), mineIndex}, + {QStringLiteral("chargeTypeId"), chargeTypeId}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("relPositionValid"), relPositionValid}}; + } + + + DusMineReactivation DusMineReactivation::fromJson(const QJsonObject &obj) + { + DusMineReactivation ret; + get(obj, QStringLiteral("dusSerialNumbers"), ret.dusSerialNumbers); + return ret; + } + + QJsonObject DusMineReactivation::toJson() const + { + return QJsonObject{{QStringLiteral("dusSerialNumbers"), arrayToJson(dusSerialNumbers)}}; + } + + + void IedBaseData::fromJson(const QJsonObject &obj, IedBaseData &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("iedId"), ret.iedId); + get(obj, QStringLiteral("tacticalState"), ret.tacticalState); + get(obj, QStringLiteral("statePyrotechnics"), ret.statePyrotechnics); + } + + QJsonObject IedBaseData::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("iedId"), iedId}, + {QStringLiteral("tacticalState"), enumToJson(tacticalState)}, + {QStringLiteral("statePyrotechnics"), statePyrotechnics}}; + } + + + DefinitionIed DefinitionIed::fromJson(const QJsonObject &obj) + { + DefinitionIed ret; + IedBaseData::fromJson(obj, ret); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("iedType"), ret.iedType); + get(obj, QStringLiteral("trigger"), ret.trigger); + get(obj, QStringLiteral("explosiveForce"), ret.explosiveForce); + get(obj, QStringLiteral("pairingState"), ret.pairingState); + get(obj, QStringLiteral("pairedId"), ret.pairedId); + get(obj, QStringLiteral("partyId"), ret.partyId); + return ret; + } + + QJsonObject DefinitionIed::toJson() const + { + QJsonObject obj = IedBaseData::toJson(); + obj[QStringLiteral("relPosition")] = relPosition.toJson(); + obj[QStringLiteral("iedType")] = enumToJson(iedType); + obj[QStringLiteral("trigger")] = trigger; + obj[QStringLiteral("explosiveForce")] = explosiveForce; + obj[QStringLiteral("pairingState")] = enumToJson(pairingState); + obj[QStringLiteral("pairedId")] = pairedId; + obj[QStringLiteral("partyId")] = partyId; + return obj; + } + + + StateIed StateIed::fromJson(const QJsonObject &obj) + { + StateIed ret; + IedBaseData::fromJson(obj, ret); + get(obj, QStringLiteral("batteryWarnings"), ret.batteryWarnings); + get(obj, QStringLiteral("errorStateElectronics"), ret.errorStateElectronics); + get(obj, QStringLiteral("errorStatePyrotechnics1"), ret.errorStatePyrotechnics1); + get(obj, QStringLiteral("errorStatePyrotechnics2"), ret.errorStatePyrotechnics2); + get(obj, QStringLiteral("errorStatePyrotechnics3"), ret.errorStatePyrotechnics3); + return ret; + } + + QJsonObject StateIed::toJson() const + { + QJsonObject obj = IedBaseData::toJson(); + obj[QStringLiteral("batteryWarnings")] = batteryWarnings; + obj[QStringLiteral("errorStateElectronics")] = enumToJson(errorStateElectronics); + obj[QStringLiteral("errorStatePyrotechnics1")] = enumToJson(errorStatePyrotechnics1); + obj[QStringLiteral("errorStatePyrotechnics2")] = enumToJson(errorStatePyrotechnics2); + obj[QStringLiteral("errorStatePyrotechnics3")] = enumToJson(errorStatePyrotechnics3); + return obj; + } + + + DusSingleMineState DusSingleMineState::fromJson(const QJsonObject &obj) + { + DusSingleMineState ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("mineId"), ret.mineId); + get(obj, QStringLiteral("effectStart"), ret.effectStart); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + get(obj, QStringLiteral("state"), ret.state); + return ret; + } + + QJsonObject DusSingleMineState::toJson() const + { + QJsonObject obj; + obj[QStringLiteral("header")] = header.toJson(); + obj[QStringLiteral("mineId")] = mineId; + obj[QStringLiteral("effectStart")] = effectStart; + obj[QStringLiteral("relPosition")] = relPosition.toJson(); + obj[QStringLiteral("chargeTypeId")] = chargeTypeId; + obj[QStringLiteral("state")] = state; + return obj; + } + + + CreateDusSingleMine CreateDusSingleMine::fromJson(const QJsonObject &obj) + { + CreateDusSingleMine ret; + CreateCombatAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("mineId"), ret.mineId); + return ret; + } + + QJsonObject CreateDusSingleMine::toJson() const + { + QJsonObject obj = CreateCombatAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("mineId")] = mineId; + return obj; + } + + + void StateChangeBase::fromJson(const QJsonObject &obj, StateChangeBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + + bool bAtLeastOneFound = false; + if (get(obj, QStringLiteral("relPosition"), ret.relPosition, true)) + bAtLeastOneFound = true; + if (get(obj, QStringLiteral("geoPosition"), ret.geoPosition, true)) + bAtLeastOneFound = true; + + get(obj, QStringLiteral("opsPosition"), ret.opsPosition, bAtLeastOneFound); + + get(obj, QStringLiteral("vulnerabilityState"), ret.vulnerabilityState); + get(obj, QStringLiteral("tasVulnerabilityKindId"), ret.tasVulnerabilityKindId); + get(obj, QStringLiteral("tasVitality"), ret.tasVitality, true); + get(obj, QStringLiteral("vulnerabilityBits"), ret.vulnerabilityBits); + + get(obj, QStringLiteral("originatorId"), ret.originatorId); + } + + QJsonObject StateChangeBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("geoPosition"), geoPosition.toJson()}, + {QStringLiteral("opsPosition"), opsPosition.toJson()}, + {QStringLiteral("vulnerabilityState"), enumToJson(vulnerabilityState)}, + {QStringLiteral("tasVulnerabilityKindId"), tasVulnerabilityKindId}, + {QStringLiteral("tasVitality"), tasVitality}, + {QStringLiteral("vulnerabilityBits"), vulnerabilityBits}, + {QStringLiteral("originatorId"), originatorId}}; + } + + + StateChangeDirect StateChangeDirect::fromJson(const QJsonObject &obj) + { + StateChangeDirect ret; + StateChangeBase::fromJson(obj, ret); + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + return ret; + } + + QJsonObject StateChangeDirect::toJson() const + { + QJsonObject obj = StateChangeBase::toJson(); + obj[QStringLiteral("chargeTypeId")] = chargeTypeId; + return obj; + } + + + StateChangeIndirect StateChangeIndirect::fromJson(const QJsonObject &obj) + { + StateChangeIndirect ret; + StateChangeBase::fromJson(obj, ret); + get(obj, QStringLiteral("isSecondaryEffect"), ret.isSecondaryEffect); + return ret; + } + + QJsonObject StateChangeIndirect::toJson() const + { + QJsonObject obj = StateChangeBase::toJson(); + obj[QStringLiteral("isSecondaryEffect")] = isSecondaryEffect; + return obj; + } + + + DemandVulnerabilityStateChange DemandVulnerabilityStateChange::fromJson(const QJsonObject &obj) + { + DemandVulnerabilityStateChange ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("workstationId"), ret.workstationId); + get(obj, QStringLiteral("reqestedState"), ret.reqestedState); + get(obj, QStringLiteral("vulnerabilityVitalityIndex"), ret.vulnerabilityVitalityIndex); + return ret; + } + + QJsonObject DemandVulnerabilityStateChange::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("workstationId"), workstationId}, + {QStringLiteral("reqestedState"), enumToJson(reqestedState)}, + {QStringLiteral("vulnerabilityVitalityIndex"), vulnerabilityVitalityIndex}}; + } + + + OperatorAction OperatorAction::fromJson(const QJsonObject &obj) + { + OperatorAction ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("operatorId"), ret.operatorId); + get(obj, QStringLiteral("action"), ret.action); + return ret; + } + + QJsonObject OperatorAction::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("operatorId"), operatorId}, + {QStringLiteral("action"), action}}; + } + + + Reammunition Reammunition::fromJson(const QJsonObject &obj) + { + Reammunition ret; + get(obj, QStringLiteral("chargeTypeId"), ret.chargeTypeId); + get(obj, QStringLiteral("newStock"), ret.newStock); + get(obj, QStringLiteral("newDefaultStock"), ret.newDefaultStock); + get(obj, QStringLiteral("tracerRatio"), ret.tracerRatio); + return ret; + } + + QJsonObject Reammunition::toJson() const + { + return QJsonObject{{QStringLiteral("chargeTypeId"), chargeTypeId}, + {QStringLiteral("newStock"), newStock}, + {QStringLiteral("newDefaultStock"), newDefaultStock}, + {QStringLiteral("tracerRatio"), tracerRatio}}; + } + + + SelectiveReammunition SelectiveReammunition::fromJson(const QJsonObject &obj) + { + SelectiveReammunition ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("gearId"), ret.gearId); + get(obj, QStringLiteral("reammunitions"), ret.reammunitions); + + return ret; + } + + QJsonObject SelectiveReammunition::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("gearId"), gearId}, {QStringLiteral("reammunitions"), arrayToJson(reammunitions)}}; + } + + + StateChange StateChange::fromJson(const QJsonObject &obj) + { + StateChange ret; + StateChangeBase::fromJson(obj, ret); + get(obj, QStringLiteral("originatorType"), ret.originatorType); + return ret; + } + + QJsonObject StateChange::toJson() const + { + QJsonObject obj = StateChangeBase::toJson(); + obj[QStringLiteral("originatorType")] = enumToJson(originatorType); + return obj; + } + + + CreateFunctionalArea CreateFunctionalArea::fromJson(const QJsonObject &obj) + { + CreateFunctionalArea ret; + CreateAreaEffectSimulationBase::fromJson(obj, ret); + get(obj, QStringLiteral("relEffectPosition"), ret.relEffectPosition); + get(obj, QStringLiteral("width"), ret.width); + get(obj, QStringLiteral("height"), ret.height); + get(obj, QStringLiteral("deconTimeout"), ret.deconTimeout); + get(obj, QStringLiteral("maintenanceTimeout"), ret.maintenanceTimeout); + get(obj, QStringLiteral("medicalTimeout"), ret.medicalTimeout); + get(obj, QStringLiteral("deconMode"), ret.deconMode); + get(obj, QStringLiteral("maintenanceMode"), ret.maintenanceMode); + get(obj, QStringLiteral("medicalMode"), ret.medicalMode); + return ret; + } + + QJsonObject CreateFunctionalArea::toJson() const + { + QJsonObject obj = CreateAreaEffectSimulationBase::toJson(); + obj[QStringLiteral("relEffectPosition")] = relEffectPosition.toJson(); + obj[QStringLiteral("width")] = width; + obj[QStringLiteral("height")] = height; + obj[QStringLiteral("deconTimeout")] = qint64(deconTimeout); + obj[QStringLiteral("maintenanceTimeout")] = qint64(maintenanceTimeout); + obj[QStringLiteral("medicalTimeout")] = qint64(medicalTimeout); + obj[QStringLiteral("deconMode")] = enumToJson(deconMode); + obj[QStringLiteral("maintenanceMode")] = enumToJson(maintenanceMode); + obj[QStringLiteral("medicalMode")] = enumToJson(medicalMode); + return obj; + } + + + FunctionalAreaEntry FunctionalAreaEntry::fromJson(const QJsonObject &obj) + { + FunctionalAreaEntry ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + return ret; + } + + QJsonObject FunctionalAreaEntry::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("relPosition"), relPosition.toJson()}, {QStringLiteral("aesDdsId"), aesDdsId}}; + } + + + RequestBroadcastTelegrams RequestBroadcastTelegrams::fromJson(const QJsonObject &obj) + { + RequestBroadcastTelegrams ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("resetCounter"), ret.resetCounter); + get(obj, QStringLiteral("broadcastIndex"), ret.broadcastIndex); + return ret; + } + + QJsonObject RequestBroadcastTelegrams::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("resetCounter"), resetCounter}, {QStringLiteral("broadcastIndex"), broadcastIndex}}; + } + + + SpecialSensorData SpecialSensorData::fromJson(const QJsonObject &obj) + { + SpecialSensorData ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("operationalState"), ret.operationalState); + get(obj, QStringLiteral("airSensor"), ret.airSensor); + get(obj, QStringLiteral("tireSensor"), ret.tireSensor); + get(obj, QStringLiteral("pointSensor"), ret.pointSensor); + get(obj, QStringLiteral("solidMatterSampleExtractor"), ret.solidMatterSampleExtractor); + get(obj, QStringLiteral("type"), ret.type); + get(obj, QStringLiteral("nbcType"), ret.nbcType); + return ret; + } + + QJsonObject SpecialSensorData::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("operationalState"), operationalState}, + {QStringLiteral("airSensor"), airSensor}, + {QStringLiteral("tireSensor"), tireSensor}, + {QStringLiteral("pointSensor"), pointSensor}, + {QStringLiteral("solidMatterSampleExtractor"), solidMatterSampleExtractor}, + {QStringLiteral("type"), type}, + {QStringLiteral("nbcType"), nbcType}}; + } + + + void MinelayerTrailerDataBase::fromJson(const QJsonObject &obj, MinelayerTrailerDataBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("barrierId"), ret.barrierId); + get(obj, QStringLiteral("layingDensity"), ret.layingDensity); + get(obj, QStringLiteral("effectStart"), ret.effectStart); + get(obj, QStringLiteral("effectDuration"), ret.effectDuration); + get(obj, QStringLiteral("indirectChargeTasCode"), ret.indirectChargeTasCode); + get(obj, QStringLiteral("mineCount"), ret.mineCount); + } + + QJsonObject MinelayerTrailerDataBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("barrierId"), barrierId}, + {QStringLiteral("layingDensity"), layingDensity}, + {QStringLiteral("effectStart"), qint64(effectStart)}, + {QStringLiteral("effectDuration"), effectDuration}, + {QStringLiteral("indirectChargeTasCode"), indirectChargeTasCode}, + {QStringLiteral("mineCount"), mineCount}}; + } + + + MinelayerTrailerData MinelayerTrailerData::fromJson(const QJsonObject &obj) + { + MinelayerTrailerData ret; + MinelayerTrailerDataBase::fromJson(obj, ret); + return ret; + } + + QJsonObject MinelayerTrailerData::toJson() const + { + return MinelayerTrailerDataBase::toJson(); + } + + + MinelayerThrowerData MinelayerThrowerData::fromJson(const QJsonObject &obj) + { + MinelayerThrowerData ret; + MinelayerTrailerDataBase::fromJson(obj, ret); + get(obj, QStringLiteral("throwingType"), ret.throwingType); + return ret; + } + + QJsonObject MinelayerThrowerData::toJson() const + { + QJsonObject obj = MinelayerTrailerDataBase::toJson(); + obj[QStringLiteral("throwingType")] = enumToJson(throwingType); + return obj; + } + MinelayerTrailerPosition MinelayerTrailerPosition::fromJson(const QJsonObject &obj) + { + MinelayerTrailerPosition ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("indirectChargeTasCode"), ret.indirectChargeTasCode); + get(obj, QStringLiteral("dusSerialNo"), ret.dusSerialNo); + return ret; + } + + QJsonObject MinelayerTrailerPosition::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("indirectChargeTasCode"), indirectChargeTasCode}, + {QStringLiteral("dusSerialNo"), qint64(dusSerialNo)}}; + } + + + LanguageSelection LanguageSelection::fromJson(const QJsonObject &obj) + { + LanguageSelection ret; + get(obj, QStringLiteral("aesDdsId"), ret.header); + get(obj, QStringLiteral("languageSelection"), ret.languageSelection); + return ret; + } + + QJsonObject LanguageSelection::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("languageSelection"), enumToJson(languageSelection)}}; + } + + + EquipmentMessage EquipmentMessage::fromJson(const QJsonObject &obj) + { + EquipmentMessage ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("message"), ret.message); + get(obj, QStringLiteral("msgId"), ret.msgId); + return ret; + } + + QJsonObject EquipmentMessage::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("message"), QString::fromStdString(message)}, {QStringLiteral("msgId"), msgId}}; + } + + + EquipmentMessageOC EquipmentMessageOC::fromJson(const QJsonObject &obj) + { + EquipmentMessageOC ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("subject"), ret.subject); + get(obj, QStringLiteral("message"), ret.message); + get(obj, QStringLiteral("senderId"), ret.senderId); + get(obj, QStringLiteral("receiverId"), ret.receiverId); + return ret; + } + + QJsonObject EquipmentMessageOC::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("subject"), QString::fromStdString(subject)}, + {QStringLiteral("message"), QString::fromStdString(message)}, + {QStringLiteral("senderId"), senderId}, + {QStringLiteral("receiverId"), receiverId}}; + } + + + void OpaquePayloadDataBase::fromJson(const QJsonObject &obj, OpaquePayloadDataBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("payload"), ret.payload); + get(obj, QStringLiteral("payloadType"), ret.payloadType); + } + + QJsonObject OpaquePayloadDataBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("payload"), arrayToJson(payload)}, + {QStringLiteral("payloadType"), enumToJson(payloadType)}}; + } + + + OpaquePayloadDataOut OpaquePayloadDataOut::fromJson(const QJsonObject &obj) + { + OpaquePayloadDataOut ret; + OpaquePayloadDataBase::fromJson(obj, ret); + get(obj, QStringLiteral("header"), ret.header); + return ret; + } + + QJsonObject OpaquePayloadDataOut::toJson() const + { + QJsonObject obj = OpaquePayloadDataBase::toJson(); + obj[QStringLiteral("header")] = header.toJson(); + return obj; + } + + + OpaquePayloadDataIn OpaquePayloadDataIn::fromJson(const QJsonObject &obj) + { + OpaquePayloadDataIn ret; + OpaquePayloadDataBase::fromJson(obj, ret); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + return ret; + } + + QJsonObject OpaquePayloadDataIn::toJson() const + { + QJsonObject obj = OpaquePayloadDataBase::toJson(); + obj[QStringLiteral("relPosition")] = relPosition.toJson(); + return obj; + } + + + EquipmentEvent EquipmentEvent::fromJson(const QJsonObject &obj) + { + EquipmentEvent ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); + get(obj, QStringLiteral("subDeviceId"), ret.subDeviceId); + get(obj, QStringLiteral("uniqueId"), ret.uniqueId); + get(obj, QStringLiteral("code"), ret.code); + get(obj, QStringLiteral("payload"), ret.payload); + return ret; + } + + QJsonObject EquipmentEvent::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("equipmentFunctionId"), equipmentFunctionId}, + {QStringLiteral("subDeviceId"), subDeviceId}, + {QStringLiteral("uniqueId"), uniqueId}, + {QStringLiteral("code"), code}, + {QStringLiteral("payload"), arrayToJson(payload)}}; + } + + + EquipmentGearAssignment EquipmentGearAssignment::fromJson(const QJsonObject &obj) + { + EquipmentGearAssignment ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("gears"), ret.gears, true); + return ret; + } + + QJsonObject EquipmentGearAssignment::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("gears"), arrayToJson(gears)}}; + } + + + EquipmentGearChargeState EquipmentGearChargeState::fromJson(const QJsonObject &obj) + { + EquipmentGearChargeState ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("charges"), ret.charges); + return ret; + } + + QJsonObject EquipmentGearChargeState::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("charges"), arrayToJson(charges)}}; + } + + + ExerciseEnvironmentData ExerciseEnvironmentData::fromJson(const QJsonObject &obj) + { + ExerciseEnvironmentData ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("exerciseId"), ret.exerciseId); + int tz; + get(obj, QStringLiteral("timeZone"), tz); + ret.timeZone = tz; + get(obj, QStringLiteral("utmZone"), ret.utmZone); + get(obj, QStringLiteral("utmBand"), ret.utmBand); + get(obj, QStringLiteral("grid"), ret.grid); + return ret; + } + + QJsonObject ExerciseEnvironmentData::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("exerciseId"), exerciseId}, + {QStringLiteral("timeZone"), timeZone}, + {QStringLiteral("utmZone"), utmZone}, + {QStringLiteral("utmBand"), utmBand}, + {QStringLiteral("grid"), QString::fromStdString(grid)}}; + } + + + BiteError BiteError::fromJson(const QJsonObject &obj) + { + BiteError ret; + get(obj, QStringLiteral("errorNumber"), ret.errorNumber); + get(obj, QStringLiteral("canDeviceNumber"), ret.canDeviceNumber); + get(obj, QStringLiteral("subdeviceNumber"), ret.subdeviceNumber); + get(obj, QStringLiteral("uniqueId"), ret.uniqueId); + return ret; + } + + QJsonObject BiteError::toJson() const + { + return QJsonObject{{QStringLiteral("errorNumber"), errorNumber}, + {QStringLiteral("canDeviceNumber"), canDeviceNumber}, + {QStringLiteral("subdeviceNumber"), subdeviceNumber}, + {QStringLiteral("uniqueId"), uniqueId}}; + } + + + BiteReport BiteReport::fromJson(const QJsonObject &obj) + { + BiteReport ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("loginType"), ret.loginType); + get(obj, QStringLiteral("biteState"), ret.biteState); + get(obj, QStringLiteral("configState"), ret.configState); + get(obj, QStringLiteral("batteryState"), ret.batteryState); + get(obj, QStringLiteral("configError"), ret.configError); + get(obj, QStringLiteral("biteErrors"), ret.biteErrors, true); + return ret; + } + + QJsonObject BiteReport::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("loginType"), enumToJson(loginType)}, + {QStringLiteral("biteState"), biteState}, + {QStringLiteral("configState"), configState}, + {QStringLiteral("batteryState"), batteryState}, + {QStringLiteral("configError"), configError}, + {QStringLiteral("biteErrors"), arrayToJson(biteErrors)}}; + } + + + EquipmentGearEvent EquipmentGearEvent::fromJson(const QJsonObject &obj) + { + EquipmentGearEvent ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("charge"), ret.charge); + get(obj, QStringLiteral("chargeAmount"), ret.chargeAmount); + return ret; + } + + QJsonObject EquipmentGearEvent::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("charge"), charge.toJson()}, {QStringLiteral("chargeAmount"), chargeAmount}}; + } + + + CesHitInformation CesHitInformation::fromJson(const QJsonObject &obj) + { + CesHitInformation ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("chargeTasCodeDirect"), ret.chargeTasCodeDirect); + get(obj, QStringLiteral("chargeTasCodeIndirect"), ret.chargeTasCodeIndirect); + get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); + get(obj, QStringLiteral("directionDegree"), ret.directionDegree); + get(obj, QStringLiteral("distance"), ret.distance); + get(obj, QStringLiteral("effectPercent"), ret.effectPercent); + return ret; + } + + QJsonObject CesHitInformation::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("chargeTasCodeDirect"), chargeTasCodeDirect}, + {QStringLiteral("chargeTasCodeIndirect"), chargeTasCodeIndirect}, + {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, + {QStringLiteral("directionDegree"), directionDegree}, + {QStringLiteral("distance"), distance}, + {QStringLiteral("effectPercent"), effectPercent}}; + } + + + ParticipantSwVersionsRequest ParticipantSwVersionsRequest::fromJson(const QJsonObject &obj) + { + ParticipantSwVersionsRequest ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("charge"), ret.equipmentFunctionId); + return ret; + } + + QJsonObject ParticipantSwVersionsRequest::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("chargeAmount"), equipmentFunctionId}}; + } + + + EquipmentSwVersion EquipmentSwVersion::fromJson(const QJsonObject &obj) + { + EquipmentSwVersion ret; + get(obj, QStringLiteral("equipmentFunctionId"), ret.equipmentFunctionId); + get(obj, QStringLiteral("subDeviceId"), ret.subDeviceId); + get(obj, QStringLiteral("uniqueId"), ret.uniqueId); + get(obj, QStringLiteral("swVersion"), ret.swVersion); + return ret; + } + + QJsonObject EquipmentSwVersion::toJson() const + { + return QJsonObject{{QStringLiteral("equipmentFunctionId"), equipmentFunctionId}, + {QStringLiteral("subDeviceId"), subDeviceId}, + {QStringLiteral("uniqueId"), uniqueId}, + {QStringLiteral("swVersion"), swVersion}}; + } + + + ParticipantSwVersions ParticipantSwVersions::fromJson(const QJsonObject &obj) + { + ParticipantSwVersions ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("subDeviceId"), ret.equipments); + return ret; + } + + QJsonObject ParticipantSwVersions::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("subDeviceId"), arrayToJson(equipments)}}; + } + + + CesHitRequest CesHitRequest::fromJson(const QJsonObject &obj) + { + CesHitRequest ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("chargeTasCodeDirect"), ret.chargeTasCodeDirect); + get(obj, QStringLiteral("chargeTasCodeIndirect"), ret.chargeTasCodeIndirect); + get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("aesType"), ret.aesType); + get(obj, QStringLiteral("mineId"), ret.mineId); + get(obj, QStringLiteral("remainEffectPercent"), ret.remainEffectPercent); + get(obj, QStringLiteral("remainEffectTasCodeDirect"), ret.remainEffectTasCodeDirect); + get(obj, QStringLiteral("buildingId"), ret.buildingId); + get(obj, QStringLiteral("roomId"), ret.roomId); + get(obj, QStringLiteral("relPosition"), ret.relPosition); + get(obj, QStringLiteral("reserve1"), ret.reserve1); + get(obj, QStringLiteral("reserve2"), ret.reserve2); + + return ret; + } + + QJsonObject CesHitRequest::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("chargeTasCodeDirect"), chargeTasCodeDirect}, + {QStringLiteral("chargeTasCodeIndirect"), chargeTasCodeIndirect}, + {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, + {QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("aesType"), enumToJson(aesType)}, + {QStringLiteral("mineId"), mineId}, + {QStringLiteral("remainEffectPercent"), remainEffectPercent}, + {QStringLiteral("remainEffectTasCodeDirect"), remainEffectTasCodeDirect}, + {QStringLiteral("buildingId"), buildingId}, + {QStringLiteral("roomId"), roomId}, + {QStringLiteral("relPosition"), relPosition.toJson()}, + {QStringLiteral("reserve1"), reserve1}, + {QStringLiteral("reserve2"), reserve2}}; + } + + + TechnicalArea TechnicalArea::fromJson(const QJsonObject &obj) + { + TechnicalArea ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("aesDdsId"), ret.aesDdsId); + get(obj, QStringLiteral("taType"), ret.taType); + get(obj, QStringLiteral("name"), ret.name); + get(obj, QStringLiteral("relCorner"), ret.relCorner); + get(obj, QStringLiteral("width"), ret.width); + get(obj, QStringLiteral("height"), ret.height); + return ret; + } + + QJsonObject TechnicalArea::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("aesDdsId"), aesDdsId}, + {QStringLiteral("taType"), enumToJson(taType)}, + {QStringLiteral("name"), QString::fromStdString(name)}, + {QStringLiteral("relCorner"), relCorner.toJson()}, + {QStringLiteral("width"), width}, + {QStringLiteral("height"), height}}; + } + + + void ParticipantModeBase::fromJson(const QJsonObject &obj, ParticipantModeBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("language"), ret.language); + get(obj, QStringLiteral("operationMode"), ret.operationMode); + get(obj, QStringLiteral("reactivationDetoxication"), ret.reactivationDetoxication); + get(obj, QStringLiteral("reactivationMaintenance"), ret.reactivationMaintenance); + get(obj, QStringLiteral("reactivationMedic"), ret.reactivationMedic); + get(obj, QStringLiteral("modeVest"), ret.modeVest); + get(obj, QStringLiteral("modeHelmet"), ret.modeHelmet); + get(obj, QStringLiteral("personellProtectionMode"), ret.personellProtectionMode); + get(obj, QStringLiteral("protectionLevel"), ret.protectionLevel); + get(obj, QStringLiteral("handgrenadeSearchMode"), ret.handgrenadeSearchMode); + get(obj, QStringLiteral("internationalMode"), ret.internationalMode); + get(obj, QStringLiteral("abcProtectionMode"), ret.abcProtectionMode); + } + + QJsonObject ParticipantModeBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("language"), enumToJson(language)}, + {QStringLiteral("operationMode"), enumToJson(operationMode)}, + {QStringLiteral("reactivationDetoxication"), reactivationDetoxication}, + {QStringLiteral("reactivationMaintenance"), reactivationMaintenance}, + {QStringLiteral("reactivationMedic"), reactivationMedic}, + {QStringLiteral("modeVest"), enumToJson(modeVest)}, + {QStringLiteral("modeHelmet"), enumToJson(modeHelmet)}, + {QStringLiteral("personellProtectionMode"), enumToJson(personellProtectionMode)}, + {QStringLiteral("protectionLevel"), enumToJson(protectionLevel)}, + {QStringLiteral("handgrenadeSearchMode"), enumToJson(handgrenadeSearchMode)}, + {QStringLiteral("internationalMode"), enumToJson(internationalMode)}, + {QStringLiteral("abcProtectionMode"), enumToJson(abcProtectionMode)}}; + } + + + ParticipantMode ParticipantMode::fromJson(const QJsonObject &obj) + { + ParticipantMode ret; + ParticipantModeBase::fromJson(obj, ret); + return ret; + } + + QJsonObject ParticipantMode::toJson() const + { + return ParticipantModeBase::toJson(); + } + + + ParticipantModeReport ParticipantModeReport::fromJson(const QJsonObject &obj) + { + ParticipantModeReport ret; + ParticipantModeBase::fromJson(obj, ret); + return ret; + } + + QJsonObject ParticipantModeReport::toJson() const + { + return ParticipantModeBase::toJson(); + } + + + DemandParticipantMode DemandParticipantMode::fromJson(const QJsonObject &obj) + { + DemandParticipantMode ret; + get(obj, QStringLiteral("header"), ret.header); + return ret; + } + + QJsonObject DemandParticipantMode::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}}; + } + + + void ParticipantConfigurationBase::fromJson(const QJsonObject &obj, ParticipantConfigurationBase &ret) + { + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("positionIntervallVehicle"), ret.positionIntervallVehicle); + get(obj, QStringLiteral("positionIntervallPersonell"), ret.positionIntervallPersonell); + get(obj, QStringLiteral("positionIntervallAircraft"), ret.positionIntervallAircraft); + get(obj, QStringLiteral("positionTransmissionIntervall"), ret.positionTransmissionIntervall); + get(obj, QStringLiteral("heightbarrier"), ret.heightbarrier); + get(obj, QStringLiteral("faultPositionHandling"), ret.faultPositionHandling); + get(obj, QStringLiteral("switchingPositionIntervall"), ret.switchingPositionIntervall); + get(obj, QStringLiteral("waittimeAdditionalBroadcastDemand"), ret.waittimeAdditionalBroadcastDemand); + get(obj, QStringLiteral("factorWaittimeIncreaseAtHighload"), ret.factorWaittimeIncreaseAtHighload); + get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel1"), ret.waittimeAutomaticVulnerabilityIncreaseLevel1); + get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel2"), ret.waittimeAutomaticVulnerabilityIncreaseLevel2); + get(obj, QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel3"), ret.waittimeAutomaticVulnerabilityIncreaseLevel3); + get(obj, QStringLiteral("opticalCode"), ret.opticalCode); + get(obj, QStringLiteral("vulnerabilityModel"), ret.vulnerabilityModel); + get(obj, QStringLiteral("validTimeOps"), ret.validTimeOps); + } + + QJsonObject ParticipantConfigurationBase::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("positionIntervallVehicle"), positionIntervallVehicle}, + {QStringLiteral("positionIntervallPersonell"), positionIntervallPersonell}, + {QStringLiteral("positionIntervallAircraft"), positionIntervallAircraft}, + {QStringLiteral("positionTransmissionIntervall"), positionTransmissionIntervall}, + {QStringLiteral("heightbarrier"), heightbarrier}, + {QStringLiteral("faultPositionHandling"), enumToJson(faultPositionHandling)}, + {QStringLiteral("switchingPositionIntervall"), enumToJson(switchingPositionIntervall)}, + {QStringLiteral("waittimeAdditionalBroadcastDemand"), waittimeAdditionalBroadcastDemand}, + {QStringLiteral("factorWaittimeIncreaseAtHighload"), factorWaittimeIncreaseAtHighload}, + {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel1"), waittimeAutomaticVulnerabilityIncreaseLevel1}, + {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel2"), waittimeAutomaticVulnerabilityIncreaseLevel2}, + {QStringLiteral("waittimeAutomaticVulnerabilityIncreaseLevel3"), waittimeAutomaticVulnerabilityIncreaseLevel3}, + {QStringLiteral("opticalCode"), enumToJson(opticalCode)}, + {QStringLiteral("vulnerabilityModel"), vulnerabilityModel}, + {QStringLiteral("validTimeOps"), validTimeOps}}; + } + + + ParticipantConfigurationReport ParticipantConfigurationReport::fromJson(const QJsonObject &obj) + { + ParticipantConfigurationReport ret; + ParticipantConfigurationBase::fromJson(obj, ret); + return ret; + } + + QJsonObject ParticipantConfigurationReport::toJson() const + { + return ParticipantConfigurationBase::toJson(); + } + + + ParticipantConfiguration ParticipantConfiguration::fromJson(const QJsonObject &obj) + { + ParticipantConfiguration ret; + ParticipantConfigurationBase::fromJson(obj, ret); + return ret; + } + + QJsonObject ParticipantConfiguration::toJson() const + { + return ParticipantConfigurationBase::toJson(); + } + + + DemandParticipantConfiguration DemandParticipantConfiguration::fromJson(const QJsonObject &obj) + { + DemandParticipantConfiguration ret; + get(obj, QStringLiteral("header"), ret.header); + return ret; + } + + QJsonObject DemandParticipantConfiguration::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}}; + } + + + ExerciseStateData ExerciseStateData::fromJson(const QJsonObject &obj) + { + ExerciseStateData ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("exerciseState"), ret.exerciseState); + get(obj, QStringLiteral("exerciseId"), ret.exerciseId); + return ret; + } + + QJsonObject ExerciseStateData::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("exerciseState"), enumToJson(exerciseState)}, + {QStringLiteral("exerciseId"), exerciseId}}; + } + + + EmergencyCall EmergencyCall::fromJson(const QJsonObject &obj) + { + EmergencyCall ret; + get(obj, QStringLiteral("issi"), ret.issi); + get(obj, QStringLiteral("absPosition"), ret.absPosition); + get(obj, QStringLiteral("timeStamp"), ret.timeStamp); + return ret; + } + + QJsonObject EmergencyCall::toJson() const + { + return QJsonObject{{QStringLiteral("issi"), issi}, {QStringLiteral("absPosition"), absPosition.toJson()}, {QStringLiteral("timeStamp"), timeStamp}}; + } + + + RequestBroadcastStatistics RequestBroadcastStatistics::fromJson(const QJsonObject &obj) + { + RequestBroadcastStatistics ret; + get(obj, QStringLiteral("header"), ret.header); + return ret; + } + + QJsonObject RequestBroadcastStatistics::toJson() const + { + return QJsonObject{{QStringLiteral("issi"), header.toJson()}}; + } + + + BroadcastInformation BroadcastInformation::fromJson(const QJsonObject &obj) + { + BroadcastInformation ret; + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("broadcastRequests"), ret.broadcastRequests); + return ret; + } + + QJsonObject BroadcastInformation::toJson() const + { + return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, {QStringLiteral("broadcastRequests"), broadcastRequests}}; + } + + + BroadcastStatistics BroadcastStatistics::fromJson(const QJsonObject &obj) + { + BroadcastStatistics ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("information"), ret.information); + return ret; + } + + QJsonObject BroadcastStatistics::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("information"), arrayToJson(information)}}; + } + + + GroupIssiInformation GroupIssiInformation::fromJson(const QJsonObject &obj) + { + GroupIssiInformation ret; + get(obj, QStringLiteral("exerciseId"), ret.exerciseId); + get(obj, QStringLiteral("serverIssi"), ret.serverIssi); + get(obj, QStringLiteral("broadcastIssi1"), ret.broadcastIssi1); + get(obj, QStringLiteral("broadcastIssi2"), ret.broadcastIssi2); + return ret; + } + + QJsonObject GroupIssiInformation::toJson() const + { + return QJsonObject{{QStringLiteral("exerciseId"), exerciseId}, + {QStringLiteral("serverIssi"), serverIssi}, + {QStringLiteral("broadcastIssi1"), broadcastIssi1}, + {QStringLiteral("broadcastIssi2"), broadcastIssi2}}; + } + + + ExerciseEquipmentAssignmentComplete ExerciseEquipmentAssignmentComplete::fromJson(const QJsonObject &obj) + { + ExerciseEquipmentAssignmentComplete ret; + QJsonArray arrExercise; + get(obj, QStringLiteral("exerciseEquipmentAssignments"), arrExercise); + for (const auto &ele : std::as_const(arrExercise)) + { + const QJsonObject elem = ele.toObject(); + int exerciseId; + QJsonArray equipmentNumbers; + get(elem, QStringLiteral("exerciseId"), exerciseId); + get(elem, QStringLiteral("equipmentNumbers"), equipmentNumbers); + auto &cont = ret.exerciseEquipmentAssignments[exerciseId]; + for (const auto &eq : std::as_const(equipmentNumbers)) + cont.insert(eq.toInt()); + } + get(obj, QStringLiteral("groupIssiInformation"), ret.groupIssiInformation); + return ret; + } + + QJsonObject ExerciseEquipmentAssignmentComplete::toJson() const + { + QJsonArray arrExercise; + for (const auto &it : exerciseEquipmentAssignments) + { + QJsonArray equipmentNumbers; + for (const int equipmentNumber : it.second) + equipmentNumbers += equipmentNumber; + arrExercise += QJsonObject{{QStringLiteral("exerciseId"), it.first}, {QStringLiteral("equipmentNumbers"), equipmentNumbers}}; + } + + return QJsonObject{{QStringLiteral("exerciseEquipmentAssignments"), arrExercise}, {QStringLiteral("groupIssiInformation"), arrayToJson(groupIssiInformation)}}; + } + + + ProxyConnectionState ProxyConnectionState::fromJson(const QJsonObject &obj) + { + ProxyConnectionState ret; + get(obj, QStringLiteral("connectedToSystem"), ret.connectedToSystem); + return ret; + } + + QJsonObject ProxyConnectionState::toJson() const + { + return QJsonObject{{QStringLiteral("connectedToSystem"), connectedToSystem}}; + } + + + ParticipantLicenseChange ParticipantLicenseChange::fromJson(const QJsonObject &obj) + { + ParticipantLicenseChange ret; + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("licenseState"), ret.licenseState); + return ret; + } + + QJsonObject ParticipantLicenseChange::toJson() const + { + return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, {QStringLiteral("licenseState"), enumToJson(licenseState)}}; + } + + + WlsParticipantsStateRequest WlsParticipantsStateRequest::fromJson(const QJsonObject &obj) + { + Q_UNUSED(obj); + return WlsParticipantsStateRequest(); + } + + QJsonObject WlsParticipantsStateRequest::toJson() const + { + return QJsonObject(); + } + + + WlsParticipantsStateReport WlsParticipantsStateReport::fromJson(const QJsonObject &obj) + { + WlsParticipantsStateReport ret; + get(obj, QStringLiteral("participantStates"), ret.participantStates); + return ret; + } + + QJsonObject WlsParticipantsStateReport::toJson() const + { + return QJsonObject{{QStringLiteral("participantStates"), arrayToJson(participantStates)}}; + } + + + WlsBinarySfmData WlsBinarySfmData::fromJson(const QJsonObject &obj) + { + WlsBinarySfmData ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("payload"), ret.payload); + return ret; + } + + QJsonObject WlsBinarySfmData::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("payload"), arrayToJson(payload)}}; + } + + + WlsParticipantsConnectionState WlsParticipantsConnectionState::fromJson(const QJsonObject &obj) + { + WlsParticipantsConnectionState ret; + get(obj, QStringLiteral("equipmentNumber"), ret.equipmentNumber); + get(obj, QStringLiteral("dataCommunicationPossible"), ret.dataCommunicationPossible); + return ret; + } + + QJsonObject WlsParticipantsConnectionState::toJson() const + { + return QJsonObject{{QStringLiteral("equipmentNumber"), equipmentNumber}, {QStringLiteral("dataCommunicationPossible"), dataCommunicationPossible}}; + } + + + SanitationRepair SanitationRepair::fromJson(const QJsonObject &obj) + { + SanitationRepair ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("originatorType"), ret.originatorType); + get(obj, QStringLiteral("equipmentNumberOrigin"), ret.equipmentNumberOrigin); + get(obj, QStringLiteral("stateStart"), ret.stateStart); + get(obj, QStringLiteral("typeOfTreatment"), ret.typeOfTreatment); + get(obj, QStringLiteral("triage"), ret.triage); + get(obj, QStringLiteral("tyeOfDamage"), ret.tyeOfDamage); + get(obj, QStringLiteral("stateResult"), ret.stateResult); + get(obj, QStringLiteral("treatmentResult"), ret.treatmentResult); + get(obj, QStringLiteral("triagePriority"), ret.triagePriority); + get(obj, QStringLiteral("fullState"), ret.fullState); + get(obj, QStringLiteral("timeOfTreatment"), ret.timeOfTreatment); + get(obj, QStringLiteral("timeOfRecovery"), ret.timeOfRecovery); + + return ret; + } + + QJsonObject SanitationRepair::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("originatorType"), enumToJson(originatorType)}, + {QStringLiteral("equipmentNumberOrigin"), equipmentNumberOrigin}, + {QStringLiteral("stateStart"), enumToJson(stateStart)}, + {QStringLiteral("typeOfTreatment"), typeOfTreatment}, + {QStringLiteral("triage"), triage}, + {QStringLiteral("tyeOfDamage"), tyeOfDamage}, + {QStringLiteral("stateResult"), enumToJson(stateResult)}, + {QStringLiteral("treatmentResult"), enumToJson(treatmentResult)}, + {QStringLiteral("triagePriority"), triagePriority}, + {QStringLiteral("fullState"), fullState}, + {QStringLiteral("timeOfTreatment"), timeOfTreatment}, + {QStringLiteral("timeOfRecovery"), timeOfRecovery}}; + } + + SanitaryMaterialStockReport SanitaryMaterialStockReport::fromJson(const QJsonObject &obj) + { + SanitaryMaterialStockReport ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); + get(obj, QStringLiteral("qualification"), ret.qualification); + get(obj, QStringLiteral("uniqueId"), ret.uniqueId); + get(obj, QStringLiteral("sanitaryMaterialCount"), ret.sanitaryMaterialCount); + get(obj, QStringLiteral("sanitaryMaterialStock"), ret.sanitaryMaterialStock); + return ret; + } + + QJsonObject SanitaryMaterialStockReport::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("sanitaryMaterialCount"), sanitaryMaterialCount}, + {QStringLiteral("uniqueId"), uniqueId}, + {QStringLiteral("sanitaryMaterialStock"), arrayToJson(sanitaryMaterialStock)}, + {QStringLiteral("qualification"), enumToJson(qualification)}, + {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}}; + } + + ApacheLaserDesignation ApacheLaserDesignation::fromJson(const QJsonObject &obj) + { + ApacheLaserDesignation ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("gearId"), ret.gearId); + get(obj, QStringLiteral("code"), ret.code); + get(obj, QStringLiteral("outputPower"), ret.outputPower); + get(obj, QStringLiteral("spotLocation"), ret.spotLocation); + return ret; + } + + QJsonObject ApacheLaserDesignation::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("gearId"), gearId}, + {QStringLiteral("code"), code}, + {QStringLiteral("outputPower"), outputPower}, + {QStringLiteral("spotLocation"), spotLocation.toJson()}}; + } + + Sanitation Sanitation::fromJson(const QJsonObject &obj) + { + Sanitation ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("originatorEquipmentNumber"), ret.originatorEquipmentNumber); + get(obj, QStringLiteral("uniqeId"), ret.uniqeId); + get(obj, QStringLiteral("proceduresTaken"), ret.proceduresTaken); + get(obj, QStringLiteral("sanitationResult"), ret.sanitationResult); + get(obj, QStringLiteral("sanitationEvaluation"), ret.sanitationEvaluation); + get(obj, QStringLiteral("qualification"), ret.qualification); + return ret; + } + + QJsonObject Sanitation::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, + {QStringLiteral("originatorEquipmentNumber"), originatorEquipmentNumber}, + {QStringLiteral("uniqeId"), uniqeId}, + {QStringLiteral("proceduresTaken"), proceduresTaken}, + {QStringLiteral("sanitationResult"), enumToJson(sanitationResult)}, + {QStringLiteral("sanitationEvaluation"), enumToJson(sanitationEvaluation)}, + {QStringLiteral("qualification"), enumToJson(qualification)}}; + } + + BatteryInfo BatteryInfo::fromJson(const QJsonObject &obj) + { + BatteryInfo ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("batteryStates"), ret.batteryStates); + + return ret; + } + + QJsonObject BatteryInfo::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("batteryStates"), arrayToJson(batteryStates)}}; + } + + BatteryAlarm BatteryAlarm::fromJson(const QJsonObject &obj) + { + BatteryAlarm ret; + get(obj, QStringLiteral("header"), ret.m_header); + get(obj, QStringLiteral("id"), ret.m_id); + get(obj, QStringLiteral("description"), ret.m_description); + get(obj, QStringLiteral("acknowledge"), ret.m_acknowledge); + get(obj, QStringLiteral("condition"), ret.m_condition); + get(obj, QStringLiteral("uniqueAlarmNumber"), ret.m_uniqueAlarmNumber); + get(obj, QStringLiteral("alarmTime"), ret.m_alarmTime); + return ret; + } + + QJsonObject BatteryAlarm::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header().toJson()}, + {QStringLiteral("id"), m_id}, + {QStringLiteral("description"), description()}, + {QStringLiteral("acknowledge"), acknowledge()}, + {QStringLiteral("condition"), condition()}, + {QStringLiteral("uniqueAlarmNumber"), uniqueAlarmNumber()}, + {QStringLiteral("alarmTime"), alarmTime()}}; + } + + ServiceControl ServiceControl::fromJson(const QJsonObject &obj) + { + ServiceControl ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("serviceControlState"), ret.serviceControlState); + + return ret; + } + + QJsonObject ServiceControl::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("serviceControlState"), enumToJson(serviceControlState)}}; + } + + SetDevicePowerRequest SetDevicePowerRequest::fromJson(const QJsonObject &obj) + { + SetDevicePowerRequest ret; + get(obj, QStringLiteral("header"), ret.header); + get(obj, QStringLiteral("powerType"), ret.powerType); + get(obj, QStringLiteral("subdeviceId"), ret.subdeviceId); + + return ret; + } + + QJsonObject SetDevicePowerRequest::toJson() const + { + return QJsonObject{{QStringLiteral("header"), header.toJson()}, {QStringLiteral("powerType"), enumToJson(powerType)}, {QStringLiteral("subdeviceId"), subdeviceId}}; + } + + RestoreRadioReadiness RestoreRadioReadiness::fromJson(const QJsonObject &obj) + { + RestoreRadioReadiness ret; + + get(obj, HEADER(), ret.header); + get(obj, READINESS_LOSS_POSITION(), ret.readinessLossPosition); + get(obj, READINESS_LOSS_TIME(), ret.readinessLossTime); + get(obj, READINESS_RESTORE_POSITION(), ret.readinessRestorePosition); + get(obj, READINESS_RESTORE_TIME(), ret.readinessRestoreTime); + + return ret; + } + + QJsonObject RestoreRadioReadiness::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, + {READINESS_LOSS_POSITION(), readinessLossPosition.toJson()}, + {READINESS_LOSS_TIME(), readinessLossTime}, + {READINESS_RESTORE_POSITION(), readinessRestorePosition.toJson()}, + {READINESS_RESTORE_TIME(), readinessRestoreTime}}; + } + + + UAVAction UAVAction::fromJson(const QJsonObject &obj) + { + UAVAction ret; + + get(obj, TASK(), ret.task); + get(obj, POSITION(), ret.absPosition); + + return ret; + } + + QJsonObject UAVAction::toJson() const + { + return QJsonObject{{TASK(), enumToJson(task)}, {POSITION(), absPosition.toJson()}}; + } + + + UAVPerformMission UAVPerformMission::fromJson(const QJsonObject &obj) + { + UAVPerformMission ret; + + get(obj, HEADER(), ret.header); + get(obj, ACTIONS(), ret.actions); + get(obj, MISSION_NAME(), ret.missionName); + get(obj, MISSION_ID(), ret.missionId); + + return ret; + } + + QJsonObject UAVPerformMission::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {ACTIONS(), arrayToJson(actions)}, {MISSION_NAME(), missionName}, {MISSION_ID(), missionId}}; + } + + + UAVStatus UAVStatus::fromJson(const QJsonObject &obj) + { + UAVStatus ret; + + get(obj, HEADER(), ret.header); + get(obj, UAVSTATE(), ret.uavState); + + return ret; + } + + QJsonObject UAVStatus::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {UAVSTATE(), enumToJson(uavState)}}; + } + + + UAVRadioLinkConnectionStatus UAVRadioLinkConnectionStatus::fromJson(const QJsonObject &obj) + { + UAVRadioLinkConnectionStatus ret; + get(obj, HEADER(), ret.header); + get(obj, UAVCONNECTIONSTATE(), ret.uavConnectionState); -UAVChangeState UAVChangeState::fromJson(const QJsonObject &obj) -{ - UAVChangeState ret; + return ret; + } - get(obj, HEADER(), ret.header); - get(obj, REQUESTED_STATE(), ret.requestedState); + QJsonObject UAVRadioLinkConnectionStatus::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {UAVCONNECTIONSTATE(), enumToJson(uavConnectionState)}}; + } - return ret; -} - -QJsonObject UAVChangeState::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {REQUESTED_STATE(), enumToJson(requestedState)}}; -} - -ExFireReadiness ExFireReadiness::fromJson(const QJsonObject &obj) -{ - ExFireReadiness ret; - get(obj, HEADER(), ret.header); - get(obj, PARTY_ID(), ret.partyId); - get(obj, REFERENCE(), ret.reference); - - return ret; -} - -QJsonObject ExFireReadiness::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {PARTY_ID(), partyId}, - {REFERENCE(), reference}}; -} - -ExFiredReport ExFiredReport::fromJson(const QJsonObject &obj) -{ - ExFiredReport ret; - - get(obj, HEADER(), ret.header); - get(obj, PARTY_ID(), ret.partyId); - get(obj, REFERENCE(), ret.reference); - get(obj, UNIT_IDENTIFIER(), ret.unitIdentifier); - get(obj, IDENTIFIER(), ret.identifier); - return ret; -} - -QJsonObject ExFiredReport::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {PARTY_ID(), partyId}, - {REFERENCE(), reference}, - {UNIT_IDENTIFIER(), unitIdentifier}, - {IDENTIFIER(), identifier}}; -} - -ExConfirmationReport ExConfirmationReport::fromJson(const QJsonObject &obj) -{ - ExConfirmationReport ret; - - get(obj, HEADER(), ret.header); - get(obj, PARTY_ID(), ret.partyId); - get(obj, REFERENCE(), ret.reference); - get(obj, UNIT_IDENTIFIER(), ret.unitIdentifier); - get(obj, IDENTIFIER(), ret.identifier); - return ret; -} - -QJsonObject ExConfirmationReport::toJson() const -{ - return QJsonObject{{HEADER(), header.toJson()}, - {PARTY_ID(), partyId}, - {REFERENCE(), reference}, - {UNIT_IDENTIFIER(), unitIdentifier}, - {IDENTIFIER(), identifier}}; -} - -} // namespace TetraIcd + UAVMissionStatus UAVMissionStatus::fromJson(const QJsonObject &obj) + { + UAVMissionStatus ret; + + get(obj, HEADER(), ret.header); + get(obj, CURRENT_ACTION(), ret.currentAction); + get(obj, CURRENT_MISSION_NAME(), ret.currentMissionName); + get(obj, MISSION_ENDED(), ret.missionEnded); + + return ret; + } + + QJsonObject UAVMissionStatus::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, + {CURRENT_ACTION(), enumToJson(currentAction)}, + {CURRENT_MISSION_NAME(), currentMissionName}, + {MISSION_ENDED(), missionEnded}}; + } + + + UAVChangeState UAVChangeState::fromJson(const QJsonObject &obj) + { + UAVChangeState ret; + + get(obj, HEADER(), ret.header); + get(obj, REQUESTED_STATE(), ret.requestedState); + + return ret; + } + + QJsonObject UAVChangeState::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {REQUESTED_STATE(), enumToJson(requestedState)}}; + } + + ExFireReadiness ExFireReadiness::fromJson(const QJsonObject &obj) + { + ExFireReadiness ret; + + get(obj, HEADER(), ret.header); + get(obj, PARTY_ID(), ret.partyId); + get(obj, REFERENCE(), ret.reference); + + return ret; + } + + QJsonObject ExFireReadiness::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {PARTY_ID(), partyId}, {REFERENCE(), reference}}; + } + + ExFiredReport ExFiredReport::fromJson(const QJsonObject &obj) + { + ExFiredReport ret; + + get(obj, HEADER(), ret.header); + get(obj, PARTY_ID(), ret.partyId); + get(obj, REFERENCE(), ret.reference); + get(obj, UNIT_IDENTIFIER(), ret.unitIdentifier); + get(obj, IDENTIFIER(), ret.identifier); + return ret; + } + + QJsonObject ExFiredReport::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {PARTY_ID(), partyId}, {REFERENCE(), reference}, {UNIT_IDENTIFIER(), unitIdentifier}, {IDENTIFIER(), identifier}}; + } + + ExConfirmationReport ExConfirmationReport::fromJson(const QJsonObject &obj) + { + ExConfirmationReport ret; + + get(obj, HEADER(), ret.header); + get(obj, PARTY_ID(), ret.partyId); + get(obj, REFERENCE(), ret.reference); + get(obj, UNIT_IDENTIFIER(), ret.unitIdentifier); + get(obj, IDENTIFIER(), ret.identifier); + return ret; + } + + QJsonObject ExConfirmationReport::toJson() const + { + return QJsonObject{{HEADER(), header.toJson()}, {PARTY_ID(), partyId}, {REFERENCE(), reference}, {UNIT_IDENTIFIER(), unitIdentifier}, {IDENTIFIER(), identifier}}; + } + + } // namespace TetraIcd } // namespace TrainingAreaBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.h old mode 100755 new mode 100644 index 93a8d70ee..2b5ea15f1 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/TrainingAreaBase/training_area_telegrams.h @@ -16,2508 +16,2544 @@ namespace TrainingAreaBase { -namespace TetraIcd -{ - -class JsonException final : public std::exception -{ -public: - JsonException(const QJsonObject &obj, const QString &key); - const char *what() const noexcept override { return m_what.data(); } -private: - QJsonObject m_obj; - QString m_key; - QByteArray m_what; -}; - - -enum TelegramId -{ - UNKNOWN = -1, - BESTAETIGUNG = 0, - INIT = 1, - MANIPULATIONSMELDUNG = 2, - UMGEBUNGS_MELDUNG2 = 203, - AUFFORDERUNG_BITE_MELDUNG = 4, - BITE_MELDUNG2 = 205, - BETRIEBSZUSTAND_AUSSTATTUNG = 7, - KONFIGURATION_WIRKMODELL = 9, - ANFORDERUNG_KONFIGURATIONSDATEN = 10, - KONFIGURATIONSMELDUNG = 11, - FEHLERMELDUNG_GFD = 12, - WIEDERHERSTELLUNG_FUNKBEREITSCHAFT = 13, - POSITIONS_MELDUNG = 21, - POSITIONS_MELDUNG_MIT_TEILNEHMER = 22, - POSITIONS_MELDUNG_LFZ = 23, - SCHIEDSRICHTERKOMMANDO = 25, - IPS_POSITIONSDATEN = 201, - WIRKFELD_EINZELGESCHOSS = 31, - WIRKFELD_FLAECHENDECKENDES_FEUER = 32, - WIRKFELD_FLAECHENDECKENDES_FEUER_STOP = 33, - WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN = 34, - WIRKFELD_MINENSPERRE = 35, - WIRKFELD_STATUS_MINENSPERRE = 36, - WIRKFELD_A_KAMPFMITTEL = 37, - WIRKFELD_C_KAMPFMITTEL = 38, - DEAKTIVIERUNG_WIRKFELD = 39, - WIRKFELD_AENDERUNG_BEZEICHNER = 40, - DEAKTIVIERUNG_EINZELMINE = 41, - REAKTIVIERUNG_DUS_MINE = 42, - DEFINITION_IED = 43, - ZUSTAND_IED = 44, - STATUS_EINZELMINENSIMULATOR = 45, - WIRKFELD_EINZELMINENSIMULATOR = 46, - TREFFER_EREIGNIS_DUS = 52, - TREFFER_EREIGNIS_WIRKSIMULATION = 53, - TREFFER_AUSLOESUNG = 54, - SCHIEDSRICHTEREINGRIFF = 55, - SELEKTIVE_AUFMUNITIONIERUNG = 56, - TREFFER_EREIGNIS_SEKUNDAERWIRKUNG = 218, - TREFFER_EREIGNIS_DUS_IPS = 228, - TREFFER_EREIGNIS_WIRKSIMULATION_IPS = 229, - TAKTISCHER_STATUS = 61, - FUNKTIONSRAUM = 62, - EINTRETEN_FUNKTIONSRAUM = 63, - DEAKTIVIEREN_FUNKTIONSRAUM = 64, - DATENVERKEHR_SRT_TDS = 71, - DATENVERKEHR_TDS_SRT = 72, - DATENVERKEHR_DMF_TDS = 73, - DATENVERKEHR_TDS_DMF = 74, - NACHFORDERUNG_BROADCAST_TELEGRAMME = 82, - SONDERSENSORIK_FAHRSPUR = 92, - SONDERSENSORIK_MIVANH_VERLEGEDATEN = 95, - SONDERSENSORIK_WMIV_VERLEGEDATEN = 96, - SONDERSENSORIK_MIVANH_VERLEGEPOSITION = 97, - SPRACHAUSWAHL = 101, - ALLGEMEINE_NACHRICHT = 102, - GERAETEEREIGNIS = 185, - WAFFENZUORDNUNG = 200, - MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE = 202, - FEUEREREIGNIS_MIT_WAFFENZUORDNUNG = 210, - AUSLOESUNG_DUS_TREFFER = 211, - ANFORDERUNG_SW_VERSION = 212, - SW_VERSIONSMELDUNG = 213, - TECHNIK_FUNKTIONSRAUM = 219, - TEILNEHMERMODE_SETZEN = 230, - TEILNEHMERMODE_MELDUNG = 231, - TEILNEHMERMODE_ANFORDERN = 232, - TEILNEHMER_KONFIG_ANTWORT = 233, - TEILNEHMER_KONFIG_SETZEN = 234, - TEILNEHMER_KONFIG_ANFORDERN = 235, - SANITAETSDIENST_INSTANDSETZUNG = 240, - BESTANDSMELDUNG_SANITAETSMATERIAL = 241, - SANITAETSDIENST_INSTANDSETZUNG_PVSAN = 242, - NOTRUF = 1120, - BETRIEBSZUSTANDSMELDUNG = 2008, - ANFORDERUNG_STATISTIK_BROADCAST_NACHFORDERUNGEN = 2009, - STATISTIK_BROADCAST_NACHFORDERUNGEN = 2010, - EXERCISE_EQUIPMENT_ASSIGNMENT_COMPLETE = 2012, - PROXY_CONNECTION_STATE = 2013, - PARTICIPANT_LICENSE_CHANGE = 2014, - WLS_PARTICIPANTS_STATE_REQUEST = 3001, - WLS_PARTICIPANTS_STATE_REPORT = 3002, - WLS_BINARY_SFM_DATA = 3003, - WLS_PARTICIPANT_CONNECTION_STATE = 3004, - SR_DMF_NACHRICHT = 6130, - APACHE_LASER_DESIGNATION = 8004, - BATTERY_INFO = 9000, - BATTERY_ALARM = 9001, - SERVICE_CONTROL = 9002, - DEVICE_POWER_SET_REQUEST = 9003, - UAV_PERFORM_MISSION = 9004, - UAV_STATUS = 9005, - UAV_RADIO_LINK_CONNECTION_STATUS = 9006, - UAV_MISSION_STATUS = 9007, - UAV_CHANGE_STATE = 9008, - - - EX_FIRE_READINESS = 9100, - EX_FIRED_REPORT = 9101, - EX_CONFIRMATION_REPORT = 9102, -}; - - - - - - - - - - - - - - - - - - - - -template -struct Constraints; - - -struct TrainingAreaTelegram -{ - TrainingAreaTelegram() = default; - virtual ~TrainingAreaTelegram() = default; - - virtual QJsonObject toJson() const = 0; - virtual QString type() const = 0; - virtual TelegramId id() const = 0; -}; - -template -struct TrainingAreaTelegramTmpl : TrainingAreaTelegram -{ - QString type() const override final { return Constraints::type(); } - TelegramId id() const override final { return Constraints::id(); } -}; - -enum class Qualification { - NotDefined = 0, - FAA = 1, - FAB = 2, - SANPers = 3 -}; - -enum class SanitationResult { - NoEffect = 0, - Unhandled = 1, - Insufficient = 2, - Sufficient = 3, - Optimal = 4 -}; - -enum class SanitationEvaluation { - NotApplicable = -1, - Okay = 0, - PartlyWrong = 1, - Wrong = 2, -}; - -enum class VulnerabilityState -{ - CombatReady = 0, - LightDamage = 1, - MediumDamage = 2, - HeavyDamage = 3, - MobilityKill = 4, - VisibleMobilityKill = 5, - WeaponSystemDamage = 6, - VisibleWeaponSystemDamage = 7, - CatastrophicKill = 8, - TemporarySeverance = 9, - NearMiss = 10, - HitWithNoEffect = 11, - VulnerabilityBitsChanged = 12, - Reserved = 13, - NContamination = 14, - BContamination = 15, - CContamination = 16 -}; - -enum class OriginatorType -{ - Initialisation = 0, - ObserverController = 1, - ExerciseControl = 2, - FunctionalArea = 6, - MedicTimeout = 7, - Sanitation = 8, - MedicDecontamination = 9, - MaintainanceRepair = 10, - MaintainanceDecontamination = 11, -}; - - -enum class AreaEffectSimulationType -{ - Unknown = 0, - MineArea = 1, - ExplosionArea = 2, - ExplosionSingle = 3, - NContamination = 4, - CContamination = 5, - FunctionalArea = 6, - TechnicalArea = 7, - DusSingleMineSimulator = 8, - GasPipeDetonation = 9, - SpecialArea = 10, - BeStillWarning = 11, - DangerZoneExplosion = 12, - AirSupport = 13 -}; - -enum class ServiceControlEnum -{ - PRESHUTDOWN = 0, - SHUTDOWN = 1, - STOP = 2 -}; - -enum class PowerMethod -{ - Unknown = 0, - PowerOn = 1, - PowerOff = 2 -}; - -inline std::ostream &operator<<(std::ostream &stream, AreaEffectSimulationType val) -{ - switch (val) + namespace TetraIcd { - case AreaEffectSimulationType::Unknown: - stream << "AreaEffectSimulationType::Unknown"; return stream; - case AreaEffectSimulationType::MineArea: - stream << "AreaEffectSimulationType::MineArea"; return stream; - case AreaEffectSimulationType::ExplosionArea: - stream << "AreaEffectSimulationType::ExplosionArea"; return stream; - case AreaEffectSimulationType::ExplosionSingle: - stream << "AreaEffectSimulationType::ExplosionSingle"; return stream; - case AreaEffectSimulationType::NContamination: - stream << "AreaEffectSimulationType::NContamination"; return stream; - case AreaEffectSimulationType::CContamination: - stream << "AreaEffectSimulationType::CContamination"; return stream; - case AreaEffectSimulationType::FunctionalArea: - stream << "AreaEffectSimulationType::FunctionalArea"; return stream; - case AreaEffectSimulationType::TechnicalArea: - stream << "AreaEffectSimulationType::TechnicalArea"; return stream; - case AreaEffectSimulationType::DusSingleMineSimulator: - stream << "AreaEffectSimulationType::DusSingleMineSimulator"; return stream; - case AreaEffectSimulationType::GasPipeDetonation: - stream << "AreaEffectSimulationType::GasPipeDetonation"; return stream; - case AreaEffectSimulationType::SpecialArea: - stream << "AreaEffectSimulationType::SpecialArea"; return stream; - case AreaEffectSimulationType::BeStillWarning: - stream << "AreaEffectSimulationType::BeStillWarning"; return stream; - case AreaEffectSimulationType::DangerZoneExplosion: - stream << "AreaEffectSimulationType::DangerZoneExplosion"; return stream; - case AreaEffectSimulationType::AirSupport: - stream << "AreaEffectSimulationType::AirSupport"; return stream; + + class JsonException final : public std::exception + { + public: + JsonException(const QJsonObject &obj, const QString &key); + const char *what() const noexcept override { return m_what.data(); } + + private: + QJsonObject m_obj; + QString m_key; + QByteArray m_what; + }; + + + enum TelegramId + { + UNKNOWN = -1, + BESTAETIGUNG = 0, + INIT = 1, + MANIPULATIONSMELDUNG = 2, + UMGEBUNGS_MELDUNG2 = 203, + AUFFORDERUNG_BITE_MELDUNG = 4, + BITE_MELDUNG2 = 205, + BETRIEBSZUSTAND_AUSSTATTUNG = 7, + KONFIGURATION_WIRKMODELL = 9, + ANFORDERUNG_KONFIGURATIONSDATEN = 10, + KONFIGURATIONSMELDUNG = 11, + FEHLERMELDUNG_GFD = 12, + WIEDERHERSTELLUNG_FUNKBEREITSCHAFT = 13, + POSITIONS_MELDUNG = 21, + POSITIONS_MELDUNG_MIT_TEILNEHMER = 22, + POSITIONS_MELDUNG_LFZ = 23, + SCHIEDSRICHTERKOMMANDO = 25, + IPS_POSITIONSDATEN = 201, + WIRKFELD_EINZELGESCHOSS = 31, + WIRKFELD_FLAECHENDECKENDES_FEUER = 32, + WIRKFELD_FLAECHENDECKENDES_FEUER_STOP = 33, + WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN = 34, + WIRKFELD_MINENSPERRE = 35, + WIRKFELD_STATUS_MINENSPERRE = 36, + WIRKFELD_A_KAMPFMITTEL = 37, + WIRKFELD_C_KAMPFMITTEL = 38, + DEAKTIVIERUNG_WIRKFELD = 39, + WIRKFELD_AENDERUNG_BEZEICHNER = 40, + DEAKTIVIERUNG_EINZELMINE = 41, + REAKTIVIERUNG_DUS_MINE = 42, + DEFINITION_IED = 43, + ZUSTAND_IED = 44, + STATUS_EINZELMINENSIMULATOR = 45, + WIRKFELD_EINZELMINENSIMULATOR = 46, + TREFFER_EREIGNIS_DUS = 52, + TREFFER_EREIGNIS_WIRKSIMULATION = 53, + TREFFER_AUSLOESUNG = 54, + SCHIEDSRICHTEREINGRIFF = 55, + SELEKTIVE_AUFMUNITIONIERUNG = 56, + TREFFER_EREIGNIS_SEKUNDAERWIRKUNG = 218, + TREFFER_EREIGNIS_DUS_IPS = 228, + TREFFER_EREIGNIS_WIRKSIMULATION_IPS = 229, + TAKTISCHER_STATUS = 61, + FUNKTIONSRAUM = 62, + EINTRETEN_FUNKTIONSRAUM = 63, + DEAKTIVIEREN_FUNKTIONSRAUM = 64, + DATENVERKEHR_SRT_TDS = 71, + DATENVERKEHR_TDS_SRT = 72, + DATENVERKEHR_DMF_TDS = 73, + DATENVERKEHR_TDS_DMF = 74, + NACHFORDERUNG_BROADCAST_TELEGRAMME = 82, + SONDERSENSORIK_FAHRSPUR = 92, + SONDERSENSORIK_MIVANH_VERLEGEDATEN = 95, + SONDERSENSORIK_WMIV_VERLEGEDATEN = 96, + SONDERSENSORIK_MIVANH_VERLEGEPOSITION = 97, + SPRACHAUSWAHL = 101, + ALLGEMEINE_NACHRICHT = 102, + GERAETEEREIGNIS = 185, + WAFFENZUORDNUNG = 200, + MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE = 202, + FEUEREREIGNIS_MIT_WAFFENZUORDNUNG = 210, + AUSLOESUNG_DUS_TREFFER = 211, + ANFORDERUNG_SW_VERSION = 212, + SW_VERSIONSMELDUNG = 213, + TECHNIK_FUNKTIONSRAUM = 219, + TEILNEHMERMODE_SETZEN = 230, + TEILNEHMERMODE_MELDUNG = 231, + TEILNEHMERMODE_ANFORDERN = 232, + TEILNEHMER_KONFIG_ANTWORT = 233, + TEILNEHMER_KONFIG_SETZEN = 234, + TEILNEHMER_KONFIG_ANFORDERN = 235, + SANITAETSDIENST_INSTANDSETZUNG = 240, + BESTANDSMELDUNG_SANITAETSMATERIAL = 241, + SANITAETSDIENST_INSTANDSETZUNG_PVSAN = 242, + NOTRUF = 1120, + BETRIEBSZUSTANDSMELDUNG = 2008, + ANFORDERUNG_STATISTIK_BROADCAST_NACHFORDERUNGEN = 2009, + STATISTIK_BROADCAST_NACHFORDERUNGEN = 2010, + EXERCISE_EQUIPMENT_ASSIGNMENT_COMPLETE = 2012, + PROXY_CONNECTION_STATE = 2013, + PARTICIPANT_LICENSE_CHANGE = 2014, + WLS_PARTICIPANTS_STATE_REQUEST = 3001, + WLS_PARTICIPANTS_STATE_REPORT = 3002, + WLS_BINARY_SFM_DATA = 3003, + WLS_PARTICIPANT_CONNECTION_STATE = 3004, + SR_DMF_NACHRICHT = 6130, + APACHE_LASER_DESIGNATION = 8004, + BATTERY_INFO = 9000, + BATTERY_ALARM = 9001, + SERVICE_CONTROL = 9002, + DEVICE_POWER_SET_REQUEST = 9003, + UAV_PERFORM_MISSION = 9004, + UAV_STATUS = 9005, + UAV_RADIO_LINK_CONNECTION_STATUS = 9006, + UAV_MISSION_STATUS = 9007, + UAV_CHANGE_STATE = 9008, + + + EX_FIRE_READINESS = 9100, + EX_FIRED_REPORT = 9101, + EX_CONFIRMATION_REPORT = 9102, + }; + + + template struct Constraints; + + + struct TrainingAreaTelegram + { + TrainingAreaTelegram() = default; + virtual ~TrainingAreaTelegram() = default; + + virtual QJsonObject toJson() const = 0; + virtual QString type() const = 0; + virtual TelegramId id() const = 0; + }; + + template struct TrainingAreaTelegramTmpl : TrainingAreaTelegram + { + QString type() const override final { return Constraints::type(); } + TelegramId id() const override final { return Constraints::id(); } + }; + + enum class Qualification + { + NotDefined = 0, + FAA = 1, + FAB = 2, + SANPers = 3 + }; + + enum class SanitationResult + { + NoEffect = 0, + Unhandled = 1, + Insufficient = 2, + Sufficient = 3, + Optimal = 4 + }; + + enum class SanitationEvaluation + { + NotApplicable = -1, + Okay = 0, + PartlyWrong = 1, + Wrong = 2, + }; + + enum class VulnerabilityState + { + CombatReady = 0, + LightDamage = 1, + MediumDamage = 2, + HeavyDamage = 3, + MobilityKill = 4, + VisibleMobilityKill = 5, + WeaponSystemDamage = 6, + VisibleWeaponSystemDamage = 7, + CatastrophicKill = 8, + TemporarySeverance = 9, + NearMiss = 10, + HitWithNoEffect = 11, + VulnerabilityBitsChanged = 12, + Reserved = 13, + NContamination = 14, + BContamination = 15, + CContamination = 16 + }; + + enum class OriginatorType + { + Initialisation = 0, + ObserverController = 1, + ExerciseControl = 2, + FunctionalArea = 6, + MedicTimeout = 7, + Sanitation = 8, + MedicDecontamination = 9, + MaintainanceRepair = 10, + MaintainanceDecontamination = 11, + }; + + + enum class AreaEffectSimulationType + { + Unknown = 0, + MineArea = 1, + ExplosionArea = 2, + ExplosionSingle = 3, + NContamination = 4, + CContamination = 5, + FunctionalArea = 6, + TechnicalArea = 7, + DusSingleMineSimulator = 8, + GasPipeDetonation = 9, + SpecialArea = 10, + BeStillWarning = 11, + DangerZoneExplosion = 12, + AirSupport = 13 + }; + + enum class ServiceControlEnum + { + PRESHUTDOWN = 0, + SHUTDOWN = 1, + STOP = 2 + }; + + enum class PowerMethod + { + Unknown = 0, + PowerOn = 1, + PowerOff = 2 + }; + + inline std::ostream &operator<<(std::ostream &stream, AreaEffectSimulationType val) + { + switch (val) + { + case AreaEffectSimulationType::Unknown: + stream << "AreaEffectSimulationType::Unknown"; + return stream; + case AreaEffectSimulationType::MineArea: + stream << "AreaEffectSimulationType::MineArea"; + return stream; + case AreaEffectSimulationType::ExplosionArea: + stream << "AreaEffectSimulationType::ExplosionArea"; + return stream; + case AreaEffectSimulationType::ExplosionSingle: + stream << "AreaEffectSimulationType::ExplosionSingle"; + return stream; + case AreaEffectSimulationType::NContamination: + stream << "AreaEffectSimulationType::NContamination"; + return stream; + case AreaEffectSimulationType::CContamination: + stream << "AreaEffectSimulationType::CContamination"; + return stream; + case AreaEffectSimulationType::FunctionalArea: + stream << "AreaEffectSimulationType::FunctionalArea"; + return stream; + case AreaEffectSimulationType::TechnicalArea: + stream << "AreaEffectSimulationType::TechnicalArea"; + return stream; + case AreaEffectSimulationType::DusSingleMineSimulator: + stream << "AreaEffectSimulationType::DusSingleMineSimulator"; + return stream; + case AreaEffectSimulationType::GasPipeDetonation: + stream << "AreaEffectSimulationType::GasPipeDetonation"; + return stream; + case AreaEffectSimulationType::SpecialArea: + stream << "AreaEffectSimulationType::SpecialArea"; + return stream; + case AreaEffectSimulationType::BeStillWarning: + stream << "AreaEffectSimulationType::BeStillWarning"; + return stream; + case AreaEffectSimulationType::DangerZoneExplosion: + stream << "AreaEffectSimulationType::DangerZoneExplosion"; + return stream; + case AreaEffectSimulationType::AirSupport: + stream << "AreaEffectSimulationType::AirSupport"; + return stream; + } + stream << "Unknown (" << std::to_string(int(val)) << ")"; + return stream; + } + + enum class FunctionalAreaOperatingMode + { + NotUsed = 0, + OperatedByOC = 1, + WaitForTimeout = 2 + }; + + enum class Language + { + NoChange = 0, + German = 1, + English = 2, + French = 3, + Arabic = 4, + Spanish = 5, + Russian = 6 + }; + + enum class ParticipantLicenseState + { + Unknown = 0, + Licensed = 1, + Rejected = 2, + Unlicense = 3, + }; + + enum class UAVActionTask + { + Undefined = 0, + Disarm = 1, + Arm = 2, + Takeoff = 3, + Connect = 4, + Loiter = 5, + Return = 6, + Observe = 8, + }; + + enum class UAVRadioLinkConnectionStatusType + { + + Undefined = 0, + + Disconnected = 1, + + Connecting = 2, + + Diconnecting = 3, + + Connected = 4, + + Error = 5, + }; + + enum class UAVState + { + Undefined = 0, + Off = 1, + On = 2, + Standby = 3, + Init = 4, + Shutdown = 5, + Normal = 6, + Manual = 7, + Auto = 8, + Calibrating = 9, + Maintenance = 10 + }; + + struct Header + { + int equipmentNumber = 0; + qint64 timeStamp = 0; + + static Header fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct RelativePosition + { + int offsetX = 0; + int offsetY = 0; + double offsetZ = 0; + + explicit RelativePosition(int x = 0, int y = 0, double z = 0) + : offsetX(x) + , offsetY(y) + , offsetZ(z) + { + } + + static RelativePosition fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + + struct AbsolutePosition + { + double lon = 0; + double lat = 0; + double z = 0; + + bool isValid() const { return (lon != 0 && lat != 0); } + + static AbsolutePosition fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct OpsPosition + { + int opsId = 0; + int moutObjectId = 0; + int moutRoomId = 0; + + static OpsPosition fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct GpsQuality + { + bool moreThan4SatellitesAvailable = false; + bool dgpsModeAvailable = false; + int pdopValue = 0; + + static GpsQuality fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct Gear + { + int gearTasCode = 0; + int gearSerialNumber = 0; + bool chargeCounting = false; + + static Gear fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct GearCharge + { + int gearTasCode = 0; + int gearSerialNumber = 0; + int chargeTypeId = 0; + int remain = 0; + int location = 0; + + static GearCharge fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + + struct WlsPosition + { + double x = 0; + double y = 0; + double z = 0; + int wlsAreaId = 0; + int wlsZone = 0; + int wlsBuildingId = 0; + int wlsRoomNumber = 0; + int playerOrientation = 0; + int weaponOrientation = 0; + bool isValid = false; + + static WlsPosition fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct WlsParticipantState + { + QString tagId; + qint64 lastSeen = 0; + double voltage = 0; + int equipmentNumber = 0; + int tacticalState = -1; + bool gpsOn = false; + bool inBlockedArea = false; + WlsPosition relativePosition; + + static WlsParticipantState fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct BatteryState + { + int m_batteryPort; + int m_batteryPercent; + int m_voltage; + int m_temperature; + int m_frequency; + int m_generic; + int m_current; + bool m_switchOrValue; + QString m_serialNumber; + + int batteryPort() const { return m_batteryPort; } + int batteryPercent() const { return m_batteryPercent; } + int voltage() const { return m_voltage; } + int temperature() const { return m_temperature; } + int frequency() const { return m_frequency; } + int generic() const { return m_generic; } + int current() const { return m_current; } + bool switchOrValue() const { return m_switchOrValue; } + QString serialNumber() const { return m_serialNumber; } + + static BatteryState fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct UAVAction + { + UAVActionTask task; + AbsolutePosition absPosition; + + + static QString TASK() { return QLatin1String("task"); } + static QString POSITION() { return QLatin1String("position"); } + + static UAVAction fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + + struct Acknowledge : TrainingAreaTelegramTmpl + { + qint64 timeStamp = 0; + int32_t ackCounter = 0; + + static Acknowledge fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("Acknowledge"); } + static constexpr TelegramId id() { return TelegramId::BESTAETIGUNG; } + }; + + + struct Init : TrainingAreaTelegramTmpl + { + Header header; + int workstationId = 0; + bool restockCharges = false; + bool resetManipulation = false; + bool resetVulnerabilityState = false; + bool restockSanitationMaterial = false; + + static Init fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("Init"); } + static constexpr TelegramId id() { return TelegramId::INIT; } + }; + + + struct ManipulationReport : TrainingAreaTelegramTmpl + { + Header header; + bool isManipulation = false; + int equipmentFunctionId; + + static ManipulationReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ManipulationReport"); } + static constexpr TelegramId id() { return TelegramId::MANIPULATIONSMELDUNG; } + }; + + + struct DemandBite : TrainingAreaTelegramTmpl + { + Header header; + bool withSelfTest = false; + + static DemandBite fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DemandBite"); } + static constexpr TelegramId id() { return TelegramId::AUFFORDERUNG_BITE_MELDUNG; } + }; + + + struct EquipmentOperationalState : TrainingAreaTelegramTmpl + { + Header header; + bool nbcProtectionActive = false; + + static EquipmentOperationalState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentOperationalState"); } + static constexpr TelegramId id() { return TelegramId::BETRIEBSZUSTAND_AUSSTATTUNG; } + }; + + + struct VulnerabilityModelBase + { + Header header; + int vulnerabilityModelMineIed = 0; + int vulnerabilityModelAreaFire = 0; + int vulnerabilityModelOperatingResource = 0; + int vulnerabilityModelAcWeaponry = 0; + + static void fromJson(const QJsonObject &obj, VulnerabilityModelBase &ret); + QJsonObject toJson() const; + }; + + struct SetVulnerabilityModel + : TrainingAreaTelegramTmpl + , VulnerabilityModelBase + { + static SetVulnerabilityModel fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SetVulnerabilityModel"); } + static constexpr TelegramId id() { return TelegramId::KONFIGURATION_WIRKMODELL; } + }; + + + struct DemandEquipmentConfigurationReport : TrainingAreaTelegramTmpl + { + Header header; + + static DemandEquipmentConfigurationReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DemandEquipmentConfigurationReport"); } + static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_KONFIGURATIONSDATEN; } + }; + + + struct EquipmentConfigurationReport + : TrainingAreaTelegramTmpl + , VulnerabilityModelBase + { + int equipmentNumber = 0; + int canStartUpTime = 0; + int equipmentType = 0; + + int loginWaittimeBitweenTrys = 0; + int loginMaxRetryCnt = 0; + bool loginMasteringFlag = false; + + int canDeviceConfiguration; + + bool displayDeviceVoiceOutput = false; + Language displayDeviceLanguage = Language::NoChange; + bool pyrotechnics = false; + enum class MineHandgrenadeSensorMode + { + PersonellMode = 0, + NormalVehicleMode = 2, + OcVehicleMode = 3 + }; + MineHandgrenadeSensorMode mhgrsMode = MineHandgrenadeSensorMode::PersonellMode; + bool mhgrsEnergySaving = false; + + enum class FirMode + { + NoFir = 0, + Fir = 1, + FirSpzMarder = 2 + }; + enum class MineLayerMode + { + NoMineLayerDevice = 0, + MinLayerTrailer = 1, + MineLayerThrower = 2 + }; + enum class SpecialSensorStandardMode + { + NoSpecialSensorStandard = 0, + ZABC = 3, + CSF = 4, + PzBr = 5, + MRF = 7 + }; + FirMode specialSensorFir = FirMode::NoFir; + MineLayerMode specialSensorMinelayer = MineLayerMode::NoMineLayerDevice; + SpecialSensorStandardMode specialSensorStandard = SpecialSensorStandardMode::NoSpecialSensorStandard; + + enum class AgdusHwMode + { + WithoutHelmetWithoutVest = 1, + WithHelmetWithoutVest = 2, + WithHelmetWithVest = 3 + }; + AgdusHwMode agdusHwMode = AgdusHwMode::WithoutHelmetWithoutVest; + + enum class PositionUpdateInterval + { + Vehicle = 0, + Personnell = 1, + Aircraft = 2 + }; + PositionUpdateInterval positionUpdateInterval = PositionUpdateInterval::Personnell; + + int displayTextMainGroup; + int displayTextSubGroup; + + int vulnerabilityModelAgdus; + + static EquipmentConfigurationReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentConfigurationReport"); } + static constexpr TelegramId id() { return TelegramId::KONFIGURATIONSMELDUNG; } + }; + + + struct CtaDataError : TrainingAreaTelegramTmpl + { + enum class Reason + { + WrongParameter = 1, + TelegramOutdated = 2, + InvalidByteCount = 3, + InvalidData = 4, + FragmentationError = 5, + Unknown = 6, + AdditionalDemandTimeout = 7, + ErrorLoginEquipmentNumber = 50, + ErrorLoginTetraId = 51, + InfoLoginMasteringFlag = 52, + ErrorSendingNamelist = 53, + ErrorSendingToExerciseControl = 54, + ErrorNotLoggedIn = 55, + ErrorNotLicensed = 56, + ErrorConfigSelfTest = 57, + JsonDecodeFailure = 101, + WrongCrc = 105, + BroadcastCounterOverflow = 106, + InvalidTime = 256, + InvalidPosition = 257, + InvalidTacticalState = 258 + }; + + Header header; + Reason reason = Reason::Unknown; + int originTelegramId = 0; + + static CtaDataError fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CtaDataError"); } + static constexpr TelegramId id() { return TelegramId::FEHLERMELDUNG_GFD; } + }; + + struct PositionReportBase + { + Header header; + RelativePosition relPosition; + AbsolutePosition geoPosition; + OpsPosition opsPosition; + GpsQuality gpsQuality; + + static void fromJson(const QJsonObject &obj, PositionReportBase &ret); + QJsonObject toJson() const; + }; + + + struct RestoreRadioReadiness : public TrainingAreaTelegramTmpl + { + Header header; + + RelativePosition readinessLossPosition; + int readinessLossTime; + RelativePosition readinessRestorePosition; + int readinessRestoreTime; + + static RestoreRadioReadiness fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + + static QString HEADER() { return QLatin1String("header"); } + static QString READINESS_LOSS_POSITION() { return QLatin1String("readinessLossPosition"); } + static QString READINESS_LOSS_TIME() { return QLatin1String("readinessLossTime"); } + static QString READINESS_RESTORE_POSITION() { return QLatin1String("readinessRestorePosition"); } + static QString READINESS_RESTORE_TIME() { return QLatin1String("readinessRestoreTime"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("RestoreRadioReadiness"); } + static constexpr TelegramId id() { return TelegramId::WIEDERHERSTELLUNG_FUNKBEREITSCHAFT; } + }; + + + struct PositionReport + : public TrainingAreaTelegramTmpl + , PositionReportBase + { + static PositionReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("PositionReport"); } + static constexpr TelegramId id() { return TelegramId::POSITIONS_MELDUNG; } + }; + + + struct PositionReportWithMountedEquipments + : TrainingAreaTelegramTmpl + , PositionReportBase + { + std::vector mountedEquipments; + + static PositionReportWithMountedEquipments fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("PositionReportWithMountedEquipments"); } + static constexpr TelegramId id() { return TelegramId::POSITIONS_MELDUNG_MIT_TEILNEHMER; } + }; + + struct CreateAreaEffectSimulationBase + { + Header header; + int aesDdsId = 0; + + std::string name; + int partyId = 0; + RelativePosition relEffectPosition; + + static void fromJson(const QJsonObject &obj, CreateAreaEffectSimulationBase &ret); + QJsonObject toJson() const; + }; + + struct CreateCombatAreaEffectSimulationBase : CreateAreaEffectSimulationBase + { + int chargeTypeId = 0; + qint64 effectStart = 0; + qint64 effectDuration = 0; + + static void fromJson(const QJsonObject &obj, CreateCombatAreaEffectSimulationBase &ret); + QJsonObject toJson() const; + }; + + + struct OcCommand : TrainingAreaTelegramTmpl + { + Header header; + int action = 0; + + static OcCommand fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("OcCommand"); } + static constexpr TelegramId id() { return TelegramId::SCHIEDSRICHTERKOMMANDO; } + }; + + + struct CreateSingleExplosion + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + int effectDiameter = 0; + + static CreateSingleExplosion fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateSingleExplosion"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_EINZELGESCHOSS; } + }; + + + struct CreateAreaExplosion + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + RelativePosition relCorner; + int height{0}; + int width{0}; + double rotationAngle{0.0}; + int impactCount{0}; + int impactEdgeLength{0}; + double mhpRotation{0.0}; + int mhpLength{0}; + int mhpWidth{0}; + int impactRadius{0}; + std::vector mhPoints; + int hazardDistance; + + static CreateAreaExplosion fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateAreaExplosion"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER; } + }; + + + struct PauseEffectSimulation : TrainingAreaTelegramTmpl + { + int aesDdsId = 0; + + + static PauseEffectSimulation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("PauseEffectSimulation"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER_STOP; } + }; + + + struct ResumeEffectSimulation : TrainingAreaTelegramTmpl + { + int aesDdsId = 0; + + int sequelNumber = 0; + int nextImpact = 0; + qint64 resumeTime; + int remainDuration; + + static ResumeEffectSimulation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ResumeEffectSimulation"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN; } + }; + + + struct MineAreaSegment + { + RelativePosition relStart; + RelativePosition relEnd; + + static MineAreaSegment fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct CreateMineArea + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + + + double layingDepth = 0; + double layingDensity = 0; + std::vector segments; + + static CreateMineArea fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateMineArea"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_MINENSPERRE; } + }; + + + struct MineAreaSingleMineState : TrainingAreaTelegramTmpl + { + int aesDdsId = 0; + + int mineCount = 0; + std::vector mineState; + + static MineAreaSingleMineState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("MineAreaSingleMineState"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_STATUS_MINENSPERRE; } + }; + + + struct CreateNContamination + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + int innerRadius = 0; + int borderLengthInner = 0; + int borderLengthOuter = 0; + double spanAngle = 0; + double rotationAngle = 0; + + static CreateNContamination fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateNContamination"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_A_KAMPFMITTEL; } + }; + + + struct CreateCContamination + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + int effectRadius = 0; + double expansionFactor = 0; + double propagationDirection = 0; + int windSpeed = 0; + qint64 validityTimeWind; + RelativePosition relPositionValidityTimeWind; + enum class Volatiliy + { + Floating = 1, + Resident = 2 + } volatility = Volatiliy::Resident; + + static CreateCContamination fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateCContamination"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_C_KAMPFMITTEL; } + }; + + + struct DeactivateEffectSimulation : TrainingAreaTelegramTmpl + { + AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; + int aesDdsId = 0; + + + static DeactivateEffectSimulation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DeactivateEffectSimulation"); } + static constexpr TelegramId id() { return TelegramId::DEAKTIVIERUNG_WIRKFELD; } + }; + + + struct ModifyAreaEffectSimulationName : TrainingAreaTelegramTmpl + { + AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; + int aesDdsId = 0; + + std::string name; + + static ModifyAreaEffectSimulationName fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ModifyAreaEffectSimulationName"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_AENDERUNG_BEZEICHNER; } + }; + + + struct MineTriggered : TrainingAreaTelegramTmpl + { + Header header; + int mineAreaId = 0; + int mineIndex = 0; + int chargeTypeId = 0; + RelativePosition relPosition; + bool relPositionValid = false; + + static MineTriggered fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("MineTriggered"); } + static constexpr TelegramId id() { return TelegramId::DEAKTIVIERUNG_EINZELMINE; } + }; + + + struct DusMineReactivation : TrainingAreaTelegramTmpl + { + Header header; + std::vector dusSerialNumbers; + + static DusMineReactivation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DusMineReactivation"); } + static constexpr TelegramId id() { return TelegramId::REAKTIVIERUNG_DUS_MINE; } + }; + + + enum class IedType + { + SuicideIed = 1, + IedSmallPyro = 2, + IedBigPyro = 3 + }; + + enum class IedPairingState + { + NotPaired = 1, + PairedToParticipant = 2, + PairedToOps = 3 + }; + + enum class IedTacticalState + { + NotActive = 0, + Active = 1, + Defused = 2, + TriggeredBySwitch = 3, + TriggeredByRemote = 4, + TriggeredByLightBarrier = 5, + TriggeredByTautWire = 6, + TriggeredByControlDevice = 7, + Unknown = 255 + }; + + struct IedBaseData + { + Header header; + int iedId = 0; + IedTacticalState tacticalState = IedTacticalState::Unknown; + bool statePyrotechnics = false; + + static void fromJson(const QJsonObject &obj, IedBaseData &ret); + QJsonObject toJson() const; + }; + + struct DefinitionIed + : TrainingAreaTelegramTmpl + , IedBaseData + { + RelativePosition relPosition; + IedType iedType = IedType::SuicideIed; + enum class TriggerTypes + { + Remote = 0x01, + Switch = 0x02, + LightBarrier = 0x04, + TautWire = 0x08 + }; + int trigger = 0; + int explosiveForce = 0; + IedPairingState pairingState = IedPairingState::NotPaired; + int pairedId = 0; + int partyId = 0; + + static DefinitionIed fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DefinitionIed"); } + static constexpr TelegramId id() { return TelegramId::DEFINITION_IED; } + }; + + + enum class IedError + { + NoError = 0, + DeviceMissing = 1 + }; + + struct StateIed + : TrainingAreaTelegramTmpl + , IedBaseData + { + int batteryWarnings = 0; + IedError errorStateElectronics = IedError::NoError; + IedError errorStatePyrotechnics1 = IedError::NoError; + IedError errorStatePyrotechnics2 = IedError::NoError; + IedError errorStatePyrotechnics3 = IedError::NoError; + + static StateIed fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("StateIed"); } + static constexpr TelegramId id() { return TelegramId::ZUSTAND_IED; } + }; + + + struct DusSingleMineState : TrainingAreaTelegramTmpl + { + Header header; + int mineId = 0; + qint64 effectStart = 0; + RelativePosition relPosition; + int chargeTypeId = 0; + bool state = false; + + static DusSingleMineState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DusSingleMineState"); } + static constexpr TelegramId id() { return TelegramId::STATUS_EINZELMINENSIMULATOR; } + }; + + + struct CreateDusSingleMine + : TrainingAreaTelegramTmpl + , CreateCombatAreaEffectSimulationBase + { + int mineId; + + static CreateDusSingleMine fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateDusSingleMine"); } + static constexpr TelegramId id() { return TelegramId::WIRKFELD_EINZELMINENSIMULATOR; } + }; + + struct StateChangeBase + { + Header header; + RelativePosition relPosition; + AbsolutePosition geoPosition; + OpsPosition opsPosition; + VulnerabilityState vulnerabilityState = VulnerabilityState::CombatReady; + int tasVulnerabilityKindId = 0; + int tasVitality = 0; + int vulnerabilityBits = 0; + int originatorId = 0; + + static void fromJson(const QJsonObject &obj, StateChangeBase &ret); + QJsonObject toJson() const; + }; + + + struct StateChangeDirect + : TrainingAreaTelegramTmpl + , StateChangeBase + { + int chargeTypeId = 0; + + static StateChangeDirect fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("StateChangeDirect"); } + static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_DUS; } + }; + + + struct StateChangeIndirect + : TrainingAreaTelegramTmpl + , StateChangeBase + { + bool isSecondaryEffect = false; + + static StateChangeIndirect fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("StateChangeIndirect"); } + static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_WIRKSIMULATION; } + }; + + + struct DemandVulnerabilityStateChange : TrainingAreaTelegramTmpl + { + Header header; + int workstationId = 0; + VulnerabilityState reqestedState = VulnerabilityState::CombatReady; + int vulnerabilityVitalityIndex = 0; + + static DemandVulnerabilityStateChange fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DemandVulnerabilityStateChange"); } + static constexpr TelegramId id() { return TelegramId::TREFFER_AUSLOESUNG; } + }; + + + struct OperatorAction : TrainingAreaTelegramTmpl + { + Header header; + RelativePosition relPosition; + int operatorId = 0; + int action = 0; + + static OperatorAction fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("OperatorAction"); } + static constexpr TelegramId id() { return TelegramId::SCHIEDSRICHTEREINGRIFF; } + }; + + + struct Reammunition + { + int chargeTypeId = 0; + int location = 0; + int newStock = 0xfffe; + int newDefaultStock = 0xfffe; + int tracerRatio = 0; + + static Reammunition fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct SelectiveReammunition : TrainingAreaTelegramTmpl + { + Header header; + int gearId = 0; + std::vector reammunitions; + + static SelectiveReammunition fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SelectiveReammunition"); } + static constexpr TelegramId id() { return TelegramId::SELEKTIVE_AUFMUNITIONIERUNG; } + }; + + + struct StateChange + : TrainingAreaTelegramTmpl + , StateChangeBase + { + OriginatorType originatorType = OriginatorType::Initialisation; + + static StateChange fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("StateChange"); } + static constexpr TelegramId id() { return TelegramId::TAKTISCHER_STATUS; } + }; + + + struct CreateFunctionalArea + : TrainingAreaTelegramTmpl + , CreateAreaEffectSimulationBase + { + int width = 0; + int height = 0; + qint64 deconTimeout = 0; + qint64 maintenanceTimeout = 0; + qint64 medicalTimeout = 0; + FunctionalAreaOperatingMode deconMode = FunctionalAreaOperatingMode::NotUsed; + FunctionalAreaOperatingMode maintenanceMode = FunctionalAreaOperatingMode::NotUsed; + FunctionalAreaOperatingMode medicalMode = FunctionalAreaOperatingMode::NotUsed; + + static CreateFunctionalArea fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CreateFunctionalArea"); } + static constexpr TelegramId id() { return TelegramId::FUNKTIONSRAUM; } + }; + + + struct FunctionalAreaEntry : TrainingAreaTelegramTmpl + { + Header header; + RelativePosition relPosition; + int aesDdsId = 0; + + + static FunctionalAreaEntry fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("FunctionalAreaEntry"); } + static constexpr TelegramId id() { return TelegramId::EINTRETEN_FUNKTIONSRAUM; } + }; + + + struct RequestBroadcastTelegrams : TrainingAreaTelegramTmpl + { + Header header; + int resetCounter = 0; + int broadcastIndex = 0; + + static RequestBroadcastTelegrams fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("RequestBroadcastTelegrams"); } + static constexpr TelegramId id() { return TelegramId::NACHFORDERUNG_BROADCAST_TELEGRAMME; } + }; + + + struct SpecialSensorData : TrainingAreaTelegramTmpl + { + Header header; + RelativePosition relPosition; + int operationalState = 0; + bool airSensor = false; + bool tireSensor = false; + bool pointSensor = false; + bool solidMatterSampleExtractor = false; + int type = 0; + int nbcType = 0; + + static SpecialSensorData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SpecialSensorData"); } + static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_FAHRSPUR; } + }; + + + struct MinelayerTrailerDataBase + { + Header header; + RelativePosition relPosition; + + + int barrierId = 0; + int layingDensity = 0; + qint64 effectStart = 0; + int effectDuration = 0; + int indirectChargeTasCode = 0; + int mineCount = 0; + + static void fromJson(const QJsonObject &obj, MinelayerTrailerDataBase &ret); + QJsonObject toJson() const; + }; + + struct MinelayerTrailerData + : public TrainingAreaTelegramTmpl + , MinelayerTrailerDataBase + { + static MinelayerTrailerData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("MinelayerTrailerData"); } + static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_MIVANH_VERLEGEDATEN; } + }; + + + struct MinelayerThrowerData + : TrainingAreaTelegramTmpl + , MinelayerTrailerDataBase + { + enum class ThrowingType + { + Straight = 0, + Right = 1, + Left = 2, + LeftAndRight = 3, + SingleRight = 5, + SingleLeft = 6, + SingleLeftAndRight = 7 + } throwingType = ThrowingType::Straight; + + static MinelayerThrowerData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("MinelayerThrowerData"); } + static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_WMIV_VERLEGEDATEN; } + }; + + + struct MinelayerTrailerPosition : public TrainingAreaTelegramTmpl + { + Header header; + RelativePosition relPosition; + qint64 dusSerialNo = 0; + int indirectChargeTasCode = 0; + + static MinelayerTrailerPosition fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("MinelayerTrailerPosition"); } + static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_MIVANH_VERLEGEPOSITION; } + }; + + + struct LanguageSelection : TrainingAreaTelegramTmpl + { + Header header; + Language languageSelection = Language::NoChange; + + static LanguageSelection fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("LanguageSelection"); } + static constexpr TelegramId id() { return TelegramId::SPRACHAUSWAHL; } + }; + + + struct EquipmentMessage : TrainingAreaTelegramTmpl + { + Header header; + std::string message; + int msgId = -1; + + static EquipmentMessage fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentMessage"); } + static constexpr TelegramId id() { return TelegramId::ALLGEMEINE_NACHRICHT; } + }; + + + struct EquipmentMessageOC : TrainingAreaTelegramTmpl + { + Header header; + std::string subject; + std::string message; + int senderId = 0; + int receiverId = 0; + + static EquipmentMessageOC fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentMessageOC"); } + static constexpr TelegramId id() { return TelegramId::SR_DMF_NACHRICHT; } + }; + + struct OpaquePayloadDataBase + { + Header header; + std::vector payload; + enum class Type + { + FireSmokeMarker, + Geopairing, + Target, + OC + } payloadType = Type::FireSmokeMarker; + + static void fromJson(const QJsonObject &obj, OpaquePayloadDataBase &ret); + QJsonObject toJson() const; + }; + + + struct OpaquePayloadDataOut + : TrainingAreaTelegramTmpl + , OpaquePayloadDataBase + { + static OpaquePayloadDataOut fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("OpaquePayloadDataOut"); } + static constexpr TelegramId id() { return TelegramId::DATENVERKEHR_TDS_SRT; } + }; + + + struct OpaquePayloadDataIn + : TrainingAreaTelegramTmpl + , OpaquePayloadDataBase + { + RelativePosition relPosition; + GpsQuality gpsQuality; + + static OpaquePayloadDataIn fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("OpaquePayloadDataIn"); } + static constexpr TelegramId id() { return TelegramId::DATENVERKEHR_SRT_TDS; } + }; + + + struct EquipmentEvent : TrainingAreaTelegramTmpl + { + Header header; + RelativePosition relPosition; + int equipmentFunctionId = 0; + int subDeviceId = 0; + int uniqueId = 0; + int code = 0; + std::vector payload; + + static EquipmentEvent fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentEvent"); } + static constexpr TelegramId id() { return TelegramId::GERAETEEREIGNIS; } + }; + + + struct EquipmentGearAssignment : TrainingAreaTelegramTmpl + { + Header header; + std::vector gears; + + static EquipmentGearAssignment fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentGearAssignment"); } + static constexpr TelegramId id() { return TelegramId::WAFFENZUORDNUNG; } + }; + + + struct EquipmentGearChargeState : TrainingAreaTelegramTmpl + { + Header header; + std::vector charges; + + static EquipmentGearChargeState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentGearChargeState"); } + static constexpr TelegramId id() { return TelegramId::MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE; } + }; + + + struct ExerciseEnvironmentData : TrainingAreaTelegramTmpl + { + Header header; + int exerciseId = 0; + int timeZone = 90; + + int utmZone = 0; + int utmBand = 0; + std::string grid; + + static ExerciseEnvironmentData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExerciseEnvironmentData"); } + static constexpr TelegramId id() { return TelegramId::UMGEBUNGS_MELDUNG2; } + }; + + + struct BiteError + { + int errorNumber = 0; + int canDeviceNumber = 0; + int subdeviceNumber = 0; + int uniqueId = 0; + + static BiteError fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct BiteReport : TrainingAreaTelegramTmpl + { + Header header; + enum class LoginType + { + NoLogin = 0, + NewLogin = 1, + Relogin = 2, + InvalidLogin = 3, + } loginType = LoginType::NoLogin; + int biteState = 0; + int configState = 0; + int batteryState = 0; + bool configError = false; + std::vector biteErrors; + + static BiteReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("BiteReport"); } + static constexpr TelegramId id() { return TelegramId::BITE_MELDUNG2; } + }; + + + struct EquipmentGearEvent : TrainingAreaTelegramTmpl + { + Header header; + GearCharge charge; + int chargeAmount = 0; + + static EquipmentGearEvent fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EquipmentGearEvent"); } + static constexpr TelegramId id() { return TelegramId::FEUEREREIGNIS_MIT_WAFFENZUORDNUNG; } + }; + + + struct CesHitInformation : TrainingAreaTelegramTmpl + { + Header header; + + int chargeTasCodeDirect = 0; + int chargeTasCodeIndirect = 0; + int originatorEquipmentNumber = 0; + int directionDegree = 0; + int distance = 0; + int effectPercent = 0; + + static CesHitInformation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CesHitInformation"); } + static constexpr TelegramId id() { return TelegramId::AUSLOESUNG_DUS_TREFFER; } + }; + + + struct ParticipantSwVersionsRequest : TrainingAreaTelegramTmpl + { + Header header; + int equipmentFunctionId; + + static ParticipantSwVersionsRequest fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantSwVersionsRequest"); } + static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_SW_VERSION; } + }; + + struct EquipmentSwVersion + { + int equipmentFunctionId = 0; + int subDeviceId = 0; + int uniqueId = 0; + int swVersion = 0; + + static EquipmentSwVersion fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + + struct ParticipantSwVersions : TrainingAreaTelegramTmpl + { + Header header; + std::vector equipments; + + static ParticipantSwVersions fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantSwVersions"); } + static constexpr TelegramId id() { return TelegramId::SW_VERSIONSMELDUNG; } + }; + + + struct CesHitRequest : TrainingAreaTelegramTmpl + { + Header header; + int chargeTasCodeDirect = 0; + int chargeTasCodeIndirect = 0; + int originatorEquipmentNumber = 0; + int aesDdsId = 0; + + AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; + int mineId = 0; + int remainEffectPercent = 0; + int remainEffectTasCodeDirect = 0; + int buildingId = 0; + int roomId = 0; + RelativePosition relPosition; + int reserve1 = 0; + int reserve2 = 0; + static CesHitRequest fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("CesHitRequest"); } + static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_SEKUNDAERWIRKUNG; } + }; + + + struct TechnicalArea : TrainingAreaTelegramTmpl + { + Header header; + int aesDdsId = 0; + + enum Type + { + Reserved = 0, + RemoveArea = 1, + MoutArea = 2, + RestingAreaPersonnel = 3, + RestingAreaVehicle = 4, + RestingAreaPersonnelAndVehicle = 5 + } taType = Type::Reserved; + std::string name; + RelativePosition relCorner; + int width = 0; + int height = 0; + + static TechnicalArea fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("TechnicalArea"); } + static constexpr TelegramId id() { return TelegramId::TECHNIK_FUNKTIONSRAUM; } + }; + + + struct ParticipantModeBase + { + Header header; + Language language = Language::NoChange; + enum class OperationMode + { + NoChange = 0, + Normal = 1, + BeStill = 2 + } operationMode = OperationMode::NoChange; + int reactivationDetoxication; + int reactivationMaintenance; + int reactivationMedic; + enum class WphMode + { + NoChange = 0, + Without = 1, + With = 2 + }; + WphMode modeVest = WphMode::NoChange; + WphMode modeHelmet = WphMode::NoChange; + enum class PersonellProtection + { + NoChange = 0, + Without = 1, + Suit = 2, + SuitAndGloves = 3 + } personellProtectionMode = PersonellProtection::NoChange; + enum class ProtectionLevel + { + NoChange = 0, + IdzEs = 1, + IdzBs = 2, + Ksk = 3, + SoldierWithBodyArmor = 4, + SoldierActor = 5 + } protectionLevel = ProtectionLevel::NoChange; + enum class HandgrenadeSearchMode + { + NoChange = 0, + Off = 1, + On = 2 + } handgrenadeSearchMode = HandgrenadeSearchMode::NoChange; + + enum class InternationalMode + { + NoChange = 0, + Off = 1, + On = 2 + } internationalMode = InternationalMode::NoChange; + + enum class ABCProtectionMode + { + NoChange = 0, + Off = 1, + On = 2 + } abcProtectionMode = ABCProtectionMode::NoChange; + + static void fromJson(const QJsonObject &obj, ParticipantModeBase &ret); + QJsonObject toJson() const; + }; + + + struct ParticipantMode + : TrainingAreaTelegramTmpl + , ParticipantModeBase + { + static ParticipantMode fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantMode"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_SETZEN; } + }; + + + struct ParticipantModeReport + : TrainingAreaTelegramTmpl + , ParticipantModeBase + { + static ParticipantModeReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantModeReport"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_MELDUNG; } + }; + + + struct DemandParticipantMode : TrainingAreaTelegramTmpl + { + Header header; + + static DemandParticipantMode fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DemandParticipantMode"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_ANFORDERN; } + }; + + + struct ParticipantConfigurationBase + { + Header header; + int positionIntervallVehicle = 0; + int positionIntervallPersonell = 0; + int positionIntervallAircraft = 0; + int positionTransmissionIntervall = 0; + int heightbarrier = 0; + enum class FaultPositionHandling + { + NoChange = 0, + NoPositions = 1, + InvalidPositionValue = 2, + EstimatedPosition = 3 + } faultPositionHandling = FaultPositionHandling::NoChange; + enum class SwitchingPositionIntervall + { + NoChange = 0, + On = 1, + Off = 2 + } switchingPositionIntervall = SwitchingPositionIntervall::NoChange; + int waittimeAdditionalBroadcastDemand = 0; + int factorWaittimeIncreaseAtHighload = 0; + int waittimeAutomaticVulnerabilityIncreaseLevel1 = 0; + int waittimeAutomaticVulnerabilityIncreaseLevel2 = 0; + int waittimeAutomaticVulnerabilityIncreaseLevel3 = 0; + enum class OpticalCode + { + NoChange = 0, + Osag10 = 1, + Osag20Basic = 2, + SisoStandard = 3 + } opticalCode = OpticalCode::NoChange; + int vulnerabilityModel = 0; + int validTimeOps = 0; + + static void fromJson(const QJsonObject &obj, ParticipantConfigurationBase &ret); + QJsonObject toJson() const; + }; + + + struct ParticipantConfigurationReport + : TrainingAreaTelegramTmpl + , ParticipantConfigurationBase + { + static ParticipantConfigurationReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantConfigurationReport"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_ANTWORT; } + }; + + + struct ParticipantConfiguration + : TrainingAreaTelegramTmpl + , ParticipantConfigurationBase + { + static ParticipantConfiguration fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantConfiguration"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_SETZEN; } + }; + + + struct DemandParticipantConfiguration : TrainingAreaTelegramTmpl + { + Header header; + + static DemandParticipantConfiguration fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("DemandParticipantConfiguration"); } + static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_ANFORDERN; } + }; + + + struct SanitationRepair : TrainingAreaTelegramTmpl + { + Header header; + OriginatorType originatorType; + int equipmentNumberOrigin; + VulnerabilityState stateStart; + int typeOfTreatment; + int triage; + int tyeOfDamage; + VulnerabilityState stateResult; + enum class TreatmentResult + { + None = 0, + Success = 1, + Stabilized = 2, + Failure = 3 + } treatmentResult = TreatmentResult::None; + int triagePriority; + int fullState; + int timeOfTreatment; + int timeOfRecovery; + + static SanitationRepair fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SanitationRepair"); } + static constexpr TelegramId id() { return TelegramId::SANITAETSDIENST_INSTANDSETZUNG; } + }; + + + struct SanitaryMaterialStockReport : TrainingAreaTelegramTmpl + { + Header header; + int uniqueId; + int originatorEquipmentNumber; + Qualification qualification; + int sanitaryMaterialCount; + std::vector sanitaryMaterialStock; + + static SanitaryMaterialStockReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SanitaryMaterialStockReport"); } + static constexpr TelegramId id() { return TelegramId::BESTANDSMELDUNG_SANITAETSMATERIAL; } + }; + + + struct Sanitation : TrainingAreaTelegramTmpl + { + Header header; + qint64 proceduresTaken; + SanitationResult sanitationResult; + SanitationEvaluation sanitationEvaluation; + int uniqeId; + int originatorEquipmentNumber; + Qualification qualification = Qualification::NotDefined; + static Sanitation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("Sanitation"); } + static constexpr TelegramId id() { return TelegramId::SANITAETSDIENST_INSTANDSETZUNG_PVSAN; } + }; + + + struct ExerciseStateData : TrainingAreaTelegramTmpl + { + Header header; + + enum class ExerciseState + { + Unknown = 0, + Created = 1, + Started = 2, + Paused = 3, + Stopped = 5, + Terminated = 6 + } exerciseState = ExerciseState::Unknown; + int exerciseId = 0; + + static ExerciseStateData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExerciseStateData"); } + static constexpr TelegramId id() { return TelegramId::BETRIEBSZUSTANDSMELDUNG; } + }; + + + struct EmergencyCall : TrainingAreaTelegramTmpl + { + int issi = 0; + AbsolutePosition absPosition; + qint64 timeStamp; + + static EmergencyCall fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("EmergencyCall"); } + static constexpr TelegramId id() { return TelegramId::NOTRUF; } + }; + + + struct RequestBroadcastStatistics : TrainingAreaTelegramTmpl + { + Header header; + + static RequestBroadcastStatistics fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("RequestBroadcastStatistics"); } + static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_STATISTIK_BROADCAST_NACHFORDERUNGEN; } + }; + + + struct BroadcastInformation + { + int equipmentNumber = 0; + int broadcastRequests = 0; + + static BroadcastInformation fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + struct BroadcastStatistics : TrainingAreaTelegramTmpl + { + Header header; + std::vector information; + + static BroadcastStatistics fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("BroadcastStatistics"); } + static constexpr TelegramId id() { return TelegramId::STATISTIK_BROADCAST_NACHFORDERUNGEN; } + }; + + + struct GroupIssiInformation + { + int exerciseId = 0; + int serverIssi = 0; + int broadcastIssi1 = 0; + int broadcastIssi2 = 0; + + static GroupIssiInformation fromJson(const QJsonObject &obj); + QJsonObject toJson() const; + }; + + + struct ExerciseEquipmentAssignmentComplete : TrainingAreaTelegramTmpl + { + std::unordered_map> exerciseEquipmentAssignments; + std::vector groupIssiInformation; + + static ExerciseEquipmentAssignmentComplete fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExerciseEquipmentAssignmentComplete"); } + static constexpr TelegramId id() { return TelegramId::EXERCISE_EQUIPMENT_ASSIGNMENT_COMPLETE; } + }; + + + struct ProxyConnectionState : public TrainingAreaTelegramTmpl + { + bool connectedToSystem = false; + + static ProxyConnectionState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ProxyConnectionState"); } + static constexpr TelegramId id() { return TelegramId::PROXY_CONNECTION_STATE; } + }; + + + struct ParticipantLicenseChange : public TrainingAreaTelegramTmpl + { + int equipmentNumber = 0; + ParticipantLicenseState licenseState = ParticipantLicenseState::Unknown; + + static ParticipantLicenseChange fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ParticipantLicenseChange"); } + static constexpr TelegramId id() { return TelegramId::PARTICIPANT_LICENSE_CHANGE; } + }; + + + struct WlsParticipantsStateRequest : public TrainingAreaTelegramTmpl + { + static WlsParticipantsStateRequest fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("WlsParticipantsStateRequest"); } + static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANTS_STATE_REQUEST; } + }; + + + struct WlsParticipantsStateReport : public TrainingAreaTelegramTmpl + { + std::vector participantStates; + + static WlsParticipantsStateReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("WlsParticipantsStateReport"); } + static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANTS_STATE_REPORT; } + }; + + + struct WlsBinarySfmData : public TrainingAreaTelegramTmpl + { + Header header; + std::vector payload; + + static WlsBinarySfmData fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("WlsBinarySfmData"); } + static constexpr TelegramId id() { return TelegramId::WLS_BINARY_SFM_DATA; } + }; + + + struct WlsParticipantsConnectionState : public TrainingAreaTelegramTmpl + { + int equipmentNumber = 0; + bool dataCommunicationPossible = false; + + static WlsParticipantsConnectionState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("WlsParticipantsConnectionState"); } + static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANT_CONNECTION_STATE; } + }; + + + struct ApacheLaserDesignation : TrainingAreaTelegramTmpl + { + Header header; + int gearId; + int code; + double outputPower; + AbsolutePosition spotLocation; + + static ApacheLaserDesignation fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ApacheLaserDesignation"); } + static constexpr TelegramId id() { return TelegramId::APACHE_LASER_DESIGNATION; } + }; + + + struct BatteryInfo : TrainingAreaTelegramTmpl + { + Header header; + std::vector batteryStates; + + static BatteryInfo fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("BatteryInfo"); } + static constexpr TelegramId id() { return TelegramId::BATTERY_INFO; } + }; + + + struct BatteryAlarm : TrainingAreaTelegramTmpl + { + Header m_header; + int m_id; + QString m_description; + bool m_acknowledge; + bool m_condition; + int m_uniqueAlarmNumber; + qint64 m_alarmTime; + + Header header() const { return m_header; } + QString description() const { return m_description; } + bool acknowledge() const { return m_acknowledge; } + bool condition() const { return m_condition; } + int uniqueAlarmNumber() const { return m_uniqueAlarmNumber; } + qint64 alarmTime() const { return m_alarmTime; } + + static BatteryAlarm fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("BatteryAlarm"); } + static constexpr TelegramId id() { return TelegramId::BATTERY_ALARM; } + }; + + + struct ServiceControl : TrainingAreaTelegramTmpl + { + Header header; + ServiceControlEnum serviceControlState; + + static ServiceControl fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ServiceControl"); } + static constexpr TelegramId id() { return TelegramId::SERVICE_CONTROL; } + }; + + + struct SetDevicePowerRequest : TrainingAreaTelegramTmpl + { + Header header; + PowerMethod powerType; + int subdeviceId; + + static SetDevicePowerRequest fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("SetPowerDeviceRequest"); } + static constexpr TelegramId id() { return TelegramId::DEVICE_POWER_SET_REQUEST; } + }; + + + struct UAVPerformMission : TrainingAreaTelegramTmpl + { + Header header; + std::vector actions; + int missionId; + QString missionName; + + static UAVPerformMission fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString ACTIONS() { return QLatin1String("actions"); } + static QString MISSION_ID() { return QLatin1String("missionId"); } + static QString MISSION_NAME() { return QLatin1String("missionName"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("UAVPerformMission"); } + static constexpr TelegramId id() { return TelegramId::UAV_PERFORM_MISSION; } + }; + + + struct UAVStatus : TrainingAreaTelegramTmpl + { + Header header; + UAVState uavState; + + static UAVStatus fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString UAVSTATE() { return QLatin1String("uavState"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("UAVState"); } + static constexpr TelegramId id() { return TelegramId::UAV_STATUS; } + }; + + + struct UAVRadioLinkConnectionStatus : TrainingAreaTelegramTmpl + { + Header header; + UAVRadioLinkConnectionStatusType uavConnectionState; + + static UAVRadioLinkConnectionStatus fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString UAVCONNECTIONSTATE() { return QLatin1String("uavConnectionState"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("UAVRadioLinkConnectionStatus"); } + static constexpr TelegramId id() { return TelegramId::UAV_RADIO_LINK_CONNECTION_STATUS; } + }; + + + struct UAVMissionStatus : TrainingAreaTelegramTmpl + { + Header header; + UAVActionTask currentAction; + QString currentMissionName; + QString missionEnded; + + static UAVMissionStatus fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString CURRENT_ACTION() { return QLatin1String("currentAction"); } + static QString CURRENT_MISSION_NAME() { return QLatin1String("currentMissionName"); } + static QString MISSION_ENDED() { return QLatin1String("missionEnded"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("UAVMissionStatus"); } + static constexpr TelegramId id() { return TelegramId::UAV_MISSION_STATUS; } + }; + + + struct UAVChangeState : TrainingAreaTelegramTmpl + { + Header header; + UAVState requestedState; + + static UAVChangeState fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString REQUESTED_STATE() { return QLatin1String("requestedState"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("UAVChangeState"); } + static constexpr TelegramId id() { return TelegramId::UAV_CHANGE_STATE; } + }; + + + struct ExFireReadiness : TrainingAreaTelegramTmpl + { + Header header; + int partyId; + QString reference; + + + static ExFireReadiness fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString PARTY_ID() { return QLatin1String("partyId"); } + static QString REFERENCE() { return QLatin1String("reference"); } + }; + + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExFiredReport"); } + static constexpr TelegramId id() { return TelegramId::EX_FIRE_READINESS; } + }; + + + struct ExFiredReport : TrainingAreaTelegramTmpl + { + Header header; + int partyId; + QString reference; + QString unitIdentifier; + QString identifier; + + static ExFiredReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString PARTY_ID() { return QLatin1String("partyId"); } + static QString REFERENCE() { return QLatin1String("reference"); } + static QString UNIT_IDENTIFIER() { return QLatin1String("unitIdentifier"); } + static QString IDENTIFIER() { return QLatin1String("identifier"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExFiredReport"); } + static constexpr TelegramId id() { return TelegramId::EX_FIRED_REPORT; } + }; + + + struct ExConfirmationReport : TrainingAreaTelegramTmpl + { + Header header; + int partyId; + QString reference; + QString unitIdentifier; + QString identifier; + + static ExConfirmationReport fromJson(const QJsonObject &obj); + QJsonObject toJson() const override; + + static QString HEADER() { return QLatin1String("header"); } + static QString PARTY_ID() { return QLatin1String("partyId"); } + static QString REFERENCE() { return QLatin1String("reference"); } + static QString UNIT_IDENTIFIER() { return QLatin1String("unitIdentifier"); } + static QString IDENTIFIER() { return QLatin1String("identifier"); } + }; + template <> struct Constraints + { + static QString type() { return QStringLiteral("ExConfirmationReport"); } + static constexpr TelegramId id() { return TelegramId::EX_CONFIRMATION_REPORT; } + }; + } - stream << "Unknown (" << std::to_string(int(val)) << ")"; - return stream; } - -enum class FunctionalAreaOperatingMode -{ - NotUsed = 0, - OperatedByOC = 1, - WaitForTimeout = 2 -}; - -enum class Language -{ - NoChange = 0, - German = 1, - English = 2, - French = 3, - Arabic = 4, - Spanish = 5, - Russian = 6 -}; - -enum class ParticipantLicenseState -{ - Unknown = 0, - Licensed = 1, - Rejected = 2, - Unlicense = 3, -}; - -enum class UAVActionTask -{ - Undefined = 0, - Disarm = 1, - Arm = 2, - Takeoff = 3, - Connect = 4, - Loiter = 5, - Return = 6, - Observe = 8, -}; - -enum class UAVRadioLinkConnectionStatusType -{ - - Undefined = 0, - - Disconnected = 1, - - Connecting = 2, - - Diconnecting = 3, - - Connected = 4, - - Error = 5, -}; - -enum class UAVState -{ - Undefined = 0, - Off = 1, - On = 2, - Standby = 3, - Init = 4, - Shutdown = 5, - Normal = 6, - Manual = 7, - Auto = 8, - Calibrating = 9, - Maintenance = 10 -}; - -struct Header -{ - int equipmentNumber = 0; - qint64 timeStamp = 0; - - static Header fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct RelativePosition -{ - int offsetX = 0; - int offsetY = 0; - double offsetZ = 0; - - explicit RelativePosition(int x = 0, int y = 0, double z = 0) - : offsetX(x) - , offsetY(y) - , offsetZ(z) - {} - - static RelativePosition fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - - -struct AbsolutePosition -{ - double lon = 0; - double lat = 0; - double z = 0; - - bool isValid() const - { - return (lon != 0 && lat != 0); - } - - static AbsolutePosition fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct OpsPosition -{ - int opsId = 0; - int moutObjectId = 0; - int moutRoomId = 0; - - static OpsPosition fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct GpsQuality -{ - bool moreThan4SatellitesAvailable = false; - bool dgpsModeAvailable = false; - int pdopValue = 0; - - static GpsQuality fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct Gear -{ - int gearTasCode = 0; - int gearSerialNumber = 0; - bool chargeCounting = false; - - static Gear fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct GearCharge -{ - int gearTasCode = 0; - int gearSerialNumber = 0; - int chargeTypeId = 0; - int remain = 0; - int location = 0; - - static GearCharge fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - - -struct WlsPosition -{ - double x = 0; - double y = 0; - double z = 0; - int wlsAreaId = 0; - int wlsZone = 0; - int wlsBuildingId = 0; - int wlsRoomNumber = 0; - int playerOrientation = 0; - int weaponOrientation = 0; - bool isValid = false; - - static WlsPosition fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct WlsParticipantState -{ - QString tagId; - qint64 lastSeen = 0; - double voltage = 0; - int equipmentNumber = 0; - int tacticalState = -1; - bool gpsOn = false; - bool inBlockedArea = false; - WlsPosition relativePosition; - - static WlsParticipantState fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct BatteryState -{ - int m_batteryPort; - int m_batteryPercent; - int m_voltage; - int m_temperature; - int m_frequency; - int m_generic; - int m_current; - bool m_switchOrValue; - QString m_serialNumber; - - int batteryPort() const { return m_batteryPort; } - int batteryPercent() const { return m_batteryPercent; } - int voltage() const { return m_voltage; } - int temperature() const { return m_temperature; } - int frequency() const { return m_frequency; } - int generic() const { return m_generic; } - int current() const { return m_current; } - bool switchOrValue() const { return m_switchOrValue; } - QString serialNumber() const { return m_serialNumber; } - - static BatteryState fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct UAVAction -{ - UAVActionTask task; - AbsolutePosition absPosition; - - - - static QString TASK() { return QLatin1String("task"); } - static QString POSITION() { return QLatin1String("position"); } - - static UAVAction fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - - -struct Acknowledge : TrainingAreaTelegramTmpl -{ - qint64 timeStamp = 0; - int32_t ackCounter = 0; - - static Acknowledge fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("Acknowledge"); } - static constexpr TelegramId id() { return TelegramId::BESTAETIGUNG; } -}; - - -struct Init : TrainingAreaTelegramTmpl -{ - Header header; - int workstationId = 0; - bool restockCharges = false; - bool resetManipulation = false; - bool resetVulnerabilityState = false; - bool restockSanitationMaterial = false; - - static Init fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("Init"); } - static constexpr TelegramId id() { return TelegramId::INIT; } -}; - - -struct ManipulationReport : TrainingAreaTelegramTmpl -{ - Header header; - bool isManipulation = false; - int equipmentFunctionId; - - static ManipulationReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ManipulationReport"); } - static constexpr TelegramId id() { return TelegramId::MANIPULATIONSMELDUNG; } -}; - - -struct DemandBite : TrainingAreaTelegramTmpl -{ - Header header; - bool withSelfTest = false; - - static DemandBite fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DemandBite"); } - static constexpr TelegramId id() { return TelegramId::AUFFORDERUNG_BITE_MELDUNG; } -}; - - -struct EquipmentOperationalState : TrainingAreaTelegramTmpl -{ - Header header; - bool nbcProtectionActive = false; - - static EquipmentOperationalState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentOperationalState"); } - static constexpr TelegramId id() { return TelegramId::BETRIEBSZUSTAND_AUSSTATTUNG; } -}; - - -struct VulnerabilityModelBase -{ - Header header; - int vulnerabilityModelMineIed = 0; - int vulnerabilityModelAreaFire = 0; - int vulnerabilityModelOperatingResource = 0; - int vulnerabilityModelAcWeaponry = 0; - - static void fromJson(const QJsonObject &obj, VulnerabilityModelBase &ret); - QJsonObject toJson() const; -}; - -struct SetVulnerabilityModel : TrainingAreaTelegramTmpl, VulnerabilityModelBase -{ - static SetVulnerabilityModel fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SetVulnerabilityModel"); } - static constexpr TelegramId id() { return TelegramId::KONFIGURATION_WIRKMODELL; } -}; - - -struct DemandEquipmentConfigurationReport : TrainingAreaTelegramTmpl -{ - Header header; - - static DemandEquipmentConfigurationReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DemandEquipmentConfigurationReport"); } - static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_KONFIGURATIONSDATEN; } -}; - - -struct EquipmentConfigurationReport : TrainingAreaTelegramTmpl, VulnerabilityModelBase -{ - int equipmentNumber = 0; - int canStartUpTime = 0; - int equipmentType = 0; - - int loginWaittimeBitweenTrys = 0; - int loginMaxRetryCnt = 0; - bool loginMasteringFlag = false; - - int canDeviceConfiguration; - - bool displayDeviceVoiceOutput = false; - Language displayDeviceLanguage = Language::NoChange; - bool pyrotechnics = false; - enum class MineHandgrenadeSensorMode - { - PersonellMode = 0, - NormalVehicleMode = 2, - OcVehicleMode = 3 - }; - MineHandgrenadeSensorMode mhgrsMode = MineHandgrenadeSensorMode::PersonellMode; - bool mhgrsEnergySaving = false; - - enum class FirMode - { - NoFir = 0, - Fir = 1, - FirSpzMarder = 2 - }; - enum class MineLayerMode - { - NoMineLayerDevice = 0, - MinLayerTrailer = 1, - MineLayerThrower = 2 - }; - enum class SpecialSensorStandardMode - { - NoSpecialSensorStandard = 0, - ZABC = 3, - CSF = 4, - PzBr = 5, - MRF = 7 - }; - FirMode specialSensorFir = FirMode::NoFir; - MineLayerMode specialSensorMinelayer = MineLayerMode::NoMineLayerDevice; - SpecialSensorStandardMode specialSensorStandard = SpecialSensorStandardMode::NoSpecialSensorStandard; - - enum class AgdusHwMode - { - WithoutHelmetWithoutVest = 1, - WithHelmetWithoutVest = 2, - WithHelmetWithVest = 3 - }; - AgdusHwMode agdusHwMode = AgdusHwMode::WithoutHelmetWithoutVest; - - enum class PositionUpdateInterval - { - Vehicle = 0, - Personnell = 1, - Aircraft = 2 - }; - PositionUpdateInterval positionUpdateInterval = PositionUpdateInterval::Personnell; - - int displayTextMainGroup; - int displayTextSubGroup; - - int vulnerabilityModelAgdus; - - static EquipmentConfigurationReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentConfigurationReport"); } - static constexpr TelegramId id() { return TelegramId::KONFIGURATIONSMELDUNG; } -}; - - -struct CtaDataError : TrainingAreaTelegramTmpl -{ - enum class Reason - { - WrongParameter = 1, - TelegramOutdated = 2, - InvalidByteCount = 3, - InvalidData = 4, - FragmentationError = 5, - Unknown = 6, - AdditionalDemandTimeout = 7, - ErrorLoginEquipmentNumber = 50, - ErrorLoginTetraId = 51, - InfoLoginMasteringFlag = 52, - ErrorSendingNamelist = 53, - ErrorSendingToExerciseControl = 54, - ErrorNotLoggedIn = 55, - ErrorNotLicensed = 56, - ErrorConfigSelfTest = 57, - JsonDecodeFailure = 101, - WrongCrc = 105, - BroadcastCounterOverflow = 106, - InvalidTime = 256, - InvalidPosition = 257, - InvalidTacticalState = 258 - }; - - Header header; - Reason reason = Reason::Unknown; - int originTelegramId = 0; - - static CtaDataError fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CtaDataError"); } - static constexpr TelegramId id() { return TelegramId::FEHLERMELDUNG_GFD; } -}; - -struct PositionReportBase -{ - Header header; - RelativePosition relPosition; - AbsolutePosition geoPosition; - OpsPosition opsPosition; - GpsQuality gpsQuality; - - static void fromJson(const QJsonObject &obj, PositionReportBase &ret); - QJsonObject toJson() const; -}; - - -struct RestoreRadioReadiness : public TrainingAreaTelegramTmpl -{ - Header header; - - RelativePosition readinessLossPosition; - int readinessLossTime; - RelativePosition readinessRestorePosition; - int readinessRestoreTime; - - static RestoreRadioReadiness fromJson(const QJsonObject &obj); - QJsonObject toJson() const; - - static QString HEADER() { return QLatin1String("header"); } - static QString READINESS_LOSS_POSITION() { return QLatin1String("readinessLossPosition"); } - static QString READINESS_LOSS_TIME() { return QLatin1String("readinessLossTime"); } - static QString READINESS_RESTORE_POSITION() { return QLatin1String("readinessRestorePosition"); } - static QString READINESS_RESTORE_TIME() { return QLatin1String("readinessRestoreTime"); } -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("RestoreRadioReadiness"); } - static constexpr TelegramId id() { return TelegramId::WIEDERHERSTELLUNG_FUNKBEREITSCHAFT; } -}; - - -struct PositionReport : public TrainingAreaTelegramTmpl, PositionReportBase -{ - static PositionReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("PositionReport"); } - static constexpr TelegramId id() { return TelegramId::POSITIONS_MELDUNG; } -}; - - -struct PositionReportWithMountedEquipments : TrainingAreaTelegramTmpl, PositionReportBase -{ - std::vector mountedEquipments; - - static PositionReportWithMountedEquipments fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("PositionReportWithMountedEquipments"); } - static constexpr TelegramId id() { return TelegramId::POSITIONS_MELDUNG_MIT_TEILNEHMER; } -}; - -struct CreateAreaEffectSimulationBase -{ - Header header; - int aesDdsId = 0; - - std::string name; - int partyId = 0; - RelativePosition relEffectPosition; - - static void fromJson(const QJsonObject &obj, CreateAreaEffectSimulationBase &ret); - QJsonObject toJson() const; -}; - -struct CreateCombatAreaEffectSimulationBase : CreateAreaEffectSimulationBase -{ - int chargeTypeId = 0; - qint64 effectStart = 0; - qint64 effectDuration = 0; - - static void fromJson(const QJsonObject &obj, CreateCombatAreaEffectSimulationBase &ret); - QJsonObject toJson() const; -}; - - -struct OcCommand : TrainingAreaTelegramTmpl -{ - Header header; - int action = 0; - - static OcCommand fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("OcCommand"); } - static constexpr TelegramId id() { return TelegramId::SCHIEDSRICHTERKOMMANDO; } -}; - - -struct CreateSingleExplosion : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - int effectDiameter = 0; - - static CreateSingleExplosion fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateSingleExplosion"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_EINZELGESCHOSS; } -}; - - -struct CreateAreaExplosion : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - RelativePosition relCorner; - int height{0}; - int width{0}; - double rotationAngle{0.0}; - int impactCount{0}; - int impactEdgeLength{0}; - double mhpRotation{0.0}; - int mhpLength{0}; - int mhpWidth{0}; - int impactRadius{0}; - std::vector mhPoints; - int hazardDistance; - - static CreateAreaExplosion fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateAreaExplosion"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER; } -}; - - -struct PauseEffectSimulation : TrainingAreaTelegramTmpl -{ - int aesDdsId = 0; - - - static PauseEffectSimulation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("PauseEffectSimulation"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER_STOP; } -}; - - -struct ResumeEffectSimulation : TrainingAreaTelegramTmpl -{ - int aesDdsId = 0; - - int sequelNumber = 0; - int nextImpact = 0; - qint64 resumeTime; - int remainDuration; - - static ResumeEffectSimulation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ResumeEffectSimulation"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN; } -}; - - -struct MineAreaSegment -{ - RelativePosition relStart; - RelativePosition relEnd; - - static MineAreaSegment fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct CreateMineArea : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - - - double layingDepth = 0; - double layingDensity = 0; - std::vector segments; - - static CreateMineArea fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateMineArea"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_MINENSPERRE; } -}; - - -struct MineAreaSingleMineState : TrainingAreaTelegramTmpl -{ - int aesDdsId = 0; - - int mineCount = 0; - std::vector mineState; - - static MineAreaSingleMineState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("MineAreaSingleMineState"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_STATUS_MINENSPERRE; } -}; - - -struct CreateNContamination : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - int innerRadius = 0; - int borderLengthInner = 0; - int borderLengthOuter = 0; - double spanAngle = 0; - double rotationAngle = 0; - - static CreateNContamination fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateNContamination"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_A_KAMPFMITTEL; } -}; - - -struct CreateCContamination : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - int effectRadius = 0; - double expansionFactor = 0; - double propagationDirection = 0; - int windSpeed = 0; - qint64 validityTimeWind; - RelativePosition relPositionValidityTimeWind; - enum class Volatiliy - { - Floating = 1, - Resident = 2 - } volatility = Volatiliy::Resident; - - static CreateCContamination fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateCContamination"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_C_KAMPFMITTEL; } -}; - - -struct DeactivateEffectSimulation : TrainingAreaTelegramTmpl -{ - AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; - int aesDdsId = 0; - - - static DeactivateEffectSimulation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DeactivateEffectSimulation"); } - static constexpr TelegramId id() { return TelegramId::DEAKTIVIERUNG_WIRKFELD; } -}; - - -struct ModifyAreaEffectSimulationName : TrainingAreaTelegramTmpl -{ - AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; - int aesDdsId = 0; - - std::string name; - - static ModifyAreaEffectSimulationName fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ModifyAreaEffectSimulationName"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_AENDERUNG_BEZEICHNER; } -}; - - -struct MineTriggered : TrainingAreaTelegramTmpl -{ - Header header; - int mineAreaId = 0; - int mineIndex = 0; - int chargeTypeId = 0; - RelativePosition relPosition; - bool relPositionValid = false; - - static MineTriggered fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("MineTriggered"); } - static constexpr TelegramId id() { return TelegramId::DEAKTIVIERUNG_EINZELMINE; } -}; - - -struct DusMineReactivation : TrainingAreaTelegramTmpl -{ - Header header; - std::vector dusSerialNumbers; - - static DusMineReactivation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DusMineReactivation"); } - static constexpr TelegramId id() { return TelegramId::REAKTIVIERUNG_DUS_MINE; } -}; - - -enum class IedType -{ - SuicideIed = 1, - IedSmallPyro = 2, - IedBigPyro = 3 -}; - -enum class IedPairingState -{ - NotPaired = 1, - PairedToParticipant = 2, - PairedToOps = 3 -}; - -enum class IedTacticalState -{ - NotActive = 0, - Active = 1, - Defused = 2, - TriggeredBySwitch = 3, - TriggeredByRemote = 4, - TriggeredByLightBarrier = 5, - TriggeredByTautWire = 6, - TriggeredByControlDevice = 7, - Unknown = 255 -}; - -struct IedBaseData -{ - Header header; - int iedId = 0; - IedTacticalState tacticalState = IedTacticalState::Unknown; - bool statePyrotechnics = false; - - static void fromJson(const QJsonObject &obj, IedBaseData &ret); - QJsonObject toJson() const; -}; - -struct DefinitionIed : TrainingAreaTelegramTmpl, IedBaseData -{ - RelativePosition relPosition; - IedType iedType = IedType::SuicideIed; - enum class TriggerTypes { - Remote = 0x01, - Switch = 0x02, - LightBarrier = 0x04, - TautWire = 0x08 - }; - int trigger = 0; - int explosiveForce = 0; - IedPairingState pairingState = IedPairingState::NotPaired; - int pairedId = 0; - int partyId = 0; - - static DefinitionIed fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DefinitionIed"); } - static constexpr TelegramId id() { return TelegramId::DEFINITION_IED; } -}; - - -enum class IedError -{ - NoError = 0, - DeviceMissing = 1 -}; - -struct StateIed : TrainingAreaTelegramTmpl, IedBaseData -{ - int batteryWarnings = 0; - IedError errorStateElectronics = IedError::NoError; - IedError errorStatePyrotechnics1 = IedError::NoError; - IedError errorStatePyrotechnics2 = IedError::NoError; - IedError errorStatePyrotechnics3 = IedError::NoError; - - static StateIed fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("StateIed"); } - static constexpr TelegramId id() { return TelegramId::ZUSTAND_IED; } -}; - - -struct DusSingleMineState : TrainingAreaTelegramTmpl -{ - Header header; - int mineId = 0; - qint64 effectStart = 0; - RelativePosition relPosition; - int chargeTypeId = 0; - bool state = false; - - static DusSingleMineState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DusSingleMineState"); } - static constexpr TelegramId id() { return TelegramId::STATUS_EINZELMINENSIMULATOR; } -}; - - -struct CreateDusSingleMine : TrainingAreaTelegramTmpl, CreateCombatAreaEffectSimulationBase -{ - int mineId; - - static CreateDusSingleMine fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateDusSingleMine"); } - static constexpr TelegramId id() { return TelegramId::WIRKFELD_EINZELMINENSIMULATOR; } -}; - -struct StateChangeBase -{ - Header header; - RelativePosition relPosition; - AbsolutePosition geoPosition; - OpsPosition opsPosition; - VulnerabilityState vulnerabilityState = VulnerabilityState::CombatReady; - int tasVulnerabilityKindId = 0; - int tasVitality = 0; - int vulnerabilityBits = 0; - int originatorId = 0; - - static void fromJson(const QJsonObject &obj, StateChangeBase &ret); - QJsonObject toJson() const; -}; - - -struct StateChangeDirect : TrainingAreaTelegramTmpl, StateChangeBase -{ - int chargeTypeId = 0; - - static StateChangeDirect fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("StateChangeDirect"); } - static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_DUS; } -}; - - -struct StateChangeIndirect : TrainingAreaTelegramTmpl, StateChangeBase -{ - bool isSecondaryEffect = false; - - static StateChangeIndirect fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("StateChangeIndirect"); } - static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_WIRKSIMULATION; } -}; - - -struct DemandVulnerabilityStateChange : TrainingAreaTelegramTmpl -{ - Header header; - int workstationId = 0; - VulnerabilityState reqestedState = VulnerabilityState::CombatReady; - int vulnerabilityVitalityIndex = 0; - - static DemandVulnerabilityStateChange fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DemandVulnerabilityStateChange"); } - static constexpr TelegramId id() { return TelegramId::TREFFER_AUSLOESUNG; } -}; - - -struct OperatorAction : TrainingAreaTelegramTmpl -{ - Header header; - RelativePosition relPosition; - int operatorId = 0; - int action = 0; - - static OperatorAction fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("OperatorAction"); } - static constexpr TelegramId id() { return TelegramId::SCHIEDSRICHTEREINGRIFF; } -}; - - -struct Reammunition -{ - int chargeTypeId = 0; - int location = 0; - int newStock = 0xfffe; - int newDefaultStock = 0xfffe; - int tracerRatio = 0; - - static Reammunition fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct SelectiveReammunition : TrainingAreaTelegramTmpl -{ - Header header; - int gearId = 0; - std::vector reammunitions; - - static SelectiveReammunition fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SelectiveReammunition"); } - static constexpr TelegramId id() { return TelegramId::SELEKTIVE_AUFMUNITIONIERUNG; } -}; - - -struct StateChange : TrainingAreaTelegramTmpl, StateChangeBase -{ - OriginatorType originatorType = OriginatorType::Initialisation; - - static StateChange fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("StateChange"); } - static constexpr TelegramId id() { return TelegramId::TAKTISCHER_STATUS; } -}; - - -struct CreateFunctionalArea : TrainingAreaTelegramTmpl, CreateAreaEffectSimulationBase -{ - int width = 0; - int height = 0; - qint64 deconTimeout = 0; - qint64 maintenanceTimeout = 0; - qint64 medicalTimeout = 0; - FunctionalAreaOperatingMode deconMode = FunctionalAreaOperatingMode::NotUsed; - FunctionalAreaOperatingMode maintenanceMode = FunctionalAreaOperatingMode::NotUsed; - FunctionalAreaOperatingMode medicalMode = FunctionalAreaOperatingMode::NotUsed; - - static CreateFunctionalArea fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CreateFunctionalArea"); } - static constexpr TelegramId id() { return TelegramId::FUNKTIONSRAUM; } -}; - - -struct FunctionalAreaEntry : TrainingAreaTelegramTmpl -{ - Header header; - RelativePosition relPosition; - int aesDdsId = 0; - - - static FunctionalAreaEntry fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("FunctionalAreaEntry"); } - static constexpr TelegramId id() { return TelegramId::EINTRETEN_FUNKTIONSRAUM; } -}; - - -struct RequestBroadcastTelegrams : TrainingAreaTelegramTmpl -{ - Header header; - int resetCounter = 0; - int broadcastIndex = 0; - - static RequestBroadcastTelegrams fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("RequestBroadcastTelegrams"); } - static constexpr TelegramId id() { return TelegramId::NACHFORDERUNG_BROADCAST_TELEGRAMME; } -}; - - -struct SpecialSensorData : TrainingAreaTelegramTmpl -{ - Header header; - RelativePosition relPosition; - int operationalState = 0; - bool airSensor = false; - bool tireSensor = false; - bool pointSensor = false; - bool solidMatterSampleExtractor = false; - int type = 0; - int nbcType = 0; - - static SpecialSensorData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SpecialSensorData"); } - static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_FAHRSPUR; } -}; - - -struct MinelayerTrailerDataBase -{ - Header header; - RelativePosition relPosition; - - - int barrierId = 0; - int layingDensity = 0; - qint64 effectStart = 0; - int effectDuration = 0; - int indirectChargeTasCode = 0; - int mineCount = 0; - - static void fromJson(const QJsonObject &obj, MinelayerTrailerDataBase &ret); - QJsonObject toJson() const; -}; - -struct MinelayerTrailerData : public TrainingAreaTelegramTmpl, MinelayerTrailerDataBase -{ - static MinelayerTrailerData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("MinelayerTrailerData"); } - static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_MIVANH_VERLEGEDATEN; } -}; - - -struct MinelayerThrowerData : TrainingAreaTelegramTmpl, MinelayerTrailerDataBase -{ - enum class ThrowingType - { - Straight = 0, - Right = 1, - Left = 2, - LeftAndRight = 3, - SingleRight = 5, - SingleLeft = 6, - SingleLeftAndRight = 7 - } throwingType = ThrowingType::Straight; - - static MinelayerThrowerData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("MinelayerThrowerData"); } - static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_WMIV_VERLEGEDATEN; } -}; - - -struct MinelayerTrailerPosition : public TrainingAreaTelegramTmpl -{ - Header header; - RelativePosition relPosition; - qint64 dusSerialNo = 0; - int indirectChargeTasCode = 0; - - static MinelayerTrailerPosition fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("MinelayerTrailerPosition"); } - static constexpr TelegramId id() { return TelegramId::SONDERSENSORIK_MIVANH_VERLEGEPOSITION; } -}; - - -struct LanguageSelection : TrainingAreaTelegramTmpl -{ - Header header; - Language languageSelection = Language::NoChange; - - static LanguageSelection fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("LanguageSelection"); } - static constexpr TelegramId id() { return TelegramId::SPRACHAUSWAHL; } -}; - - -struct EquipmentMessage : TrainingAreaTelegramTmpl -{ - Header header; - std::string message; - int msgId = -1; - - static EquipmentMessage fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentMessage"); } - static constexpr TelegramId id() { return TelegramId::ALLGEMEINE_NACHRICHT; } -}; - - -struct EquipmentMessageOC : TrainingAreaTelegramTmpl -{ - Header header; - std::string subject; - std::string message; - int senderId = 0; - int receiverId = 0; - - static EquipmentMessageOC fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentMessageOC"); } - static constexpr TelegramId id() { return TelegramId::SR_DMF_NACHRICHT; } -}; - -struct OpaquePayloadDataBase -{ - Header header; - std::vector payload; - enum class Type - { - FireSmokeMarker, - Geopairing, - Target, - OC - } payloadType = Type::FireSmokeMarker; - - static void fromJson(const QJsonObject &obj, OpaquePayloadDataBase &ret); - QJsonObject toJson() const; -}; - - -struct OpaquePayloadDataOut : TrainingAreaTelegramTmpl, OpaquePayloadDataBase -{ - static OpaquePayloadDataOut fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("OpaquePayloadDataOut"); } - static constexpr TelegramId id() { return TelegramId::DATENVERKEHR_TDS_SRT; } -}; - - -struct OpaquePayloadDataIn : TrainingAreaTelegramTmpl, OpaquePayloadDataBase -{ - RelativePosition relPosition; - GpsQuality gpsQuality; - - static OpaquePayloadDataIn fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("OpaquePayloadDataIn"); } - static constexpr TelegramId id() { return TelegramId::DATENVERKEHR_SRT_TDS; } -}; - - -struct EquipmentEvent : TrainingAreaTelegramTmpl -{ - Header header; - RelativePosition relPosition; - int equipmentFunctionId = 0; - int subDeviceId = 0; - int uniqueId = 0; - int code = 0; - std::vector payload; - - static EquipmentEvent fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentEvent"); } - static constexpr TelegramId id() { return TelegramId::GERAETEEREIGNIS; } -}; - - -struct EquipmentGearAssignment : TrainingAreaTelegramTmpl -{ - Header header; - std::vector gears; - - static EquipmentGearAssignment fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentGearAssignment"); } - static constexpr TelegramId id() { return TelegramId::WAFFENZUORDNUNG; } -}; - - -struct EquipmentGearChargeState : TrainingAreaTelegramTmpl -{ - Header header; - std::vector charges; - - static EquipmentGearChargeState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentGearChargeState"); } - static constexpr TelegramId id() { return TelegramId::MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE; } -}; - - -struct ExerciseEnvironmentData : TrainingAreaTelegramTmpl -{ - Header header; - int exerciseId = 0; - int timeZone = 90; - - int utmZone = 0; - int utmBand = 0; - std::string grid; - - static ExerciseEnvironmentData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExerciseEnvironmentData"); } - static constexpr TelegramId id() { return TelegramId::UMGEBUNGS_MELDUNG2; } -}; - - -struct BiteError -{ - int errorNumber = 0; - int canDeviceNumber = 0; - int subdeviceNumber = 0; - int uniqueId = 0; - - static BiteError fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct BiteReport : TrainingAreaTelegramTmpl -{ - Header header; - enum class LoginType - { - NoLogin = 0, - NewLogin = 1, - Relogin = 2, - InvalidLogin = 3, - } loginType = LoginType::NoLogin; - int biteState = 0; - int configState = 0; - int batteryState = 0; - bool configError = false; - std::vector biteErrors; - - static BiteReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("BiteReport"); } - static constexpr TelegramId id() { return TelegramId::BITE_MELDUNG2; } -}; - - -struct EquipmentGearEvent : TrainingAreaTelegramTmpl -{ - Header header; - GearCharge charge; - int chargeAmount = 0; - - static EquipmentGearEvent fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EquipmentGearEvent"); } - static constexpr TelegramId id() { return TelegramId::FEUEREREIGNIS_MIT_WAFFENZUORDNUNG; } -}; - - -struct CesHitInformation : TrainingAreaTelegramTmpl -{ - Header header; - - int chargeTasCodeDirect = 0; - int chargeTasCodeIndirect = 0; - int originatorEquipmentNumber = 0; - int directionDegree = 0; - int distance = 0; - int effectPercent = 0; - - static CesHitInformation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CesHitInformation"); } - static constexpr TelegramId id() { return TelegramId::AUSLOESUNG_DUS_TREFFER; } -}; - - -struct ParticipantSwVersionsRequest : TrainingAreaTelegramTmpl -{ - Header header; - int equipmentFunctionId; - - static ParticipantSwVersionsRequest fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantSwVersionsRequest"); } - static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_SW_VERSION; } -}; - -struct EquipmentSwVersion -{ - int equipmentFunctionId = 0; - int subDeviceId = 0; - int uniqueId = 0; - int swVersion = 0; - - static EquipmentSwVersion fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - - -struct ParticipantSwVersions : TrainingAreaTelegramTmpl -{ - Header header; - std::vector equipments; - - static ParticipantSwVersions fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantSwVersions"); } - static constexpr TelegramId id() { return TelegramId::SW_VERSIONSMELDUNG; } -}; - - - - -struct CesHitRequest : TrainingAreaTelegramTmpl -{ - Header header; - int chargeTasCodeDirect = 0; - int chargeTasCodeIndirect = 0; - int originatorEquipmentNumber = 0; - int aesDdsId = 0; - - AreaEffectSimulationType aesType = AreaEffectSimulationType::Unknown; - int mineId = 0; - int remainEffectPercent = 0; - int remainEffectTasCodeDirect = 0; - int buildingId = 0; - int roomId = 0; - RelativePosition relPosition; - int reserve1 = 0; - int reserve2 = 0; - static CesHitRequest fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("CesHitRequest"); } - static constexpr TelegramId id() { return TelegramId::TREFFER_EREIGNIS_SEKUNDAERWIRKUNG; } -}; - - -struct TechnicalArea : TrainingAreaTelegramTmpl -{ - Header header; - int aesDdsId = 0; - - enum Type - { - Reserved = 0, - RemoveArea = 1, - MoutArea = 2, - RestingAreaPersonnel = 3, - RestingAreaVehicle = 4, - RestingAreaPersonnelAndVehicle = 5 - } taType = Type::Reserved; - std::string name; - RelativePosition relCorner; - int width = 0; - int height = 0; - - static TechnicalArea fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("TechnicalArea"); } - static constexpr TelegramId id() { return TelegramId::TECHNIK_FUNKTIONSRAUM; } -}; - - -struct ParticipantModeBase -{ - Header header; - Language language = Language::NoChange; - enum class OperationMode - { - NoChange = 0, - Normal = 1, - BeStill = 2 - } operationMode = OperationMode::NoChange; - int reactivationDetoxication; - int reactivationMaintenance; - int reactivationMedic; - enum class WphMode - { - NoChange = 0, - Without = 1, - With = 2 - }; - WphMode modeVest = WphMode::NoChange; - WphMode modeHelmet = WphMode::NoChange; - enum class PersonellProtection - { - NoChange = 0, - Without = 1, - Suit = 2, - SuitAndGloves = 3 - } personellProtectionMode = PersonellProtection::NoChange; - enum class ProtectionLevel - { - NoChange = 0, - IdzEs = 1, - IdzBs = 2, - Ksk = 3, - SoldierWithBodyArmor = 4, - SoldierActor = 5 - } protectionLevel = ProtectionLevel::NoChange; - enum class HandgrenadeSearchMode - { - NoChange = 0, - Off = 1, - On = 2 - } handgrenadeSearchMode = HandgrenadeSearchMode::NoChange; - - enum class InternationalMode - { - NoChange = 0, - Off = 1, - On = 2 - } internationalMode = InternationalMode::NoChange; - - enum class ABCProtectionMode - { - NoChange = 0, - Off = 1, - On = 2 - } abcProtectionMode = ABCProtectionMode::NoChange; - - static void fromJson(const QJsonObject &obj, ParticipantModeBase &ret); - QJsonObject toJson() const; -}; - - -struct ParticipantMode : TrainingAreaTelegramTmpl, ParticipantModeBase -{ - static ParticipantMode fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantMode"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_SETZEN; } -}; - - -struct ParticipantModeReport : TrainingAreaTelegramTmpl, ParticipantModeBase -{ - static ParticipantModeReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantModeReport"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_MELDUNG; } -}; - - -struct DemandParticipantMode : TrainingAreaTelegramTmpl -{ - Header header; - - static DemandParticipantMode fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DemandParticipantMode"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMERMODE_ANFORDERN; } -}; - - -struct ParticipantConfigurationBase -{ - Header header; - int positionIntervallVehicle = 0; - int positionIntervallPersonell = 0; - int positionIntervallAircraft = 0; - int positionTransmissionIntervall = 0; - int heightbarrier = 0; - enum class FaultPositionHandling - { - NoChange = 0, - NoPositions = 1, - InvalidPositionValue = 2, - EstimatedPosition = 3 - } faultPositionHandling = FaultPositionHandling::NoChange; - enum class SwitchingPositionIntervall - { - NoChange = 0, - On = 1, - Off = 2 - } switchingPositionIntervall = SwitchingPositionIntervall::NoChange; - int waittimeAdditionalBroadcastDemand = 0; - int factorWaittimeIncreaseAtHighload = 0; - int waittimeAutomaticVulnerabilityIncreaseLevel1 = 0; - int waittimeAutomaticVulnerabilityIncreaseLevel2 = 0; - int waittimeAutomaticVulnerabilityIncreaseLevel3 = 0; - enum class OpticalCode { - NoChange = 0, - Osag10 = 1, - Osag20Basic = 2, - SisoStandard = 3 - } opticalCode = OpticalCode::NoChange; - int vulnerabilityModel = 0; - int validTimeOps = 0; - - static void fromJson(const QJsonObject &obj, ParticipantConfigurationBase &ret); - QJsonObject toJson() const; -}; - - -struct ParticipantConfigurationReport : TrainingAreaTelegramTmpl, ParticipantConfigurationBase -{ - static ParticipantConfigurationReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantConfigurationReport"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_ANTWORT; } -}; - - -struct ParticipantConfiguration : TrainingAreaTelegramTmpl, ParticipantConfigurationBase -{ - static ParticipantConfiguration fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantConfiguration"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_SETZEN; } -}; - - -struct DemandParticipantConfiguration : TrainingAreaTelegramTmpl -{ - Header header; - - static DemandParticipantConfiguration fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("DemandParticipantConfiguration"); } - static constexpr TelegramId id() { return TelegramId::TEILNEHMER_KONFIG_ANFORDERN; } -}; - - -struct SanitationRepair : TrainingAreaTelegramTmpl -{ - Header header; - OriginatorType originatorType; - int equipmentNumberOrigin; - VulnerabilityState stateStart; - int typeOfTreatment; - int triage; - int tyeOfDamage; - VulnerabilityState stateResult; - enum class TreatmentResult { - None = 0, - Success = 1, - Stabilized = 2, - Failure = 3 - } treatmentResult = TreatmentResult::None; - int triagePriority; - int fullState; - int timeOfTreatment; - int timeOfRecovery; - - static SanitationRepair fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SanitationRepair"); } - static constexpr TelegramId id() { return TelegramId::SANITAETSDIENST_INSTANDSETZUNG; } -}; - - -struct SanitaryMaterialStockReport : TrainingAreaTelegramTmpl -{ - Header header; - int uniqueId; - int originatorEquipmentNumber; - Qualification qualification; - int sanitaryMaterialCount; - std::vector sanitaryMaterialStock; - - static SanitaryMaterialStockReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SanitaryMaterialStockReport"); } - static constexpr TelegramId id() { return TelegramId::BESTANDSMELDUNG_SANITAETSMATERIAL; } -}; - - -struct Sanitation : TrainingAreaTelegramTmpl -{ - Header header; - qint64 proceduresTaken; - SanitationResult sanitationResult; - SanitationEvaluation sanitationEvaluation; - int uniqeId; - int originatorEquipmentNumber; - Qualification qualification = Qualification::NotDefined; - static Sanitation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("Sanitation"); } - static constexpr TelegramId id() { return TelegramId::SANITAETSDIENST_INSTANDSETZUNG_PVSAN; } -}; - - -struct ExerciseStateData : TrainingAreaTelegramTmpl -{ - Header header; - - enum class ExerciseState - { - Unknown = 0, - Created = 1, - Started = 2, - Paused = 3, - Stopped = 5, - Terminated = 6 - } exerciseState = ExerciseState::Unknown; - int exerciseId = 0; - - static ExerciseStateData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExerciseStateData"); } - static constexpr TelegramId id() { return TelegramId::BETRIEBSZUSTANDSMELDUNG; } -}; - - -struct EmergencyCall : TrainingAreaTelegramTmpl -{ - int issi = 0; - AbsolutePosition absPosition; - qint64 timeStamp; - - static EmergencyCall fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("EmergencyCall"); } - static constexpr TelegramId id() { return TelegramId::NOTRUF; } -}; - - -struct RequestBroadcastStatistics : TrainingAreaTelegramTmpl -{ - Header header; - - static RequestBroadcastStatistics fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("RequestBroadcastStatistics"); } - static constexpr TelegramId id() { return TelegramId::ANFORDERUNG_STATISTIK_BROADCAST_NACHFORDERUNGEN; } -}; - - -struct BroadcastInformation -{ - int equipmentNumber = 0; - int broadcastRequests = 0; - - static BroadcastInformation fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - -struct BroadcastStatistics : TrainingAreaTelegramTmpl -{ - Header header; - std::vector information; - - static BroadcastStatistics fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("BroadcastStatistics"); } - static constexpr TelegramId id() { return TelegramId::STATISTIK_BROADCAST_NACHFORDERUNGEN; } -}; - - -struct GroupIssiInformation -{ - int exerciseId = 0; - int serverIssi = 0; - int broadcastIssi1 = 0; - int broadcastIssi2 = 0; - - static GroupIssiInformation fromJson(const QJsonObject &obj); - QJsonObject toJson() const; -}; - - -struct ExerciseEquipmentAssignmentComplete : TrainingAreaTelegramTmpl -{ - std::unordered_map> exerciseEquipmentAssignments; - std::vector groupIssiInformation; - - static ExerciseEquipmentAssignmentComplete fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExerciseEquipmentAssignmentComplete"); } - static constexpr TelegramId id() { return TelegramId::EXERCISE_EQUIPMENT_ASSIGNMENT_COMPLETE; } -}; - - - -struct ProxyConnectionState : public TrainingAreaTelegramTmpl -{ - bool connectedToSystem = false; - - static ProxyConnectionState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ProxyConnectionState"); } - static constexpr TelegramId id() { return TelegramId::PROXY_CONNECTION_STATE; } -}; - - - -struct ParticipantLicenseChange : public TrainingAreaTelegramTmpl -{ - int equipmentNumber = 0; - ParticipantLicenseState licenseState = ParticipantLicenseState::Unknown; - - static ParticipantLicenseChange fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ParticipantLicenseChange"); } - static constexpr TelegramId id() { return TelegramId::PARTICIPANT_LICENSE_CHANGE; } -}; - - -struct WlsParticipantsStateRequest : public TrainingAreaTelegramTmpl -{ - static WlsParticipantsStateRequest fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("WlsParticipantsStateRequest"); } - static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANTS_STATE_REQUEST; } -}; - - -struct WlsParticipantsStateReport : public TrainingAreaTelegramTmpl -{ - std::vector participantStates; - - static WlsParticipantsStateReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("WlsParticipantsStateReport"); } - static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANTS_STATE_REPORT; } -}; - - -struct WlsBinarySfmData : public TrainingAreaTelegramTmpl -{ - Header header; - std::vector payload; - - static WlsBinarySfmData fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("WlsBinarySfmData"); } - static constexpr TelegramId id() { return TelegramId::WLS_BINARY_SFM_DATA; } -}; - - -struct WlsParticipantsConnectionState : public TrainingAreaTelegramTmpl -{ - int equipmentNumber = 0; - bool dataCommunicationPossible = false; - - static WlsParticipantsConnectionState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("WlsParticipantsConnectionState"); } - static constexpr TelegramId id() { return TelegramId::WLS_PARTICIPANT_CONNECTION_STATE; } -}; - - -struct ApacheLaserDesignation : TrainingAreaTelegramTmpl -{ - Header header; - int gearId; - int code; - double outputPower; - AbsolutePosition spotLocation; - - static ApacheLaserDesignation fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ApacheLaserDesignation"); } - static constexpr TelegramId id() { return TelegramId::APACHE_LASER_DESIGNATION; } -}; - - -struct BatteryInfo : TrainingAreaTelegramTmpl -{ - Header header; - std::vector batteryStates; - - static BatteryInfo fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("BatteryInfo"); } - static constexpr TelegramId id() { return TelegramId::BATTERY_INFO; } -}; - - -struct BatteryAlarm : TrainingAreaTelegramTmpl -{ - Header m_header; - int m_id; - QString m_description; - bool m_acknowledge; - bool m_condition; - int m_uniqueAlarmNumber; - qint64 m_alarmTime; - - Header header() const { return m_header; } - QString description() const { return m_description; } - bool acknowledge() const { return m_acknowledge; } - bool condition() const { return m_condition; } - int uniqueAlarmNumber() const { return m_uniqueAlarmNumber; } - qint64 alarmTime() const { return m_alarmTime; } - - static BatteryAlarm fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("BatteryAlarm"); } - static constexpr TelegramId id() { return TelegramId::BATTERY_ALARM; } -}; - - -struct ServiceControl : TrainingAreaTelegramTmpl -{ - Header header; - ServiceControlEnum serviceControlState; - - static ServiceControl fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ServiceControl"); } - static constexpr TelegramId id() { return TelegramId::SERVICE_CONTROL; } -}; - - -struct SetDevicePowerRequest : TrainingAreaTelegramTmpl -{ - Header header; - PowerMethod powerType; - int subdeviceId; - - static SetDevicePowerRequest fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("SetPowerDeviceRequest"); } - static constexpr TelegramId id() { return TelegramId::DEVICE_POWER_SET_REQUEST; } -}; - - -struct UAVPerformMission : TrainingAreaTelegramTmpl -{ - Header header; - std::vector actions; - int missionId; - QString missionName; - - static UAVPerformMission fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString ACTIONS() { return QLatin1String("actions"); } - static QString MISSION_ID() { return QLatin1String("missionId"); } - static QString MISSION_NAME() { return QLatin1String("missionName"); } -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("UAVPerformMission"); } - static constexpr TelegramId id() { return TelegramId::UAV_PERFORM_MISSION; } -}; - - -struct UAVStatus : TrainingAreaTelegramTmpl -{ - Header header; - UAVState uavState; - - static UAVStatus fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString UAVSTATE() { return QLatin1String("uavState"); } -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("UAVState"); } - static constexpr TelegramId id() { return TelegramId::UAV_STATUS; } -}; - - -struct UAVRadioLinkConnectionStatus : TrainingAreaTelegramTmpl -{ - Header header; - UAVRadioLinkConnectionStatusType uavConnectionState; - - static UAVRadioLinkConnectionStatus fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString UAVCONNECTIONSTATE() { return QLatin1String("uavConnectionState"); } -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("UAVRadioLinkConnectionStatus"); } - static constexpr TelegramId id() { return TelegramId::UAV_RADIO_LINK_CONNECTION_STATUS; } -}; - - -struct UAVMissionStatus : TrainingAreaTelegramTmpl -{ - Header header; - UAVActionTask currentAction; - QString currentMissionName; - QString missionEnded; - - static UAVMissionStatus fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString CURRENT_ACTION() { return QLatin1String("currentAction"); } - static QString CURRENT_MISSION_NAME() { return QLatin1String("currentMissionName"); } - static QString MISSION_ENDED() { return QLatin1String("missionEnded"); } -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("UAVMissionStatus"); } - static constexpr TelegramId id() { return TelegramId::UAV_MISSION_STATUS; } -}; - - -struct UAVChangeState : TrainingAreaTelegramTmpl -{ - Header header; - UAVState requestedState; - - static UAVChangeState fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString REQUESTED_STATE() { return QLatin1String("requestedState"); } - -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("UAVChangeState"); } - static constexpr TelegramId id() { return TelegramId::UAV_CHANGE_STATE; } -}; - - - -struct ExFireReadiness : TrainingAreaTelegramTmpl -{ - Header header; - int partyId; - QString reference; - - - static ExFireReadiness fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString PARTY_ID() { return QLatin1String("partyId"); } - static QString REFERENCE() { return QLatin1String("reference"); } -}; - -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExFiredReport"); } - static constexpr TelegramId id() { return TelegramId::EX_FIRE_READINESS; } -}; - - -struct ExFiredReport : TrainingAreaTelegramTmpl -{ - Header header; - int partyId; - QString reference; - QString unitIdentifier; - QString identifier; - - static ExFiredReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString PARTY_ID() { return QLatin1String("partyId"); } - static QString REFERENCE() { return QLatin1String("reference"); } - static QString UNIT_IDENTIFIER() { return QLatin1String("unitIdentifier"); } - static QString IDENTIFIER() { return QLatin1String("identifier"); } - - -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExFiredReport"); } - static constexpr TelegramId id() { return TelegramId::EX_FIRED_REPORT; } -}; - - -struct ExConfirmationReport : TrainingAreaTelegramTmpl -{ - Header header; - int partyId; - QString reference; - QString unitIdentifier; - QString identifier; - - static ExConfirmationReport fromJson(const QJsonObject &obj); - QJsonObject toJson() const override; - - static QString HEADER() { return QLatin1String("header"); } - static QString PARTY_ID() { return QLatin1String("partyId"); } - static QString REFERENCE() { return QLatin1String("reference"); } - static QString UNIT_IDENTIFIER() { return QLatin1String("unitIdentifier"); } - static QString IDENTIFIER() { return QLatin1String("identifier"); } - - -}; -template <> struct Constraints -{ - static QString type() { return QStringLiteral("ExConfirmationReport"); } - static constexpr TelegramId id() { return TelegramId::EX_CONFIRMATION_REPORT; } -}; - -} -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/ProjectDataManagement/pdm.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/ProjectDataManagement/pdm.hpp index d786915c6..d19d9b137 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/ProjectDataManagement/pdm.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/ProjectDataManagement/pdm.hpp @@ -13,34 +13,39 @@ // Forward declarations and stub types for ProjectDataManagement namespace // Used when BUILD_RTI=OFF to allow compilation without RTI Connext DDS -namespace ProjectDataManagement { +namespace ProjectDataManagement +{ -// Stub types for RTI IDL-generated classes -struct RadioGroup { + // Stub types for RTI IDL-generated classes + struct RadioGroup + { int m_id = 0; int id() const { return m_id; } void id(int val) { m_id = val; } -}; + }; -struct ChargeType { + struct ChargeType + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct GearClass { + struct GearClass + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct GearType { + struct GearType + { int m_id = 0; int m_gearClassId = 0; QString m_properties; @@ -49,10 +54,11 @@ struct GearType { int gearClassId() const { return m_gearClassId; } void gearClassId(int val) { m_gearClassId = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct GearTypeChargeType { + struct GearTypeChargeType + { int m_id = 0; int m_gearTypeId = 0; int m_chargeTypeId = 0; @@ -64,64 +70,71 @@ struct GearTypeChargeType { int chargeTypeId() const { return m_chargeTypeId; } void chargeTypeId(int val) { m_chargeTypeId = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct BuildingChargeEffect { + struct BuildingChargeEffect + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct VulnerabilityKind { + struct VulnerabilityKind + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct IgniterType { + struct IgniterType + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct LoadType { + struct LoadType + { int m_id = 0; QString m_properties; int id() const { return m_id; } void id(int val) { m_id = val; } QString properties() const { return m_properties; } - void properties(const QString& val) { m_properties = val; } -}; + void properties(const QString &val) { m_properties = val; } + }; -struct CanComponentString { + struct CanComponentString + { int m_id = 0; QString m_text; int id() const { return m_id; } void id(int val) { m_id = val; } QString text() const { return m_text; } - void text(const QString& val) { m_text = val; } -}; + void text(const QString &val) { m_text = val; } + }; -struct BiteComponentText { + struct BiteComponentText + { int m_id = 0; QString m_text; int id() const { return m_id; } void id(int val) { m_id = val; } QString text() const { return m_text; } - void text(const QString& val) { m_text = val; } -}; + void text(const QString &val) { m_text = val; } + }; -struct SanitationProcedure { + struct SanitationProcedure + { int m_id = 0; QString m_name; QString m_longName; @@ -130,15 +143,15 @@ struct SanitationProcedure { int m_minimumQualification = 0; int m_dataCode = 0; QString m_version; - + int id() const { return m_id; } void id(int val) { m_id = val; } QString name() const { return m_name; } - void name(const QString& val) { m_name = val; } + void name(const QString &val) { m_name = val; } QString longName() const { return m_longName; } - void longName(const QString& val) { m_longName = val; } + void longName(const QString &val) { m_longName = val; } QString type() const { return m_type; } - void type(const QString& val) { m_type = val; } + void type(const QString &val) { m_type = val; } int typeId() const { return m_typeId; } void typeId(int val) { m_typeId = val; } int minimumQualification() const { return m_minimumQualification; } @@ -146,21 +159,22 @@ struct SanitationProcedure { int dataCode() const { return m_dataCode; } void dataCode(int val) { m_dataCode = val; } QString version() const { return m_version; } - void version(const QString& val) { m_version = val; } -}; + void version(const QString &val) { m_version = val; } + }; -struct SanitationInjury { + struct SanitationInjury + { int m_id = 0; QString m_name; int m_kind = 0; int m_place1 = 0; int m_place2 = 0; int m_vbg = 0; - + int id() const { return m_id; } void id(int val) { m_id = val; } QString name() const { return m_name; } - void name(const QString& val) { m_name = val; } + void name(const QString &val) { m_name = val; } int kind() const { return m_kind; } void kind(int val) { m_kind = val; } int place1() const { return m_place1; } @@ -169,13 +183,14 @@ struct SanitationInjury { void place2(int val) { m_place2 = val; } int vbg() const { return m_vbg; } void vbg(int val) { m_vbg = val; } -}; + }; -// Forward declaration for Interface::Dtc -namespace Interface { -class Dtc; -} + // Forward declaration for Interface::Dtc + namespace Interface + { + class Dtc; + } } // namespace ProjectDataManagement -#endif // PDM_HPP \ No newline at end of file +#endif // PDM_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_db_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_db_stub.hpp index 2929ef62a..86581a4e9 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_db_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_db_stub.hpp @@ -6,16 +6,19 @@ #include "pdm_enums_stub.hpp" -namespace pdm { -namespace db { +namespace pdm +{ + namespace db + { -// Stub class to replace RTI IDL-generated database types -class ProjectDatabase { -public: - virtual ~ProjectDatabase() = default; -}; + // Stub class to replace RTI IDL-generated database types + class ProjectDatabase + { + public: + virtual ~ProjectDatabase() = default; + }; -} // namespace db + } // namespace db } // namespace pdm -#endif // PDM_DB_STUB_HPP \ No newline at end of file +#endif // PDM_DB_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_enums_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_enums_stub.hpp index 5c5d4815f..52ba052b5 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_enums_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_enums_stub.hpp @@ -4,23 +4,28 @@ #ifndef PDM_ENUMS_STUB_HPP #define PDM_ENUMS_STUB_HPP -namespace pdm { -namespace enums { +namespace pdm +{ + namespace enums + { -// Stub enums to replace RTI IDL-generated types -enum class ProjectState : int { - Unknown = 0 -}; + // Stub enums to replace RTI IDL-generated types + enum class ProjectState : int + { + Unknown = 0 + }; -enum class ProjectType : int { - Unknown = 0 -}; + enum class ProjectType : int + { + Unknown = 0 + }; -enum class GearClass : int { - Unknown = 0 -}; + enum class GearClass : int + { + Unknown = 0 + }; -} // namespace enums + } // namespace enums } // namespace pdm -#endif // PDM_ENUMS_STUB_HPP \ No newline at end of file +#endif // PDM_ENUMS_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_stub.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_stub.hpp index 1d90d2f43..37073b14e 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_stub.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/ProjectDataManagement/stubs/pdm_stub.hpp @@ -6,17 +6,20 @@ #include "pdm_enums_stub.hpp" -namespace pdm { +namespace pdm +{ -// Stub structs to replace RTI IDL-generated types -struct ProjectData { + // Stub structs to replace RTI IDL-generated types + struct ProjectData + { int id = 0; -}; + }; -struct ProjectConfig { + struct ProjectConfig + { int projectId = 0; -}; + }; } // namespace pdm -#endif // PDM_STUB_HPP \ No newline at end of file +#endif // PDM_STUB_HPP diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.cpp index 7b89d8c7c..82f2ec86a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.cpp @@ -12,76 +12,76 @@ namespace N_CoPrtCnv { -void CoPrtCnvCentralTelegram::setData(const QByteArray &data) -{ - m_data = data; - m_json = QJsonObject(); -} - -QByteArray CoPrtCnvCentralTelegram::data() -{ - ensureByteArray(); - return m_data; -} - -QJsonObject CoPrtCnvCentralTelegram::json() -{ - ensureJson(); - return m_json; -} - -QJsonObject CoPrtCnvCentralTelegram::jsonData() -{ - return json()[QStringLiteral("data")].toObject(); -} - -TrainingAreaBase::TetraIcd::TelegramId CoPrtCnvCentralTelegram::telegramId() -{ - if (m_telegramId != TrainingAreaBase::TetraIcd::UNKNOWN) - return m_telegramId; - - ensureJson(); - m_telegramId = static_cast(m_json[QStringLiteral("typeId")].toInt()); - return m_telegramId; -} - -void CoPrtCnvCentralTelegram::setCounter(qint32 counter) -{ - if (m_json.isEmpty()) - m_json = QJsonDocument::fromJson(m_data).object(); - m_json[QStringLiteral("counter")] = counter; - m_data.clear(); -} - -qint32 CoPrtCnvCentralTelegram::counter() -{ - ensureJson(); - const QString key(QStringLiteral("counter")); - const QJsonValue sendCounter(m_json[key]); - if (!sendCounter.isDouble()) - throw TrainingAreaBase::TetraIcd::JsonException(m_json, key); - return sendCounter.toInt(-1); -} - -void CoPrtCnvCentralTelegram::ensureJson() -{ - if (m_json.isEmpty()) + void CoPrtCnvCentralTelegram::setData(const QByteArray &data) { - if (m_data.isEmpty()) - return; - m_json = QJsonDocument::fromJson(m_data).object(); + m_data = data; + m_json = QJsonObject(); } -} -void CoPrtCnvCentralTelegram::ensureByteArray() -{ - if (m_data.isEmpty()) + QByteArray CoPrtCnvCentralTelegram::data() + { + ensureByteArray(); + return m_data; + } + + QJsonObject CoPrtCnvCentralTelegram::json() + { + ensureJson(); + return m_json; + } + + QJsonObject CoPrtCnvCentralTelegram::jsonData() + { + return json()[QStringLiteral("data")].toObject(); + } + + TrainingAreaBase::TetraIcd::TelegramId CoPrtCnvCentralTelegram::telegramId() + { + if (m_telegramId != TrainingAreaBase::TetraIcd::UNKNOWN) + return m_telegramId; + + ensureJson(); + m_telegramId = static_cast(m_json[QStringLiteral("typeId")].toInt()); + return m_telegramId; + } + + void CoPrtCnvCentralTelegram::setCounter(qint32 counter) { if (m_json.isEmpty()) - return; - m_data = QJsonDocument(m_json).toJson(QJsonDocument::Compact); + m_json = QJsonDocument::fromJson(m_data).object(); + m_json[QStringLiteral("counter")] = counter; + m_data.clear(); + } + + qint32 CoPrtCnvCentralTelegram::counter() + { + ensureJson(); + const QString key(QStringLiteral("counter")); + const QJsonValue sendCounter(m_json[key]); + if (!sendCounter.isDouble()) + throw TrainingAreaBase::TetraIcd::JsonException(m_json, key); + return sendCounter.toInt(-1); + } + + void CoPrtCnvCentralTelegram::ensureJson() + { + if (m_json.isEmpty()) + { + if (m_data.isEmpty()) + return; + m_json = QJsonDocument::fromJson(m_data).object(); + } + } + + void CoPrtCnvCentralTelegram::ensureByteArray() + { + if (m_data.isEmpty()) + { + if (m_json.isEmpty()) + return; + m_data = QJsonDocument(m_json).toJson(QJsonDocument::Compact); + } } -} } // namespace N_CoPrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.hpp index 55e1362e7..51e6a9b53 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvCentralTelegram.hpp @@ -24,24 +24,28 @@ namespace N_CoPrtCnv { public: explicit CoPrtCnvCentralTelegram(TrainingAreaBase::TetraIcd::TelegramId telegramId) - : m_telegramId(telegramId) - {} + : m_telegramId(telegramId) + { + } explicit CoPrtCnvCentralTelegram(const QByteArray &data) - : m_data(data) - , m_telegramId(TrainingAreaBase::TetraIcd::UNKNOWN) - {} + : m_data(data) + , m_telegramId(TrainingAreaBase::TetraIcd::UNKNOWN) + { + } CoPrtCnvCentralTelegram(const QByteArray &data, TrainingAreaBase::TetraIcd::TelegramId telegramId) - : m_data(data) - , m_telegramId(telegramId) - {} + : m_data(data) + , m_telegramId(telegramId) + { + } CoPrtCnvCentralTelegram(const QByteArray &data, const QJsonObject &json, TrainingAreaBase::TetraIcd::TelegramId telegramId) - : m_data(data) - , m_json(json) - , m_telegramId(telegramId) - {} + : m_data(data) + , m_json(json) + , m_telegramId(telegramId) + { + } explicit CoPrtCnvCentralTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram &tele) - : m_telegramId(tele.id()) + : m_telegramId(tele.id()) { m_json[QStringLiteral("type")] = tele.type(); m_json[QStringLiteral("typeId")] = tele.id(); @@ -50,8 +54,8 @@ namespace N_CoPrtCnv void setData(const QByteArray &data); QByteArray data(); - QJsonObject json(); // complete json - QJsonObject jsonData(); // json()["data"] + QJsonObject json(); // complete json + QJsonObject jsonData(); // json()["data"] TrainingAreaBase::TetraIcd::TelegramId telegramId(); void setCounter(qint32 counter); qint32 counter(); @@ -59,6 +63,7 @@ namespace N_CoPrtCnv private: void ensureJson(); void ensureByteArray(); + private: QByteArray m_data; QJsonObject m_json; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.cpp index 6e3e39720..cec20c78e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.cpp @@ -18,14 +18,15 @@ #include #include -static std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram* sammelTelegram) +static std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram *sammelTelegram) { const int ANZAHL_POS = 5; - const int SIZE_POS = sammelTelegram->getTelID() == GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN ? 2 : 1; + const int SIZE_POS = sammelTelegram->getTelID() == GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN ? 2 : 1; std::stringstream sstream; unsigned int cnt = sammelTelegram->getPayloadDataUInt32(ANZAHL_POS, SIZE_POS); // anzahl - for (unsigned int i = 0; i < cnt; ++i) { + for (unsigned int i = 0; i < cnt; ++i) + { uint16_t telId = sammelTelegram->getPayloadDataUInt32(ANZAHL_POS + SIZE_POS + 2 * i, 2); // add kennung sstream << telId << " "; } @@ -37,94 +38,269 @@ QByteArray telegramId2String(gef_telegramm_id_et telId) const char *str = nullptr; switch (telId) { - case GEF_BESTAETIGUNG: str = "GEF_BESTAETIGUNG"; break; - case GEF_INIT: str = "GEF_INIT"; break; - case GEF_MANIPULATIONSMELDUNG: str = "GEF_MANIPULATIONSMELDUNG"; break; - case GEF_UMGEBUNGS_MELDUNG2: str = "GEF_UMGEBUNGS_MELDUNG2"; break; - case GEF_AUFFORDERUNG_BITE_MELDUNG: str = "GEF_AUFFORDERUNG_BITE_MELDUNG"; break; - case GEF_BITE_MELDUNG2: str = "GEF_BITE_MELDUNG2"; break; - case GEF_LIZENSIERUNG_TNE: str = "GEF_LIZENSIERUNG_TNE"; break; - case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: str = "GEF_BETRIEBSZUSTAND_AUSSTATTUNG"; break; - case GEF_KONFIGURATION_WIRKMODELL: str = "GEF_KONFIGURATION_WIRKMODELL"; break; - case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: str = "GEF_ANFORDERUNG_KONFIGURATIONSDATEN"; break; - case GEF_KONFIGURATIONSMELDUNG: str = "GEF_KONFIGURATIONSMELDUNG"; break; - case GEF_FEHLERMELDUNG_GFD: str = "GEF_FEHLERMELDUNG_GFD"; break; - case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: str = "GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT"; break; - case GEF_POSITIONS_MELDUNG: str = "GEF_POSITIONS_MELDUNG"; break; - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: str = "GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER"; break; - case GEF_POSITIONS_MELDUNG_LFZ: str = "GEF_POSITIONS_MELDUNG_LFZ"; break; - case GEF_IPS_POSITIONSDATEN: str = "GEF_IPS_POSITIONSDATEN"; break; - case GEF_SCHIEDSRICHTERKOMMANDO: str = "GEF_SCHIEDSRICHTERKOMMANDO"; break; - case GEF_WIRKFELD_EINZELGESCHOSS: str = "GEF_WIRKFELD_EINZELGESCHOSS"; break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER"; break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP"; break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN"; break; - case GEF_WIRKFELD_MINENSPERRE: str = "GEF_WIRKFELD_MINENSPERRE"; break; - case GEF_WIRKFELD_STATUS_MINENSPERRE: str = "GEF_WIRKFELD_STATUS_MINENSPERRE"; break; - case GEF_WIRKFELD_A_KAMPFMITTEL: str = "GEF_WIRKFELD_A_KAMPFMITTEL"; break; - case GEF_WIRKFELD_C_KAMPFMITTEL: str = "GEF_WIRKFELD_C_KAMPFMITTEL"; break; - case GEF_DEAKTIVIERUNG_WIRKFELD: str = "GEF_DEAKTIVIERUNG_WIRKFELD"; break; - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: str = "GEF_WIRKFELD_AENDERUNG_BEZEICHNER"; break; - case GEF_DEAKTIVIERUNG_EINZELMINE: str = "GEF_DEAKTIVIERUNG_EINZELMINE"; break; - case GEF_REAKTIVIERUNG_DUS_MINE: str = "GEF_REAKTIVIERUNG_DUS_MINE"; break; - case GEF_DEFINITION_IED: str = "GEF_DEFINITION_IED"; break; - case GEF_ZUSTAND_IED: str = "GEF_ZUSTAND_IED"; break; - case GEF_STATUS_EINZELMINENSIMULATOR: str = "GEF_STATUS_EINZELMINENSIMULATOR"; break; - case GEF_WIRKFELD_EINZELMINENSIMULATOR: str = "GEF_WIRKFELD_EINZELMINENSIMULATOR"; break; - case GEF_TREFFER_EREIGNIS_DUS: str = "GEF_TREFFER_EREIGNIS_DUS"; break; - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: str = "GEF_TREFFER_EREIGNIS_WIRKSIMULATION"; break; - case GEF_TREFFER_AUSLOESUNG: str = "GEF_TREFFER_AUSLOESUNG"; break; - case GEF_SCHIEDSRICHTEREINGRIFF: str = "GEF_SCHIEDSRICHTEREINGRIFF"; break; - case GEF_SELEKTIVE_AUFMUNITIONIERUNG: str = "GEF_SELEKTIVE_AUFMUNITIONIERUNG"; break; - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: str = "GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG"; break; - case GEF_TREFFER_EREIGNIS_DUS_IPS: str = "GEF_TREFFER_EREIGNIS_DUS_IPS"; break; - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: str = "GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS"; break; - case GEF_TAKTISCHER_STATUS: str = "GEF_TAKTISCHER_STATUS"; break; - case GEF_FUNKTIONSRAUM: str = "GEF_FUNKTIONSRAUM"; break; - case GEF_EINTRETEN_FUNKTIONSRAUM: str = "GEF_EINTRETEN_FUNKTIONSRAUM"; break; - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: str = "GEF_DEAKTIVIEREN_FUNKTIONSRAUM"; break; - case GEF_DATENVERKEHR_SRT_TDS: str = "GEF_DATENVERKEHR_SRT_TDS"; break; - case GEF_DATENVERKEHR_TDS_SRT: str = "GEF_DATENVERKEHR_TDS_SRT"; break; - case GEF_DATENVERKEHR_DMF_TDS: str = "GEF_DATENVERKEHR_DMF_TDS"; break; - case GEF_DATENVERKEHR_TDS_DMF: str = "GEF_DATENVERKEHR_TDS_DMF"; break; - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: str = "GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME"; break; - case GEF_NOP: str = "GEF_NOP"; break; - case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: str = "GEF_SONDERSENSORIK_BETRIEBSZUSTAND"; break; - case GEF_SONDERSENSORIK_FAHRSPUR: str = "GEF_SONDERSENSORIK_FAHRSPUR"; break; - case GEF_SONDERSENSORIK_DATEN: str = "GEF_SONDERSENSORIK_DATEN"; break; - case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: str = "GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN"; break; - case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: str = "GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN"; break; - case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: str = "GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION"; break; - case GEF_SPRACHAUSWAHL: str = "GEF_SPRACHAUSWAHL"; break; - case GEF_ALLGEMEINE_NACHRICHT: str = "GEF_ALLGEMEINE_NACHRICHT"; break; - case GEF_ECHO_ON_OFF: str = "GEF_ECHO_ON_OFF"; break; - case GEF_ESW_MELDUNG: str = "GEF_ESW_MELDUNG"; break; - case GEF_WF_SAMMELDEAKTIVIERUNG: str = "GEF_WF_SAMMELDEAKTIVIERUNG"; break; - case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: str = "GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN"; break; - case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: str = "GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM"; break; - case GEF_DATENVERKEHR_GEOP_TDS: str = "GEF_DATENVERKEHR_GEOP_TDS"; break; - case GEF_DATENVERKEHR_TDS_GEOP: str = "GEF_DATENVERKEHR_TDS_GEOP"; break; - case GEF_DATENVERKEHR_TGTC_TDS: str = "GEF_DATENVERKEHR_TGTC_TDS"; break; - case GEF_DATENVERKEHR_TDS_TGTC: str = "GEF_DATENVERKEHR_TDS_TGTC"; break; - case GEF_GERAETEEREIGNIS: str = "GEF_GERAETEEREIGNIS"; break; - case GEF_WAFFENZUORDNUNG: str = "GEF_WAFFENZUORDNUNG"; break; - case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: str = "GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE"; break; - case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: str = "GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG"; break; - case GEF_AUSLOESUNG_DUS_TREFFER: str = "GEF_AUSLOESUNG_DUS_TREFFER"; break; - case GEF_ANFORDERUNG_SW_VERSION: str = "GEF_ANFORDERUNG_SW_VERSION"; break; - case GEF_SW_VERSIONSMELDUNG: str = "GEF_SW_VERSIONSMELDUNG"; break; - case GEF_TECHNIK_FUNKTIONSRAUM: str = "GEF_TECHNIK_FUNKTIONSRAUM"; break; - case GEF_TEILNEHMERMODE_SETZEN: str = "GEF_TEILNEHMERMODE_SETZEN"; break; - case GEF_TEILNEHMERMODE_MELDUNG: str = "GEF_TEILNEHMERMODE_MELDUNG"; break; - case GEF_TEILNEHMERMODE_ANFORDERN: str = "GEF_TEILNEHMERMODE_ANFORDERN"; break; - case GEF_TEILNEHMER_KONFIG_ANTWORT: str = "GEF_TEILNEHMER_KONFIG_ANTWORT"; break; - case GEF_TEILNEHMER_KONFIG_SETZEN: str = "GEF_TEILNEHMER_KONFIG_SETZEN"; break; - case GEF_TEILNEHMER_KONFIG_ANFORDERN: str = "GEF_TEILNEHMER_KONFIG_ANFORDERN"; break; - case GEF_SANITAETSDIENST_INSTANDSETZUNG: str = "GEF_SANITAETSDIENST_INSTANDSETZUNG"; break; - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: str = "GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN"; break; - case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: str = "GEF_BESTANDSMELDUNG_SANITAETSMATERIAL"; break; - case GEF_GEFECHTSFELDTELEGRAMM: str = "GEF_GEFECHTSFELDTELEGRAMM"; break; - default: break; + case GEF_BESTAETIGUNG: + str = "GEF_BESTAETIGUNG"; + break; + case GEF_INIT: + str = "GEF_INIT"; + break; + case GEF_MANIPULATIONSMELDUNG: + str = "GEF_MANIPULATIONSMELDUNG"; + break; + case GEF_UMGEBUNGS_MELDUNG2: + str = "GEF_UMGEBUNGS_MELDUNG2"; + break; + case GEF_AUFFORDERUNG_BITE_MELDUNG: + str = "GEF_AUFFORDERUNG_BITE_MELDUNG"; + break; + case GEF_BITE_MELDUNG2: + str = "GEF_BITE_MELDUNG2"; + break; + case GEF_LIZENSIERUNG_TNE: + str = "GEF_LIZENSIERUNG_TNE"; + break; + case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: + str = "GEF_BETRIEBSZUSTAND_AUSSTATTUNG"; + break; + case GEF_KONFIGURATION_WIRKMODELL: + str = "GEF_KONFIGURATION_WIRKMODELL"; + break; + case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: + str = "GEF_ANFORDERUNG_KONFIGURATIONSDATEN"; + break; + case GEF_KONFIGURATIONSMELDUNG: + str = "GEF_KONFIGURATIONSMELDUNG"; + break; + case GEF_FEHLERMELDUNG_GFD: + str = "GEF_FEHLERMELDUNG_GFD"; + break; + case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: + str = "GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT"; + break; + case GEF_POSITIONS_MELDUNG: + str = "GEF_POSITIONS_MELDUNG"; + break; + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: + str = "GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER"; + break; + case GEF_POSITIONS_MELDUNG_LFZ: + str = "GEF_POSITIONS_MELDUNG_LFZ"; + break; + case GEF_IPS_POSITIONSDATEN: + str = "GEF_IPS_POSITIONSDATEN"; + break; + case GEF_SCHIEDSRICHTERKOMMANDO: + str = "GEF_SCHIEDSRICHTERKOMMANDO"; + break; + case GEF_WIRKFELD_EINZELGESCHOSS: + str = "GEF_WIRKFELD_EINZELGESCHOSS"; + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER"; + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP"; + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + str = "GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN"; + break; + case GEF_WIRKFELD_MINENSPERRE: + str = "GEF_WIRKFELD_MINENSPERRE"; + break; + case GEF_WIRKFELD_STATUS_MINENSPERRE: + str = "GEF_WIRKFELD_STATUS_MINENSPERRE"; + break; + case GEF_WIRKFELD_A_KAMPFMITTEL: + str = "GEF_WIRKFELD_A_KAMPFMITTEL"; + break; + case GEF_WIRKFELD_C_KAMPFMITTEL: + str = "GEF_WIRKFELD_C_KAMPFMITTEL"; + break; + case GEF_DEAKTIVIERUNG_WIRKFELD: + str = "GEF_DEAKTIVIERUNG_WIRKFELD"; + break; + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + str = "GEF_WIRKFELD_AENDERUNG_BEZEICHNER"; + break; + case GEF_DEAKTIVIERUNG_EINZELMINE: + str = "GEF_DEAKTIVIERUNG_EINZELMINE"; + break; + case GEF_REAKTIVIERUNG_DUS_MINE: + str = "GEF_REAKTIVIERUNG_DUS_MINE"; + break; + case GEF_DEFINITION_IED: + str = "GEF_DEFINITION_IED"; + break; + case GEF_ZUSTAND_IED: + str = "GEF_ZUSTAND_IED"; + break; + case GEF_STATUS_EINZELMINENSIMULATOR: + str = "GEF_STATUS_EINZELMINENSIMULATOR"; + break; + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + str = "GEF_WIRKFELD_EINZELMINENSIMULATOR"; + break; + case GEF_TREFFER_EREIGNIS_DUS: + str = "GEF_TREFFER_EREIGNIS_DUS"; + break; + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: + str = "GEF_TREFFER_EREIGNIS_WIRKSIMULATION"; + break; + case GEF_TREFFER_AUSLOESUNG: + str = "GEF_TREFFER_AUSLOESUNG"; + break; + case GEF_SCHIEDSRICHTEREINGRIFF: + str = "GEF_SCHIEDSRICHTEREINGRIFF"; + break; + case GEF_SELEKTIVE_AUFMUNITIONIERUNG: + str = "GEF_SELEKTIVE_AUFMUNITIONIERUNG"; + break; + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + str = "GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG"; + break; + case GEF_TREFFER_EREIGNIS_DUS_IPS: + str = "GEF_TREFFER_EREIGNIS_DUS_IPS"; + break; + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: + str = "GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS"; + break; + case GEF_TAKTISCHER_STATUS: + str = "GEF_TAKTISCHER_STATUS"; + break; + case GEF_FUNKTIONSRAUM: + str = "GEF_FUNKTIONSRAUM"; + break; + case GEF_EINTRETEN_FUNKTIONSRAUM: + str = "GEF_EINTRETEN_FUNKTIONSRAUM"; + break; + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + str = "GEF_DEAKTIVIEREN_FUNKTIONSRAUM"; + break; + case GEF_DATENVERKEHR_SRT_TDS: + str = "GEF_DATENVERKEHR_SRT_TDS"; + break; + case GEF_DATENVERKEHR_TDS_SRT: + str = "GEF_DATENVERKEHR_TDS_SRT"; + break; + case GEF_DATENVERKEHR_DMF_TDS: + str = "GEF_DATENVERKEHR_DMF_TDS"; + break; + case GEF_DATENVERKEHR_TDS_DMF: + str = "GEF_DATENVERKEHR_TDS_DMF"; + break; + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: + str = "GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME"; + break; + case GEF_NOP: + str = "GEF_NOP"; + break; + case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: + str = "GEF_SONDERSENSORIK_BETRIEBSZUSTAND"; + break; + case GEF_SONDERSENSORIK_FAHRSPUR: + str = "GEF_SONDERSENSORIK_FAHRSPUR"; + break; + case GEF_SONDERSENSORIK_DATEN: + str = "GEF_SONDERSENSORIK_DATEN"; + break; + case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: + str = "GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN"; + break; + case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: + str = "GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN"; + break; + case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: + str = "GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION"; + break; + case GEF_SPRACHAUSWAHL: + str = "GEF_SPRACHAUSWAHL"; + break; + case GEF_ALLGEMEINE_NACHRICHT: + str = "GEF_ALLGEMEINE_NACHRICHT"; + break; + case GEF_ECHO_ON_OFF: + str = "GEF_ECHO_ON_OFF"; + break; + case GEF_ESW_MELDUNG: + str = "GEF_ESW_MELDUNG"; + break; + case GEF_WF_SAMMELDEAKTIVIERUNG: + str = "GEF_WF_SAMMELDEAKTIVIERUNG"; + break; + case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: + str = "GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN"; + break; + case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: + str = "GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM"; + break; + case GEF_DATENVERKEHR_GEOP_TDS: + str = "GEF_DATENVERKEHR_GEOP_TDS"; + break; + case GEF_DATENVERKEHR_TDS_GEOP: + str = "GEF_DATENVERKEHR_TDS_GEOP"; + break; + case GEF_DATENVERKEHR_TGTC_TDS: + str = "GEF_DATENVERKEHR_TGTC_TDS"; + break; + case GEF_DATENVERKEHR_TDS_TGTC: + str = "GEF_DATENVERKEHR_TDS_TGTC"; + break; + case GEF_GERAETEEREIGNIS: + str = "GEF_GERAETEEREIGNIS"; + break; + case GEF_WAFFENZUORDNUNG: + str = "GEF_WAFFENZUORDNUNG"; + break; + case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: + str = "GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE"; + break; + case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: + str = "GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG"; + break; + case GEF_AUSLOESUNG_DUS_TREFFER: + str = "GEF_AUSLOESUNG_DUS_TREFFER"; + break; + case GEF_ANFORDERUNG_SW_VERSION: + str = "GEF_ANFORDERUNG_SW_VERSION"; + break; + case GEF_SW_VERSIONSMELDUNG: + str = "GEF_SW_VERSIONSMELDUNG"; + break; + case GEF_TECHNIK_FUNKTIONSRAUM: + str = "GEF_TECHNIK_FUNKTIONSRAUM"; + break; + case GEF_TEILNEHMERMODE_SETZEN: + str = "GEF_TEILNEHMERMODE_SETZEN"; + break; + case GEF_TEILNEHMERMODE_MELDUNG: + str = "GEF_TEILNEHMERMODE_MELDUNG"; + break; + case GEF_TEILNEHMERMODE_ANFORDERN: + str = "GEF_TEILNEHMERMODE_ANFORDERN"; + break; + case GEF_TEILNEHMER_KONFIG_ANTWORT: + str = "GEF_TEILNEHMER_KONFIG_ANTWORT"; + break; + case GEF_TEILNEHMER_KONFIG_SETZEN: + str = "GEF_TEILNEHMER_KONFIG_SETZEN"; + break; + case GEF_TEILNEHMER_KONFIG_ANFORDERN: + str = "GEF_TEILNEHMER_KONFIG_ANFORDERN"; + break; + case GEF_SANITAETSDIENST_INSTANDSETZUNG: + str = "GEF_SANITAETSDIENST_INSTANDSETZUNG"; + break; + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: + str = "GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN"; + break; + case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: + str = "GEF_BESTANDSMELDUNG_SANITAETSMATERIAL"; + break; + case GEF_GEFECHTSFELDTELEGRAMM: + str = "GEF_GEFECHTSFELDTELEGRAMM"; + break; + default: + break; } Q_ASSERT(str); @@ -135,33 +311,34 @@ QByteArray telegramId2String(gef_telegramm_id_et telId) QString wirkfeldTyp2Str(TrainingAreaBase::TetraIcd::AreaEffectSimulationType wirkfeldTyp) { - switch(wirkfeldTyp) + switch (wirkfeldTyp) { - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::MineArea: - return QLatin1String("MINENSPERRE"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionArea: - return QLatin1String("FLAECHENFEUER"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionSingle: - return QLatin1String("EINZELFEUER"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::NContamination: - return QLatin1String("A_KAMPF"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::CContamination: - return QLatin1String("C_KAMPF"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::FunctionalArea: - return QLatin1String("FUNKTIONS_RAUM"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::TechnicalArea: - return QLatin1String("FUNKTIONS_RAUM_TECHNIK"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::GasPipeDetonation: - return QLatin1String("GAS_PIPE_DETONATION"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::SpecialArea: - return QLatin1String("SPECIAL_AREA"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::Unknown: - return QLatin1String("DUS"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DusSingleMineSimulator: - return QLatin1String("DUS_SINGLE_MINE_SIMULATOR"); - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::BeStillWarning: - return QLatin1String("BE_STILL_WARNING"); - default: break; + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::MineArea: + return QLatin1String("MINENSPERRE"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionArea: + return QLatin1String("FLAECHENFEUER"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionSingle: + return QLatin1String("EINZELFEUER"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::NContamination: + return QLatin1String("A_KAMPF"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::CContamination: + return QLatin1String("C_KAMPF"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::FunctionalArea: + return QLatin1String("FUNKTIONS_RAUM"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::TechnicalArea: + return QLatin1String("FUNKTIONS_RAUM_TECHNIK"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::GasPipeDetonation: + return QLatin1String("GAS_PIPE_DETONATION"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::SpecialArea: + return QLatin1String("SPECIAL_AREA"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::Unknown: + return QLatin1String("DUS"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DusSingleMineSimulator: + return QLatin1String("DUS_SINGLE_MINE_SIMULATOR"); + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::BeStillWarning: + return QLatin1String("BE_STILL_WARNING"); + default: + break; } return QStringLiteral("Unknown Wirkfeldtyp <%1>").arg(static_cast(wirkfeldTyp)); } @@ -173,70 +350,63 @@ static inline QString wirkfeldTyp2Str(int typ) void dumpTelegram(NGL::INGLLogger &m_logger, int id, N_CoPrtCnv::CoPrtCnvRadioTelegram *a_radioTelegram, const char *prefix) { - if(!m_logger.isDebugEnabled()) + if (!m_logger.isDebugEnabled()) return; if (!prefix) prefix = ""; - const QByteArray commonLog(prefix + QByteArray("BC: ") + QByteArray::number(id) + - ", " + telegramId2String(a_radioTelegram->getTelID())); + const QByteArray commonLog(prefix + QByteArray("BC: ") + QByteArray::number(id) + ", " + telegramId2String(a_radioTelegram->getTelID())); switch (a_radioTelegram->getTelID()) { - case GEF_DEAKTIVIERUNG_WIRKFELD: - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - { - uint8_t wirkfeldTyp = a_radioTelegram->getPayloadDataUInt32(5, 1); - uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); - DEBUG_LOG(m_logger) << commonLog - << ", type: " << wirkfeldTyp2Str(wirkfeldTyp) << ", kennung: " - << wirkfeldKennung; - break; - } - case GEF_DEAKTIVIERUNG_EINZELMINE: { - uint32_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(9, 2); - uint32_t minenKennung = a_radioTelegram->getPayloadDataUInt32(11, 2); - DEBUG_LOG(m_logger) << commonLog - << ", kennung: " << wirkfeldKennung << ", mineId: " << minenKennung; - break; - } - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_FUNKTIONSRAUM: - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - { - uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - DEBUG_LOG(m_logger) << commonLog << ", kennung: " << wirkfeldKennung; - break; - } - case GEF_TECHNIK_FUNKTIONSRAUM: - { - uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - uint8_t funktionsraumtyp = a_radioTelegram->getPayloadDataUInt32(7, 1); - DEBUG_LOG(m_logger) << commonLog - << ", kennung: " << funktionsraumkennung - << " type: " << int(funktionsraumtyp); - break; - } - case GEF_WF_SAMMELDEAKTIVIERUNG: - case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: - case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: - DEBUG_LOG(m_logger) << commonLog << ", Ids: " << dumpSammeldeaktivierung(a_radioTelegram); - break; - case GEF_NOP: - { - uint16_t bcFrom = a_radioTelegram->getPayloadDataUInt32(3, 2); - uint16_t bcTo = a_radioTelegram->getPayloadDataUInt32(5, 2); - DEBUG_LOG(m_logger) << prefix - << commonLog - << ", from BC " << bcFrom << " to " << bcTo; - break; - } - default: - DEBUG_LOG(m_logger) << commonLog; - break; + case GEF_DEAKTIVIERUNG_WIRKFELD: + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + { + uint8_t wirkfeldTyp = a_radioTelegram->getPayloadDataUInt32(5, 1); + uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); + DEBUG_LOG(m_logger) << commonLog << ", type: " << wirkfeldTyp2Str(wirkfeldTyp) << ", kennung: " << wirkfeldKennung; + break; + } + case GEF_DEAKTIVIERUNG_EINZELMINE: + { + uint32_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(9, 2); + uint32_t minenKennung = a_radioTelegram->getPayloadDataUInt32(11, 2); + DEBUG_LOG(m_logger) << commonLog << ", kennung: " << wirkfeldKennung << ", mineId: " << minenKennung; + break; + } + case GEF_WIRKFELD_STATUS_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + case GEF_FUNKTIONSRAUM: + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + { + uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + DEBUG_LOG(m_logger) << commonLog << ", kennung: " << wirkfeldKennung; + break; + } + case GEF_TECHNIK_FUNKTIONSRAUM: + { + uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + uint8_t funktionsraumtyp = a_radioTelegram->getPayloadDataUInt32(7, 1); + DEBUG_LOG(m_logger) << commonLog << ", kennung: " << funktionsraumkennung << " type: " << int(funktionsraumtyp); + break; + } + case GEF_WF_SAMMELDEAKTIVIERUNG: + case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: + case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: + DEBUG_LOG(m_logger) << commonLog << ", Ids: " << dumpSammeldeaktivierung(a_radioTelegram); + break; + case GEF_NOP: + { + uint16_t bcFrom = a_radioTelegram->getPayloadDataUInt32(3, 2); + uint16_t bcTo = a_radioTelegram->getPayloadDataUInt32(5, 2); + DEBUG_LOG(m_logger) << prefix << commonLog << ", from BC " << bcFrom << " to " << bcTo; + break; + } + default: + DEBUG_LOG(m_logger) << commonLog; + break; } } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.hpp index 817895dc8..5c330d4ef 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvHexDumpHelper.hpp @@ -21,12 +21,9 @@ namespace N_CoPrtCnv { -class CoPrtCnvRadioTelegram; + class CoPrtCnvRadioTelegram; } COPRTCNV_EXPORT QByteArray telegramId2String(gef_telegramm_id_et telId); -COPRTCNV_EXPORT void dumpTelegram(NGL::INGLLogger &m_logger, - int id, - N_CoPrtCnv::CoPrtCnvRadioTelegram *a_radioTelegram, - const char *prefix = nullptr); +COPRTCNV_EXPORT void dumpTelegram(NGL::INGLLogger &m_logger, int id, N_CoPrtCnv::CoPrtCnvRadioTelegram *a_radioTelegram, const char *prefix = nullptr); COPRTCNV_EXPORT QString wirkfeldTyp2Str(TrainingAreaBase::TetraIcd::AreaEffectSimulationType wirkfeldTyp); diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvInjectionHeader.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvInjectionHeader.hpp index 97a28c953..4ab6cd9bb 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvInjectionHeader.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvInjectionHeader.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -52,13 +52,13 @@ namespace N_CoPrtCnv uint16_t m_Size; CoPrtCnvInjectionHeader() - : m_Id1(0x12345678), - m_Id2(0x78236239), - m_Kind(eUnknown), - m_Size(0) - {} + : m_Id1(0x12345678) + , m_Id2(0x78236239) + , m_Kind(eUnknown) + , m_Size(0) + { + } bool isIdCorrect() const { return (m_Id1 == 0x12345678 && m_Id2 == 0x78236239); } - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvLogHeader.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvLogHeader.hpp index 5afc9fb29..f5f43468b 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvLogHeader.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvLogHeader.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp index a81c40fbf..2f91943ba 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp @@ -22,1365 +22,1351 @@ int CoPrtCnvRadioTelegram::s_3rdDelay = 60; int CoPrtCnvRadioTelegram::s_maxBroadcastSendCnt = 0; bool CoPrtCnvRadioTelegram::s_etsMode = false; -static const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_ProtocolIdentifier s_protocolIdentifier = - N_CoPrtCnv::CoPrtCnvRadioTelegram::e_TDSMessageWithoutSDS_TL; +static const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_ProtocolIdentifier s_protocolIdentifier = N_CoPrtCnv::CoPrtCnvRadioTelegram::e_TDSMessageWithoutSDS_TL; CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI) - : m_data(9, Qt::Uninitialized), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), - m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) + : m_data(9, Qt::Uninitialized) + , m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - setHeader(m_data, e_RegisterInd); + setHeader(m_data, e_RegisterInd); - setSrcISSI(a_sourceISSI); + setSrcISSI(a_sourceISSI); } -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const std::set& groups) - : m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const std::set &groups) + : m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - uint16_t len = groups.size(); - if (len > 5) - len = 5; - m_data.resize(12 + len * 4); - setHeader(m_data, e_GroupMonitorReq); + uint16_t len = groups.size(); + if (len > 5) + len = 5; + m_data.resize(12 + len * 4); + setHeader(m_data, e_GroupMonitorReq); - setSrcISSI(a_sourceISSI); + setSrcISSI(a_sourceISSI); - uint8_t mode = 1; - set1Byte(m_data, 9, mode); - set2Byte(m_data, 10, len); - std::set::iterator it = groups.begin(); - for (uint16_t i = 0; i < len; i++) - { - set4Byte(m_data, 12 + i * 4, *it); - ++it; - } + uint8_t mode = 1; + set1Byte(m_data, 9, mode); + set2Byte(m_data, 10, len); + std::set::iterator it = groups.begin(); + for (uint16_t i = 0; i < len; i++) + { + set4Byte(m_data, 12 + i * 4, *it); + ++it; + } } CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const E_DeliveryStatusForTL_Report a_delivery) - : m_data(17, Qt::Uninitialized), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), - m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) + : m_data(17, Qt::Uninitialized) + , m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - setHeader(m_data, e_ReportIndReq); + setHeader(m_data, e_ReportIndReq); - setSrcISSI(a_sourceISSI); - setDestISSI(a_sourceISSI); - set1Byte(m_data, 13, s_protocolIdentifier); - set1Byte(m_data, 14, 0); - set1Byte(m_data, 15, 0); - set1Byte(m_data, 16, a_delivery); + setSrcISSI(a_sourceISSI); + setDestISSI(a_sourceISSI); + set1Byte(m_data, 13, s_protocolIdentifier); + set1Byte(m_data, 14, 0); + set1Byte(m_data, 15, 0); + set1Byte(m_data, 16, a_delivery); } -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const QByteArray& a_data) - : m_data(a_data), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const QByteArray &a_data) + : m_data(a_data) + , m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { } -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, - const uint16_t a_identity) - : m_data(a_payloadSize + DATA_IND_REQ_HEADER_LENGTH, '\0'), m_PayloadIndex(0), m_BroadcastCounter(0), - m_NextSendTime(0), m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, const uint16_t a_identity) + : m_data(a_payloadSize + DATA_IND_REQ_HEADER_LENGTH, '\0') + , m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, e_NotFragmented); + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, e_NotFragmented); - set1Byte(m_data, m_PayloadIndex++, a_telegramId); - set1Byte(m_data, m_PayloadIndex++, 0); - set1Byte(m_data, m_PayloadIndex--, 0); - setIdentity(a_identity); - m_PayloadIndex += 2; + set1Byte(m_data, m_PayloadIndex++, a_telegramId); + set1Byte(m_data, m_PayloadIndex++, 0); + set1Byte(m_data, m_PayloadIndex--, 0); + setIdentity(a_identity); + m_PayloadIndex += 2; } -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, - uint32_t a_issi) - : m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, uint32_t a_issi) + : m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - const bool withGroupIssis = (a_loginTelegramStatus & e_LoginOtherExercise) == e_LoginOtherExercise; - m_data.resize(DATA_IND_REQ_HEADER_LENGTH + (withGroupIssis ? 12 : 3)); - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); - setDestISSI(a_issi); + const bool withGroupIssis = (a_loginTelegramStatus & e_LoginOtherExercise) == e_LoginOtherExercise; + m_data.resize(DATA_IND_REQ_HEADER_LENGTH + (withGroupIssis ? 12 : 3)); + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); + setDestISSI(a_issi); - uint16_t size = m_data.size(); - set2Byte(m_data, DATA_IND_REQ_WITH_TL_HEADER_LENGTH, - 8 * (size - DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER)); + uint16_t size = m_data.size(); + set2Byte(m_data, DATA_IND_REQ_WITH_TL_HEADER_LENGTH, 8 * (size - DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER)); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, e_NotFragmented + e_LoginTelegram); + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, e_NotFragmented + e_LoginTelegram); - set1Byte(m_data, m_PayloadIndex++, (a_identity >> 8) & 0x00FF); - set1Byte(m_data, m_PayloadIndex++, a_identity & 0x00FF); - set1Byte(m_data, m_PayloadIndex++, a_loginTelegramStatus); + set1Byte(m_data, m_PayloadIndex++, (a_identity >> 8) & 0x00FF); + set1Byte(m_data, m_PayloadIndex++, a_identity & 0x00FF); + set1Byte(m_data, m_PayloadIndex++, a_loginTelegramStatus); } void CoPrtCnvRadioTelegram::setLoginIssis(int hostIssi, int groupIssi1, int groupIssi2) { - setPayload3Byte(hostIssi); + setPayload3Byte(hostIssi); - setPayload3Byte(groupIssi1); + setPayload3Byte(groupIssi1); - setPayload3Byte(groupIssi2); + setPayload3Byte(groupIssi2); } -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const std::shared_ptr& a_bigTelegram, - const uint8_t a_fragmentIndex, bool& a_error) - : m_data(), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const std::shared_ptr &a_bigTelegram, const uint8_t a_fragmentIndex, bool &a_error) + : m_data() + , m_PayloadIndex(0) + , m_BroadcastCounter(0) + , m_NextSendTime(0) + , m_IsBroadcastOnly(false) + , m_BroadcastOnlyTelegram(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - static const uint16_t MAX_TELEGRAM_SIZE = MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH; + static const uint16_t MAX_TELEGRAM_SIZE = MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH; - const int payloadSize = a_bigTelegram->getSize() - DATA_IND_REQ_HEADER_LENGTH; - const uint8_t nbrOfFragmentedTelegrams = uint8_t((payloadSize - 1) / MAX_TELEGRAM_SIZE); - if (nbrOfFragmentedTelegrams > (MAX_NBR_OF_FRAGMENTS - 1)) + const int payloadSize = a_bigTelegram->getSize() - DATA_IND_REQ_HEADER_LENGTH; + const uint8_t nbrOfFragmentedTelegrams = uint8_t((payloadSize - 1) / MAX_TELEGRAM_SIZE); + if (nbrOfFragmentedTelegrams > (MAX_NBR_OF_FRAGMENTS - 1)) + { + ERROR_LOG(m_logger) << "Radio-telegram is too big (" << nbrOfFragmentedTelegrams + 1 << " fragments). There are max " << MAX_NBR_OF_FRAGMENTS + << " fragments of size=" << MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH << " (=" << MAX_NBR_OF_FRAGMENTS * MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + << " bytes) possible."; + a_error = true; + return; + } + if (nbrOfFragmentedTelegrams == 0) + { + ERROR_LOG(m_logger) << "Radio-telegram is too small for fragmentation. It must have at least a size of " << (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + 1); + a_error = true; + return; + } + uint8_t payloadStatus = e_FirstFragment | nbrOfFragmentedTelegrams; + + const uint16_t payloadSizeNormal = uint16_t(payloadSize / (nbrOfFragmentedTelegrams + 1)); + const uint16_t payloadSizeLast = uint16_t(payloadSize - (nbrOfFragmentedTelegrams * payloadSizeNormal)); + + uint16_t size = payloadSizeNormal; + if (0 != a_fragmentIndex) + { + if (nbrOfFragmentedTelegrams != a_fragmentIndex) { - ERROR_LOG(m_logger) << "Radio-telegram is too big (" << nbrOfFragmentedTelegrams + 1 - << " fragments). There are max " << MAX_NBR_OF_FRAGMENTS - << " fragments of size=" << MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - << " (=" << MAX_NBR_OF_FRAGMENTS * MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH << " bytes) possible."; - a_error = true; - return; - } - if (nbrOfFragmentedTelegrams == 0) - { - ERROR_LOG(m_logger) << "Radio-telegram is too small for fragmentation. It must have at least a size of " - << (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + 1); - a_error = true; - return; - } - uint8_t payloadStatus = e_FirstFragment | nbrOfFragmentedTelegrams; - const uint16_t payloadSizeNormal = uint16_t(payloadSize / (nbrOfFragmentedTelegrams + 1)); - const uint16_t payloadSizeLast = uint16_t(payloadSize - (nbrOfFragmentedTelegrams * payloadSizeNormal)); - - uint16_t size = payloadSizeNormal; - if (0 != a_fragmentIndex) - { - if (nbrOfFragmentedTelegrams != a_fragmentIndex) - { - - payloadStatus = e_MiddleFragment | (nbrOfFragmentedTelegrams - a_fragmentIndex); - } - else - { - - payloadStatus = e_LastFragment; - size = payloadSizeLast; - } - } - size += PAYLOAD_STATUS_LENGTH; - - m_data.resize(size + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, payloadStatus); - - if (size > 1) - { - const char* srcData = - a_bigTelegram->getData() + DATA_IND_REQ_HEADER_LENGTH + a_fragmentIndex * payloadSizeNormal; - const uint8_t* ptr = reinterpret_cast(srcData); - setPayloadData(ptr, size - 1); + payloadStatus = e_MiddleFragment | (nbrOfFragmentedTelegrams - a_fragmentIndex); } else { - ERROR_LOG(m_logger) << "Internal error: size must be bigger than 1"; - a_error = true; - return; + payloadStatus = e_LastFragment; + size = payloadSizeLast; } - a_error = false; + } + size += PAYLOAD_STATUS_LENGTH; + + m_data.resize(size + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, payloadStatus); + + if (size > 1) + { + const char *srcData = a_bigTelegram->getData() + DATA_IND_REQ_HEADER_LENGTH + a_fragmentIndex * payloadSizeNormal; + const uint8_t *ptr = reinterpret_cast(srcData); + setPayloadData(ptr, size - 1); + } + else + { + + ERROR_LOG(m_logger) << "Internal error: size must be bigger than 1"; + a_error = true; + return; + } + a_error = false; } CoPrtCnvRadioTelegram::~CoPrtCnvRadioTelegram() { - if (m_BroadcastOnlyTelegram != nullptr) - ERROR_LOG(m_logger) - << "Internal error: m_BroadcastOnlyTelegram was not nullptr while deletion of radio-telegram"; + if (m_BroadcastOnlyTelegram != nullptr) + ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr while deletion of radio-telegram"; } void CoPrtCnvRadioTelegram::setPayload1Byte(const uint8_t a_value) { - set1Byte(m_data, m_PayloadIndex, a_value); - m_PayloadIndex += 1; + set1Byte(m_data, m_PayloadIndex, a_value); + m_PayloadIndex += 1; } void CoPrtCnvRadioTelegram::setPayload2Byte(const uint16_t a_value) { - setPayloadData(a_value, 2); + setPayloadData(a_value, 2); } void CoPrtCnvRadioTelegram::setPayload3Byte(const uint32_t a_value) { - setPayloadData(a_value, 3); + setPayloadData(a_value, 3); } void CoPrtCnvRadioTelegram::setPayload4Byte(const uint32_t a_value) { - setPayloadData(a_value, 4); + setPayloadData(a_value, 4); } void CoPrtCnvRadioTelegram::setPayloadData(uint32_t a_value, const uint8_t a_size) { - for (int i = m_PayloadIndex + a_size - 1; i >= m_PayloadIndex; i--) - { - set1Byte(m_data, i, a_value & 0xFF); - a_value >>= 8; - } - m_PayloadIndex += a_size; + for (int i = m_PayloadIndex + a_size - 1; i >= m_PayloadIndex; i--) + { + set1Byte(m_data, i, a_value & 0xFF); + a_value >>= 8; + } + m_PayloadIndex += a_size; } -void CoPrtCnvRadioTelegram::setPayloadData(const uint8_t* a_data, const uint16_t a_size) +void CoPrtCnvRadioTelegram::setPayloadData(const uint8_t *a_data, const uint16_t a_size) { - uint8_t* ptr = reinterpret_cast(m_data.data()); - memcpy(&ptr[m_PayloadIndex], a_data, a_size); - m_PayloadIndex += a_size; + uint8_t *ptr = reinterpret_cast(m_data.data()); + memcpy(&ptr[m_PayloadIndex], a_data, a_size); + m_PayloadIndex += a_size; } void CoPrtCnvRadioTelegram::fixupTelegramIdForEts(bool convertToEtsId) { - if (!s_etsMode) - return; - char* ptr = &m_data.data()[DATA_IND_REQ_HEADER_LENGTH]; - if (convertToEtsId) - ++(*ptr); - else - --(*ptr); + if (!s_etsMode) + return; + char *ptr = &m_data.data()[DATA_IND_REQ_HEADER_LENGTH]; + if (convertToEtsId) + ++(*ptr); + else + --(*ptr); } void CoPrtCnvRadioTelegram::setEtsMode(bool bIsEtsMode) { - s_etsMode = bIsEtsMode; + s_etsMode = bIsEtsMode; } gef_telegramm_id_et CoPrtCnvRadioTelegram::getTelID() const { - return static_cast(static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH))); + return static_cast(static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH))); } uint8_t CoPrtCnvRadioTelegram::zaehler() const { - return static_cast(m_data.at(1)); + return static_cast(m_data.at(1)); } void CoPrtCnvRadioTelegram::setZaehler(const uint8_t a_counter) { - set1Byte(m_data, 1, a_counter); + set1Byte(m_data, 1, a_counter); } uint32_t CoPrtCnvRadioTelegram::getPayloadDataUInt32(size_t a_offset, uint16_t a_size) const { - uint32_t value = 0; - const uint8_t* ptr = reinterpret_cast(m_data.data()); - uint8_t* ptrValue = reinterpret_cast(&value); - a_offset += DATA_IND_REQ_HEADER_LENGTH; - switch (a_size) - { - case 4: - ptrValue[3] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 3: - ptrValue[2] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 2: - ptrValue[1] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 1: - ptrValue[0] = ptr[a_offset++]; - break; - default: - Q_ASSERT(false); - ERROR_LOG(m_logger) << "a_size must be between 1..4"; - } + uint32_t value = 0; + const uint8_t *ptr = reinterpret_cast(m_data.data()); + uint8_t *ptrValue = reinterpret_cast(&value); + a_offset += DATA_IND_REQ_HEADER_LENGTH; + switch (a_size) + { + case 4: + ptrValue[3] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 3: + ptrValue[2] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 2: + ptrValue[1] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 1: + ptrValue[0] = ptr[a_offset++]; + break; + default: + Q_ASSERT(false); + ERROR_LOG(m_logger) << "a_size must be between 1..4"; + } - return value; + return value; } uint8_t CoPrtCnvRadioTelegram::getPayloadDataUInt8(size_t a_offset) const { - return static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH + a_offset)); + return static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH + a_offset)); } uint32_t CoPrtCnvRadioTelegram::getDestISSI() const { - return getUInt32(9); + return getUInt32(9); } uint16_t CoPrtCnvRadioTelegram::getIdentity() const { - return isLoginTelegram() ? getPayloadDataUInt32(0, 2) : getPayloadDataUInt32(1, 2); + return isLoginTelegram() ? getPayloadDataUInt32(0, 2) : getPayloadDataUInt32(1, 2); } void CoPrtCnvRadioTelegram::setSrcISSI(const uint32_t a_ISSI) { - setSrcISSI_Internal(m_data, a_ISSI); + setSrcISSI_Internal(m_data, a_ISSI); } bool CoPrtCnvRadioTelegram::mustBroadcastBeSet() const { - if (isNormalTelegram()) - return getIdentity() == 0 && getBroadcastIndex() == 0; + if (isNormalTelegram()) + return getIdentity() == 0 && getBroadcastIndex() == 0; - return false; + return false; } void CoPrtCnvRadioTelegram::setBroadcastIndex(const uint16_t a_broadcastIndex) { - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 3, (a_broadcastIndex >> 8) & 0xFF); - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 4, a_broadcastIndex & 0xFF); + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 3, (a_broadcastIndex >> 8) & 0xFF); + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 4, a_broadcastIndex & 0xFF); } void CoPrtCnvRadioTelegram::setDestISSI(const uint32_t a_ISSI) { - setDestISSI_Internal(m_data, a_ISSI); + setDestISSI_Internal(m_data, a_ISSI); } CoPrtCnvRadioTelegram::E_PDU_Type CoPrtCnvRadioTelegram::getPDU_Type() const { - return static_cast(m_data.at(4)); + return static_cast(m_data.at(4)); } CoPrtCnvRadioTelegram::E_FragmentStatus CoPrtCnvRadioTelegram::getFragmentStatus() const { - return static_cast(m_data.at(26) & e_FragmentStatusMask); + return static_cast(m_data.at(26) & e_FragmentStatusMask); } uint8_t CoPrtCnvRadioTelegram::getFragmentCounter() const { - return static_cast(m_data.at(26) & e_CounterMask); + return static_cast(m_data.at(26) & e_CounterMask); } bool CoPrtCnvRadioTelegram::isCrcOk() const { - if ((m_data.at(26) & e_Checksum) == e_Checksum) + if ((m_data.at(26) & e_Checksum) == e_Checksum) + { + + uint32_t sum = getProtocolIdentifier(); + for (int i = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; i < m_data.size() - 2; i++) + sum += static_cast(m_data.at(i)); + + uint16_t checksum = getUInt8(m_data.size() - 2) * 256 + getUInt8(m_data.size() - 1); + checksum = ~checksum; + checksum++; + + auto that = const_cast(this); + that->m_data.resize(m_data.size() - 2); + that->m_data[26] = (m_data.at(26) & ~e_Checksum); + + if (sum != checksum) { - - uint32_t sum = getProtocolIdentifier(); - for (int i = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; i < m_data.size() - 2; i++) - sum += static_cast(m_data.at(i)); - - uint16_t checksum = getUInt8(m_data.size() - 2) * 256 + getUInt8(m_data.size() - 1); - checksum = ~checksum; - checksum++; - - auto that = const_cast(this); - that->m_data.resize(m_data.size() - 2); - that->m_data[26] = (m_data.at(26) & ~e_Checksum); - - if (sum != checksum) - { - ERROR_LOG(m_logger) << "Checksum of telegram is wrong: " << QString::number(checksum, 16) - << " (expected: " << QString::number(sum, 16) << "), issi: " << getUInt32(5); - return true; - } + ERROR_LOG(m_logger) << "Checksum of telegram is wrong: " << QString::number(checksum, 16) << " (expected: " << QString::number(sum, 16) + << "), issi: " << getUInt32(5); + return true; } - return true; + } + return true; } uint32_t CoPrtCnvRadioTelegram::getSrcISSI() const { - return getUInt32(5); + return getUInt32(5); } bool CoPrtCnvRadioTelegram::isLoginTelegram() const { - if (e_DataIndReq == getPDU_Type()) - return (e_LoginTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26))); - return false; + if (e_DataIndReq == getPDU_Type()) + return (e_LoginTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26))); + return false; } bool CoPrtCnvRadioTelegram::mustBeFragmented() const { - if (e_DataIndReq == getPDU_Type()) - return size_t(getSize()) > - (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); - return false; + if (e_DataIndReq == getPDU_Type()) + return size_t(getSize()) > (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); + return false; } -const uint8_t* CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) const +const uint8_t *CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) const { - return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); + return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); } -uint8_t* CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) +uint8_t *CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) { - return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); + return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); } uint16_t CoPrtCnvRadioTelegram::getPayloadSize() const { - return static_cast((getPDU_Type() == e_DataIndReq) ? m_data.size() - DATA_IND_REQ_HEADER_LENGTH : 0); + return static_cast((getPDU_Type() == e_DataIndReq) ? m_data.size() - DATA_IND_REQ_HEADER_LENGTH : 0); } -QByteArray -CoPrtCnvRadioTelegram::getUnfragmentedData(const std::multimap& a_fragTelegramList) +QByteArray CoPrtCnvRadioTelegram::getUnfragmentedData(const std::multimap &a_fragTelegramList) { - NGL::INGLLogger& l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram"); + NGL::INGLLogger &l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram"); - uint16_t totalSize = 0; - bool first = true; - uint8_t expectedNextFragment = 0; - CoPrtCnvRadioTelegram* firstFragment = nullptr; - std::multimap::const_reverse_iterator rit; - for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) + uint16_t totalSize = 0; + bool first = true; + uint8_t expectedNextFragment = 0; + CoPrtCnvRadioTelegram *firstFragment = nullptr; + std::multimap::const_reverse_iterator rit; + for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) + { + CoPrtCnvRadioTelegram *fragRadioTelegram = rit->second; + if (first) { - CoPrtCnvRadioTelegram* fragRadioTelegram = rit->second; - if (first) + if (e_FirstFragment == fragRadioTelegram->getFragmentStatus()) + { + totalSize += fragRadioTelegram->getSize(); + expectedNextFragment = fragRadioTelegram->getFragmentCounter() - 1; + firstFragment = fragRadioTelegram; + first = false; + } + else + { + ERROR_LOG(l) << "The fragment with the highest counter is not marked as first fragment"; + return nullptr; + } + } + else + { + if (e_MiddleFragment == fragRadioTelegram->getFragmentStatus() || e_LastFragment == fragRadioTelegram->getFragmentStatus()) + { + if (expectedNextFragment-- == fragRadioTelegram->getFragmentCounter()) { - if (e_FirstFragment == fragRadioTelegram->getFragmentStatus()) - { - totalSize += fragRadioTelegram->getSize(); - expectedNextFragment = fragRadioTelegram->getFragmentCounter() - 1; - firstFragment = fragRadioTelegram; - first = false; - } - else - { - ERROR_LOG(l) << "The fragment with the highest counter is not marked as first fragment"; - return nullptr; - } + if (e_LastFragment == fragRadioTelegram->getFragmentStatus() && 0 != fragRadioTelegram->getFragmentCounter()) + { + ERROR_LOG(l) << "The last fragment must have a counter of 0, but the counter is " << (int)fragRadioTelegram->getFragmentCounter(); + return nullptr; + } + totalSize += fragRadioTelegram->getPayloadSize(); } else { - if (e_MiddleFragment == fragRadioTelegram->getFragmentStatus() || - e_LastFragment == fragRadioTelegram->getFragmentStatus()) - { - if (expectedNextFragment-- == fragRadioTelegram->getFragmentCounter()) - { - if (e_LastFragment == fragRadioTelegram->getFragmentStatus() && - 0 != fragRadioTelegram->getFragmentCounter()) - { - ERROR_LOG(l) << "The last fragment must have a counter of 0, but the counter is " - << (int)fragRadioTelegram->getFragmentCounter(); - return nullptr; - } - totalSize += fragRadioTelegram->getPayloadSize(); - } - else - { - ERROR_LOG(l) << "The fragmented Radio-Telegram from TNE with id=" - << fragRadioTelegram->getIdentity() - << " with fragment-counter=" << (expectedNextFragment + 1) << " was lost"; - return nullptr; - } - } - else - { - ERROR_LOG(l) << "A fragment which is not the first one, is not marked as middle or last fragment"; - return nullptr; - } + ERROR_LOG(l) << "The fragmented Radio-Telegram from TNE with id=" << fragRadioTelegram->getIdentity() << " with fragment-counter=" << (expectedNextFragment + 1) + << " was lost"; + return nullptr; } + } + else + { + ERROR_LOG(l) << "A fragment which is not the first one, is not marked as middle or last fragment"; + return nullptr; + } } + } - if (firstFragment && - totalSize <= (DATA_IND_REQ_HEADER_LENGTH + - MAX_NBR_OF_FRAGMENTS * (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH)) && - totalSize > DATA_IND_REQ_HEADER_LENGTH) + if (firstFragment && totalSize <= (DATA_IND_REQ_HEADER_LENGTH + MAX_NBR_OF_FRAGMENTS * (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH)) && + totalSize > DATA_IND_REQ_HEADER_LENGTH) + { + QByteArray data(totalSize, Qt::Uninitialized); + + setHeader(data, e_DataIndReq); + fillDataIndReqHeader(data); + setSrcISSI_Internal(data, firstFragment->getSrcISSI()); + setDestISSI_Internal(data, firstFragment->getDestISSI()); + uint16_t index = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(data, index++, e_NotFragmented); + + for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) { - QByteArray data(totalSize, Qt::Uninitialized); + CoPrtCnvRadioTelegram *fragRadioTelegram = rit->second; + uint16_t fragSize = fragRadioTelegram->getPayloadSize(); + if (index + fragSize <= totalSize) + { + memcpy(&data.data()[index], fragRadioTelegram->getPayloadDataPtr(0), fragSize); + index += fragSize; + } + else + { - setHeader(data, e_DataIndReq); - fillDataIndReqHeader(data); - setSrcISSI_Internal(data, firstFragment->getSrcISSI()); - setDestISSI_Internal(data, firstFragment->getDestISSI()); - uint16_t index = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(data, index++, e_NotFragmented); - - for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) - { - CoPrtCnvRadioTelegram* fragRadioTelegram = rit->second; - uint16_t fragSize = fragRadioTelegram->getPayloadSize(); - if (index + fragSize <= totalSize) - { - memcpy(&data.data()[index], fragRadioTelegram->getPayloadDataPtr(0), fragSize); - index += fragSize; - } - else - { - - ERROR_LOG(l) << "Internal error: size of allocated datablock is too small"; - return QByteArray(); - } - } - - return data; + ERROR_LOG(l) << "Internal error: size of allocated datablock is too small"; + return QByteArray(); + } } - ERROR_LOG(l) << "Internal error while building unfragmented radio-telegram: fragTelegram=" << firstFragment - << " totalSize=" << totalSize; - return QByteArray(); + return data; + } + + ERROR_LOG(l) << "Internal error while building unfragmented radio-telegram: fragTelegram=" << firstFragment << " totalSize=" << totalSize; + return QByteArray(); } bool CoPrtCnvRadioTelegram::isTelegramLengthOk(const uint16_t a_lengthWithoutFrame) { - return (a_lengthWithoutFrame <= (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_HEADER_LENGTH - - sizeof(PrtCnvRadioGwHeader) - PAYLOAD_STATUS_LENGTH)); + return (a_lengthWithoutFrame <= (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_HEADER_LENGTH - sizeof(PrtCnvRadioGwHeader) - PAYLOAD_STATUS_LENGTH)); } bool CoPrtCnvRadioTelegram::isNormalTelegram() const { - return (e_DataIndReq == getPDU_Type() && - (e_NormalTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26)))); + return (e_DataIndReq == getPDU_Type() && (e_NormalTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26)))); } uint8_t CoPrtCnvRadioTelegram::getPriority() const { - if (isNormalTelegram()) + if (isNormalTelegram()) + { + switch (getTelID()) { - switch (getTelID()) - { - case GEF_INIT: - case GEF_DEAKTIVIERUNG_EINZELMINE: - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: - case GEF_SANITAETSDIENST_INSTANDSETZUNG: - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: - return 2; - case GEF_WIRKFELD_EINZELGESCHOSS: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_C_KAMPFMITTEL: - case GEF_DEAKTIVIERUNG_WIRKFELD: - case GEF_REAKTIVIERUNG_DUS_MINE: - case GEF_TECHNIK_FUNKTIONSRAUM: - case GEF_FUNKTIONSRAUM: - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - case GEF_DATENVERKEHR_TDS_GEOP: - case GEF_WIRKFELD_EINZELMINENSIMULATOR: - case GEF_POSITIONS_MELDUNG: - return 3; - case GEF_UMGEBUNGS_MELDUNG2: - case GEF_AUFFORDERUNG_BITE_MELDUNG: - case GEF_LIZENSIERUNG_TNE: - case GEF_TREFFER_AUSLOESUNG: - case GEF_SPRACHAUSWAHL: - case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: - case GEF_SELEKTIVE_AUFMUNITIONIERUNG: - case GEF_SCHIEDSRICHTERKOMMANDO: - return 4; - case GEF_KONFIGURATION_WIRKMODELL: - case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - case GEF_DATENVERKEHR_TDS_SRT: - case GEF_DATENVERKEHR_TDS_DMF: - case GEF_DATENVERKEHR_TDS_TGTC: - case GEF_TEILNEHMERMODE_SETZEN: - case GEF_TEILNEHMER_KONFIG_ANFORDERN: - case GEF_TEILNEHMER_KONFIG_SETZEN: - return 5; - case GEF_ALLGEMEINE_NACHRICHT: - return 6; - case GEF_SW_VERSIONSMELDUNG: - return 7; + case GEF_INIT: + case GEF_DEAKTIVIERUNG_EINZELMINE: + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + case GEF_SANITAETSDIENST_INSTANDSETZUNG: + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: + return 2; + case GEF_WIRKFELD_EINZELGESCHOSS: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_STATUS_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_C_KAMPFMITTEL: + case GEF_DEAKTIVIERUNG_WIRKFELD: + case GEF_REAKTIVIERUNG_DUS_MINE: + case GEF_TECHNIK_FUNKTIONSRAUM: + case GEF_FUNKTIONSRAUM: + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + case GEF_DATENVERKEHR_TDS_GEOP: + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + case GEF_POSITIONS_MELDUNG: + return 3; + case GEF_UMGEBUNGS_MELDUNG2: + case GEF_AUFFORDERUNG_BITE_MELDUNG: + case GEF_LIZENSIERUNG_TNE: + case GEF_TREFFER_AUSLOESUNG: + case GEF_SPRACHAUSWAHL: + case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: + case GEF_SELEKTIVE_AUFMUNITIONIERUNG: + case GEF_SCHIEDSRICHTERKOMMANDO: + return 4; + case GEF_KONFIGURATION_WIRKMODELL: + case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + case GEF_DATENVERKEHR_TDS_SRT: + case GEF_DATENVERKEHR_TDS_DMF: + case GEF_DATENVERKEHR_TDS_TGTC: + case GEF_TEILNEHMERMODE_SETZEN: + case GEF_TEILNEHMER_KONFIG_ANFORDERN: + case GEF_TEILNEHMER_KONFIG_SETZEN: + return 5; + case GEF_ALLGEMEINE_NACHRICHT: + return 6; + case GEF_SW_VERSIONSMELDUNG: + return 7; - case GEF_NOP: - case GEF_WF_SAMMELDEAKTIVIERUNG: - case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: - case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: - return 99; - default: - ERROR_LOG(m_logger) << "Priority of telegram with telId=" << getTelID() << " not defined."; + case GEF_NOP: + case GEF_WF_SAMMELDEAKTIVIERUNG: + case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: + case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: + return 99; + default: + ERROR_LOG(m_logger) << "Priority of telegram with telId=" << getTelID() << " not defined."; #ifdef DEBUG - abort(); + abort(); #endif - } } - else if (isLoginTelegram()) - return 4; - return 10; + } + else if (isLoginTelegram()) + return 4; + return 10; } uint16_t CoPrtCnvRadioTelegram::getBroadcastIndex() const { - if (isNormalTelegram() && m_data.size() > (DATA_IND_REQ_HEADER_LENGTH + 4)) - return getPayloadDataUInt32(3, 2); - return 0; + if (isNormalTelegram() && m_data.size() > (DATA_IND_REQ_HEADER_LENGTH + 4)) + return getPayloadDataUInt32(3, 2); + return 0; } -void CoPrtCnvRadioTelegram::setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, - const uint16_t a_size) +void CoPrtCnvRadioTelegram::setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, const uint16_t a_size) { - if (1 == a_size) - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + a_index, a_value); - else - { - uint16_t savedPayloadIndex = m_PayloadIndex; - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH + a_index; - setPayloadData(a_value, a_size); - m_PayloadIndex = savedPayloadIndex; - } + if (1 == a_size) + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + a_index, a_value); + else + { + uint16_t savedPayloadIndex = m_PayloadIndex; + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH + a_index; + setPayloadData(a_value, a_size); + m_PayloadIndex = savedPayloadIndex; + } } -void CoPrtCnvRadioTelegram::setPayloadDataComplete(const QByteArray& payload) +void CoPrtCnvRadioTelegram::setPayloadDataComplete(const QByteArray &payload) { - m_data.resize(payload.size() + DATA_IND_REQ_HEADER_LENGTH); - setHeader(m_data, getPDU_Type()); - memcpy(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH], payload.data(), payload.size()); + m_data.resize(payload.size() + DATA_IND_REQ_HEADER_LENGTH); + setHeader(m_data, getPDU_Type()); + memcpy(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH], payload.data(), payload.size()); } void CoPrtCnvRadioTelegram::resetPayloadSize(const uint16_t a_newPayloadSize) { - m_data.resize(a_newPayloadSize + DATA_IND_REQ_HEADER_LENGTH); - setHeader(m_data, getPDU_Type()); + m_data.resize(a_newPayloadSize + DATA_IND_REQ_HEADER_LENGTH); + setHeader(m_data, getPDU_Type()); - uint16_t size = m_data.size(); - set2Byte(m_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); - set2Byte(m_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); + uint16_t size = m_data.size(); + set2Byte(m_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); + set2Byte(m_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); } void CoPrtCnvRadioTelegram::setIdentity(const uint16_t a_identity) { - setPayloadDataWithIndex(isLoginTelegram() ? 0 : 1, a_identity, 2); + setPayloadDataWithIndex(isLoginTelegram() ? 0 : 1, a_identity, 2); } void CoPrtCnvRadioTelegram::setProtocolIdentifier(const E_ProtocolIdentifier a_ProtocolIdentifier) { - if (e_DataIndReq == getPDU_Type()) - set1Byte(m_data, 13, a_ProtocolIdentifier); + if (e_DataIndReq == getPDU_Type()) + set1Byte(m_data, 13, a_ProtocolIdentifier); } void CoPrtCnvRadioTelegram::setMessageReference(const uint8_t a_MessageReference) { - if (isSDSTL()) - set1Byte(m_data, 14, a_MessageReference); + if (isSDSTL()) + set1Byte(m_data, 14, a_MessageReference); } bool CoPrtCnvRadioTelegram::isSDSTL() const { - return (e_DataIndReq == getPDU_Type() && (e_UsingSDS_TL == (e_UsingSDS_TL & getProtocolIdentifier()))); + return (e_DataIndReq == getPDU_Type() && (e_UsingSDS_TL == (e_UsingSDS_TL & getProtocolIdentifier()))); } CoPrtCnvRadioTelegram::E_RegistrationStatus CoPrtCnvRadioTelegram::getRegistrationStatus() const { - return static_cast(m_data.at(5)); + return static_cast(m_data.at(5)); } std::string CoPrtCnvRadioTelegram::getRegistrationStatusAsText() const { - switch (getRegistrationStatus()) - { - case e_IssiSuccessfulRegistered: - return "IssiSuccessfulRegistered"; - case e_DuplicateISSI: - return "DuplicateISSI"; - case e_InvalidISSI: - return "InvalidISSI"; - case e_InvalidIpAddress: - return "InvalidIpAddress"; - } - return std::to_string(getRegistrationStatus()); + switch (getRegistrationStatus()) + { + case e_IssiSuccessfulRegistered: + return "IssiSuccessfulRegistered"; + case e_DuplicateISSI: + return "DuplicateISSI"; + case e_InvalidISSI: + return "InvalidISSI"; + case e_InvalidIpAddress: + return "InvalidIpAddress"; + } + return std::to_string(getRegistrationStatus()); } CoPrtCnvRadioTelegram::E_ProtocolIdentifier CoPrtCnvRadioTelegram::getProtocolIdentifier() const { - return static_cast(m_data.at(13)); + return static_cast(m_data.at(13)); } std::string CoPrtCnvRadioTelegram::getProtocolIdentifierAsText() const { - switch (getProtocolIdentifier()) - { - case e_SimpleTextMessagingWithoutSDS_TL: - return "Simple Text Messaging w/o SDS/TL"; - case e_SimpleGPS_WithoutSDS_TL: - return "Simple GPS w/o SDS/TL"; - case e_TDSMessageWithoutSDS_TL: - return "TDS Message w/o SDS/TL"; - case e_UsingSDS_TL: - return "SDS/TL"; - case e_SimpleTextMessagingUsingSDS_TL: - return "Simple Text Messaging with SDS/TL"; - case e_SimpleGPS_UsingSDS_TL: - return "Simple GPS with SDS/TL"; - case e_LoginTest: - return "Login-Test / Hohenfels"; - } - return std::to_string(getProtocolIdentifier()); + switch (getProtocolIdentifier()) + { + case e_SimpleTextMessagingWithoutSDS_TL: + return "Simple Text Messaging w/o SDS/TL"; + case e_SimpleGPS_WithoutSDS_TL: + return "Simple GPS w/o SDS/TL"; + case e_TDSMessageWithoutSDS_TL: + return "TDS Message w/o SDS/TL"; + case e_UsingSDS_TL: + return "SDS/TL"; + case e_SimpleTextMessagingUsingSDS_TL: + return "Simple Text Messaging with SDS/TL"; + case e_SimpleGPS_UsingSDS_TL: + return "Simple GPS with SDS/TL"; + case e_LoginTest: + return "Login-Test / Hohenfels"; + } + return std::to_string(getProtocolIdentifier()); } uint8_t CoPrtCnvRadioTelegram::getMessageReference() const { - return static_cast(m_data.at(14)); + return static_cast(m_data.at(14)); } uint8_t CoPrtCnvRadioTelegram::getAreaSelection() const { - return static_cast(m_data.at(15)); + return static_cast(m_data.at(15)); } uint8_t CoPrtCnvRadioTelegram::getValidityPeriod() const { - return static_cast(m_data.at(16)); + return static_cast(m_data.at(16)); } uint32_t CoPrtCnvRadioTelegram::getForwardAddress() const { - return getUInt32(17); + return getUInt32(17); } CoPrtCnvRadioTelegram::E_Flags CoPrtCnvRadioTelegram::getFlags() const { - return static_cast(m_data.at(21)); + return static_cast(m_data.at(21)); } std::string CoPrtCnvRadioTelegram::getFlagsAsText() const { - switch (getFlags()) - { - case e_FlagsNone: - return "No Flags"; + switch (getFlags()) + { + case e_FlagsNone: + return "No Flags"; - case e_StorageAllowed: - return "Storage Allowed"; + case e_StorageAllowed: + return "Storage Allowed"; - case e_GroupServiceOrOnlyStandardReportAllowed: - return "Group Service or only Standard Report Allowed"; + case e_GroupServiceOrOnlyStandardReportAllowed: + return "Group Service or only Standard Report Allowed"; - case e_ReceivedConfirmationRequested: - return "Received Confirmation Requested"; + case e_ReceivedConfirmationRequested: + return "Received Confirmation Requested"; - case e_ConsumedConfirmationRequested: - return "Consumed Confirmation Requested"; - } - std::ostringstream str; - str << getFlags(); - return str.str(); + case e_ConsumedConfirmationRequested: + return "Consumed Confirmation Requested"; + } + std::ostringstream str; + str << getFlags(); + return str.str(); } uint16_t CoPrtCnvRadioTelegram::getLengthInBits() const { - return getUInt16(22); + return getUInt16(22); } uint16_t CoPrtCnvRadioTelegram::getLengthInBytes() const { - return getUInt16(24); + return getUInt16(24); } bool CoPrtCnvRadioTelegram::getWithCrc() const { - if (getSize() > 26) - return ((m_data.at(26) & e_Checksum) == e_Checksum); - return false; + if (getSize() > 26) + return ((m_data.at(26) & e_Checksum) == e_Checksum); + return false; } CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report CoPrtCnvRadioTelegram::getDelivery() const { - return static_cast(m_data.at(16)); + return static_cast(m_data.at(16)); } std::string CoPrtCnvRadioTelegram::getDeliveryAsText() const { - switch (getDelivery()) - { - case e_SDS_ReceiptAcknowledgedByDestination: - return "SDS receipt acknowledged by destination"; + switch (getDelivery()) + { + case e_SDS_ReceiptAcknowledgedByDestination: + return "SDS receipt acknowledged by destination"; - case e_SDS_ConsumedByDestination: - return "SDS consumed by destination"; + case e_SDS_ConsumedByDestination: + return "SDS consumed by destination"; - case e_SourceIsNotAuthorizedForSDS: - return "Source is not authorized for SDS"; + case e_SourceIsNotAuthorizedForSDS: + return "Source is not authorized for SDS"; - case e_DestinationIsNotAuthorizedForSDS: - return "Destination is not authorized for SDS"; + case e_DestinationIsNotAuthorizedForSDS: + return "Destination is not authorized for SDS"; - case e_UnknownDestinationAddress: - return "Unknown destination address"; + case e_UnknownDestinationAddress: + return "Unknown destination address"; - case e_DeliveryFailed: - return "Delivery failed"; + case e_DeliveryFailed: + return "Delivery failed"; - case e_DestinationNotRegisteredOnSystem: - return "Destination not registered on system"; + case e_DestinationNotRegisteredOnSystem: + return "Destination not registered on system"; - case e_DestinationQueueFull: - return "Destination queue full"; + case e_DestinationQueueFull: + return "Destination queue full"; - case e_MessageTooLong: - return "Message too long"; + case e_MessageTooLong: + return "Message too long"; - case e_DestinationHostPC_NotConnected: - return "Destination host PC not connected"; + case e_DestinationHostPC_NotConnected: + return "Destination host PC not connected"; - case e_ProtocolNotSupported: - return "Protocol not supported"; + case e_ProtocolNotSupported: + return "Protocol not supported"; - case e_DataCodingSchemeNotSupported: - return "Datat coding scheme not supported"; + case e_DataCodingSchemeNotSupported: + return "Datat coding scheme not supported"; - case e_DestinationNotReachable: - return "Destination not reachable"; - } - std::ostringstream str; - str << getDelivery(); - return str.str(); + case e_DestinationNotReachable: + return "Destination not reachable"; + } + std::ostringstream str; + str << getDelivery(); + return str.str(); } int32_t CoPrtCnvRadioTelegram::getPayloadDataSInt24(uint16_t a_offset) const { - uint32_t value = getPayloadDataUInt32(a_offset, 3); + uint32_t value = getPayloadDataUInt32(a_offset, 3); - if (value & 0x800000) - value |= 0xFF800000; + if (value & 0x800000) + value |= 0xFF800000; - return value; + return value; } bool CoPrtCnvRadioTelegram::needsLicensing() const { - if (isNormalTelegram()) + if (isNormalTelegram()) + { + switch (getTelID()) { - switch (getTelID()) - { - case GEF_UMGEBUNGS_MELDUNG2: - case GEF_LIZENSIERUNG_TNE: - case GEF_AUFFORDERUNG_BITE_MELDUNG: - case GEF_ALLGEMEINE_NACHRICHT: - return false; - default: + case GEF_UMGEBUNGS_MELDUNG2: + case GEF_LIZENSIERUNG_TNE: + case GEF_AUFFORDERUNG_BITE_MELDUNG: + case GEF_ALLGEMEINE_NACHRICHT: + return false; + default: - break; - } - return true; + break; } - return false; + return true; + } + return false; } bool CoPrtCnvRadioTelegram::hasExpired() const { - uint32_t expireTime = getExpireTime(); - if (expireTime > 0) - { - uint32_t now = time(nullptr); - return (now >= expireTime); - } - return false; + uint32_t expireTime = getExpireTime(); + if (expireTime > 0) + { + uint32_t now = time(nullptr); + return (now >= expireTime); + } + return false; } uint32_t CoPrtCnvRadioTelegram::getExpireTime() const { - if (isNormalTelegram()) + if (isNormalTelegram()) + { + uint32_t wirkBegin = 0; + uint32_t wirkDauer = 0; + switch (getTelID()) { - uint32_t wirkBegin = 0; - uint32_t wirkDauer = 0; - switch (getTelID()) - { - case GEF_WIRKFELD_EINZELGESCHOSS: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = 5; - break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 2); - break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - wirkBegin = getPayloadDataUInt32(11, 4); - wirkDauer = getPayloadDataUInt32(15, 2); - break; - case GEF_WIRKFELD_A_KAMPFMITTEL: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 2) * 60 * 10; - break; - case GEF_WIRKFELD_C_KAMPFMITTEL: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60; - break; - case GEF_WIRKFELD_MINENSPERRE: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60 * 60; - break; - default: - return 0; - } - - if (0 == wirkDauer) - { - return 0; - } - - if (wirkBegin > 0) - return (wirkBegin + wirkDauer); + case GEF_WIRKFELD_EINZELGESCHOSS: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = 5; + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 2); + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + wirkBegin = getPayloadDataUInt32(11, 4); + wirkDauer = getPayloadDataUInt32(15, 2); + break; + case GEF_WIRKFELD_A_KAMPFMITTEL: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 2) * 60 * 10; + break; + case GEF_WIRKFELD_C_KAMPFMITTEL: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60; + break; + case GEF_WIRKFELD_MINENSPERRE: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60 * 60; + break; + default: + return 0; } - return 0; + + if (0 == wirkDauer) + { + return 0; + } + + if (wirkBegin > 0) + return (wirkBegin + wirkDauer); + } + return 0; } bool CoPrtCnvRadioTelegram::isContentValid() { - if (isNormalTelegram()) + if (isNormalTelegram()) + { + uint16_t wirkfeldkennung = 0; + uint8_t wirkfeldtyp = 0; + switch (getTelID()) { - uint16_t wirkfeldkennung = 0; - uint8_t wirkfeldtyp = 0; - switch (getTelID()) + case GEF_WIRKFELD_EINZELGESCHOSS: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_STATUS_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_C_KAMPFMITTEL: + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + wirkfeldkennung = getPayloadDataUInt32(5, 2); + wirkfeldtyp = 3; + Q_FALLTHROUGH(); + case GEF_DEAKTIVIERUNG_WIRKFELD: + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + if (GEF_DEAKTIVIERUNG_WIRKFELD == getTelID() || GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID()) { - case GEF_WIRKFELD_EINZELGESCHOSS: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_C_KAMPFMITTEL: - case GEF_WIRKFELD_EINZELMINENSIMULATOR: - wirkfeldkennung = getPayloadDataUInt32(5, 2); - wirkfeldtyp = 3; - Q_FALLTHROUGH(); - case GEF_DEAKTIVIERUNG_WIRKFELD: - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - if (GEF_DEAKTIVIERUNG_WIRKFELD == getTelID() || GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID()) - { - wirkfeldtyp = getPayloadDataUInt8(5); - wirkfeldkennung = getPayloadDataUInt32(6, 2); - } - - if ((wirkfeldtyp >= 1 && wirkfeldtyp <= 5) || (wirkfeldtyp == 8)) - { - if (wirkfeldkennung > 0 && wirkfeldkennung <= 32767) - return true; - ERROR_LOG(m_logger) << "Wirkfeldkennung (" << wirkfeldkennung - << ") of telegram with telId=" << getTelID() - << " is invalid. Must be 1..32768."; - return false; - } - if (GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID() && wirkfeldkennung > 0) - return true; - - ERROR_LOG(m_logger) << "Wirkfeldtyp (" << wirkfeldtyp << ") of telegram with telId=" << getTelID() - << " is invalid. Must be 1..5 or 8."; - return false; - - case GEF_DEAKTIVIERUNG_EINZELMINE: - if (isPayloadLengthOk(13)) - { - wirkfeldkennung = getPayloadDataUInt32(9, 2); - { - if (wirkfeldkennung > 32767) - { - ERROR_LOG(m_logger) << "DeaktivierungEinzelmine: wirkfeldkennung=" << wirkfeldkennung - << " too big. Must be 1..32767"; - return false; - } - } - return true; - } - return false; - - case GEF_TECHNIK_FUNKTIONSRAUM: - case GEF_FUNKTIONSRAUM: - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: { - uint32_t funktionsraumkennung = getPayloadDataUInt32(5, 2); - if (funktionsraumkennung > 0) - return true; - - ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung - << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; - return false; - } - case GEF_EINTRETEN_FUNKTIONSRAUM: - if (isPayloadLengthOk(15)) - { - uint32_t funktionsraumkennung = getPayloadDataUInt32(13, 2); - if (funktionsraumkennung > 0) - return true; - - ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung - << ") of telegram with telId=" << getTelID() - << " is invalid. Must be 1..65535."; - return false; - } - return false; - - case GEF_SPRACHAUSWAHL: { - uint8_t sprache = getPayloadDataUInt8(5); - if (sprache <= 3) - return true; - - ERROR_LOG(m_logger) << "Sprache (" << sprache << ") of telegram with telId=" << getTelID() - << " is invalid. Must be 0..3."; - return false; - } - - case GEF_MANIPULATIONSMELDUNG: - return isPayloadLengthOk(12); - - case GEF_BITE_MELDUNG2: - return isPayloadLengthOk(27, 19, 7); - - case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: - return isPayloadLengthOk(9); - - case GEF_FEHLERMELDUNG_GFD: - return isPayloadLengthOk(9); - - case GEF_POSITIONS_MELDUNG: - return isPayloadLengthOk(14); - - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: - return isPayloadLengthOk(15, 14, 2); - - case GEF_POSITIONS_MELDUNG_LFZ: - return isPayloadLengthOk(15); - - case GEF_TREFFER_EREIGNIS_DUS: - return isPayloadLengthOk(23); - - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: - return isPayloadLengthOk(22); - - case GEF_SCHIEDSRICHTEREINGRIFF: - return isPayloadLengthOk(16); - - case GEF_SELEKTIVE_AUFMUNITIONIERUNG: - return isPayloadLengthOk(8, 7, 8); - - case GEF_TAKTISCHER_STATUS: - return isPayloadLengthOk(16); - - case GEF_DATENVERKEHR_SRT_TDS: - case GEF_DATENVERKEHR_DMF_TDS: { - uint16_t length = m_data.size() - DATA_IND_REQ_HEADER_LENGTH; - - const uint16_t MIN_LENGTH = 7; - if (length >= MIN_LENGTH) - return true; - - ERROR_LOG(m_logger) << "The payload-length of telegram with telId=" << getTelID() - << " must be at least " << MIN_LENGTH << ", but it is only " << length; - return false; - } - - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: - return isPayloadLengthOk(10); - - case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: - return isPayloadLengthOk(9); - - case GEF_SONDERSENSORIK_FAHRSPUR: - return isPayloadLengthOk(15); - - case GEF_SONDERSENSORIK_DATEN: - return isPayloadLengthOk(17); - - case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: - return isPayloadLengthOk(24); - - case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: - return isPayloadLengthOk(25); - - case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: - return isPayloadLengthOk(16); - - case GEF_DATENVERKEHR_GEOP_TDS: - - return isPayloadLengthOk(15, 14, 1); - - case GEF_DATENVERKEHR_TGTC_TDS: - - return isPayloadLengthOk(8, 7, 1); - - case GEF_GERAETEEREIGNIS: - - return isPayloadLengthOk(25, 24, 1); - - case GEF_WAFFENZUORDNUNG: - - return isPayloadLengthOk(8, 7, 6); - - case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: - - return isPayloadLengthOk(13, 12, 5); - - case GEF_IPS_POSITIONSDATEN: - - return isPayloadLengthOk(8, 7, 2); - - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: - return isPayloadLengthOk({13, 17}); - - case GEF_TEILNEHMERMODE_MELDUNG: - return isPayloadLengthOk(15); - - case GEF_TEILNEHMER_KONFIG_ANTWORT: - return isPayloadLengthOk(27); - - case GEF_DEFINITION_IED: - return isPayloadLengthOk(24); - - case GEF_ZUSTAND_IED: - return isPayloadLengthOk(16); - - case GEF_STATUS_EINZELMINENSIMULATOR: - return isPayloadLengthOk(17); - - default: - - break; + wirkfeldtyp = getPayloadDataUInt8(5); + wirkfeldkennung = getPayloadDataUInt32(6, 2); } + + if ((wirkfeldtyp >= 1 && wirkfeldtyp <= 5) || (wirkfeldtyp == 8)) + { + if (wirkfeldkennung > 0 && wirkfeldkennung <= 32767) + return true; + ERROR_LOG(m_logger) << "Wirkfeldkennung (" << wirkfeldkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..32768."; + return false; + } + if (GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID() && wirkfeldkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Wirkfeldtyp (" << wirkfeldtyp << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..5 or 8."; + return false; + + case GEF_DEAKTIVIERUNG_EINZELMINE: + if (isPayloadLengthOk(13)) + { + wirkfeldkennung = getPayloadDataUInt32(9, 2); + { + if (wirkfeldkennung > 32767) + { + ERROR_LOG(m_logger) << "DeaktivierungEinzelmine: wirkfeldkennung=" << wirkfeldkennung << " too big. Must be 1..32767"; + return false; + } + } + return true; + } + return false; + + case GEF_TECHNIK_FUNKTIONSRAUM: + case GEF_FUNKTIONSRAUM: + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + { + uint32_t funktionsraumkennung = getPayloadDataUInt32(5, 2); + if (funktionsraumkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; + return false; + } + case GEF_EINTRETEN_FUNKTIONSRAUM: + if (isPayloadLengthOk(15)) + { + uint32_t funktionsraumkennung = getPayloadDataUInt32(13, 2); + if (funktionsraumkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; + return false; + } + return false; + + case GEF_SPRACHAUSWAHL: + { + uint8_t sprache = getPayloadDataUInt8(5); + if (sprache <= 3) + return true; + + ERROR_LOG(m_logger) << "Sprache (" << sprache << ") of telegram with telId=" << getTelID() << " is invalid. Must be 0..3."; + return false; + } + + case GEF_MANIPULATIONSMELDUNG: + return isPayloadLengthOk(12); + + case GEF_BITE_MELDUNG2: + return isPayloadLengthOk(27, 19, 7); + + case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: + return isPayloadLengthOk(9); + + case GEF_FEHLERMELDUNG_GFD: + return isPayloadLengthOk(9); + + case GEF_POSITIONS_MELDUNG: + return isPayloadLengthOk(14); + + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: + return isPayloadLengthOk(15, 14, 2); + + case GEF_POSITIONS_MELDUNG_LFZ: + return isPayloadLengthOk(15); + + case GEF_TREFFER_EREIGNIS_DUS: + return isPayloadLengthOk(23); + + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: + return isPayloadLengthOk(22); + + case GEF_SCHIEDSRICHTEREINGRIFF: + return isPayloadLengthOk(16); + + case GEF_SELEKTIVE_AUFMUNITIONIERUNG: + return isPayloadLengthOk(8, 7, 8); + + case GEF_TAKTISCHER_STATUS: + return isPayloadLengthOk(16); + + case GEF_DATENVERKEHR_SRT_TDS: + case GEF_DATENVERKEHR_DMF_TDS: + { + uint16_t length = m_data.size() - DATA_IND_REQ_HEADER_LENGTH; + + const uint16_t MIN_LENGTH = 7; + if (length >= MIN_LENGTH) + return true; + + ERROR_LOG(m_logger) << "The payload-length of telegram with telId=" << getTelID() << " must be at least " << MIN_LENGTH << ", but it is only " << length; + return false; + } + + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: + return isPayloadLengthOk(10); + + case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: + return isPayloadLengthOk(9); + + case GEF_SONDERSENSORIK_FAHRSPUR: + return isPayloadLengthOk(15); + + case GEF_SONDERSENSORIK_DATEN: + return isPayloadLengthOk(17); + + case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: + return isPayloadLengthOk(24); + + case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: + return isPayloadLengthOk(25); + + case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: + return isPayloadLengthOk(16); + + case GEF_DATENVERKEHR_GEOP_TDS: + + return isPayloadLengthOk(15, 14, 1); + + case GEF_DATENVERKEHR_TGTC_TDS: + + return isPayloadLengthOk(8, 7, 1); + + case GEF_GERAETEEREIGNIS: + + return isPayloadLengthOk(25, 24, 1); + + case GEF_WAFFENZUORDNUNG: + + return isPayloadLengthOk(8, 7, 6); + + case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: + + return isPayloadLengthOk(13, 12, 5); + + case GEF_IPS_POSITIONSDATEN: + + return isPayloadLengthOk(8, 7, 2); + + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + return isPayloadLengthOk({13, 17}); + + case GEF_TEILNEHMERMODE_MELDUNG: + return isPayloadLengthOk(15); + + case GEF_TEILNEHMER_KONFIG_ANTWORT: + return isPayloadLengthOk(27); + + case GEF_DEFINITION_IED: + return isPayloadLengthOk(24); + + case GEF_ZUSTAND_IED: + return isPayloadLengthOk(16); + + case GEF_STATUS_EINZELMINENSIMULATOR: + return isPayloadLengthOk(17); + + default: + + break; } - return true; + } + return true; } -bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, const uint16_t a_dataAmountOffset, - const uint8_t a_variableDataElementSize) const +bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, const uint16_t a_dataAmountOffset, const uint8_t a_variableDataElementSize) const { - if (0 == a_variableDataElementSize) - return isPayloadLengthOk(a_minLength); + if (0 == a_variableDataElementSize) + return isPayloadLengthOk(a_minLength); - const uint16_t length = getPayloadSize(); - if (length >= a_minLength) + const uint16_t length = getPayloadSize(); + if (length >= a_minLength) + { + uint8_t dataAmount = getPayloadDataUInt8(a_dataAmountOffset); + uint16_t dataSize = a_variableDataElementSize * dataAmount; + uint16_t expectedLength = dataSize + a_minLength; + if (expectedLength != length) { - uint8_t dataAmount = getPayloadDataUInt8(a_dataAmountOffset); - uint16_t dataSize = a_variableDataElementSize * dataAmount; - uint16_t expectedLength = dataSize + a_minLength; - if (expectedLength != length) - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " - << expectedLength << ", but it is " << length - << " (the amount of variable data in telegram was " << dataAmount << " => " - << dataSize << " bytes)"; - return false; - } + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " << expectedLength << ", but it is " << length + << " (the amount of variable data in telegram was " << dataAmount << " => " << dataSize << " bytes)"; + return false; } - else - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be at least " - << a_minLength << ", but it is only " << length; - return false; - } - return true; + } + else + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be at least " << a_minLength << ", but it is only " << length; + return false; + } + return true; } bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, uint16_t a_maxLength) const { - if (a_maxLength == 0) - return isPayloadLengthOk(a_minLength); + if (a_maxLength == 0) + return isPayloadLengthOk(a_minLength); - const uint16_t length = getPayloadSize(); - if (length < a_minLength) - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() - << " must be greater or equal to " << a_minLength << ", but it is " << length; - return false; - } + const uint16_t length = getPayloadSize(); + if (length < a_minLength) + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be greater or equal to " << a_minLength << ", but it is " << length; + return false; + } - if (length > a_maxLength) - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be fewer than " - << a_minLength << ", but it is " << length; - return false; - } - return true; + if (length > a_maxLength) + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be fewer than " << a_minLength << ", but it is " << length; + return false; + } + return true; } bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_length) const { - const uint16_t length = getPayloadSize(); - if (length == a_length) - return true; + const uint16_t length = getPayloadSize(); + if (length == a_length) + return true; - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " << a_length - << ", but it is " << length; - return false; + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " << a_length << ", but it is " << length; + return false; } -bool CoPrtCnvRadioTelegram::isPayloadLengthOk(const std::vector& a_lengths) const +bool CoPrtCnvRadioTelegram::isPayloadLengthOk(const std::vector &a_lengths) const { - const uint16_t length = getPayloadSize(); - if (std::any_of(a_lengths.begin(), a_lengths.end(), [length](int len) { return len == length; })) - return true; + const uint16_t length = getPayloadSize(); + if (std::any_of(a_lengths.begin(), a_lengths.end(), [length](int len) { return len == length; })) + return true; - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << ", is: " << length; - return false; + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << ", is: " << length; + return false; } -bool CoPrtCnvRadioTelegram::mustBeSentAsBroadcast(time_t a_currentTime, bool& a_wasLastBroadcast, - const bool a_updateBroadcastCounter) +bool CoPrtCnvRadioTelegram::mustBeSentAsBroadcast(time_t a_currentTime, bool &a_wasLastBroadcast, const bool a_updateBroadcastCounter) { - a_wasLastBroadcast = false; + a_wasLastBroadcast = false; - if (m_BroadcastCounter < s_maxBroadcastSendCnt && m_NextSendTime <= a_currentTime) + if (m_BroadcastCounter < s_maxBroadcastSendCnt && m_NextSendTime <= a_currentTime) + { + if (a_updateBroadcastCounter) { - if (a_updateBroadcastCounter) - { - switch (m_BroadcastCounter) - { - case 0: - if (s_2ndDelay >= 0) - { - m_NextSendTime = time(nullptr) + s_2ndDelay; - INFO_LOG(m_logger) - << "1st Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); - break; - } - ++m_BroadcastCounter; - Q_FALLTHROUGH(); - case 1: - if (s_3rdDelay >= 0) - { - m_NextSendTime = time(nullptr) + s_3rdDelay; - INFO_LOG(m_logger) - << "2nd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); - break; - } - ++m_BroadcastCounter; - Q_FALLTHROUGH(); - default: - INFO_LOG(m_logger) << "3rd Broadcast-Telegram telId=" << getTelID() - << " BC=" << getBroadcastIndex(); - m_NextSendTime = 0; - a_wasLastBroadcast = true; - } - ++m_BroadcastCounter; - } - return true; + switch (m_BroadcastCounter) + { + case 0: + if (s_2ndDelay >= 0) + { + m_NextSendTime = time(nullptr) + s_2ndDelay; + INFO_LOG(m_logger) << "1st Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); + break; + } + ++m_BroadcastCounter; + Q_FALLTHROUGH(); + case 1: + if (s_3rdDelay >= 0) + { + m_NextSendTime = time(nullptr) + s_3rdDelay; + INFO_LOG(m_logger) << "2nd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); + break; + } + ++m_BroadcastCounter; + Q_FALLTHROUGH(); + default: + INFO_LOG(m_logger) << "3rd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); + m_NextSendTime = 0; + a_wasLastBroadcast = true; + } + ++m_BroadcastCounter; } - return false; + return true; + } + return false; } void CoPrtCnvRadioTelegram::setBroadcastDelayTimes(int a_2ndDelay, int a_3rdDelay) { - s_2ndDelay = a_2ndDelay; - s_3rdDelay = a_3rdDelay; + s_2ndDelay = a_2ndDelay; + s_3rdDelay = a_3rdDelay; } void CoPrtCnvRadioTelegram::setMaxBroadcastSendCnt(int a_maxSendCnt) { - s_maxBroadcastSendCnt = a_maxSendCnt; + s_maxBroadcastSendCnt = a_maxSendCnt; } bool CoPrtCnvRadioTelegram::isMovedToBroadcastList() const { - return (m_BroadcastCounter >= 1); + return (m_BroadcastCounter >= 1); } void CoPrtCnvRadioTelegram::setBroadcastOnly(const bool a_doSet) { - m_IsBroadcastOnly = a_doSet; + m_IsBroadcastOnly = a_doSet; } bool CoPrtCnvRadioTelegram::isBroadcastOnly() const { - return m_IsBroadcastOnly; + return m_IsBroadcastOnly; } -void CoPrtCnvRadioTelegram::setBroadcastonlyTelegram( - const std::shared_ptr& a_radioTelegram) +void CoPrtCnvRadioTelegram::setBroadcastonlyTelegram(const std::shared_ptr &a_radioTelegram) { - if (a_radioTelegram != nullptr && m_BroadcastOnlyTelegram != nullptr) - ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr"; - if (a_radioTelegram != nullptr) - { - INFO_LOG(m_logger) << "Set braodcastonly-telegram: telId=" << a_radioTelegram->getTelID() - << " BC=" << a_radioTelegram->getBroadcastIndex(); - } - m_BroadcastOnlyTelegram = a_radioTelegram; + if (a_radioTelegram != nullptr && m_BroadcastOnlyTelegram != nullptr) + ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr"; + if (a_radioTelegram != nullptr) + { + INFO_LOG(m_logger) << "Set braodcastonly-telegram: telId=" << a_radioTelegram->getTelID() << " BC=" << a_radioTelegram->getBroadcastIndex(); + } + m_BroadcastOnlyTelegram = a_radioTelegram; } std::shared_ptr CoPrtCnvRadioTelegram::getBroadcastonlyTelegram() const { - return m_BroadcastOnlyTelegram; + return m_BroadcastOnlyTelegram; } -void CoPrtCnvRadioTelegram::set1Byte(QByteArray& a_data, uint16_t a_offset, uint8_t a_value) +void CoPrtCnvRadioTelegram::set1Byte(QByteArray &a_data, uint16_t a_offset, uint8_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint8_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint8_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } -void CoPrtCnvRadioTelegram::set2Byte(QByteArray& a_data, uint16_t a_offset, uint16_t a_value) +void CoPrtCnvRadioTelegram::set2Byte(QByteArray &a_data, uint16_t a_offset, uint16_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint16_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint16_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } -void CoPrtCnvRadioTelegram::set4Byte(QByteArray& a_data, uint16_t a_offset, uint32_t a_value) +void CoPrtCnvRadioTelegram::set4Byte(QByteArray &a_data, uint16_t a_offset, uint32_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint32_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint32_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } uint16_t CoPrtCnvRadioTelegram::getUInt16(const uint16_t a_offset) const { - const uint16_t* ptr = reinterpret_cast(&m_data.data()[a_offset]); - return *ptr; + const uint16_t *ptr = reinterpret_cast(&m_data.data()[a_offset]); + return *ptr; } uint32_t CoPrtCnvRadioTelegram::getUInt32(const uint16_t a_offset) const { - const uint32_t* ptr = reinterpret_cast(&m_data.data()[a_offset]); - return *ptr; + const uint32_t *ptr = reinterpret_cast(&m_data.data()[a_offset]); + return *ptr; } -void CoPrtCnvRadioTelegram::setHeader(QByteArray& data, E_PDU_Type pduType) +void CoPrtCnvRadioTelegram::setHeader(QByteArray &data, E_PDU_Type pduType) { - set1Byte(data, 0, MAGIC_NUMBER); - set1Byte(data, 1, 0); - set2Byte(data, 2, data.size() - sizeof(PrtCnvRadioGwHeader)); - set1Byte(data, 4, pduType); + set1Byte(data, 0, MAGIC_NUMBER); + set1Byte(data, 1, 0); + set2Byte(data, 2, data.size() - sizeof(PrtCnvRadioGwHeader)); + set1Byte(data, 4, pduType); } -void CoPrtCnvRadioTelegram::fillDataIndReqHeader(QByteArray& a_data) +void CoPrtCnvRadioTelegram::fillDataIndReqHeader(QByteArray &a_data) { - set1Byte(a_data, 4, e_DataIndReq); - setSrcISSI_Internal(a_data, 0); - setDestISSI_Internal(a_data, 0); + set1Byte(a_data, 4, e_DataIndReq); + setSrcISSI_Internal(a_data, 0); + setDestISSI_Internal(a_data, 0); - set1Byte(a_data, 13, s_protocolIdentifier); - set1Byte(a_data, 14, 0); - set1Byte(a_data, 15, 0); - set1Byte(a_data, 16, 0); - set1Byte(a_data, 17, 0); - set1Byte(a_data, 18, 0); - set1Byte(a_data, 19, 0); - set1Byte(a_data, 20, 0); - set1Byte(a_data, 21, e_FlagsNone); + set1Byte(a_data, 13, s_protocolIdentifier); + set1Byte(a_data, 14, 0); + set1Byte(a_data, 15, 0); + set1Byte(a_data, 16, 0); + set1Byte(a_data, 17, 0); + set1Byte(a_data, 18, 0); + set1Byte(a_data, 19, 0); + set1Byte(a_data, 20, 0); + set1Byte(a_data, 21, e_FlagsNone); - uint16_t size = a_data.size(); - set2Byte(a_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); - set2Byte(a_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); + uint16_t size = a_data.size(); + set2Byte(a_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); + set2Byte(a_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); } -void CoPrtCnvRadioTelegram::setSrcISSI_Internal(QByteArray& data, const uint32_t issi) +void CoPrtCnvRadioTelegram::setSrcISSI_Internal(QByteArray &data, const uint32_t issi) { - set4Byte(data, 5, issi); + set4Byte(data, 5, issi); } uint16_t CoPrtCnvRadioTelegram::getBroadcastCounter() const { - return m_BroadcastCounter; + return m_BroadcastCounter; } -void CoPrtCnvRadioTelegram::setDestISSI_Internal(QByteArray& data, const uint32_t issi) +void CoPrtCnvRadioTelegram::setDestISSI_Internal(QByteArray &data, const uint32_t issi) { - set4Byte(data, 9, issi); + set4Byte(data, 9, issi); } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp index 5d0a55b7f..0213436ad 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp @@ -23,44 +23,44 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } namespace N_CoPrtCnv { -/** + /** * used for telegram "LizenzierungTNE" to Radio */ -enum class E_LicensingKind -{ - /** + enum class E_LicensingKind + { + /** * Anmeldung erfolgreich */ - Success = 0, - /** + Success = 0, + /** * Anmeldung abgelehnt */ - Rejected = 1, - /** + Rejected = 1, + /** * Abmeldung */ - Unlicense = 2 -}; + Unlicense = 2 + }; -/** + /** * used for telegram "LizenzierungTNE" to Radio */ -enum class E_LicensingErrorCode -{ - Ok = 0, - Selftest = 1, - Battery = 2, - Configuration = 3, - Unlicense = 4, - IdentityDenied = 5 -}; + enum class E_LicensingErrorCode + { + Ok = 0, + Selftest = 1, + Battery = 2, + Configuration = 3, + Unlicense = 4, + IdentityDenied = 5 + }; -/** + /** * The radio-telegram, holds the data of telegram and additiional data for filling * and sending as braodcast. * @@ -68,45 +68,44 @@ enum class E_LicensingErrorCode * @version 1.0 * @created 12-Mrz-2010 16:37:23 */ -class COPRTCNV_EXPORT CoPrtCnvRadioTelegram -{ -public: - - /** + class COPRTCNV_EXPORT CoPrtCnvRadioTelegram + { + public: + /** * The radio-telegram flags * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - enum E_Flags - { - e_FlagsNone = 0x00, - e_StorageAllowed = 0x10, - e_GroupServiceOrOnlyStandardReportAllowed = 0x20, - e_ReceivedConfirmationRequested = 0x40, - e_ConsumedConfirmationRequested = 0x80 - }; + enum E_Flags + { + e_FlagsNone = 0x00, + e_StorageAllowed = 0x10, + e_GroupServiceOrOnlyStandardReportAllowed = 0x20, + e_ReceivedConfirmationRequested = 0x40, + e_ConsumedConfirmationRequested = 0x80 + }; - /** + /** * The transmission-protocoll to be used for radio-telegram * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - enum E_ProtocolIdentifier - { - e_SimpleTextMessagingWithoutSDS_TL = 0x02, - e_SimpleGPS_WithoutSDS_TL = 0x03, - e_TDSMessageWithoutSDS_TL = 0x50, // 80dec - e_UsingSDS_TL = 0x80, - e_SimpleTextMessagingUsingSDS_TL = 0x82, - e_SimpleGPS_UsingSDS_TL = 0x83, - e_LoginTest = 0x1D - }; + enum E_ProtocolIdentifier + { + e_SimpleTextMessagingWithoutSDS_TL = 0x02, + e_SimpleGPS_WithoutSDS_TL = 0x03, + e_TDSMessageWithoutSDS_TL = 0x50, // 80dec + e_UsingSDS_TL = 0x80, + e_SimpleTextMessagingUsingSDS_TL = 0x82, + e_SimpleGPS_UsingSDS_TL = 0x83, + e_LoginTest = 0x1D + }; - /** + /** * The telegram-type: * Fragmented, normal or login-telegram. * @@ -114,214 +113,213 @@ public: * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - enum E_FragmentStatus - { - e_NotFragmented = 0x00, - e_FirstFragment = 0x40, - e_MiddleFragment = 0xC0, - e_LastFragment = 0x80, - e_FragmentStatusMask = 0xC0, - e_Checksum = 0x20, - e_CounterMask = 0x0F, - e_NormalTelegram = 0x00, - e_LoginTelegram = 0x02, - e_DgpsTelegram = 0x03 - }; + enum E_FragmentStatus + { + e_NotFragmented = 0x00, + e_FirstFragment = 0x40, + e_MiddleFragment = 0xC0, + e_LastFragment = 0x80, + e_FragmentStatusMask = 0xC0, + e_Checksum = 0x20, + e_CounterMask = 0x0F, + e_NormalTelegram = 0x00, + e_LoginTelegram = 0x02, + e_DgpsTelegram = 0x03 + }; - /** + /** * The header of a radio-telegram * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - struct PrtCnvRadioGwHeader - { - /** + struct PrtCnvRadioGwHeader + { + /** * The first byte must be the magic number A5 */ - uint8_t m_MagicNumber; - /** + uint8_t m_MagicNumber; + /** * The telegram-counter */ - uint8_t m_Counter; - /** + uint8_t m_Counter; + /** * length of the following message in bytes */ - uint16_t m_Length; + uint16_t m_Length; + }; - }; - - /** + /** * The PDU-type of radio-telegram * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - enum E_PDU_Type - { - e_RegisterInd = 0, - e_RegisterRsp = 1, - e_DataIndReq = 2, - e_ReportIndReq = 3, - e_StatusIndReq = 4, - e_GroupMonitorReq = 6, - e_AirInterfaceLoadReq = 8, - e_AirLoadHyterra = 19 - }; + enum E_PDU_Type + { + e_RegisterInd = 0, + e_RegisterRsp = 1, + e_DataIndReq = 2, + e_ReportIndReq = 3, + e_StatusIndReq = 4, + e_GroupMonitorReq = 6, + e_AirInterfaceLoadReq = 8, + e_AirLoadHyterra = 19 + }; - /** + /** * @author alois.wismer * @version 1.0 * @created 17-Mrz-2010 13:06:40 */ - enum E_RegistrationStatus - { - e_IssiSuccessfulRegistered = 0, - e_DuplicateISSI = 1, - e_InvalidISSI = 2, - e_InvalidIpAddress = 3 - }; + enum E_RegistrationStatus + { + e_IssiSuccessfulRegistered = 0, + e_DuplicateISSI = 1, + e_InvalidISSI = 2, + e_InvalidIpAddress = 3 + }; - /** + /** * The delivery-status (only for SDS-TL) * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:39:54 */ - enum E_DeliveryStatusForTL_Report - { - e_SDS_ReceiptAcknowledgedByDestination = 0x00, - e_SDS_ConsumedByDestination = 0x02, - e_SourceIsNotAuthorizedForSDS = 0x43, - e_DestinationIsNotAuthorizedForSDS = 0x44, - e_UnknownDestinationAddress = 0x45, - e_DeliveryFailed = 0x4A, - e_DestinationNotRegisteredOnSystem = 0x4B, - e_DestinationQueueFull = 0x4C, - e_MessageTooLong = 0x4D, - e_DestinationHostPC_NotConnected = 0x4F, - e_ProtocolNotSupported = 0x50, - e_DataCodingSchemeNotSupported = 0x51, - e_DestinationNotReachable = 0x5A - }; + enum E_DeliveryStatusForTL_Report + { + e_SDS_ReceiptAcknowledgedByDestination = 0x00, + e_SDS_ConsumedByDestination = 0x02, + e_SourceIsNotAuthorizedForSDS = 0x43, + e_DestinationIsNotAuthorizedForSDS = 0x44, + e_UnknownDestinationAddress = 0x45, + e_DeliveryFailed = 0x4A, + e_DestinationNotRegisteredOnSystem = 0x4B, + e_DestinationQueueFull = 0x4C, + e_MessageTooLong = 0x4D, + e_DestinationHostPC_NotConnected = 0x4F, + e_ProtocolNotSupported = 0x50, + e_DataCodingSchemeNotSupported = 0x51, + e_DestinationNotReachable = 0x5A + }; - /** + /** * The status of the login-telegram * * @author wia * @version 1.0 * @created 12-Mrz-2010 16:41:22 */ - enum E_LoginStatus - { - e_LoginRequest = 0x40, - e_LoginAccept = 0x80, - e_LoginReject = 0xC0, - e_LoginStatusMask = 0xC0, - e_LoginMastering = 0x20, + enum E_LoginStatus + { + e_LoginRequest = 0x40, + e_LoginAccept = 0x80, + e_LoginReject = 0xC0, + e_LoginStatusMask = 0xC0, + e_LoginMastering = 0x20, - // Bits 2 & 3 - e_LoginNoExerciseAssignment = 0x00, // none set - e_LoginOtherEqId = 0x02, // bit2 set - e_LoginOtherISSI = 0x04, // bit3 set - e_LoginOtherExercise = 0x06, // bit2+3 set - }; + // Bits 2 & 3 + e_LoginNoExerciseAssignment = 0x00, // none set + e_LoginOtherEqId = 0x02, // bit2 set + e_LoginOtherISSI = 0x04, // bit3 set + e_LoginOtherExercise = 0x06, // bit2+3 set + }; - /** + /** * The first byte of the radio-telegram. Must be A5 */ - static constexpr uint8_t MAGIC_NUMBER = 0xA5; - /** + static constexpr uint8_t MAGIC_NUMBER = 0xA5; + /** * length of a data-ind/req-telegram-header with TL and without the 4-byte frame- * header. * It contains PDUtype, SourceISSI, DestinationISSI, ProtocolIdentifier, * LengthInBits and LengthInBytes. Payload-status is not included. */ - static constexpr uint16_t DATA_IND_REQ_WITH_TL_HEADER_LENGTH = 22; - /** + static constexpr uint16_t DATA_IND_REQ_WITH_TL_HEADER_LENGTH = 22; + /** * frameheader (4) + tetra-header (22) + payloadheader (1) */ - static constexpr uint16_t DATA_IND_REQ_HEADER_LENGTH = 27; - /** + static constexpr uint16_t DATA_IND_REQ_HEADER_LENGTH = 27; + /** * frameheader (4) + tetra-header (22) */ - static constexpr uint16_t DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER = DATA_IND_REQ_HEADER_LENGTH -1; - /** + static constexpr uint16_t DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER = DATA_IND_REQ_HEADER_LENGTH - 1; + /** * length of a data-ind/req-telegram-header without TL and without the 4-byte * frame-header. * It contains PDUtype, SourceISSI, DestinationISSI, ProtocolIdentifier, * LengthInBits and LengthInBytes. */ - static constexpr uint16_t DATA_IND_REQ_NO_TL_HEADER_LENGTH = 14; - /** + static constexpr uint16_t DATA_IND_REQ_NO_TL_HEADER_LENGTH = 14; + /** * the maximum length of payload-data (including payload-status-byte) of a radio- * telegram. If payload-data is larger, fragmentation must be made. */ - static constexpr uint16_t MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH = 249; // 256: 1 Byte Protokoll-ID + 255 Byte Daten - /** + static constexpr uint16_t MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH = 249; // 256: 1 Byte Protokoll-ID + 255 Byte Daten + /** * frameheader (4) + tetra-header (22) + payloadheader (1) */ - static constexpr uint16_t PAYLOAD_STATUS_LENGTH = 1; - /** + static constexpr uint16_t PAYLOAD_STATUS_LENGTH = 1; + /** * The protocol allows a max of 16 fragments, but due to definitions in file * zsksxdit.x it could be less. */ - static constexpr uint8_t MAX_NBR_OF_FRAGMENTS = 16; + static constexpr uint8_t MAX_NBR_OF_FRAGMENTS = 16; - /** + /** * constructor for a Register-Ind telegram * * @param a_sourceISSI */ - explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI); + explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI); - /** + /** * constructor for a Group-Monitoring-Ind telegram * * @param a_sourceISSI */ - explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const std::set &groups); + explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const std::set &groups); - /** + /** * constructor for a Report-Ind telegram * * @param a_sourceISSI * @param a_delivery */ - explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const E_DeliveryStatusForTL_Report a_delivery); + explicit CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const E_DeliveryStatusForTL_Report a_delivery); - /** + /** * Constructor for received telegrams (Data-Ind/Req, PDU type = 2) * * @param a_data */ - explicit CoPrtCnvRadioTelegram(const QByteArray &a_data); + explicit CoPrtCnvRadioTelegram(const QByteArray &a_data); - /** + /** * the telegraminformation will be set * * @param a_telegramId * @param a_payloadSize inclusive 3 byte telegraminformation * @param a_identity */ - explicit CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, const uint16_t a_identity); + explicit CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, const uint16_t a_identity); - /** + /** * for login-telegram * * @param a_loginTelegramStatus * @param a_identity * @param a_issi */ - explicit CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, uint32_t a_issi); - // set this issis for a login repsone e_LoginReject | e_LoginOtherExercise - void setLoginIssis(int hostIssi, int groupIssi1, int groupIssi2); + explicit CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, uint32_t a_issi); + // set this issis for a login repsone e_LoginReject | e_LoginOtherExercise + void setLoginIssis(int hostIssi, int groupIssi1, int groupIssi2); - /** + /** * for generating fragmented telegrams. * a_error will be true, if the fragmented telegrams cannot be generated. * @@ -329,176 +327,175 @@ public: * @param a_fragmentIndex * @param a_error */ - explicit CoPrtCnvRadioTelegram(const std::shared_ptr &a_bigTelegram, - const uint8_t a_fragmentIndex, bool &a_error); + explicit CoPrtCnvRadioTelegram(const std::shared_ptr &a_bigTelegram, const uint8_t a_fragmentIndex, bool &a_error); - virtual ~CoPrtCnvRadioTelegram(); + virtual ~CoPrtCnvRadioTelegram(); - /** + /** * ETS Hack due to +/-1 telegram id on tetra ... */ - void fixupTelegramIdForEts(bool convertToEtsId); - static void setEtsMode(bool bIsEtsMode); + void fixupTelegramIdForEts(bool convertToEtsId); + static void setEtsMode(bool bIsEtsMode); - /** + /** * Sets the paylaod-data. * * @param a_value * @param a_size */ - void setPayload1Byte(uint8_t a_value); - void setPayload2Byte(uint16_t a_value); - void setPayload3Byte(uint32_t a_value); - void setPayload4Byte(uint32_t a_value); - void setPayloadData(uint32_t a_value, const uint8_t a_size); + void setPayload1Byte(uint8_t a_value); + void setPayload2Byte(uint16_t a_value); + void setPayload3Byte(uint32_t a_value); + void setPayload4Byte(uint32_t a_value); + void setPayloadData(uint32_t a_value, const uint8_t a_size); - /** + /** * Sets the paylaod-data. * * @param a_value */ - void setPayloadData(const uint8_t a_value) { return setPayload1Byte(a_value); } + void setPayloadData(const uint8_t a_value) { return setPayload1Byte(a_value); } - /** + /** * Sets the paylaod-data. * * @param a_data * @param a_size */ - void setPayloadData(const uint8_t *a_data, const uint16_t a_size); + void setPayloadData(const uint8_t *a_data, const uint16_t a_size); - /** + /** * Returns a pointer to data of radio-telegram. */ - const char *getData() const { return m_data.data(); } - char *getData() { return m_data.data(); } - QByteArray data() const { return m_data; } + const char *getData() const { return m_data.data(); } + char *getData() { return m_data.data(); } + QByteArray data() const { return m_data; } - /** + /** * the overall size of telegram, including all headers */ - int getSize() const { return m_data.size(); } + int getSize() const { return m_data.size(); } - /** + /** * Returns the telegramId of radio-telegram. */ - gef_telegramm_id_et getTelID() const; + gef_telegramm_id_et getTelID() const; - /** + /** * Returns the counter. */ - uint8_t zaehler() const; + uint8_t zaehler() const; - /** + /** * Sets the counter. * * @param a_counter */ - void setZaehler(const uint8_t a_counter); + void setZaehler(const uint8_t a_counter); - /** + /** * Returns a paylaod-value. Its size depends on a_size. * * @param a_offset * @param a_size */ - uint32_t getPayloadDataUInt32(size_t a_offset, uint16_t a_size) const; + uint32_t getPayloadDataUInt32(size_t a_offset, uint16_t a_size) const; - /** + /** * Returns a 1-byte paylaod-value. * * @param a_offset */ - uint8_t getPayloadDataUInt8(size_t a_offset) const; + uint8_t getPayloadDataUInt8(size_t a_offset) const; - /** + /** * Returns the destISSI of radio-telegram. */ - uint32_t getDestISSI() const; + uint32_t getDestISSI() const; - /** + /** * Returns the identiy of radio-telegram. */ - uint16_t getIdentity() const; + uint16_t getIdentity() const; - /** + /** * Sets the srcISSI. * * @param a_ISSI */ - void setSrcISSI(const uint32_t a_ISSI); + void setSrcISSI(const uint32_t a_ISSI); - /** + /** * Returns true if it is broadcast-telegram, which has not yet set a broadcast- * index. */ - bool mustBroadcastBeSet() const; + bool mustBroadcastBeSet() const; - /** + /** * Sets the broadcast-index. * * @param a_broadcastIndex */ - void setBroadcastIndex(const uint16_t a_broadcastIndex); + void setBroadcastIndex(const uint16_t a_broadcastIndex); - /** + /** * Set the dstISSI. * * @param a_ISSI */ - void setDestISSI(const uint32_t a_ISSI); + void setDestISSI(const uint32_t a_ISSI); - /** + /** * Returns the PDU-type of radio-telegram. */ - CoPrtCnvRadioTelegram::E_PDU_Type getPDU_Type() const; + CoPrtCnvRadioTelegram::E_PDU_Type getPDU_Type() const; - /** + /** * Returns the fragment-status of radio-telegram. */ - CoPrtCnvRadioTelegram::E_FragmentStatus getFragmentStatus() const; + CoPrtCnvRadioTelegram::E_FragmentStatus getFragmentStatus() const; - /** + /** * Returns the fragment-counter of radio-telegram. */ - uint8_t getFragmentCounter() const; + uint8_t getFragmentCounter() const; - /** + /** * If CRC-bit is set, it checks the CRC and removes CRC-stuff from telegram. * If CRC-bit is not set, simply true will be returned */ - bool isCrcOk() const; + bool isCrcOk() const; - /** + /** * Returns the srcISSI of radio-telegram. */ - uint32_t getSrcISSI() const; + uint32_t getSrcISSI() const; - /** + /** * returns true if the it is a special login telegram */ - bool isLoginTelegram() const; + bool isLoginTelegram() const; - /** + /** * returns true if the it is a special login telegram */ - bool mustBeFragmented() const; + bool mustBeFragmented() const; - /** + /** * Returns a pointer to payload-data on a certain position of radio-telegram. * * @param a_offset */ - const uint8_t *getPayloadDataPtr(uint16_t a_offset) const; - uint8_t *getPayloadDataPtr(uint16_t a_offset); + const uint8_t *getPayloadDataPtr(uint16_t a_offset) const; + uint8_t *getPayloadDataPtr(uint16_t a_offset); - /** + /** * the size of payload-data without payload-status-header */ - virtual uint16_t getPayloadSize() const; + virtual uint16_t getPayloadSize() const; - /** + /** * Converts the list of fragmented telegrams into 1 big radio-telegram. * The function allocates a block of data. The caller is responsible to delete * this block of data, when no longer used. @@ -506,346 +503,342 @@ public: * * @param a_fragTelegramList */ - static QByteArray getUnfragmentedData(const std::multimap &a_fragTelegramList); + static QByteArray getUnfragmentedData(const std::multimap &a_fragTelegramList); - /** + /** * length without frame-header (4 byte) * * @param a_lengthWithoutFrame */ - static bool isTelegramLengthOk(const uint16_t a_lengthWithoutFrame); + static bool isTelegramLengthOk(const uint16_t a_lengthWithoutFrame); - /** + /** * returns true if the it is a normal, unfragmented telegram (but not a login- * telegram) */ - bool isNormalTelegram() const; + bool isNormalTelegram() const; - /** + /** * Returns the priority of radio-telegram. */ - uint8_t getPriority() const; + uint8_t getPriority() const; - /** + /** * Returns the broadcast-index of radio-telegram. */ - uint16_t getBroadcastIndex() const; + uint16_t getBroadcastIndex() const; - /** + /** * Sets the paylaod-data based on a_index with size a_size. * * @param a_index the payload-based position where the byte should be written * @param a_value * @param a_size */ - void setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, const uint16_t a_size); + void setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, const uint16_t a_size); - /** + /** * Sets the complete paylaod-data. * * @param a_data * @param a_length */ - void setPayloadDataComplete(const QByteArray &payload); + void setPayloadDataComplete(const QByteArray &payload); - /** + /** * ATTENTION with use of this function, because it is a (little) dirty trick to * resize the sammel-telegrams without memory-allocation. * It is the responsibity of the user to not overwrite memory!!! * * @param a_newPayloadSize */ - void resetPayloadSize(const uint16_t a_newPayloadSize); + void resetPayloadSize(const uint16_t a_newPayloadSize); - /** + /** * Set the identity. * * @param a_identity */ - void setIdentity(const uint16_t a_identity); + void setIdentity(const uint16_t a_identity); - /** + /** * Sets the protocol-identifier. * * @param a_ProtocolIdentifier */ - void setProtocolIdentifier(const E_ProtocolIdentifier a_ProtocolIdentifier); + void setProtocolIdentifier(const E_ProtocolIdentifier a_ProtocolIdentifier); - /** + /** * Sets the message-reference. * * @param a_MessageReference */ - void setMessageReference(const uint8_t a_MessageReference); + void setMessageReference(const uint8_t a_MessageReference); - /** + /** * returns true if the it is a SDS/TL telegram */ - bool isSDSTL() const; + bool isSDSTL() const; - /** + /** * Returns the registration-status of TETRA-header of SdsGw-Register-Rsp telegram */ - CoPrtCnvRadioTelegram::E_RegistrationStatus getRegistrationStatus() const; + CoPrtCnvRadioTelegram::E_RegistrationStatus getRegistrationStatus() const; - /** + /** * Returns the registration-status of TETRA-header of SdsGw-Register-Rsp telegram * in text-form */ - std::string getRegistrationStatusAsText() const; + std::string getRegistrationStatusAsText() const; - /** + /** * Returns the protocolIdentifier of radio-telegram. */ - CoPrtCnvRadioTelegram::E_ProtocolIdentifier getProtocolIdentifier() const; + CoPrtCnvRadioTelegram::E_ProtocolIdentifier getProtocolIdentifier() const; - /** + /** * Returns the protocolIdentifier of radio-telegram in text-form */ - std::string getProtocolIdentifierAsText() const; + std::string getProtocolIdentifierAsText() const; - /** + /** * Returns the message-reference of radio-telegram. */ - uint8_t getMessageReference() const; + uint8_t getMessageReference() const; - /** + /** * Returns the area selection of TETRA-Header */ - uint8_t getAreaSelection() const; + uint8_t getAreaSelection() const; - /** + /** * Returns the validity period of radio-telegram. */ - uint8_t getValidityPeriod() const; + uint8_t getValidityPeriod() const; - /** + /** * Returns the forward-address of TETRA-Header */ - uint32_t getForwardAddress() const; + uint32_t getForwardAddress() const; - /** + /** * Returns the flags of TETRA-Header */ - CoPrtCnvRadioTelegram::E_Flags getFlags() const; + CoPrtCnvRadioTelegram::E_Flags getFlags() const; - /** + /** * Returns the flags of TETRA-Header as text */ - std::string getFlagsAsText() const; + std::string getFlagsAsText() const; - /** + /** * Returns the length in bits-field of TETRA-Header */ - uint16_t getLengthInBits() const; + uint16_t getLengthInBits() const; - /** + /** * Returns the length in bytes-field of TETRA-Header */ - uint16_t getLengthInBytes() const; + uint16_t getLengthInBytes() const; - /** + /** * Returns true when the Telegram has a crc checksum. */ - bool getWithCrc() const; + bool getWithCrc() const; - /** + /** * Returns the delivery-field of TETRA-Header of SdsGw-Report-Ind/Req telegrams. */ - CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report getDelivery() const; + CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report getDelivery() const; - /** + /** * Returns the delivery-field of TETRA-Header of SdsGw-Report-Ind/Req telegrams as * text. */ - std::string getDeliveryAsText() const; + std::string getDeliveryAsText() const; - /** + /** * Converts a signed 3-byte value into a signed 4-byte-value. I.e. used for * positions (north and east). * * @param a_offset */ - int32_t getPayloadDataSInt24(uint16_t a_offset) const; + int32_t getPayloadDataSInt24(uint16_t a_offset) const; - /** + /** * Returns true if the telegram needs licensing. */ - bool needsLicensing() const; + bool needsLicensing() const; - /** + /** * returns true when the telegram has an expiry-date and is expired. * Returns false if the telegram has no expiry-date */ - bool hasExpired() const; + bool hasExpired() const; - /** + /** * Returns the expire-time of the telegram. * Returns 0 if the telegram has not expire-time. */ - uint32_t getExpireTime() const; + uint32_t getExpireTime() const; - /** + /** * checks whether the content of telegram is valid, but only a few data will be * checked, i.e. the kennung of wirkfeld and funktionsraum. * Returns true if content of telegram is vaild (or will not be checked) */ - bool isContentValid(); + bool isContentValid(); - /** + /** * returns true if it is time to send this telegram as normal broadcast. * * @param a_currentTime * @param a_wasLastBroadcast * @param a_updateBroadcastCounter */ - bool mustBeSentAsBroadcast(time_t a_currentTime, bool &a_wasLastBroadcast, const bool a_updateBroadcastCounter = true); + bool mustBeSentAsBroadcast(time_t a_currentTime, bool &a_wasLastBroadcast, const bool a_updateBroadcastCounter = true); - /** + /** * Set the delay-times for 2nd and 3rd broadcast. * * @param a_2ndDelay * @param a_3rdDelay */ - static void setBroadcastDelayTimes(int a_2ndDelay, int a_3rdDelay); + static void setBroadcastDelayTimes(int a_2ndDelay, int a_3rdDelay); - /** + /** * Set the max count of how often a Broadcasttelegram will be send (0 is ignored, the telegram is send at least one time. * * @brief setMaxBroadcastSendCnt * @param a_maxSendCnt */ - static void setMaxBroadcastSendCnt(int a_maxSendCnt); + static void setMaxBroadcastSendCnt(int a_maxSendCnt); - /** + /** * returns true if it is a broadcast-telegram and it is moved to broadcast-list */ - bool isMovedToBroadcastList() const; + bool isMovedToBroadcastList() const; - /** + /** * Sets the broadcast-only-flag. * * @param a_doSet */ - void setBroadcastOnly(const bool a_doSet = true); + void setBroadcastOnly(const bool a_doSet = true); - /** + /** * Returns the broadcast-only-flag. */ - bool isBroadcastOnly() const; + bool isBroadcastOnly() const; - /** + /** * Defines the telegram which will be sent as normal broadcast instead a * Sammeltelegram. * * @param a_radioTelegram */ - void setBroadcastonlyTelegram(const std::shared_ptr &a_radioTelegram); + void setBroadcastonlyTelegram(const std::shared_ptr &a_radioTelegram); - /** + /** * Returns the telegram which will be sent as normal broadcast instead a * Sammeltelegram. */ - std::shared_ptr getBroadcastonlyTelegram() const; + std::shared_ptr getBroadcastonlyTelegram() const; - /** + /** * nbr of times already sent this normal broadcast (only used for broadcast- * telegrams) */ - uint16_t getBroadcastCounter() const; + uint16_t getBroadcastCounter() const; - //begin_public_{ACFD8558-E5A4-4877-B503-41FCB730B678} - //end_public_{ACFD8558-E5A4-4877-B503-41FCB730B678} + //begin_public_{ACFD8558-E5A4-4877-B503-41FCB730B678} + //end_public_{ACFD8558-E5A4-4877-B503-41FCB730B678} -protected: - - /** + protected: + /** * The telegram-data, including header */ - QByteArray m_data; + QByteArray m_data; - /** + /** * The internal index for filling telegram with setPayloadData() */ - uint16_t m_PayloadIndex; - /** + uint16_t m_PayloadIndex; + /** * nbr of times already sent this normal broadcast (only used for broadcast- * telegrams) */ - uint16_t m_BroadcastCounter; - /** + uint16_t m_BroadcastCounter; + /** * time when sending next normal broadcast (only used for broadcast-telegrams) */ - time_t m_NextSendTime; - /** + time_t m_NextSendTime; + /** * The delay between 1st and 2nd normal broadcast */ - static int s_2ndDelay; - /** + static int s_2ndDelay; + /** * The delay between 2nd and 3rd normal broadcast */ - static int s_3rdDelay; - /** + static int s_3rdDelay; + /** * The delay between 2nd and 3rd normal broadcast */ - static int s_maxBroadcastSendCnt; - /** + static int s_maxBroadcastSendCnt; + /** * True if the telegram is used only as normal broadcast, not as nachforderung */ - bool m_IsBroadcastOnly; - /** + bool m_IsBroadcastOnly; + /** * Contains the normal broadcast-telegram, which will be sent instead of * sammeltelegram for Nachfoderung */ - std::shared_ptr m_BroadcastOnlyTelegram; + std::shared_ptr m_BroadcastOnlyTelegram; - /** + /** * For ETS - there al telgram ids are +1, therefore we have to remove 1 to be able * to work with our ids. */ - static bool s_etsMode; + static bool s_etsMode; - /** + /** * checks the payload-length of telegram. Returns true if the length is ok. * Logs an error if length not ok. */ - bool isPayloadLengthOk(uint16_t a_minLength, - const uint16_t a_dataAmountOffset, - const uint8_t a_variableDataElementSize) const; - bool isPayloadLengthOk(uint16_t a_minLength, - uint16_t a_maxLength) const; - bool isPayloadLengthOk(uint16_t a_length) const; - bool isPayloadLengthOk(const std::vector &a_lengths) const; + bool isPayloadLengthOk(uint16_t a_minLength, const uint16_t a_dataAmountOffset, const uint8_t a_variableDataElementSize) const; + bool isPayloadLengthOk(uint16_t a_minLength, uint16_t a_maxLength) const; + bool isPayloadLengthOk(uint16_t a_length) const; + bool isPayloadLengthOk(const std::vector &a_lengths) const; - /** + /** * Set a 1-byte value at offset a_offset. */ - static void set1Byte(QByteArray &a_data, uint16_t a_offset, uint8_t a_value); + static void set1Byte(QByteArray &a_data, uint16_t a_offset, uint8_t a_value); - /** + /** * Set a 2-byte value at offset a_offset. */ - static void set2Byte(QByteArray &a_data, uint16_t a_offset, uint16_t a_value); + static void set2Byte(QByteArray &a_data, uint16_t a_offset, uint16_t a_value); - /** + /** * Set a 4-byte value at offset a_offset. */ - static void set4Byte(QByteArray &a_data, uint16_t a_offset, uint32_t a_value); + static void set4Byte(QByteArray &a_data, uint16_t a_offset, uint32_t a_value); - uint8_t getUInt8(const uint16_t a_offset) const { return static_cast(m_data.at(a_offset)); } - uint16_t getUInt16(const uint16_t a_offset) const; - uint32_t getUInt32(const uint16_t a_offset) const; + uint8_t getUInt8(const uint16_t a_offset) const { return static_cast(m_data.at(a_offset)); } + uint16_t getUInt16(const uint16_t a_offset) const; + uint32_t getUInt32(const uint16_t a_offset) const; - /** + /** * Sets the header with magic-number and size. The length will be 0. * * @param a_data * @param a_size The overall-size including all headers */ - static void setHeader(QByteArray &data, E_PDU_Type pduType); + static void setHeader(QByteArray &data, E_PDU_Type pduType); - /** + /** * Fills the header with SrcISSI, DstISSI, length in bits and length in bytes. PDU * will be set for DataIndicationRequest. * ProtocolIdentifier, message reference, area selection, forward address, flags @@ -853,29 +846,29 @@ protected: * * @param a_data */ - static void fillDataIndReqHeader(QByteArray &a_data); + static void fillDataIndReqHeader(QByteArray &a_data); - /** + /** * Internal function to set the srcISSI. * * @param a_data * @param a_ISSI */ - static void setSrcISSI_Internal(QByteArray &data, const uint32_t issi); + static void setSrcISSI_Internal(QByteArray &data, const uint32_t issi); - /** + /** * Internal function to set the dstISSI. * * @param a_data * @param a_ISSI */ - static void setDestISSI_Internal(QByteArray &data, const uint32_t issi); + static void setDestISSI_Internal(QByteArray &data, const uint32_t issi); -private: - /** + private: + /** * The logger object */ - NGL::INGLLogger &m_logger; -}; + NGL::INGLLogger &m_logger; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverter.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverter.hpp index b6d41780c..1a9fcc2fe 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverter.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverter.hpp @@ -17,56 +17,56 @@ namespace TrainingAreaBase { -namespace TetraIcd -{ -struct TrainingAreaTelegram; -} + namespace TetraIcd + { + struct TrainingAreaTelegram; + } } namespace N_CoPrtCnv { -class CoPrtCnvRadioTelegram; -class CoPrtCnvCentralTelegram; + class CoPrtCnvRadioTelegram; + class CoPrtCnvCentralTelegram; -/** + /** * This class is responsible to convert radio-telegrams into central-telegrams and * vice versa. * @author alois.wismer * @version 1.0 * @created 19-Mrz-2010 13:32:40 */ -namespace CoPrtCnvTelegramConverter -{ -/** + namespace CoPrtCnvTelegramConverter + { + /** * Converts central-telegrams to radio-telegrams. * Returns NULL if conversion was failed. * * @param a_telegram */ -COPRTCNV_EXPORT CoPrtCnvRadioTelegram *convertToRadio(CoPrtCnvCentralTelegram *a_telegram); -COPRTCNV_EXPORT CoPrtCnvRadioTelegram *convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *a_telegram); + COPRTCNV_EXPORT CoPrtCnvRadioTelegram *convertToRadio(CoPrtCnvCentralTelegram *a_telegram); + COPRTCNV_EXPORT CoPrtCnvRadioTelegram *convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *a_telegram); -/** + /** * converts a radiotelegram into a central. * returns nullptr if conversion failed * * @param a_radioTelegram */ -COPRTCNV_EXPORT CoPrtCnvCentralTelegram *convertToCentral(const CoPrtCnvRadioTelegram *a_radioTelegram); -COPRTCNV_EXPORT TrainingAreaBase::TetraIcd::TrainingAreaTelegram *convertToTabTele(const CoPrtCnvRadioTelegram *a_radioTelegram); + COPRTCNV_EXPORT CoPrtCnvCentralTelegram *convertToCentral(const CoPrtCnvRadioTelegram *a_radioTelegram); + COPRTCNV_EXPORT TrainingAreaBase::TetraIcd::TrainingAreaTelegram *convertToTabTele(const CoPrtCnvRadioTelegram *a_radioTelegram); -/** + /** * Set the text codec to use for string send to/received from tetra */ -COPRTCNV_EXPORT void setTetraTextCodec(const char *codecName); + COPRTCNV_EXPORT void setTetraTextCodec(const char *codecName); -/** + /** * Set to trueif single fire (WIRKFELD_EINZELGESCHOSS) has two bytes for diameter, otherwise only one byte is used */ -COPRTCNV_EXPORT void setUse2BytesForSingleFireDiameter(bool bUse); -COPRTCNV_EXPORT void setUsePvSan(bool bUse); + COPRTCNV_EXPORT void setUse2BytesForSingleFireDiameter(bool bUse); + COPRTCNV_EXPORT void setUsePvSan(bool bUse); -} + } } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp index d0326be85..45586d2c6 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp @@ -18,1798 +18,1812 @@ using namespace TrainingAreaBase::TetraIcd; namespace N_CoPrtCnv { -namespace CoPrtCnvTelegramConverter -{ + namespace CoPrtCnvTelegramConverter + { -static bool s_use2BytesForSingleFireDiameter = true; -static bool s_usePvSan = false; + static bool s_use2BytesForSingleFireDiameter = true; + static bool s_usePvSan = false; -static inline NGL::INGLLogger& logger() -{ - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvTelegramConverter"); -} - -template static inline bool checkBitmask(const T& d, int bitmask) -{ - return ((d & bitmask) == bitmask); -} - -template void getSpecialSensorData(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset, T* tele) -{ - const uint8_t betrZust = a_radioTelegram->getPayloadDataUInt32(offset, 1); - const uint8_t spuerfunktion = a_radioTelegram->getPayloadDataUInt32(offset + 1, 1); - tele->operationalState = betrZust; - tele->airSensor = checkBitmask(spuerfunktion, 0x80); - tele->tireSensor = checkBitmask(spuerfunktion, 0x40); - tele->pointSensor = checkBitmask(spuerfunktion, 0x20); - tele->solidMatterSampleExtractor = checkBitmask(spuerfunktion, 0x10); -} - -int getVitality(uint32_t index) -{ - uint32_t vitalty = (index &= 0xF000); - uint32_t retVitalty = 0; - retVitalty = vitalty >> 12; - if (retVitalty > 0) + static inline NGL::INGLLogger &logger() { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvTelegramConverter"); + } + + template static inline bool checkBitmask(const T &d, int bitmask) + { + return ((d & bitmask) == bitmask); + } + + template void getSpecialSensorData(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset, T *tele) + { + const uint8_t betrZust = a_radioTelegram->getPayloadDataUInt32(offset, 1); + const uint8_t spuerfunktion = a_radioTelegram->getPayloadDataUInt32(offset + 1, 1); + tele->operationalState = betrZust; + tele->airSensor = checkBitmask(spuerfunktion, 0x80); + tele->tireSensor = checkBitmask(spuerfunktion, 0x40); + tele->pointSensor = checkBitmask(spuerfunktion, 0x20); + tele->solidMatterSampleExtractor = checkBitmask(spuerfunktion, 0x10); + } + + int getVitality(uint32_t index) + { + uint32_t vitalty = (index &= 0xF000); + uint32_t retVitalty = 0; + retVitalty = vitalty >> 12; + if (retVitalty > 0) + { retVitalty -= 1; return retVitalty * 10; + } + return UINT16_MAX; } - return UINT16_MAX; -} -void setVitality(uint16_t& index, uint16_t vitality) -{ - if (vitality == UINT16_MAX) - vitality = 0; - else + void setVitality(uint16_t &index, uint16_t vitality) { + if (vitality == UINT16_MAX) + vitality = 0; + else + { vitality /= 10; vitality += 1; if (vitality > 11) { - ERROR_LOG(logger()) << "Cant convert Vitality!"; - return; + ERROR_LOG(logger()) << "Cant convert Vitality!"; + return; } - } - for (int i = 0; i <= 3; i++) - { + } + for (int i = 0; i <= 3; i++) + { if (((vitality) & (1 << (i)))) - index |= (1UL << (i + 12)); + index |= (1UL << (i + 12)); + } } -} -template void getTaktZustand(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t iOffset, T* tele) -{ - tele->vulnerabilityState = static_cast( - a_radioTelegram->getPayloadDataUInt32(iOffset + 0, 1)); - - const uint32_t teilnehmertyp = a_radioTelegram->getPayloadDataUInt32(iOffset + 1, 1); - const uint32_t index = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 2); - if (index) + template void getTaktZustand(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t iOffset, T *tele) { + tele->vulnerabilityState = static_cast(a_radioTelegram->getPayloadDataUInt32(iOffset + 0, 1)); + + const uint32_t teilnehmertyp = a_radioTelegram->getPayloadDataUInt32(iOffset + 1, 1); + const uint32_t index = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 2); + if (index) + { uint32_t indexForVulnerabilit = index; indexForVulnerabilit &= 0x0FFF; tele->tasVulnerabilityKindId = teilnehmertyp; tele->tasVulnerabilityKindId <<= 16; tele->tasVulnerabilityKindId |= indexForVulnerabilit; tele->tasVitality = getVitality(index); - } - else + } + else tele->tasVulnerabilityKindId = 0; - tele->vulnerabilityBits = 0; - int tmp = a_radioTelegram->getPayloadDataUInt32(iOffset + 4, 2); + tele->vulnerabilityBits = 0; + int tmp = a_radioTelegram->getPayloadDataUInt32(iOffset + 4, 2); - if (tmp == 0) + if (tmp == 0) tele->vulnerabilityBits |= 0x1; - else - { + else + { for (int i = 1; i <= static_cast(VulnerabilityState::CContamination); ++i) - tele->vulnerabilityBits |= ((tmp >> (16 - i)) & 0x1) << (i); + tele->vulnerabilityBits |= ((tmp >> (16 - i)) & 0x1) << (i); + } } -} -static BiteError getBiteError(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t iOffset) -{ - BiteError ret; - ret.canDeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 0); - ret.subdeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 1); - ret.uniqueId = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 4); - ret.errorNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 6); - - return ret; -} - -static void convertToTetraEncoding(N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegramm, const std::string& stdString, - const uint16_t a_size) -{ - QByteArray encodedData = QByteArray::fromStdString(stdString); - encodedData = encodedData.leftJustified(a_size, '\0', true); - encodedData[a_size - 1] = '\0'; - - const uint8_t* data = reinterpret_cast(encodedData.data()); - radioTelegramm->setPayloadData(data, a_size); -} - -void setTetraTextCodec(const char* /*codecName*/) -{ - // Qt6 uses UTF-8 by default, QTextCodec is no longer available -} - -void setUse2BytesForSingleFireDiameter(bool bUse) -{ - s_use2BytesForSingleFireDiameter = bUse; -} - -void setUsePvSan(bool bUse) -{ - s_usePvSan = bUse; -} - -template T fromJson(CoPrtCnvCentralTelegram* radioTelegram) -{ - return T::fromJson(radioTelegram->jsonData()); -} - -template const T& fromJson(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* tabTelegram) -{ - return static_cast(*tabTelegram); -} - -TrainingAreaBase::TetraIcd::TelegramId getTelegramId(CoPrtCnvCentralTelegram* centralTelegram) -{ - return TrainingAreaBase::TetraIcd::TelegramId(centralTelegram->telegramId()); -} - -TrainingAreaBase::TetraIcd::TelegramId -getTelegramId(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* tabTelegram) -{ - return tabTelegram->id(); -} - -void convertToSecAndSetTime(int64_t timeStamp, N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegram) -{ - radioTelegram->setPayloadData((uint32_t)(timeStamp / 1000), 4); -} - -template void setCommonAesParams(const T& tele, CoPrtCnvRadioTelegram* radioTelegram) -{ - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.partyId, 1); - convertToSecAndSetTime(tele.effectStart, radioTelegram); -} - -template void setAesPosition(const T& tele, CoPrtCnvRadioTelegram* radioTelegram) -{ - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); -} - -static inline int compassToMathAngleForSfm(double compassDegree) -{ - int ret = qRound((90.0 - compassDegree) * 100.0); - while (ret < 0) - ret += 36000; - while (ret > 36000) - ret -= 36000; - return ret; -} - -template static CoPrtCnvRadioTelegram* convertToRadioInternal(T* a_telegram) -{ - N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegram = nullptr; - switch (getTelegramId(a_telegram)) + static BiteError getBiteError(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t iOffset) { - case Constraints::id(): { - const Init& tele(fromJson(a_telegram)); + BiteError ret; + ret.canDeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 0); + ret.subdeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 1); + ret.uniqueId = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 4); + ret.errorNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 6); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_INIT, 4, tele.header.equipmentNumber); - uint8_t initialisierungsdaten = 0; - initialisierungsdaten |= ((uint8_t(tele.resetVulnerabilityState) & 0x01) << 6); - initialisierungsdaten |= ((uint8_t(tele.restockCharges) & 0x01) << 5); - initialisierungsdaten |= ((uint8_t(tele.resetManipulation) & 0x01) << 0); - initialisierungsdaten |= ((uint8_t(tele.restockSanitationMaterial) & 0x01) << 1); + return ret; + } - radioTelegram->setPayloadData(initialisierungsdaten); - break; + static void convertToTetraEncoding(N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegramm, const std::string &stdString, const uint16_t a_size) + { + QByteArray encodedData = QByteArray::fromStdString(stdString); + encodedData = encodedData.leftJustified(a_size, '\0', true); + encodedData[a_size - 1] = '\0'; + + const uint8_t *data = reinterpret_cast(encodedData.data()); + radioTelegramm->setPayloadData(data, a_size); + } + + void setTetraTextCodec(const char * /*codecName*/) + { + // Qt6 uses UTF-8 by default, QTextCodec is no longer available + } + + void setUse2BytesForSingleFireDiameter(bool bUse) + { + s_use2BytesForSingleFireDiameter = bUse; + } + + void setUsePvSan(bool bUse) + { + s_usePvSan = bUse; + } + + template T fromJson(CoPrtCnvCentralTelegram *radioTelegram) + { + return T::fromJson(radioTelegram->jsonData()); + } + + template const T &fromJson(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tabTelegram) + { + return static_cast(*tabTelegram); + } + + TrainingAreaBase::TetraIcd::TelegramId getTelegramId(CoPrtCnvCentralTelegram *centralTelegram) + { + return TrainingAreaBase::TetraIcd::TelegramId(centralTelegram->telegramId()); + } + + TrainingAreaBase::TetraIcd::TelegramId getTelegramId(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tabTelegram) + { + return tabTelegram->id(); + } + + void convertToSecAndSetTime(int64_t timeStamp, N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram) + { + radioTelegram->setPayloadData((uint32_t)(timeStamp / 1000), 4); + } + + template void setCommonAesParams(const T &tele, CoPrtCnvRadioTelegram *radioTelegram) + { + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.partyId, 1); + convertToSecAndSetTime(tele.effectStart, radioTelegram); + } + + template void setAesPosition(const T &tele, CoPrtCnvRadioTelegram *radioTelegram) + { + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + } + + static inline int compassToMathAngleForSfm(double compassDegree) + { + int ret = qRound((90.0 - compassDegree) * 100.0); + while (ret < 0) + ret += 36000; + while (ret > 36000) + ret -= 36000; + return ret; + } + + template static CoPrtCnvRadioTelegram *convertToRadioInternal(T *a_telegram) + { + N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram = nullptr; + switch (getTelegramId(a_telegram)) + { + case Constraints::id(): + { + const Init &tele(fromJson(a_telegram)); + + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_INIT, 4, tele.header.equipmentNumber); + uint8_t initialisierungsdaten = 0; + initialisierungsdaten |= ((uint8_t(tele.resetVulnerabilityState) & 0x01) << 6); + initialisierungsdaten |= ((uint8_t(tele.restockCharges) & 0x01) << 5); + initialisierungsdaten |= ((uint8_t(tele.resetManipulation) & 0x01) << 0); + initialisierungsdaten |= ((uint8_t(tele.restockSanitationMaterial) & 0x01) << 1); + + radioTelegram->setPayloadData(initialisierungsdaten); + break; } - case Constraints::id(): { - const SetVulnerabilityModel& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_KONFIGURATION_WIRKMODELL, 9, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelMineIed); - radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAreaFire); - radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelOperatingResource); - radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAcWeaponry); - break; + case Constraints::id(): + { + const SetVulnerabilityModel &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_KONFIGURATION_WIRKMODELL, 9, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelMineIed); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAreaFire); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelOperatingResource); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAcWeaponry); + break; } - case Constraints::id(): { - const DemandEquipmentConfigurationReport& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_KONFIGURATIONSDATEN, 3, - tele.header.equipmentNumber); - break; + case Constraints::id(): + { + const DemandEquipmentConfigurationReport &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_KONFIGURATIONSDATEN, 3, tele.header.equipmentNumber); + break; } - case Constraints::id(): { - const StateChange& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TAKTISCHER_STATUS, 16, tele.header.equipmentNumber); + case Constraints::id(): + { + const StateChange &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TAKTISCHER_STATUS, 16, tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityState); - radioTelegram->setPayloadData((uint8_t)(tele.tasVulnerabilityKindId & 0xFF)); - uint16_t vulnerabilityVitalityIndex = 0; - vulnerabilityVitalityIndex = (uint16_t)((tele.tasVulnerabilityKindId >> 16) & 0xFFFF); - setVitality(vulnerabilityVitalityIndex, tele.tasVitality); - radioTelegram->setPayloadData((uint16_t)vulnerabilityVitalityIndex, 2); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityState); + radioTelegram->setPayloadData((uint8_t)(tele.tasVulnerabilityKindId & 0xFF)); + uint16_t vulnerabilityVitalityIndex = 0; + vulnerabilityVitalityIndex = (uint16_t)((tele.tasVulnerabilityKindId >> 16) & 0xFFFF); + setVitality(vulnerabilityVitalityIndex, tele.tasVitality); + radioTelegram->setPayloadData((uint16_t)vulnerabilityVitalityIndex, 2); - radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityBits, 2); + radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityBits, 2); - radioTelegram->setPayloadData((uint8_t)tele.originatorId); - radioTelegram->setPayloadData((uint16_t)tele.originatorType, 2); - break; + radioTelegram->setPayloadData((uint8_t)tele.originatorId); + radioTelegram->setPayloadData((uint16_t)tele.originatorType, 2); + break; } - case Constraints::id(): { - const BiteReport& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BITE_MELDUNG2, 27, tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData((uint8_t)tele.loginType); - radioTelegram->setPayloadData((uint32_t)tele.biteState, 3); - radioTelegram->setPayloadData((uint8_t)tele.batteryState); + case Constraints::id(): + { + const BiteReport &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BITE_MELDUNG2, 27, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData((uint8_t)tele.loginType); + radioTelegram->setPayloadData((uint32_t)tele.biteState, 3); + radioTelegram->setPayloadData((uint8_t)tele.batteryState); - if (tele.biteErrors.size() > 0) - { - radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].canDeviceNumber); - radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].subdeviceNumber); - radioTelegram->setPayloadData((uint32_t)tele.biteErrors[0].uniqueId, 4); - radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].errorNumber); - radioTelegram->setPayloadData((uint8_t)tele.biteErrors.size() - 1); - } - else - { - radioTelegram->setPayloadData((uint8_t)0); - radioTelegram->setPayloadData((uint8_t)0); - radioTelegram->setPayloadData((uint32_t)0, 4); - radioTelegram->setPayloadData((uint8_t)0); - radioTelegram->setPayloadData((uint8_t)0); - } - - radioTelegram->setPayloadData((uint32_t)0, 3); - radioTelegram->setPayloadData((uint8_t)tele.configError); - radioTelegram->setPayloadData((uint32_t)tele.configState, 3); - - for (const BiteError& be : tele.biteErrors) - { - radioTelegram->setPayloadData((uint8_t)be.canDeviceNumber); - radioTelegram->setPayloadData((uint8_t)be.subdeviceNumber); - radioTelegram->setPayloadData((uint32_t)be.uniqueId, 4); - radioTelegram->setPayloadData((uint8_t)be.errorNumber); - } - break; - } - case Constraints::id(): { - const ExerciseEnvironmentData& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_UMGEBUNGS_MELDUNG2, 20, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.exerciseId, 2); - radioTelegram->setPayloadData((uint8_t)0); - radioTelegram->setPayloadData((uint8_t)0); - radioTelegram->setPayloadData((uint8_t)tele.timeZone); - radioTelegram->setPayloadData((uint8_t)tele.utmZone); - radioTelegram->setPayloadData(tele.utmBand); - radioTelegram->setPayloadData((uint8_t*)tele.grid.c_str(), 2); + if (tele.biteErrors.size() > 0) + { + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].canDeviceNumber); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].subdeviceNumber); + radioTelegram->setPayloadData((uint32_t)tele.biteErrors[0].uniqueId, 4); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].errorNumber); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors.size() - 1); + } + else + { radioTelegram->setPayloadData((uint8_t)0); radioTelegram->setPayloadData((uint8_t)0); radioTelegram->setPayloadData((uint32_t)0, 4); - break; - } - case Constraints::id(): { - const DemandBite& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUFFORDERUNG_BITE_MELDUNG, 4, tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.withSelfTest, 1); - break; - } - case Constraints::id(): { - const PositionReport& tele(fromJson(a_telegram)); - - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_POSITIONS_MELDUNG, 14, tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.relPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relPosition.offsetX, 3); - radioTelegram->setPayloadData((uint8_t)(((tele.gpsQuality.moreThan4SatellitesAvailable) ? 0x80 : 0) | - ((tele.gpsQuality.dgpsModeAvailable) ? 0x40 : 0) | - (tele.gpsQuality.pdopValue & 0x3f)), - 1); - break; - } - case Constraints::id(): { - const CreateSingleExplosion& tele(fromJson(a_telegram)); - - const int teleSize = s_use2BytesForSingleFireDiameter ? 29 : 28; - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELGESCHOSS, teleSize, - tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - setAesPosition(tele, radioTelegram); - if (s_use2BytesForSingleFireDiameter) - { - Q_ASSERT(tele.effectDiameter < 256 * 256 && tele.effectDiameter >= 0); - radioTelegram->setPayloadData(tele.effectDiameter, 2); - } - else - { - Q_ASSERT(tele.effectDiameter < 256 && tele.effectDiameter >= 0); - radioTelegram->setPayloadData(tele.effectDiameter, 1); - } - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - break; - } - case Constraints::id(): { - const CreateAreaExplosion& tele(fromJson(a_telegram)); -#ifdef GUEZ_MODE - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 44 + tele.mhPoints.size() * 6, tele.header.equipmentNumber); -#else - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 36, - tele.header.equipmentNumber); -#endif - - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / 1000, 2); - - radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); - radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); - radioTelegram->setPayloadData(tele.width / 5, 1); - radioTelegram->setPayloadData(tele.height / 5, 1); - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle + 90.0), 2); - -#ifdef GUEZ_MODE - - radioTelegram->setPayloadData(tele.mhpWidth / 5, 1); - radioTelegram->setPayloadData(tele.mhpLength / 5, 1); - - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.mhpRotation + 90.0), 2); -#endif - radioTelegram->setPayloadData(tele.impactCount, 2); -#ifdef GUEZ_MODE - radioTelegram->setPayloadData(tele.impactRadius, 2); -#else - radioTelegram->setPayloadData(tele.impactEdgeLength, 1); -#endif - radioTelegram->setPayloadData(tele.chargeTypeId, 1); -#ifdef GUEZ_MODE - - radioTelegram->setPayloadData((tele.hazardDistance / 5), 1); radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + } - radioTelegram->setPayloadData(tele.mhPoints.size(), 1); - for (auto pos : std::as_const(tele.mhPoints)) - { - radioTelegram->setPayloadData(pos.offsetY, 3); - radioTelegram->setPayloadData(pos.offsetX, 3); - } + radioTelegram->setPayloadData((uint32_t)0, 3); + radioTelegram->setPayloadData((uint8_t)tele.configError); + radioTelegram->setPayloadData((uint32_t)tele.configState, 3); + + for (const BiteError &be : tele.biteErrors) + { + radioTelegram->setPayloadData((uint8_t)be.canDeviceNumber); + radioTelegram->setPayloadData((uint8_t)be.subdeviceNumber); + radioTelegram->setPayloadData((uint32_t)be.uniqueId, 4); + radioTelegram->setPayloadData((uint8_t)be.errorNumber); + } + break; + } + case Constraints::id(): + { + const ExerciseEnvironmentData &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_UMGEBUNGS_MELDUNG2, 20, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.exerciseId, 2); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)tele.timeZone); + radioTelegram->setPayloadData((uint8_t)tele.utmZone); + radioTelegram->setPayloadData(tele.utmBand); + radioTelegram->setPayloadData((uint8_t *)tele.grid.c_str(), 2); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint32_t)0, 4); + break; + } + case Constraints::id(): + { + const DemandBite &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUFFORDERUNG_BITE_MELDUNG, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.withSelfTest, 1); + break; + } + case Constraints::id(): + { + const PositionReport &tele(fromJson(a_telegram)); + + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_POSITIONS_MELDUNG, 14, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.relPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relPosition.offsetX, 3); + radioTelegram->setPayloadData((uint8_t)(((tele.gpsQuality.moreThan4SatellitesAvailable) ? 0x80 : 0) | ((tele.gpsQuality.dgpsModeAvailable) ? 0x40 : 0) | + (tele.gpsQuality.pdopValue & 0x3f)), + 1); + break; + } + case Constraints::id(): + { + const CreateSingleExplosion &tele(fromJson(a_telegram)); + + const int teleSize = s_use2BytesForSingleFireDiameter ? 29 : 28; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELGESCHOSS, teleSize, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + setAesPosition(tele, radioTelegram); + if (s_use2BytesForSingleFireDiameter) + { + Q_ASSERT(tele.effectDiameter < 256 * 256 && tele.effectDiameter >= 0); + radioTelegram->setPayloadData(tele.effectDiameter, 2); + } + else + { + Q_ASSERT(tele.effectDiameter < 256 && tele.effectDiameter >= 0); + radioTelegram->setPayloadData(tele.effectDiameter, 1); + } + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + break; + } + case Constraints::id(): + { + const CreateAreaExplosion &tele(fromJson(a_telegram)); +#ifdef GUEZ_MODE + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 44 + tele.mhPoints.size() * 6, tele.header.equipmentNumber); +#else + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 36, tele.header.equipmentNumber); #endif - break; + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / 1000, 2); + + radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); + radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); + radioTelegram->setPayloadData(tele.width / 5, 1); + radioTelegram->setPayloadData(tele.height / 5, 1); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle + 90.0), 2); + +#ifdef GUEZ_MODE + + radioTelegram->setPayloadData(tele.mhpWidth / 5, 1); + radioTelegram->setPayloadData(tele.mhpLength / 5, 1); + + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.mhpRotation + 90.0), 2); +#endif + radioTelegram->setPayloadData(tele.impactCount, 2); +#ifdef GUEZ_MODE + radioTelegram->setPayloadData(tele.impactRadius, 2); +#else + radioTelegram->setPayloadData(tele.impactEdgeLength, 1); +#endif + radioTelegram->setPayloadData(tele.chargeTypeId, 1); +#ifdef GUEZ_MODE + + radioTelegram->setPayloadData((tele.hazardDistance / 5), 1); + radioTelegram->setPayloadData((uint8_t)0); + + radioTelegram->setPayloadData(tele.mhPoints.size(), 1); + for (auto pos : std::as_const(tele.mhPoints)) + { + radioTelegram->setPayloadData(pos.offsetY, 3); + radioTelegram->setPayloadData(pos.offsetX, 3); + } +#endif + + break; } - case Constraints::id(): { - const PauseEffectSimulation& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP, 7, 0); + case Constraints::id(): + { + const PauseEffectSimulation &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP, 7, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + break; + } + case Constraints::id(): + { + const ResumeEffectSimulation &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN, 17, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.sequelNumber, 2); + radioTelegram->setPayloadData(tele.nextImpact, 2); + convertToSecAndSetTime(tele.resumeTime, radioTelegram); + radioTelegram->setPayloadData(tele.remainDuration / 1000, 2); + break; + } + case Constraints::id(): + { + const CreateMineArea &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_MINENSPERRE, 5 + 22 + tele.segments.size() * 12, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60 * 60), 1); + + radioTelegram->setPayloadData(qRound(tele.layingDepth), 1); + radioTelegram->setPayloadData(qRound(tele.layingDensity * 100), 1); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + + double length = 0; + for (const MineAreaSegment &ms : tele.segments) + { + length += QLineF(ms.relStart.offsetX, ms.relStart.offsetY, ms.relEnd.offsetX, ms.relEnd.offsetY).length(); + } + int minecount = qRound(length * tele.layingDensity); + if (minecount > 1200) + minecount = 1200; + radioTelegram->setPayloadData((uint32_t)minecount, 2); + radioTelegram->setPayloadData(tele.segments.size(), 1); + for (const MineAreaSegment &ms : tele.segments) + { + radioTelegram->setPayloadData(ms.relStart.offsetY, 3); + radioTelegram->setPayloadData(ms.relStart.offsetX, 3); + radioTelegram->setPayloadData(ms.relEnd.offsetY, 3); + radioTelegram->setPayloadData(ms.relEnd.offsetX, 3); + } + break; + } + case Constraints::id(): + { + const MineAreaSingleMineState &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_STATUS_MINENSPERRE, 5 + 4 + tele.mineState.size(), 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.mineCount, 2); + radioTelegram->setPayloadData((uint8_t *)(tele.mineState.data()), tele.mineState.size()); + break; + } + case Constraints::id(): + { + const CreateNContamination &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_A_KAMPFMITTEL, 38, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 2); + setAesPosition(tele, radioTelegram); + radioTelegram->setPayloadData(tele.innerRadius, 2); + radioTelegram->setPayloadData(tele.borderLengthInner, 2); + radioTelegram->setPayloadData(tele.borderLengthOuter, 2); + radioTelegram->setPayloadData(qRound(tele.spanAngle * 100), 2); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle), 2); + break; + } + case Constraints::id(): + { + const CreateCContamination &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_C_KAMPFMITTEL, 45, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 1); + setAesPosition(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectRadius, 2); + radioTelegram->setPayloadData(qRound(tele.expansionFactor * 100), 1); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.propagationDirection), 2); + radioTelegram->setPayloadData(tele.windSpeed, 1); + convertToSecAndSetTime(tele.validityTimeWind, radioTelegram); + radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetY, 3); + radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetX, 3); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + radioTelegram->setPayloadData((uint8_t)tele.volatility, 1); + break; + } + case Constraints::id(): + { + const DeactivateEffectSimulation &tele(fromJson(a_telegram)); + if (tele.aesType == AreaEffectSimulationType::FunctionalArea) + { + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIEREN_FUNKTIONSRAUM, 7, 0); radioTelegram->setPayloadData((uint32_t)0, 2); radioTelegram->setPayloadData(tele.aesDdsId, 2); - break; - } - case Constraints::id(): { - const ResumeEffectSimulation& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN, 17, 0); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.sequelNumber, 2); - radioTelegram->setPayloadData(tele.nextImpact, 2); - convertToSecAndSetTime(tele.resumeTime, radioTelegram); - radioTelegram->setPayloadData(tele.remainDuration / 1000, 2); - break; - } - case Constraints::id(): { - const CreateMineArea& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_WIRKFELD_MINENSPERRE, 5 + 22 + tele.segments.size() * 12, tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60 * 60), 1); - - radioTelegram->setPayloadData(qRound(tele.layingDepth), 1); - radioTelegram->setPayloadData(qRound(tele.layingDensity * 100), 1); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - - double length = 0; - for (const MineAreaSegment& ms : tele.segments) - { - length += - QLineF(ms.relStart.offsetX, ms.relStart.offsetY, ms.relEnd.offsetX, ms.relEnd.offsetY).length(); - } - int minecount = qRound(length * tele.layingDensity); - if (minecount > 1200) - minecount = 1200; - radioTelegram->setPayloadData((uint32_t)minecount, 2); - radioTelegram->setPayloadData(tele.segments.size(), 1); - for (const MineAreaSegment& ms : tele.segments) - { - radioTelegram->setPayloadData(ms.relStart.offsetY, 3); - radioTelegram->setPayloadData(ms.relStart.offsetX, 3); - radioTelegram->setPayloadData(ms.relEnd.offsetY, 3); - radioTelegram->setPayloadData(ms.relEnd.offsetX, 3); - } - break; - } - case Constraints::id(): { - const MineAreaSingleMineState& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_STATUS_MINENSPERRE, - 5 + 4 + tele.mineState.size(), 0); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.mineCount, 2); - radioTelegram->setPayloadData((uint8_t*)(tele.mineState.data()), tele.mineState.size()); - break; - } - case Constraints::id(): { - const CreateNContamination& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_A_KAMPFMITTEL, 38, tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 2); - setAesPosition(tele, radioTelegram); - radioTelegram->setPayloadData(tele.innerRadius, 2); - radioTelegram->setPayloadData(tele.borderLengthInner, 2); - radioTelegram->setPayloadData(tele.borderLengthOuter, 2); - radioTelegram->setPayloadData(qRound(tele.spanAngle * 100), 2); - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle), 2); - break; - } - case Constraints::id(): { - const CreateCContamination& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_C_KAMPFMITTEL, 45, tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 1); - setAesPosition(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectRadius, 2); - radioTelegram->setPayloadData(qRound(tele.expansionFactor * 100), 1); - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.propagationDirection), 2); - radioTelegram->setPayloadData(tele.windSpeed, 1); - convertToSecAndSetTime(tele.validityTimeWind, radioTelegram); - radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetY, 3); - radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetX, 3); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - radioTelegram->setPayloadData((uint8_t)tele.volatility, 1); - break; - } - case Constraints::id(): { - const DeactivateEffectSimulation& tele(fromJson(a_telegram)); - if (tele.aesType == AreaEffectSimulationType::FunctionalArea) - { - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIEREN_FUNKTIONSRAUM, 7, 0); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - } - else - { - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_WIRKFELD, 8, 0); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData((uint8_t)tele.aesType, 1); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - } - break; - } - case Constraints::id(): { - const ModifyAreaEffectSimulationName& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_AENDERUNG_BEZEICHNER, 16, 0); + } + else + { + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_WIRKFELD, 8, 0); radioTelegram->setPayloadData((uint32_t)0, 2); radioTelegram->setPayloadData((uint8_t)tele.aesType, 1); radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - break; + } + break; } - case Constraints::id(): { - const MineTriggered& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_EINZELMINE, 13, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.mineAreaId, 2); - radioTelegram->setPayloadData(tele.mineIndex, 2); - break; + case Constraints::id(): + { + const ModifyAreaEffectSimulationName &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_AENDERUNG_BEZEICHNER, 16, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.aesType, 1); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + break; } - case Constraints::id(): { - const DusMineReactivation& tele(fromJson(a_telegram)); + case Constraints::id(): + { + const MineTriggered &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_EINZELMINE, 13, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.mineAreaId, 2); + radioTelegram->setPayloadData(tele.mineIndex, 2); + break; + } + case Constraints::id(): + { + const DusMineReactivation &tele(fromJson(a_telegram)); - const size_t cnt = tele.dusSerialNumbers.size() > 500 ? 500 : tele.dusSerialNumbers.size(); + const size_t cnt = tele.dusSerialNumbers.size() > 500 ? 500 : tele.dusSerialNumbers.size(); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_REAKTIVIERUNG_DUS_MINE, 3 + 2 + 2 + 2 * cnt, - tele.header.equipmentNumber); - radioTelegram->setPayload2Byte(0); - radioTelegram->setPayload2Byte(cnt); - for (size_t i = 0; i < cnt; i++) - radioTelegram->setPayload2Byte(tele.dusSerialNumbers.at(i)); - break; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_REAKTIVIERUNG_DUS_MINE, 3 + 2 + 2 + 2 * cnt, tele.header.equipmentNumber); + radioTelegram->setPayload2Byte(0); + radioTelegram->setPayload2Byte(cnt); + for (size_t i = 0; i < cnt; i++) + radioTelegram->setPayload2Byte(tele.dusSerialNumbers.at(i)); + break; } - case Constraints::id(): { - const CreateDusSingleMine& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELMINENSIMULATOR, 21, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.partyId, 1); - radioTelegram->setPayloadData(tele.mineId, 2); - convertToSecAndSetTime(tele.effectStart, radioTelegram); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - break; + case Constraints::id(): + { + const CreateDusSingleMine &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELMINENSIMULATOR, 21, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.partyId, 1); + radioTelegram->setPayloadData(tele.mineId, 2); + convertToSecAndSetTime(tele.effectStart, radioTelegram); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + break; } - case Constraints::id(): { - const DemandVulnerabilityStateChange& tele(fromJson(a_telegram)); + case Constraints::id(): + { + const DemandVulnerabilityStateChange &tele(fromJson(a_telegram)); #ifdef GUEZ_MODE - if (s_usePvSan) - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 10, tele.header.equipmentNumber); - else - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); + if (s_usePvSan) + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 10, tele.header.equipmentNumber); + else + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); #else - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); #endif - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData((uint8_t)tele.reqestedState, 1); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData((uint8_t)tele.reqestedState, 1); #ifdef GUEZ_MODE - if (s_usePvSan) - radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityVitalityIndex, 2); + if (s_usePvSan) + radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityVitalityIndex, 2); #endif - break; + break; } - case Constraints::id(): { - const TechnicalArea& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TECHNIK_FUNKTIONSRAUM, 34, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.taType, 1); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); - radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); - radioTelegram->setPayloadData(tele.width, 2); - radioTelegram->setPayloadData(tele.height, 2); - radioTelegram->setPayloadData((uint32_t)0, 4); - radioTelegram->setPayloadData((uint32_t)0, 4); - break; + case Constraints::id(): + { + const TechnicalArea &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TECHNIK_FUNKTIONSRAUM, 34, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.taType, 1); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); + radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); + radioTelegram->setPayloadData(tele.width, 2); + radioTelegram->setPayloadData(tele.height, 2); + radioTelegram->setPayloadData((uint32_t)0, 4); + radioTelegram->setPayloadData((uint32_t)0, 4); + break; } - case Constraints::id(): { - const CreateFunctionalArea& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_FUNKTIONSRAUM, 30, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.partyId, 1); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); - radioTelegram->setPayloadData(tele.width / 5, 1); - radioTelegram->setPayloadData(tele.height / 5, 1); - radioTelegram->setPayloadData((uint8_t)tele.deconMode, 1); - radioTelegram->setPayloadData(tele.deconTimeout / 1000 / 60 / 10, 1); - radioTelegram->setPayloadData((uint8_t)tele.maintenanceMode, 1); - radioTelegram->setPayloadData(tele.maintenanceTimeout / 1000 / 60 / 10, 1); - radioTelegram->setPayloadData((uint8_t)tele.medicalMode, 1); - radioTelegram->setPayloadData(tele.medicalTimeout / 1000 / 60 / 10, 1); - break; + case Constraints::id(): + { + const CreateFunctionalArea &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_FUNKTIONSRAUM, 30, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.partyId, 1); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + radioTelegram->setPayloadData(tele.width / 5, 1); + radioTelegram->setPayloadData(tele.height / 5, 1); + radioTelegram->setPayloadData((uint8_t)tele.deconMode, 1); + radioTelegram->setPayloadData(tele.deconTimeout / 1000 / 60 / 10, 1); + radioTelegram->setPayloadData((uint8_t)tele.maintenanceMode, 1); + radioTelegram->setPayloadData(tele.maintenanceTimeout / 1000 / 60 / 10, 1); + radioTelegram->setPayloadData((uint8_t)tele.medicalMode, 1); + radioTelegram->setPayloadData(tele.medicalTimeout / 1000 / 60 / 10, 1); + break; } - case Constraints::id(): { - const LanguageSelection& tele(fromJson(a_telegram)); + case Constraints::id(): + { + const LanguageSelection &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SPRACHAUSWAHL, 6, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData((uint8_t)tele.languageSelection, 1); - break; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SPRACHAUSWAHL, 6, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.languageSelection, 1); + break; } - case Constraints::id(): { + case Constraints::id(): + { - const EquipmentMessage& tele(fromJson(a_telegram)); + const EquipmentMessage &tele(fromJson(a_telegram)); - int len = 0; - int messageLength = (tele.message.size() > 81) ? 81 : tele.message.size(); - if (tele.msgId == -1) - len = messageLength + 6; + int len = 0; + int messageLength = (tele.message.size() > 81) ? 81 : tele.message.size(); + if (tele.msgId == -1) + len = messageLength + 6; - else - len = 9; - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ALLGEMEINE_NACHRICHT, len, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - if (tele.msgId != -1) - { + else + len = 9; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ALLGEMEINE_NACHRICHT, len, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + if (tele.msgId != -1) + { - radioTelegram->setPayloadData(3, 1); + radioTelegram->setPayloadData(3, 1); - radioTelegram->setPayloadData((uint32_t)0, 1); - radioTelegram->setPayloadData(tele.msgId, 2); - } - else - { - radioTelegram->setPayloadData(tele.message.size(), 1); - radioTelegram->setPayloadData((uint8_t*)(tele.message.c_str()), messageLength); - } - break; + radioTelegram->setPayloadData((uint32_t)0, 1); + radioTelegram->setPayloadData(tele.msgId, 2); + } + else + { + radioTelegram->setPayloadData(tele.message.size(), 1); + radioTelegram->setPayloadData((uint8_t *)(tele.message.c_str()), messageLength); + } + break; } - case Constraints::id(): { - const OpaquePayloadDataOut& tele(fromJson(a_telegram)); - switch (tele.payloadType) - { - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::FireSmokeMarker: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_DATENVERKEHR_TDS_DMF, tele.payload.size() + 3, tele.header.equipmentNumber); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Geopairing: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_DATENVERKEHR_TDS_GEOP, tele.payload.size() + 4, tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.payload.size(), 1); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Target: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_DATENVERKEHR_TDS_TGTC, tele.payload.size() + 4, tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.payload.size(), 1); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::OC: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_DATENVERKEHR_TDS_SRT, tele.payload.size() + 3, tele.header.equipmentNumber); - break; - } + case Constraints::id(): + { + const OpaquePayloadDataOut &tele(fromJson(a_telegram)); + switch (tele.payloadType) + { + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::FireSmokeMarker: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_DMF, tele.payload.size() + 3, tele.header.equipmentNumber); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Geopairing: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_GEOP, tele.payload.size() + 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.payload.size(), 1); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Target: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_TGTC, tele.payload.size() + 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.payload.size(), 1); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::OC: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_SRT, tele.payload.size() + 3, tele.header.equipmentNumber); + break; + } - radioTelegram->setPayloadData((uint8_t*)(tele.payload.data()), tele.payload.size()); - break; + radioTelegram->setPayloadData((uint8_t *)(tele.payload.data()), tele.payload.size()); + break; } - case Constraints::id(): { - const CesHitInformation& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUSLOESUNG_DUS_TREFFER, 16, tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.chargeTasCodeDirect, 2); - radioTelegram->setPayloadData(tele.directionDegree, 2); - radioTelegram->setPayloadData(tele.distance, 2); - radioTelegram->setPayloadData(tele.effectPercent, 1); - radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); - break; + case Constraints::id(): + { + const CesHitInformation &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUSLOESUNG_DUS_TREFFER, 16, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.chargeTasCodeDirect, 2); + radioTelegram->setPayloadData(tele.directionDegree, 2); + radioTelegram->setPayloadData(tele.distance, 2); + radioTelegram->setPayloadData(tele.effectPercent, 1); + radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); + break; } - case Constraints::id(): { - const ParticipantSwVersionsRequest& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_SW_VERSION, 4, tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.equipmentFunctionId, 1); - break; + case Constraints::id(): + { + const ParticipantSwVersionsRequest &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_SW_VERSION, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.equipmentFunctionId, 1); + break; } - case Constraints::id(): { - const ParticipantMode& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_SETZEN, 13, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData((uint8_t)tele.language, 1); - radioTelegram->setPayloadData((uint8_t)tele.operationMode, 1); - radioTelegram->setPayloadData(tele.reactivationDetoxication / 10, 1); - radioTelegram->setPayloadData(tele.reactivationMaintenance / 10, 1); - radioTelegram->setPayloadData(tele.reactivationMedic / 10, 1); - unsigned char wph_mode = 0; - wph_mode |= ((uint8_t)tele.modeHelmet & 0x03); - wph_mode |= ((uint8_t)tele.modeVest & 0x03) << 2; - wph_mode |= ((uint8_t)tele.personellProtectionMode & 0x07) << 4; - radioTelegram->setPayloadData(wph_mode, 1); + case Constraints::id(): + { + const ParticipantMode &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_SETZEN, 13, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.language, 1); + radioTelegram->setPayloadData((uint8_t)tele.operationMode, 1); + radioTelegram->setPayloadData(tele.reactivationDetoxication / 10, 1); + radioTelegram->setPayloadData(tele.reactivationMaintenance / 10, 1); + radioTelegram->setPayloadData(tele.reactivationMedic / 10, 1); + unsigned char wph_mode = 0; + wph_mode |= ((uint8_t)tele.modeHelmet & 0x03); + wph_mode |= ((uint8_t)tele.modeVest & 0x03) << 2; + wph_mode |= ((uint8_t)tele.personellProtectionMode & 0x07) << 4; + radioTelegram->setPayloadData(wph_mode, 1); - unsigned char protection_mode = 0; - protection_mode |= ((uint8_t)tele.protectionLevel & 0x07); - protection_mode |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; - radioTelegram->setPayloadData(protection_mode, 1); + unsigned char protection_mode = 0; + protection_mode |= ((uint8_t)tele.protectionLevel & 0x07); + protection_mode |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; + radioTelegram->setPayloadData(protection_mode, 1); - unsigned char specialFunction = 0; - specialFunction |= ((uint8_t)tele.handgrenadeSearchMode & 0x03); - specialFunction |= ((uint8_t)tele.internationalMode & 0x03) << 2; - specialFunction |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; - radioTelegram->setPayloadData(specialFunction, 1); - break; + unsigned char specialFunction = 0; + specialFunction |= ((uint8_t)tele.handgrenadeSearchMode & 0x03); + specialFunction |= ((uint8_t)tele.internationalMode & 0x03) << 2; + specialFunction |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; + radioTelegram->setPayloadData(specialFunction, 1); + break; } - case Constraints::id(): { - const DemandParticipantMode& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_ANFORDERN, 3, tele.header.equipmentNumber); - break; + case Constraints::id(): + { + const DemandParticipantMode &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_ANFORDERN, 3, tele.header.equipmentNumber); + break; } - case Constraints::id(): { - const ParticipantConfiguration& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_SETZEN, 25, tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t)0, 2); - radioTelegram->setPayloadData(tele.positionIntervallVehicle, 2); - radioTelegram->setPayloadData(tele.positionIntervallPersonell, 2); - radioTelegram->setPayloadData(tele.positionIntervallAircraft, 2); - radioTelegram->setPayloadData(tele.positionTransmissionIntervall, 2); - radioTelegram->setPayloadData(tele.heightbarrier, 2); - unsigned char tmp = ((uint8_t)tele.faultPositionHandling & 0x03) << 6; - tmp |= ((uint8_t)tele.switchingPositionIntervall & 0x03); - radioTelegram->setPayloadData(tmp, 1); - radioTelegram->setPayloadData(tele.waittimeAdditionalBroadcastDemand, 2); - radioTelegram->setPayloadData(tele.factorWaittimeIncreaseAtHighload, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel1, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel2, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel3, 1); - radioTelegram->setPayloadData((uint8_t)tele.opticalCode, 1); - radioTelegram->setPayloadData(tele.vulnerabilityModel, 1); - radioTelegram->setPayloadData(tele.validTimeOps, 1); - break; + case Constraints::id(): + { + const ParticipantConfiguration &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_SETZEN, 25, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.positionIntervallVehicle, 2); + radioTelegram->setPayloadData(tele.positionIntervallPersonell, 2); + radioTelegram->setPayloadData(tele.positionIntervallAircraft, 2); + radioTelegram->setPayloadData(tele.positionTransmissionIntervall, 2); + radioTelegram->setPayloadData(tele.heightbarrier, 2); + unsigned char tmp = ((uint8_t)tele.faultPositionHandling & 0x03) << 6; + tmp |= ((uint8_t)tele.switchingPositionIntervall & 0x03); + radioTelegram->setPayloadData(tmp, 1); + radioTelegram->setPayloadData(tele.waittimeAdditionalBroadcastDemand, 2); + radioTelegram->setPayloadData(tele.factorWaittimeIncreaseAtHighload, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel1, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel2, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel3, 1); + radioTelegram->setPayloadData((uint8_t)tele.opticalCode, 1); + radioTelegram->setPayloadData(tele.vulnerabilityModel, 1); + radioTelegram->setPayloadData(tele.validTimeOps, 1); + break; } - case Constraints::id(): { - const DemandParticipantConfiguration& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_ANFORDERN, 3, tele.header.equipmentNumber); - break; + case Constraints::id(): + { + const DemandParticipantConfiguration &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_ANFORDERN, 3, tele.header.equipmentNumber); + break; } - case Constraints::id(): { - const SanitationRepair& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG, 19, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + case Constraints::id(): + { + const SanitationRepair &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG, 19, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayload1Byte(uint8_t(tele.originatorType)); - radioTelegram->setPayload2Byte(tele.equipmentNumberOrigin); - radioTelegram->setPayload1Byte(uint8_t(tele.stateStart)); + radioTelegram->setPayload1Byte(uint8_t(tele.originatorType)); + radioTelegram->setPayload2Byte(tele.equipmentNumberOrigin); + radioTelegram->setPayload1Byte(uint8_t(tele.stateStart)); - unsigned int bitfield1 = 0; - if (tele.timeOfTreatment) - bitfield1 |= 0x7F; - if (tele.triage) - bitfield1 |= 0x80; - radioTelegram->setPayload1Byte(bitfield1); + unsigned int bitfield1 = 0; + if (tele.timeOfTreatment) + bitfield1 |= 0x7F; + if (tele.triage) + bitfield1 |= 0x80; + radioTelegram->setPayload1Byte(bitfield1); - radioTelegram->setPayload1Byte(tele.tyeOfDamage); + radioTelegram->setPayload1Byte(tele.tyeOfDamage); - unsigned int bitfield2 = 0; - bitfield2 |= (uint8_t(tele.stateResult) | 0x0F); - bitfield2 |= ((uint8_t(tele.treatmentResult) | 0x30) << 4); - bitfield2 |= (0xC0 << 6); - radioTelegram->setPayload1Byte(bitfield2); + unsigned int bitfield2 = 0; + bitfield2 |= (uint8_t(tele.stateResult) | 0x0F); + bitfield2 |= ((uint8_t(tele.treatmentResult) | 0x30) << 4); + bitfield2 |= (0xC0 << 6); + radioTelegram->setPayload1Byte(bitfield2); - radioTelegram->setPayload1Byte(tele.fullState); - radioTelegram->setPayloadData(tele.timeOfTreatment, 2); - radioTelegram->setPayloadData(tele.timeOfRecovery, 2); - break; + radioTelegram->setPayload1Byte(tele.fullState); + radioTelegram->setPayloadData(tele.timeOfTreatment, 2); + radioTelegram->setPayloadData(tele.timeOfRecovery, 2); + break; } - case Constraints::id(): { - const SanitaryMaterialStockReport& tele(fromJson(a_telegram)); + case Constraints::id(): + { + const SanitaryMaterialStockReport &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_BESTANDSMELDUNG_SANITAETSMATERIAL, 15 + tele.sanitaryMaterialCount, tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayload4Byte(tele.uniqueId); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTANDSMELDUNG_SANITAETSMATERIAL, 15 + tele.sanitaryMaterialCount, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayload4Byte(tele.uniqueId); + radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); + radioTelegram->setPayload1Byte((uint8_t)tele.qualification); + + radioTelegram->setPayload1Byte(tele.sanitaryMaterialCount); + + for (const auto stock : tele.sanitaryMaterialStock) + radioTelegram->setPayloadData(stock, 1); + + break; + } + case Constraints::id(): + { + const Sanitation &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN, 23, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + + int p1 = tele.proceduresTaken & 0xFFFFFFFF; + int p2 = tele.proceduresTaken >> 32; + + radioTelegram->setPayloadData(p2, 4); + radioTelegram->setPayloadData(p1, 4); + radioTelegram->setPayloadData(tele.uniqeId, 4); + radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); + radioTelegram->setPayloadData((uint8_t)tele.qualification, 1); + + quint8 sanResultAndEvaluation = (((uint8_t)tele.sanitationEvaluation & 0x03) << 6) + ((uint8_t)tele.sanitationResult & 0x3f); + radioTelegram->setPayloadData(sanResultAndEvaluation, 1); + + break; + } + case Constraints::id(): + { + const CesHitRequest &tele(fromJson(a_telegram)); + + int chargeTasCode = tele.chargeTasCodeDirect; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG, 17, tele.header.equipmentNumber); + const bool insideBuilding = (tele.roomId > 0 && tele.buildingId > 0); + int remainEffectOrTasCodeDirect = 0; + int reserve1 = tele.mineId; + int reserve2 = 0; + int gpsZeit = tele.header.timeStamp; + switch (tele.aesType) + { + case AreaEffectSimulationType::Unknown: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + if (remainEffectOrTasCodeDirect == 100) + { + remainEffectOrTasCodeDirect = 49; + } + break; + case AreaEffectSimulationType::FunctionalArea: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + + chargeTasCode = tele.chargeTasCodeIndirect; + reserve1 = tele.reserve1; + reserve2 = tele.reserve2; + break; + case AreaEffectSimulationType::AirSupport: + case AreaEffectSimulationType::NContamination: + case AreaEffectSimulationType::MineArea: + case AreaEffectSimulationType::CContamination: + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + chargeTasCode = tele.chargeTasCodeIndirect; + break; + case AreaEffectSimulationType::DangerZoneExplosion: + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + chargeTasCode = tele.chargeTasCodeIndirect; + reserve1 = tele.reserve1; + break; + case AreaEffectSimulationType::ExplosionArea: + case AreaEffectSimulationType::ExplosionSingle: + if (insideBuilding) + { + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + } + else + { + + remainEffectOrTasCodeDirect = 255; + chargeTasCode = tele.chargeTasCodeIndirect; + } + break; + case AreaEffectSimulationType::GasPipeDetonation: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + break; + default: + + remainEffectOrTasCodeDirect = tele.remainEffectPercent; + chargeTasCode = tele.chargeTasCodeIndirect; + break; + } + + radioTelegram->setPayloadData((uint32_t)gpsZeit, 4); + radioTelegram->setPayload2Byte(chargeTasCode); + if (tele.aesDdsId != 0) + radioTelegram->setPayload2Byte(tele.aesDdsId); + else radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); - radioTelegram->setPayload1Byte((uint8_t)tele.qualification); - radioTelegram->setPayload1Byte(tele.sanitaryMaterialCount); + radioTelegram->setPayload1Byte(uint8_t(tele.aesType)); + radioTelegram->setPayload1Byte(remainEffectOrTasCodeDirect); + radioTelegram->setPayload2Byte(reserve1); + radioTelegram->setPayload2Byte(reserve2); + DEBUG_LOG(logger()) << "Reserve1 of CesHitRequest: " << reserve1 << " Reserve2: " << reserve2; - for (const auto stock : tele.sanitaryMaterialStock) - radioTelegram->setPayloadData(stock, 1); - - break; + break; } - case Constraints::id(): { - const Sanitation& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN, 23, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - - int p1 = tele.proceduresTaken & 0xFFFFFFFF; - int p2 = tele.proceduresTaken >> 32; - - radioTelegram->setPayloadData(p2, 4); - radioTelegram->setPayloadData(p1, 4); - radioTelegram->setPayloadData(tele.uniqeId, 4); - radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); - radioTelegram->setPayloadData((uint8_t)tele.qualification, 1); - - quint8 sanResultAndEvaluation = - (((uint8_t)tele.sanitationEvaluation & 0x03) << 6) + ((uint8_t)tele.sanitationResult & 0x3f); - radioTelegram->setPayloadData(sanResultAndEvaluation, 1); - - break; + case Constraints::id(): + { + const SelectiveReammunition &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SELEKTIVE_AUFMUNITIONIERUNG, 8 + tele.reammunitions.size() * 8, tele.header.equipmentNumber); + radioTelegram->setPayload4Byte(tele.gearId); + radioTelegram->setPayload1Byte(tele.reammunitions.size()); + for (const auto &reammunition : tele.reammunitions) + { + radioTelegram->setPayload2Byte(reammunition.chargeTypeId); + radioTelegram->setPayload1Byte(reammunition.location); + radioTelegram->setPayload2Byte(reammunition.newStock); + radioTelegram->setPayload2Byte(reammunition.newDefaultStock); + radioTelegram->setPayload1Byte(reammunition.tracerRatio); + } + break; } - case Constraints::id(): { - const CesHitRequest& tele(fromJson(a_telegram)); - - int chargeTasCode = tele.chargeTasCodeDirect; - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG, 17, - tele.header.equipmentNumber); - const bool insideBuilding = (tele.roomId > 0 && tele.buildingId > 0); - int remainEffectOrTasCodeDirect = 0; - int reserve1 = tele.mineId; - int reserve2 = 0; - int gpsZeit = tele.header.timeStamp; - switch (tele.aesType) - { - case AreaEffectSimulationType::Unknown: - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - if (remainEffectOrTasCodeDirect == 100) - { - remainEffectOrTasCodeDirect = 49; - } - break; - case AreaEffectSimulationType::FunctionalArea: - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - - chargeTasCode = tele.chargeTasCodeIndirect; - reserve1 = tele.reserve1; - reserve2 = tele.reserve2; - break; - case AreaEffectSimulationType::AirSupport: - case AreaEffectSimulationType::NContamination: - case AreaEffectSimulationType::MineArea: - case AreaEffectSimulationType::CContamination: - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - chargeTasCode = tele.chargeTasCodeIndirect; - break; - case AreaEffectSimulationType::DangerZoneExplosion: - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - chargeTasCode = tele.chargeTasCodeIndirect; - reserve1 = tele.reserve1; - break; - case AreaEffectSimulationType::ExplosionArea: - case AreaEffectSimulationType::ExplosionSingle: - if (insideBuilding) - { - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - } - else - { - - remainEffectOrTasCodeDirect = 255; - chargeTasCode = tele.chargeTasCodeIndirect; - } - break; - case AreaEffectSimulationType::GasPipeDetonation: - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - break; - default: - - remainEffectOrTasCodeDirect = tele.remainEffectPercent; - chargeTasCode = tele.chargeTasCodeIndirect; - break; - } - - radioTelegram->setPayloadData((uint32_t)gpsZeit, 4); - radioTelegram->setPayload2Byte(chargeTasCode); - if (tele.aesDdsId != 0) - radioTelegram->setPayload2Byte(tele.aesDdsId); - else - radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); - - radioTelegram->setPayload1Byte(uint8_t(tele.aesType)); - radioTelegram->setPayload1Byte(remainEffectOrTasCodeDirect); - radioTelegram->setPayload2Byte(reserve1); - radioTelegram->setPayload2Byte(reserve2); - DEBUG_LOG(logger()) << "Reserve1 of CesHitRequest: " << reserve1 << " Reserve2: " << reserve2; - - break; + case Constraints::id(): + { + const OcCommand &tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SCHIEDSRICHTERKOMMANDO, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.action, 1); + break; } - case Constraints::id(): { - const SelectiveReammunition& tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( - GEF_SELEKTIVE_AUFMUNITIONIERUNG, 8 + tele.reammunitions.size() * 8, tele.header.equipmentNumber); - radioTelegram->setPayload4Byte(tele.gearId); - radioTelegram->setPayload1Byte(tele.reammunitions.size()); - for (const auto& reammunition : tele.reammunitions) - { - radioTelegram->setPayload2Byte(reammunition.chargeTypeId); - radioTelegram->setPayload1Byte(reammunition.location); - radioTelegram->setPayload2Byte(reammunition.newStock); - radioTelegram->setPayload2Byte(reammunition.newDefaultStock); - radioTelegram->setPayload1Byte(reammunition.tracerRatio); - } - break; - } - case Constraints::id(): { - const OcCommand& tele(fromJson(a_telegram)); - radioTelegram = - new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SCHIEDSRICHTERKOMMANDO, 4, tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.action, 1); - break; - } - default: { - ERROR_LOG(logger()) << "Conversion of Central-Telegram to Radio-Telegram with telId=" - << getTelegramId(a_telegram) << " not implemented!"; + default: + { + ERROR_LOG(logger()) << "Conversion of Central-Telegram to Radio-Telegram with telId=" << getTelegramId(a_telegram) << " not implemented!"; } + } + return radioTelegram; } - return radioTelegram; -} -CoPrtCnvRadioTelegram* convertToRadio(CoPrtCnvCentralTelegram* a_telegram) -{ - return convertToRadioInternal(a_telegram); -} - -CoPrtCnvRadioTelegram* convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* a_telegram) -{ - return convertToRadioInternal(a_telegram); -} - -static inline Header getHeader(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t tsOffset) -{ - Header hdr; - hdr.equipmentNumber = a_radioTelegram->getIdentity(); - hdr.timeStamp = a_radioTelegram->getPayloadDataUInt32(tsOffset, 4) * 1000LL; - return hdr; -} - -static inline RelativePosition getRelativePosition(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset) -{ - RelativePosition pos; - pos.offsetY = a_radioTelegram->getPayloadDataSInt24(offset); - pos.offsetX = a_radioTelegram->getPayloadDataSInt24(offset + 3); - return pos; -} - -static inline GpsQuality getGpsQuality(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset) -{ - const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(offset); - GpsQuality ret; - ret.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); - ret.dgpsModeAvailable = ((gps & 0x40) == 0x40); - ret.pdopValue = (gps & 0x3f); - return ret; -} - -static inline OpsPosition getOpsPosition(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset, - size_t* newOffset = nullptr) -{ - const uint8_t opsLen = a_radioTelegram->getPayloadDataUInt8(offset); - offset += 1; - OpsPosition pos; - pos.opsId = -1; - if (opsLen > 0) + CoPrtCnvRadioTelegram *convertToRadio(CoPrtCnvCentralTelegram *a_telegram) { + return convertToRadioInternal(a_telegram); + } + + CoPrtCnvRadioTelegram *convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *a_telegram) + { + return convertToRadioInternal(a_telegram); + } + + static inline Header getHeader(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t tsOffset) + { + Header hdr; + hdr.equipmentNumber = a_radioTelegram->getIdentity(); + hdr.timeStamp = a_radioTelegram->getPayloadDataUInt32(tsOffset, 4) * 1000LL; + return hdr; + } + + static inline RelativePosition getRelativePosition(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset) + { + RelativePosition pos; + pos.offsetY = a_radioTelegram->getPayloadDataSInt24(offset); + pos.offsetX = a_radioTelegram->getPayloadDataSInt24(offset + 3); + return pos; + } + + static inline GpsQuality getGpsQuality(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset) + { + const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(offset); + GpsQuality ret; + ret.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); + ret.dgpsModeAvailable = ((gps & 0x40) == 0x40); + ret.pdopValue = (gps & 0x3f); + return ret; + } + + static inline OpsPosition getOpsPosition(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset, size_t *newOffset = nullptr) + { + const uint8_t opsLen = a_radioTelegram->getPayloadDataUInt8(offset); + offset += 1; + OpsPosition pos; + pos.opsId = -1; + if (opsLen > 0) + { std::vector opse; opse.reserve(opsLen); for (uint32_t i = 0; i < opsLen; i++) { - opse.push_back(a_radioTelegram->getPayloadDataUInt32(offset, 2)); - offset += 2; + opse.push_back(a_radioTelegram->getPayloadDataUInt32(offset, 2)); + offset += 2; } pos.opsId = opse.at(opse.size() - 1); - } - if (newOffset) + } + if (newOffset) *newOffset = offset; - return pos; -} + return pos; + } -static inline std::vector getPayload(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offsetData) -{ - int payloadLen = a_radioTelegram->getPayloadSize(); - payloadLen -= offsetData; - if (payloadLen <= 0) + static inline std::vector getPayload(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offsetData) { + int payloadLen = a_radioTelegram->getPayloadSize(); + payloadLen -= offsetData; + if (payloadLen <= 0) + { ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " << payloadLen; return {}; + } + std::vector ret; + ret.resize(payloadLen); + memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); + return ret; } - std::vector ret; - ret.resize(payloadLen); - memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); - return ret; -} -static inline std::vector getPayload(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offsetLen, - size_t offsetData) -{ - int payloadLen = a_radioTelegram->getPayloadDataUInt8(offsetLen); - if (payloadLen <= 0) + static inline std::vector getPayload(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offsetLen, size_t offsetData) { + int payloadLen = a_radioTelegram->getPayloadDataUInt8(offsetLen); + if (payloadLen <= 0) + { ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " << payloadLen; return {}; + } + std::vector ret; + ret.resize(payloadLen); + memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); + return ret; } - std::vector ret; - ret.resize(payloadLen); - memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); - return ret; -} -static N_CoPrtCnv::CoPrtCnvCentralTelegram* toCentral(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* data) -{ - QJsonObject obj; - obj[QStringLiteral("data")] = data->toJson(); - obj[QStringLiteral("type")] = data->type(); - obj[QStringLiteral("typeId")] = data->id(); - const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); - return new N_CoPrtCnv::CoPrtCnvCentralTelegram(ba, static_cast(data->id())); -} + static N_CoPrtCnv::CoPrtCnvCentralTelegram *toCentral(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data) + { + QJsonObject obj; + obj[QStringLiteral("data")] = data->toJson(); + obj[QStringLiteral("type")] = data->type(); + obj[QStringLiteral("typeId")] = data->id(); + const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); + return new N_CoPrtCnv::CoPrtCnvCentralTelegram(ba, static_cast(data->id())); + } -template void fixupEnum(T lowerBound, T upperBound, T defaultVal, T& valToFixup) -{ - if (valToFixup >= lowerBound && valToFixup <= upperBound) + template void fixupEnum(T lowerBound, T upperBound, T defaultVal, T &valToFixup) + { + if (valToFixup >= lowerBound && valToFixup <= upperBound) return; - valToFixup = defaultVal; -} + valToFixup = defaultVal; + } -static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram* tele, uint16_t a_length) -{ - const uint16_t length = tele->getPayloadSize(); - if (length >= a_length) + static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram *tele, uint16_t a_length) + { + const uint16_t length = tele->getPayloadSize(); + if (length >= a_length) return true; - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " - << a_length << ", but it is " << length; - return false; -} + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " << a_length << ", but it is " << length; + return false; + } -static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram* tele, uint16_t a_minLength, - const uint16_t a_dataAmountOffset, const uint8_t a_variableDataElementSize, - bool useHalf = false) -{ - if (0 == a_variableDataElementSize) + static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram *tele, + uint16_t a_minLength, + const uint16_t a_dataAmountOffset, + const uint8_t a_variableDataElementSize, + bool useHalf = false) + { + if (0 == a_variableDataElementSize) return isPayloadLengthOk(tele, a_minLength); - const uint16_t length = tele->getPayloadSize(); - if (length >= a_minLength) - { + const uint16_t length = tele->getPayloadSize(); + if (length >= a_minLength) + { uint8_t dataAmount = tele->getPayloadDataUInt8(a_dataAmountOffset); uint16_t dataSize = a_variableDataElementSize * dataAmount; if (useHalf) { - if ((dataAmount % 2) == 1) - dataSize = a_variableDataElementSize * ((dataAmount / 2.0) + 0.5); - else - dataSize = a_variableDataElementSize * (dataAmount / 2); + if ((dataAmount % 2) == 1) + dataSize = a_variableDataElementSize * ((dataAmount / 2.0) + 0.5); + else + dataSize = a_variableDataElementSize * (dataAmount / 2); } uint16_t expectedLength = dataSize + a_minLength; if (expectedLength != length) { - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " - << expectedLength << ", but it is " << length - << " (the amount of variable data in telegram was " << dataAmount << " => " - << dataSize << " bytes)"; - return false; + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " << expectedLength << ", but it is " << length + << " (the amount of variable data in telegram was " << dataAmount << " => " << dataSize << " bytes)"; + return false; } - } - else - { - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() - << " must be at least " << a_minLength << ", but it is only " << length; + } + else + { + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be at least " << a_minLength << ", but it is only " + << length; return false; + } + return true; } - return true; -} -N_CoPrtCnv::CoPrtCnvCentralTelegram* convertToCentral(const CoPrtCnvRadioTelegram* a_radioTelegram) -{ - auto tab = convertToTabTele(a_radioTelegram); - if (!tab) - return nullptr; - auto ret = toCentral(tab); - delete tab; - return ret; -} - -TrainingAreaTelegram* convertToTabTele(const CoPrtCnvRadioTelegram* a_radioTelegram) -{ - switch (a_radioTelegram->getTelID()) + N_CoPrtCnv::CoPrtCnvCentralTelegram *convertToCentral(const CoPrtCnvRadioTelegram *a_radioTelegram) { - case GEF_MANIPULATIONSMELDUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 12)) - return nullptr; + auto tab = convertToTabTele(a_radioTelegram); + if (!tab) + return nullptr; + auto ret = toCentral(tab); + delete tab; + return ret; + } - auto tele = new ManipulationReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->isManipulation = a_radioTelegram->getPayloadDataUInt32(7, 1); - tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt32(8, 1); + TrainingAreaTelegram *convertToTabTele(const CoPrtCnvRadioTelegram *a_radioTelegram) + { + switch (a_radioTelegram->getTelID()) + { + case GEF_MANIPULATIONSMELDUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 12)) + return nullptr; - return tele; + auto tele = new ManipulationReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->isManipulation = a_radioTelegram->getPayloadDataUInt32(7, 1); + tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt32(8, 1); + + return tele; } - case GEF_BITE_MELDUNG2: { + case GEF_BITE_MELDUNG2: + { - if (!isPayloadLengthOk(a_radioTelegram, 27, 19, 7)) - return nullptr; + if (!isPayloadLengthOk(a_radioTelegram, 27, 19, 7)) + return nullptr; - auto tele = new BiteReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->loginType = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + auto tele = new BiteReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->loginType = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - uint32_t ergebnisCAN = a_radioTelegram->getPayloadDataUInt32(8, 3); - tele->biteState = ergebnisCAN; + uint32_t ergebnisCAN = a_radioTelegram->getPayloadDataUInt32(8, 3); + tele->biteState = ergebnisCAN; - uint8_t ergebnisAusstattung = a_radioTelegram->getPayloadDataUInt8(11); - tele->batteryState = ergebnisAusstattung; + uint8_t ergebnisAusstattung = a_radioTelegram->getPayloadDataUInt8(11); + tele->batteryState = ergebnisAusstattung; - const auto nonDynamic = getBiteError(a_radioTelegram, 12); - if (nonDynamic.errorNumber != 0 || nonDynamic.canDeviceNumber != 0 || nonDynamic.subdeviceNumber != 0 || - nonDynamic.uniqueId != 0) - tele->biteErrors.push_back(nonDynamic); + const auto nonDynamic = getBiteError(a_radioTelegram, 12); + if (nonDynamic.errorNumber != 0 || nonDynamic.canDeviceNumber != 0 || nonDynamic.subdeviceNumber != 0 || nonDynamic.uniqueId != 0) + tele->biteErrors.push_back(nonDynamic); - const uint8_t fehlerLen = a_radioTelegram->getPayloadDataUInt8(19); - tele->biteErrors.reserve(tele->biteErrors.size() + fehlerLen); - for (uint8_t i = 0; i < fehlerLen; ++i) + const uint8_t fehlerLen = a_radioTelegram->getPayloadDataUInt8(19); + tele->biteErrors.reserve(tele->biteErrors.size() + fehlerLen); + for (uint8_t i = 0; i < fehlerLen; ++i) + { + const uint8_t iPos = 27 + i * 7; + tele->biteErrors.push_back(getBiteError(a_radioTelegram, iPos)); + } + a_radioTelegram->getPayloadDataUInt32(20, 3); + + tele->configError = a_radioTelegram->getPayloadDataUInt8(23); + uint32_t aktuelleKonfiguration = a_radioTelegram->getPayloadDataUInt32(24, 3); + tele->configState = aktuelleKonfiguration; + return tele; + } + + case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 18)) + return nullptr; + + auto tele = new EquipmentGearEvent; + tele->header = getHeader(a_radioTelegram, 3); + tele->charge.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); + tele->charge.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); + tele->charge.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(12, 2); + tele->chargeAmount = a_radioTelegram->getPayloadDataUInt32(14, 2); + const short remain = a_radioTelegram->getPayloadDataUInt32(16, 2); + tele->charge.remain = remain; + return tele; + } + + case GEF_SW_VERSIONSMELDUNG: + { + + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 8)) + return nullptr; + + auto tele = new ParticipantSwVersions; + tele->header = getHeader(a_radioTelegram, 3); + + const uint8_t versionsliste_len = a_radioTelegram->getPayloadDataUInt8(7); + tele->equipments.reserve(versionsliste_len); + for (uint32_t i = 0; i < versionsliste_len; i++) + { + const uint8_t iPos = 8 + i * 8; + EquipmentSwVersion ver; + ver.equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(iPos); + ver.subDeviceId = a_radioTelegram->getPayloadDataUInt8(iPos + 1); + ver.uniqueId = a_radioTelegram->getPayloadDataUInt32(iPos + 2, 4); + ver.swVersion = a_radioTelegram->getPayloadDataUInt32(iPos + 6, 2); + } + return tele; + } + + case GEF_SANITAETSDIENST_INSTANDSETZUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 19)) + return nullptr; + + auto tele = new SanitationRepair; + tele->header = getHeader(a_radioTelegram, 3); + tele->originatorType = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->equipmentNumberOrigin = a_radioTelegram->getPayloadDataUInt32(8, 2); + tele->stateStart = static_cast(a_radioTelegram->getPayloadDataUInt8(10)); + unsigned int bitfield1 = a_radioTelegram->getPayloadDataUInt8(11); + tele->typeOfTreatment = bitfield1 & 0x7F; + tele->triage = (bitfield1 & 0x80) >> 7; + tele->tyeOfDamage = a_radioTelegram->getPayloadDataUInt8(12); + unsigned int bitfield2 = a_radioTelegram->getPayloadDataUInt8(13); + tele->stateResult = static_cast(bitfield2 & 0x0F); + tele->treatmentResult = static_cast((bitfield2 & 0x30) >> 4); + tele->triagePriority = ((bitfield2 & 0xC0) >> 6); + tele->fullState = a_radioTelegram->getPayloadDataUInt8(14); + tele->timeOfTreatment = a_radioTelegram->getPayloadDataUInt32(15, 2); + tele->timeOfRecovery = a_radioTelegram->getPayloadDataUInt32(17, 2); + return tele; + } + + case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: + { + if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 1)) + return nullptr; + + auto tele = new SanitaryMaterialStockReport; + tele->header = getHeader(a_radioTelegram, 3); + + tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(7, 4); + tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(11, 2); + tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + + const uint16_t sanitaryMaterialCount = a_radioTelegram->getPayloadDataUInt8(14); + + tele->sanitaryMaterialCount = sanitaryMaterialCount; + double size = sanitaryMaterialCount; + + if (tele->sanitaryMaterialCount != 0) + { + int pos = 15; + std::vector stock; + stock.reserve(sanitaryMaterialCount); + for (int i = 0; i < size; i++) { - const uint8_t iPos = 27 + i * 7; - tele->biteErrors.push_back(getBiteError(a_radioTelegram, iPos)); + + unsigned int in = a_radioTelegram->getPayloadDataUInt8(pos++); + stock.emplace_back(in); } - a_radioTelegram->getPayloadDataUInt32(20, 3); - tele->configError = a_radioTelegram->getPayloadDataUInt8(23); - uint32_t aktuelleKonfiguration = a_radioTelegram->getPayloadDataUInt32(24, 3); - tele->configState = aktuelleKonfiguration; - return tele; + tele->sanitaryMaterialStock = stock; + } + else + tele->sanitaryMaterialStock = std::vector(); + return tele; } - case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 18)) - return nullptr; + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: + { + if (!isPayloadLengthOk(a_radioTelegram, 23)) + return nullptr; + auto tele = new Sanitation; + tele->header = getHeader(a_radioTelegram, 3); - auto tele = new EquipmentGearEvent; - tele->header = getHeader(a_radioTelegram, 3); - tele->charge.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); - tele->charge.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); - tele->charge.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(12, 2); - tele->chargeAmount = a_radioTelegram->getPayloadDataUInt32(14, 2); - const short remain = a_radioTelegram->getPayloadDataUInt32(16, 2); - tele->charge.remain = remain; - return tele; + qint64 proceduresP1 = a_radioTelegram->getPayloadDataUInt32(7, 4); + qint64 proceduresP2 = a_radioTelegram->getPayloadDataUInt32(11, 4); + + tele->proceduresTaken = (proceduresP1 << 32) + proceduresP2; + + tele->uniqeId = a_radioTelegram->getPayloadDataUInt32(15, 4); + tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(19, 2); + tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(21)); + quint8 enumByte = a_radioTelegram->getPayloadDataUInt8(22); + tele->sanitationEvaluation = static_cast((enumByte & 0xc0) >> 6); + tele->sanitationResult = static_cast(enumByte & 0x3f); + return tele; + } + case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new EquipmentOperationalState; + tele->header = getHeader(a_radioTelegram, 3); + + uint8_t abcSchutz = a_radioTelegram->getPayloadDataUInt8(8); + + tele->nbcProtectionActive = checkBitmask(abcSchutz, 0x40); + return tele; + } + case GEF_FEHLERMELDUNG_GFD: + { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new CtaDataError; + tele->header = getHeader(a_radioTelegram, 3); + tele->reason = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->originTelegramId = a_radioTelegram->getPayloadDataUInt8(8); + return tele; + } + case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: + { + if (!isPayloadLengthOk(a_radioTelegram, 31)) + return nullptr; + + auto tele = new RestoreRadioReadiness; + + tele->header = getHeader(a_radioTelegram, 3); + tele->readinessLossPosition = getRelativePosition(a_radioTelegram, 7); + tele->readinessLossTime = a_radioTelegram->getPayloadDataUInt32(13, 4); + tele->readinessRestorePosition = getRelativePosition(a_radioTelegram, 17); + tele->readinessRestoreTime = a_radioTelegram->getPayloadDataUInt32(23, 4); + + return tele; + } + case GEF_POSITIONS_MELDUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 14)) + return nullptr; + + auto tele = new PositionReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); + return tele; + } + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: + { + + if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 2)) + return nullptr; + + auto tele = new PositionReportWithMountedEquipments; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(13); + tele->gpsQuality.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); + tele->gpsQuality.dgpsModeAvailable = ((gps & 0x40) == 0x40); + tele->gpsQuality.pdopValue = (gps & 0x3f); + + const uint8_t aufgesessene_teilnehmer_len = a_radioTelegram->getPayloadDataUInt8(14); + tele->mountedEquipments.reserve(aufgesessene_teilnehmer_len); + + for (uint8_t i = 0; i < aufgesessene_teilnehmer_len; i++) + { + int eqId = a_radioTelegram->getPayloadDataUInt32(15 + 2 * i, 2); + tele->mountedEquipments.push_back(eqId); + } + return tele; } - case GEF_SW_VERSIONSMELDUNG: { + case GEF_DEAKTIVIERUNG_EINZELMINE: + { + if (!isPayloadLengthOk(a_radioTelegram, 13)) + return nullptr; - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 8)) - return nullptr; + auto tele = new MineTriggered; + tele->header = getHeader(a_radioTelegram, 5); + tele->mineAreaId = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->mineIndex = a_radioTelegram->getPayloadDataUInt32(11, 2); + return tele; + } + case GEF_DEFINITION_IED: + { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; - auto tele = new ParticipantSwVersions; - tele->header = getHeader(a_radioTelegram, 3); + auto tele = new DefinitionIed; + tele->header = getHeader(a_radioTelegram, 3); + tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->iedType = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); + tele->trigger = a_radioTelegram->getPayloadDataUInt8(10); + tele->explosiveForce = a_radioTelegram->getPayloadDataUInt8(11); + tele->relPosition = getRelativePosition(a_radioTelegram, 12); + tele->partyId = a_radioTelegram->getPayloadDataUInt8(18); + tele->pairingState = static_cast(a_radioTelegram->getPayloadDataUInt8(19)); + tele->pairedId = a_radioTelegram->getPayloadDataUInt32(20, 2); + tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(22)); + tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(23); - const uint8_t versionsliste_len = a_radioTelegram->getPayloadDataUInt8(7); - tele->equipments.reserve(versionsliste_len); - for (uint32_t i = 0; i < versionsliste_len; i++) - { - const uint8_t iPos = 8 + i * 8; - EquipmentSwVersion ver; - ver.equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(iPos); - ver.subDeviceId = a_radioTelegram->getPayloadDataUInt8(iPos + 1); - ver.uniqueId = a_radioTelegram->getPayloadDataUInt32(iPos + 2, 4); - ver.swVersion = a_radioTelegram->getPayloadDataUInt32(iPos + 6, 2); - } - return tele; + fixupEnum(IedType::SuicideIed, IedType::IedBigPyro, IedType::SuicideIed, tele->iedType); + fixupEnum(IedPairingState::NotPaired, IedPairingState::PairedToOps, IedPairingState::NotPaired, tele->pairingState); + fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, IedTacticalState::Unknown, tele->tacticalState); + return tele; + } + case GEF_ZUSTAND_IED: + { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new StateIed; + tele->header = getHeader(a_radioTelegram, 3); + tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); + tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(10); + tele->batteryWarnings = a_radioTelegram->getPayloadDataUInt8(11); + tele->errorStateElectronics = static_cast(a_radioTelegram->getPayloadDataUInt8(12)); + tele->errorStatePyrotechnics1 = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + tele->errorStatePyrotechnics2 = static_cast(a_radioTelegram->getPayloadDataUInt8(14)); + tele->errorStatePyrotechnics3 = static_cast(a_radioTelegram->getPayloadDataUInt8(15)); + + fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, IedTacticalState::Unknown, tele->tacticalState); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStateElectronics); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStatePyrotechnics1); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStatePyrotechnics2); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStatePyrotechnics3); + return tele; + } + case GEF_STATUS_EINZELMINENSIMULATOR: + { + if (!isPayloadLengthOk(a_radioTelegram, 17)) + return nullptr; + + auto tele = new DusSingleMineState; + tele->header = getHeader(a_radioTelegram, 3); + tele->mineId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->relPosition = getRelativePosition(a_radioTelegram, 9); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt8(15); + tele->state = a_radioTelegram->getPayloadDataUInt8(16); + tele->effectStart = tele->header.timeStamp; + return tele; + } + case GEF_TREFFER_EREIGNIS_DUS: + { + if (!isPayloadLengthOk(a_radioTelegram, 23)) + return nullptr; + + auto tele = new StateChangeDirect; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getTaktZustand(a_radioTelegram, 13, tele); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(19, 2); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(21, 2); + return tele; + } + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: + { + if (!isPayloadLengthOk(a_radioTelegram, 22)) + return nullptr; + + auto tele = new StateChangeIndirect; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getTaktZustand(a_radioTelegram, 13, tele); + + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(20, 2); + return tele; + } + case GEF_SCHIEDSRICHTEREINGRIFF: + { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new OperatorAction; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->action = a_radioTelegram->getPayloadDataUInt8(13); + tele->operatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + return tele; + } + case GEF_TREFFER_EREIGNIS_DUS_IPS: + { + + if (!isPayloadLengthOk(a_radioTelegram, 18, 17, 2)) + return nullptr; + + auto tele = new StateChangeDirect; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(15, 2); + + size_t iPos = 17; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + return tele; + } + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: + { + + if (!isPayloadLengthOk(a_radioTelegram, 17, 16, 2)) + return nullptr; + + auto tele = new StateChangeIndirect; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + size_t iPos = 16; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + tele->isSecondaryEffect = true; + return tele; + } + case GEF_TAKTISCHER_STATUS: + { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new StateChange; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + + tele->originatorType = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + return tele; } - case GEF_SANITAETSDIENST_INSTANDSETZUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 19)) - return nullptr; + case GEF_EINTRETEN_FUNKTIONSRAUM: + { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; - auto tele = new SanitationRepair; - tele->header = getHeader(a_radioTelegram, 3); - tele->originatorType = - static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - tele->equipmentNumberOrigin = a_radioTelegram->getPayloadDataUInt32(8, 2); - tele->stateStart = - static_cast(a_radioTelegram->getPayloadDataUInt8(10)); - unsigned int bitfield1 = a_radioTelegram->getPayloadDataUInt8(11); - tele->typeOfTreatment = bitfield1 & 0x7F; - tele->triage = (bitfield1 & 0x80) >> 7; - tele->tyeOfDamage = a_radioTelegram->getPayloadDataUInt8(12); - unsigned int bitfield2 = a_radioTelegram->getPayloadDataUInt8(13); - tele->stateResult = static_cast(bitfield2 & 0x0F); - tele->treatmentResult = - static_cast((bitfield2 & 0x30) >> 4); - tele->triagePriority = ((bitfield2 & 0xC0) >> 6); - tele->fullState = a_radioTelegram->getPayloadDataUInt8(14); - tele->timeOfTreatment = a_radioTelegram->getPayloadDataUInt32(15, 2); - tele->timeOfRecovery = a_radioTelegram->getPayloadDataUInt32(17, 2); - return tele; + auto tele = new FunctionalAreaEntry; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(13, 2); + return tele; + } + case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: + { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + getSpecialSensorData(a_radioTelegram, 7, tele); + return tele; + } + case GEF_SONDERSENSORIK_FAHRSPUR: + { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getSpecialSensorData(a_radioTelegram, 13, tele); + return tele; + } + case GEF_SONDERSENSORIK_DATEN: + { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->type = a_radioTelegram->getPayloadDataUInt32(13, 1); + getSpecialSensorData(a_radioTelegram, 14, tele); + tele->nbcType = a_radioTelegram->getPayloadDataUInt32(16, 1); + return tele; + } + case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: + { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; + + auto tele = new MinelayerTrailerData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); + tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; + tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); + tele->mineCount = a_radioTelegram->getPayloadDataUInt32(22, 2); + return tele; + } + case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: + { + if (!isPayloadLengthOk(a_radioTelegram, 25)) + return nullptr; + + auto tele = new MinelayerThrowerData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); + tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; + tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); + tele->throwingType = static_cast(a_radioTelegram->getPayloadDataUInt32(22, 2)); + tele->mineCount = a_radioTelegram->getPayloadDataUInt32(23, 2); + return tele; + } + case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: + { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new MinelayerTrailerPosition; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->dusSerialNo = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(15, 1); + return tele; + } + case GEF_DATENVERKEHR_SRT_TDS: + { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::OC; + tele->payload = getPayload(a_radioTelegram, 7); + return tele; + } + case GEF_DATENVERKEHR_DMF_TDS: + { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::FireSmokeMarker; + tele->payload = getPayload(a_radioTelegram, 7); + return tele; + } + case GEF_DATENVERKEHR_GEOP_TDS: + { + if (!isPayloadLengthOk(a_radioTelegram, 14)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); + tele->payloadType = OpaquePayloadDataBase::Type::Geopairing; + tele->payload = getPayload(a_radioTelegram, 14, 15); + return tele; + } + case GEF_DATENVERKEHR_TGTC_TDS: + { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::Target; + tele->payload = getPayload(a_radioTelegram, 7, 8); + return tele; + } + case GEF_GERAETEEREIGNIS: + { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; + + auto tele = new EquipmentEvent; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(13); + tele->subDeviceId = a_radioTelegram->getPayloadDataUInt8(14); + tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(15, 4); + tele->code = a_radioTelegram->getPayloadDataUInt8(23); + tele->payload = getPayload(a_radioTelegram, 24, 25); + return tele; } - case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: { - if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 1)) - return nullptr; + case GEF_WAFFENZUORDNUNG: + { - auto tele = new SanitaryMaterialStockReport; - tele->header = getHeader(a_radioTelegram, 3); + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 6)) + return nullptr; - tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(7, 4); - tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(11, 2); - tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + auto tele = new EquipmentGearAssignment; + tele->header = getHeader(a_radioTelegram, 3); - const uint16_t sanitaryMaterialCount = a_radioTelegram->getPayloadDataUInt8(14); + const uint8_t waffen_len = a_radioTelegram->getPayloadDataUInt8(7); + tele->gears.reserve(waffen_len); + for (uint32_t i = 0; i < waffen_len && i < 10; i++) + { + const uint8_t iPos = 8 + i * 6; - tele->sanitaryMaterialCount = sanitaryMaterialCount; - double size = sanitaryMaterialCount; - - if (tele->sanitaryMaterialCount != 0) - { - int pos = 15; - std::vector stock; - stock.reserve(sanitaryMaterialCount); - for (int i = 0; i < size; i++) - { - - unsigned int in = a_radioTelegram->getPayloadDataUInt8(pos++); - stock.emplace_back(in); - } - - tele->sanitaryMaterialStock = stock; - } - else - tele->sanitaryMaterialStock = std::vector(); - return tele; + Gear gear; + gear.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(iPos, 4); + gear.gearTasCode = a_radioTelegram->getPayloadDataUInt8(iPos + 4); + gear.chargeCounting = a_radioTelegram->getPayloadDataUInt8(iPos + 5) != 0; + tele->gears.push_back(std::move(gear)); + } + return tele; } + case GEF_IPS_POSITIONSDATEN: + { - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: { - if (!isPayloadLengthOk(a_radioTelegram, 23)) - return nullptr; - auto tele = new Sanitation; - tele->header = getHeader(a_radioTelegram, 3); + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 2)) + return nullptr; - qint64 proceduresP1 = a_radioTelegram->getPayloadDataUInt32(7, 4); - qint64 proceduresP2 = a_radioTelegram->getPayloadDataUInt32(11, 4); - - tele->proceduresTaken = (proceduresP1 << 32) + proceduresP2; - - tele->uniqeId = a_radioTelegram->getPayloadDataUInt32(15, 4); - tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(19, 2); - tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(21)); - quint8 enumByte = a_radioTelegram->getPayloadDataUInt8(22); - tele->sanitationEvaluation = static_cast((enumByte & 0xc0) >> 6); - tele->sanitationResult = static_cast(enumByte & 0x3f); - return tele; + auto tele = new PositionReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->header.timeStamp += 1; + size_t iPos = 7; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + if (tele->opsPosition.opsId == -1) + { + delete tele; + tele = nullptr; + } + return tele; } - case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; + case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: + { - auto tele = new EquipmentOperationalState; - tele->header = getHeader(a_radioTelegram, 3); + constexpr int varSize = 5; - uint8_t abcSchutz = a_radioTelegram->getPayloadDataUInt8(8); + if (!isPayloadLengthOk(a_radioTelegram, 13, 12, varSize)) + return nullptr; - tele->nbcProtectionActive = checkBitmask(abcSchutz, 0x40); - return tele; + auto tele = new EquipmentGearChargeState; + tele->header = getHeader(a_radioTelegram, 3); + GearCharge gc; + gc.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); + gc.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); + const uint8_t munitionsliste_len = a_radioTelegram->getPayloadDataUInt8(12); + tele->charges.reserve(munitionsliste_len); + for (uint32_t i = 0; i < munitionsliste_len; i++) + { + int iPos = 13; + const int offset = 5 * i; + gc.location = a_radioTelegram->getPayloadDataUInt8(iPos + offset); + iPos++; + short munitionsmenge = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); + iPos += 2; + gc.remain = munitionsmenge < 0 ? -1 : munitionsmenge; + gc.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); + tele->charges.push_back(gc); + } + return tele; } - case GEF_FEHLERMELDUNG_GFD: { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 13)) + return nullptr; - auto tele = new CtaDataError; - tele->header = getHeader(a_radioTelegram, 3); - tele->reason = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - tele->originTelegramId = a_radioTelegram->getPayloadDataUInt8(8); - return tele; + auto tele = new CesHitRequest; + tele->header = getHeader(a_radioTelegram, 3); + tele->chargeTasCodeDirect = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->aesType = static_cast(a_radioTelegram->getPayloadDataUInt8(11)); + tele->remainEffectTasCodeDirect = a_radioTelegram->getPayloadDataUInt8(12); + return tele; } - case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: { - if (!isPayloadLengthOk(a_radioTelegram, 31)) - return nullptr; + case GEF_TEILNEHMERMODE_MELDUNG: + { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; - auto tele = new RestoreRadioReadiness; + auto tele = new ParticipantModeReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->language = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->operationMode = static_cast(a_radioTelegram->getPayloadDataUInt8(8)); + tele->reactivationDetoxication = a_radioTelegram->getPayloadDataUInt8(9) * 10; + tele->reactivationMaintenance = a_radioTelegram->getPayloadDataUInt8(10) * 10; + tele->reactivationMedic = a_radioTelegram->getPayloadDataUInt8(11) * 10; + unsigned char wph_mode = a_radioTelegram->getPayloadDataUInt8(12); + tele->modeHelmet = static_cast(wph_mode & 0x03); + tele->modeVest = static_cast((wph_mode >> 2) & 0x03); + tele->personellProtectionMode = static_cast((wph_mode >> 4) & 0x07); - tele->header = getHeader(a_radioTelegram, 3); - tele->readinessLossPosition = getRelativePosition(a_radioTelegram, 7); - tele->readinessLossTime = a_radioTelegram->getPayloadDataUInt32(13, 4); - tele->readinessRestorePosition = getRelativePosition(a_radioTelegram, 17); - tele->readinessRestoreTime = a_radioTelegram->getPayloadDataUInt32(23, 4); + unsigned char protection_mode = a_radioTelegram->getPayloadDataUInt8(13); + tele->protectionLevel = static_cast(protection_mode & 0x06); + tele->abcProtectionMode = static_cast((protection_mode >> 3) & 0x03); - return tele; + unsigned char specialFunction = a_radioTelegram->getPayloadDataUInt8(14); + tele->handgrenadeSearchMode = static_cast(specialFunction & 0b11); + tele->internationalMode = static_cast((specialFunction >> 2) & 0b11); + return tele; } - case GEF_POSITIONS_MELDUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 14)) - return nullptr; + case GEF_TEILNEHMER_KONFIG_ANTWORT: + { + if (!isPayloadLengthOk(a_radioTelegram, 27)) + return nullptr; - auto tele = new PositionReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); - return tele; - } - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: { - - if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 2)) - return nullptr; - - auto tele = new PositionReportWithMountedEquipments; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(13); - tele->gpsQuality.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); - tele->gpsQuality.dgpsModeAvailable = ((gps & 0x40) == 0x40); - tele->gpsQuality.pdopValue = (gps & 0x3f); - - const uint8_t aufgesessene_teilnehmer_len = a_radioTelegram->getPayloadDataUInt8(14); - tele->mountedEquipments.reserve(aufgesessene_teilnehmer_len); - - for (uint8_t i = 0; i < aufgesessene_teilnehmer_len; i++) - { - int eqId = a_radioTelegram->getPayloadDataUInt32(15 + 2 * i, 2); - tele->mountedEquipments.push_back(eqId); - } - return tele; - } - - case GEF_DEAKTIVIERUNG_EINZELMINE: { - if (!isPayloadLengthOk(a_radioTelegram, 13)) - return nullptr; - - auto tele = new MineTriggered; - tele->header = getHeader(a_radioTelegram, 5); - tele->mineAreaId = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->mineIndex = a_radioTelegram->getPayloadDataUInt32(11, 2); - return tele; - } - case GEF_DEFINITION_IED: { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new DefinitionIed; - tele->header = getHeader(a_radioTelegram, 3); - tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->iedType = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); - tele->trigger = a_radioTelegram->getPayloadDataUInt8(10); - tele->explosiveForce = a_radioTelegram->getPayloadDataUInt8(11); - tele->relPosition = getRelativePosition(a_radioTelegram, 12); - tele->partyId = a_radioTelegram->getPayloadDataUInt8(18); - tele->pairingState = static_cast(a_radioTelegram->getPayloadDataUInt8(19)); - tele->pairedId = a_radioTelegram->getPayloadDataUInt32(20, 2); - tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(22)); - tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(23); - - fixupEnum(IedType::SuicideIed, IedType::IedBigPyro, IedType::SuicideIed, tele->iedType); - fixupEnum(IedPairingState::NotPaired, IedPairingState::PairedToOps, IedPairingState::NotPaired, - tele->pairingState); - fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, - IedTacticalState::Unknown, tele->tacticalState); - return tele; - } - case GEF_ZUSTAND_IED: { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new StateIed; - tele->header = getHeader(a_radioTelegram, 3); - tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); - tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(10); - tele->batteryWarnings = a_radioTelegram->getPayloadDataUInt8(11); - tele->errorStateElectronics = static_cast(a_radioTelegram->getPayloadDataUInt8(12)); - tele->errorStatePyrotechnics1 = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); - tele->errorStatePyrotechnics2 = static_cast(a_radioTelegram->getPayloadDataUInt8(14)); - tele->errorStatePyrotechnics3 = static_cast(a_radioTelegram->getPayloadDataUInt8(15)); - - fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, - IedTacticalState::Unknown, tele->tacticalState); - fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStateElectronics); - fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, - tele->errorStatePyrotechnics1); - fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, - tele->errorStatePyrotechnics2); - fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, - tele->errorStatePyrotechnics3); - return tele; - } - case GEF_STATUS_EINZELMINENSIMULATOR: { - if (!isPayloadLengthOk(a_radioTelegram, 17)) - return nullptr; - - auto tele = new DusSingleMineState; - tele->header = getHeader(a_radioTelegram, 3); - tele->mineId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->relPosition = getRelativePosition(a_radioTelegram, 9); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt8(15); - tele->state = a_radioTelegram->getPayloadDataUInt8(16); - tele->effectStart = tele->header.timeStamp; - return tele; - } - case GEF_TREFFER_EREIGNIS_DUS: { - if (!isPayloadLengthOk(a_radioTelegram, 23)) - return nullptr; - - auto tele = new StateChangeDirect; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getTaktZustand(a_radioTelegram, 13, tele); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(19, 2); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(21, 2); - return tele; - } - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: { - if (!isPayloadLengthOk(a_radioTelegram, 22)) - return nullptr; - - auto tele = new StateChangeIndirect; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getTaktZustand(a_radioTelegram, 13, tele); - - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(20, 2); - return tele; - } - case GEF_SCHIEDSRICHTEREINGRIFF: { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new OperatorAction; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->action = a_radioTelegram->getPayloadDataUInt8(13); - tele->operatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - return tele; - } - case GEF_TREFFER_EREIGNIS_DUS_IPS: { - - if (!isPayloadLengthOk(a_radioTelegram, 18, 17, 2)) - return nullptr; - - auto tele = new StateChangeDirect; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(15, 2); - - size_t iPos = 17; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - return tele; - } - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: { - - if (!isPayloadLengthOk(a_radioTelegram, 17, 16, 2)) - return nullptr; - - auto tele = new StateChangeIndirect; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - size_t iPos = 16; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - tele->isSecondaryEffect = true; - return tele; - } - case GEF_TAKTISCHER_STATUS: { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new StateChange; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - - tele->originatorType = - static_cast(a_radioTelegram->getPayloadDataUInt8(13)); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - return tele; - } - - case GEF_EINTRETEN_FUNKTIONSRAUM: { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new FunctionalAreaEntry; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(13, 2); - return tele; - } - case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - getSpecialSensorData(a_radioTelegram, 7, tele); - return tele; - } - case GEF_SONDERSENSORIK_FAHRSPUR: { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getSpecialSensorData(a_radioTelegram, 13, tele); - return tele; - } - case GEF_SONDERSENSORIK_DATEN: { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->type = a_radioTelegram->getPayloadDataUInt32(13, 1); - getSpecialSensorData(a_radioTelegram, 14, tele); - tele->nbcType = a_radioTelegram->getPayloadDataUInt32(16, 1); - return tele; - } - case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new MinelayerTrailerData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); - tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; - tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); - tele->mineCount = a_radioTelegram->getPayloadDataUInt32(22, 2); - return tele; - } - case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: { - if (!isPayloadLengthOk(a_radioTelegram, 25)) - return nullptr; - - auto tele = new MinelayerThrowerData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); - tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; - tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); - tele->throwingType = - static_cast(a_radioTelegram->getPayloadDataUInt32(22, 2)); - tele->mineCount = a_radioTelegram->getPayloadDataUInt32(23, 2); - return tele; - } - case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new MinelayerTrailerPosition; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->dusSerialNo = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(15, 1); - return tele; - } - case GEF_DATENVERKEHR_SRT_TDS: { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::OC; - tele->payload = getPayload(a_radioTelegram, 7); - return tele; - } - case GEF_DATENVERKEHR_DMF_TDS: { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::FireSmokeMarker; - tele->payload = getPayload(a_radioTelegram, 7); - return tele; - } - case GEF_DATENVERKEHR_GEOP_TDS: { - if (!isPayloadLengthOk(a_radioTelegram, 14)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); - tele->payloadType = OpaquePayloadDataBase::Type::Geopairing; - tele->payload = getPayload(a_radioTelegram, 14, 15); - return tele; - } - case GEF_DATENVERKEHR_TGTC_TDS: { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::Target; - tele->payload = getPayload(a_radioTelegram, 7, 8); - return tele; - } - case GEF_GERAETEEREIGNIS: { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new EquipmentEvent; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(13); - tele->subDeviceId = a_radioTelegram->getPayloadDataUInt8(14); - tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(15, 4); - tele->code = a_radioTelegram->getPayloadDataUInt8(23); - tele->payload = getPayload(a_radioTelegram, 24, 25); - return tele; - } - - case GEF_WAFFENZUORDNUNG: { - - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 6)) - return nullptr; - - auto tele = new EquipmentGearAssignment; - tele->header = getHeader(a_radioTelegram, 3); - - const uint8_t waffen_len = a_radioTelegram->getPayloadDataUInt8(7); - tele->gears.reserve(waffen_len); - for (uint32_t i = 0; i < waffen_len && i < 10; i++) - { - const uint8_t iPos = 8 + i * 6; - - Gear gear; - gear.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(iPos, 4); - gear.gearTasCode = a_radioTelegram->getPayloadDataUInt8(iPos + 4); - gear.chargeCounting = a_radioTelegram->getPayloadDataUInt8(iPos + 5) != 0; - tele->gears.push_back(std::move(gear)); - } - return tele; - } - case GEF_IPS_POSITIONSDATEN: { - - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 2)) - return nullptr; - - auto tele = new PositionReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->header.timeStamp += 1; - size_t iPos = 7; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - if (tele->opsPosition.opsId == -1) - { - delete tele; - tele = nullptr; - } - return tele; - } - case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: { - - constexpr int varSize = 5; - - if (!isPayloadLengthOk(a_radioTelegram, 13, 12, varSize)) - return nullptr; - - auto tele = new EquipmentGearChargeState; - tele->header = getHeader(a_radioTelegram, 3); - GearCharge gc; - gc.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); - gc.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); - const uint8_t munitionsliste_len = a_radioTelegram->getPayloadDataUInt8(12); - tele->charges.reserve(munitionsliste_len); - for (uint32_t i = 0; i < munitionsliste_len; i++) - { - int iPos = 13; - const int offset = 5 * i; - gc.location = a_radioTelegram->getPayloadDataUInt8(iPos + offset); - iPos++; - short munitionsmenge = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); - iPos += 2; - gc.remain = munitionsmenge < 0 ? -1 : munitionsmenge; - gc.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); - tele->charges.push_back(gc); - } - return tele; - } - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 13)) - return nullptr; - - auto tele = new CesHitRequest; - tele->header = getHeader(a_radioTelegram, 3); - tele->chargeTasCodeDirect = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->aesType = static_cast(a_radioTelegram->getPayloadDataUInt8(11)); - tele->remainEffectTasCodeDirect = a_radioTelegram->getPayloadDataUInt8(12); - return tele; - } - case GEF_TEILNEHMERMODE_MELDUNG: { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new ParticipantModeReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->language = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - tele->operationMode = - static_cast(a_radioTelegram->getPayloadDataUInt8(8)); - tele->reactivationDetoxication = a_radioTelegram->getPayloadDataUInt8(9) * 10; - tele->reactivationMaintenance = a_radioTelegram->getPayloadDataUInt8(10) * 10; - tele->reactivationMedic = a_radioTelegram->getPayloadDataUInt8(11) * 10; - unsigned char wph_mode = a_radioTelegram->getPayloadDataUInt8(12); - tele->modeHelmet = static_cast(wph_mode & 0x03); - tele->modeVest = static_cast((wph_mode >> 2) & 0x03); - tele->personellProtectionMode = - static_cast((wph_mode >> 4) & 0x07); - - unsigned char protection_mode = a_radioTelegram->getPayloadDataUInt8(13); - tele->protectionLevel = static_cast(protection_mode & 0x06); - tele->abcProtectionMode = - static_cast((protection_mode >> 3) & 0x03); - - unsigned char specialFunction = a_radioTelegram->getPayloadDataUInt8(14); - tele->handgrenadeSearchMode = - static_cast(specialFunction & 0b11); - tele->internationalMode = - static_cast((specialFunction >> 2) & 0b11); - return tele; - } - case GEF_TEILNEHMER_KONFIG_ANTWORT: { - if (!isPayloadLengthOk(a_radioTelegram, 27)) - return nullptr; - - auto tele = new ParticipantConfigurationReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->positionIntervallVehicle = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->positionIntervallPersonell = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->positionIntervallAircraft = a_radioTelegram->getPayloadDataUInt32(11, 2); - tele->positionTransmissionIntervall = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->heightbarrier = a_radioTelegram->getPayloadDataUInt32(15, 2); - unsigned char tmp = a_radioTelegram->getPayloadDataUInt8(17); - tele->faultPositionHandling = - static_cast((tmp >> 6) & 0x03); - tele->switchingPositionIntervall = - static_cast(tmp & 0x03); - tele->waittimeAdditionalBroadcastDemand = a_radioTelegram->getPayloadDataUInt32(18, 2); - tele->factorWaittimeIncreaseAtHighload = a_radioTelegram->getPayloadDataUInt8(20); - tele->waittimeAutomaticVulnerabilityIncreaseLevel1 = a_radioTelegram->getPayloadDataUInt8(21); - tele->waittimeAutomaticVulnerabilityIncreaseLevel2 = a_radioTelegram->getPayloadDataUInt8(22); - tele->waittimeAutomaticVulnerabilityIncreaseLevel3 = a_radioTelegram->getPayloadDataUInt8(23); - tele->opticalCode = - static_cast(a_radioTelegram->getPayloadDataUInt8(24)); - tele->vulnerabilityModel = a_radioTelegram->getPayloadDataUInt8(25); - tele->validTimeOps = a_radioTelegram->getPayloadDataUInt8(26); - return tele; + auto tele = new ParticipantConfigurationReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->positionIntervallVehicle = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->positionIntervallPersonell = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->positionIntervallAircraft = a_radioTelegram->getPayloadDataUInt32(11, 2); + tele->positionTransmissionIntervall = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->heightbarrier = a_radioTelegram->getPayloadDataUInt32(15, 2); + unsigned char tmp = a_radioTelegram->getPayloadDataUInt8(17); + tele->faultPositionHandling = static_cast((tmp >> 6) & 0x03); + tele->switchingPositionIntervall = static_cast(tmp & 0x03); + tele->waittimeAdditionalBroadcastDemand = a_radioTelegram->getPayloadDataUInt32(18, 2); + tele->factorWaittimeIncreaseAtHighload = a_radioTelegram->getPayloadDataUInt8(20); + tele->waittimeAutomaticVulnerabilityIncreaseLevel1 = a_radioTelegram->getPayloadDataUInt8(21); + tele->waittimeAutomaticVulnerabilityIncreaseLevel2 = a_radioTelegram->getPayloadDataUInt8(22); + tele->waittimeAutomaticVulnerabilityIncreaseLevel3 = a_radioTelegram->getPayloadDataUInt8(23); + tele->opticalCode = static_cast(a_radioTelegram->getPayloadDataUInt8(24)); + tele->vulnerabilityModel = a_radioTelegram->getPayloadDataUInt8(25); + tele->validTimeOps = a_radioTelegram->getPayloadDataUInt8(26); + return tele; } case GEF_ESW_MELDUNG: + return nullptr; + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: + { + if (!isPayloadLengthOk(a_radioTelegram, 10)) return nullptr; - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: { - if (!isPayloadLengthOk(a_radioTelegram, 10)) - return nullptr; - auto tele = new RequestBroadcastTelegrams; - tele->header = getHeader(a_radioTelegram, 3); - tele->resetCounter = a_radioTelegram->getPayloadDataUInt8(7); - tele->broadcastIndex = a_radioTelegram->getPayloadDataUInt32(8, 2); - return tele; + auto tele = new RequestBroadcastTelegrams; + tele->header = getHeader(a_radioTelegram, 3); + tele->resetCounter = a_radioTelegram->getPayloadDataUInt8(7); + tele->broadcastIndex = a_radioTelegram->getPayloadDataUInt32(8, 2); + return tele; } - case GEF_LASER_TARGET_DESIGNATOR_UPDATE: { - auto tele = new ApacheLaserDesignation; + case GEF_LASER_TARGET_DESIGNATOR_UPDATE: + { + auto tele = new ApacheLaserDesignation; - tele->header = getHeader(a_radioTelegram, 3); - tele->code = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->outputPower = a_radioTelegram->getPayloadDataUInt8(9); - tele->gearId = a_radioTelegram->getPayloadDataUInt32(10, 4); + tele->header = getHeader(a_radioTelegram, 3); + tele->code = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->outputPower = a_radioTelegram->getPayloadDataUInt8(9); + tele->gearId = a_radioTelegram->getPayloadDataUInt32(10, 4); - return tele; + return tele; } - default: { - ERROR_LOG(logger()) << "Conversion of Radio-Telegram to Central-Telegram with telId=" - << a_radioTelegram->getTelID() << " not implemented."; + default: + { + ERROR_LOG(logger()) << "Conversion of Radio-Telegram to Central-Telegram with telId=" << a_radioTelegram->getTelID() << " not implemented."; } + } + return nullptr; } - return nullptr; -} -} // namespace CoPrtCnvTelegramConverter + } // namespace CoPrtCnvTelegramConverter } // namespace N_CoPrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/tetra_telegram_ids.h b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/tetra_telegram_ids.h index a0080340f..5ace5ea27 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/tetra_telegram_ids.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/tetra_telegram_ids.h @@ -10,112 +10,112 @@ enum gef_telegramm_id_et { - GEF_BESTAETIGUNG = 0, + GEF_BESTAETIGUNG = 0, - GEF_INIT = 1, - GEF_MANIPULATIONSMELDUNG = 2, - GEF_UMGEBUNGS_MELDUNG2 = 203, - GEF_AUFFORDERUNG_BITE_MELDUNG = 4, - GEF_BITE_MELDUNG2 = 205, + GEF_INIT = 1, + GEF_MANIPULATIONSMELDUNG = 2, + GEF_UMGEBUNGS_MELDUNG2 = 203, + GEF_AUFFORDERUNG_BITE_MELDUNG = 4, + GEF_BITE_MELDUNG2 = 205, - GEF_LIZENSIERUNG_TNE = 6, - GEF_BETRIEBSZUSTAND_AUSSTATTUNG = 7, - GEF_KONFIGURATION_WIRKMODELL = 9, - GEF_ANFORDERUNG_KONFIGURATIONSDATEN = 10, - GEF_KONFIGURATIONSMELDUNG = 11, - GEF_FEHLERMELDUNG_GFD = 12, - GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT = 13, + GEF_LIZENSIERUNG_TNE = 6, + GEF_BETRIEBSZUSTAND_AUSSTATTUNG = 7, + GEF_KONFIGURATION_WIRKMODELL = 9, + GEF_ANFORDERUNG_KONFIGURATIONSDATEN = 10, + GEF_KONFIGURATIONSMELDUNG = 11, + GEF_FEHLERMELDUNG_GFD = 12, + GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT = 13, - GEF_POSITIONS_MELDUNG = 21, - GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER = 22, - GEF_POSITIONS_MELDUNG_LFZ = 23, - GEF_IPS_POSITIONSDATEN = 201, + GEF_POSITIONS_MELDUNG = 21, + GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER = 22, + GEF_POSITIONS_MELDUNG_LFZ = 23, + GEF_IPS_POSITIONSDATEN = 201, - GEF_SCHIEDSRICHTERKOMMANDO = 25, + GEF_SCHIEDSRICHTERKOMMANDO = 25, - GEF_WIRKFELD_EINZELGESCHOSS = 31, - GEF_WIRKFELD_FLAECHENDECKENDES_FEUER = 32, - GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP = 33, - GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN = 34, - GEF_WIRKFELD_MINENSPERRE = 35, - GEF_WIRKFELD_STATUS_MINENSPERRE = 36, - GEF_WIRKFELD_A_KAMPFMITTEL = 37, - GEF_WIRKFELD_C_KAMPFMITTEL = 38, - GEF_DEAKTIVIERUNG_WIRKFELD = 39, - GEF_WIRKFELD_AENDERUNG_BEZEICHNER = 40, - GEF_DEAKTIVIERUNG_EINZELMINE = 41, - GEF_REAKTIVIERUNG_DUS_MINE = 42, - GEF_DEFINITION_IED = 43, - GEF_ZUSTAND_IED = 44, - GEF_STATUS_EINZELMINENSIMULATOR = 45, - GEF_WIRKFELD_EINZELMINENSIMULATOR = 46, - GEF_SELEKTIVE_AUFMUNITIONIERUNG = 56, + GEF_WIRKFELD_EINZELGESCHOSS = 31, + GEF_WIRKFELD_FLAECHENDECKENDES_FEUER = 32, + GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP = 33, + GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN = 34, + GEF_WIRKFELD_MINENSPERRE = 35, + GEF_WIRKFELD_STATUS_MINENSPERRE = 36, + GEF_WIRKFELD_A_KAMPFMITTEL = 37, + GEF_WIRKFELD_C_KAMPFMITTEL = 38, + GEF_DEAKTIVIERUNG_WIRKFELD = 39, + GEF_WIRKFELD_AENDERUNG_BEZEICHNER = 40, + GEF_DEAKTIVIERUNG_EINZELMINE = 41, + GEF_REAKTIVIERUNG_DUS_MINE = 42, + GEF_DEFINITION_IED = 43, + GEF_ZUSTAND_IED = 44, + GEF_STATUS_EINZELMINENSIMULATOR = 45, + GEF_WIRKFELD_EINZELMINENSIMULATOR = 46, + GEF_SELEKTIVE_AUFMUNITIONIERUNG = 56, - GEF_TREFFER_EREIGNIS_DUS = 52, - GEF_TREFFER_EREIGNIS_WIRKSIMULATION = 53, - GEF_TREFFER_AUSLOESUNG = 54, - GEF_SCHIEDSRICHTEREINGRIFF = 55, + GEF_TREFFER_EREIGNIS_DUS = 52, + GEF_TREFFER_EREIGNIS_WIRKSIMULATION = 53, + GEF_TREFFER_AUSLOESUNG = 54, + GEF_SCHIEDSRICHTEREINGRIFF = 55, - GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG = 218, - GEF_TREFFER_EREIGNIS_DUS_IPS = 228, - GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS = 229, + GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG = 218, + GEF_TREFFER_EREIGNIS_DUS_IPS = 228, + GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS = 229, - GEF_TAKTISCHER_STATUS = 61, - GEF_FUNKTIONSRAUM = 62, - GEF_EINTRETEN_FUNKTIONSRAUM = 63, - GEF_DEAKTIVIEREN_FUNKTIONSRAUM = 64, + GEF_TAKTISCHER_STATUS = 61, + GEF_FUNKTIONSRAUM = 62, + GEF_EINTRETEN_FUNKTIONSRAUM = 63, + GEF_DEAKTIVIEREN_FUNKTIONSRAUM = 64, - GEF_DATENVERKEHR_SRT_TDS = 71, - GEF_DATENVERKEHR_TDS_SRT = 72, - GEF_DATENVERKEHR_DMF_TDS = 73, - GEF_DATENVERKEHR_TDS_DMF = 74, + GEF_DATENVERKEHR_SRT_TDS = 71, + GEF_DATENVERKEHR_TDS_SRT = 72, + GEF_DATENVERKEHR_DMF_TDS = 73, + GEF_DATENVERKEHR_TDS_DMF = 74, - GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME = 82, - GEF_NOP = 83, + GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME = 82, + GEF_NOP = 83, - GEF_SONDERSENSORIK_BETRIEBSZUSTAND = 91, - GEF_SONDERSENSORIK_FAHRSPUR = 92, - GEF_SONDERSENSORIK_DATEN = 93, - GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN = 95, - GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN = 96, - GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION = 97, + GEF_SONDERSENSORIK_BETRIEBSZUSTAND = 91, + GEF_SONDERSENSORIK_FAHRSPUR = 92, + GEF_SONDERSENSORIK_DATEN = 93, + GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN = 95, + GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN = 96, + GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION = 97, - GEF_SPRACHAUSWAHL = 101, - GEF_ALLGEMEINE_NACHRICHT = 102, - GEF_ECHO_ON_OFF = 103, - GEF_ESW_MELDUNG = 104, + GEF_SPRACHAUSWAHL = 101, + GEF_ALLGEMEINE_NACHRICHT = 102, + GEF_ECHO_ON_OFF = 103, + GEF_ESW_MELDUNG = 104, - GEF_WF_SAMMELDEAKTIVIERUNG = 105, - GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN = 106, - GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM = 107, + GEF_WF_SAMMELDEAKTIVIERUNG = 105, + GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN = 106, + GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM = 107, - GEF_DATENVERKEHR_GEOP_TDS = 181, - GEF_DATENVERKEHR_TDS_GEOP = 182, + GEF_DATENVERKEHR_GEOP_TDS = 181, + GEF_DATENVERKEHR_TDS_GEOP = 182, - GEF_DATENVERKEHR_TGTC_TDS = 183, - GEF_DATENVERKEHR_TDS_TGTC = 184, - GEF_GERAETEEREIGNIS = 185, + GEF_DATENVERKEHR_TGTC_TDS = 183, + GEF_DATENVERKEHR_TDS_TGTC = 184, + GEF_GERAETEEREIGNIS = 185, - GEF_WAFFENZUORDNUNG = 200, - GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE = 202, - GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG = 210, - GEF_AUSLOESUNG_DUS_TREFFER = 211, - GEF_ANFORDERUNG_SW_VERSION = 212, - GEF_SW_VERSIONSMELDUNG = 213, - GEF_TECHNIK_FUNKTIONSRAUM = 219, + GEF_WAFFENZUORDNUNG = 200, + GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE = 202, + GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG = 210, + GEF_AUSLOESUNG_DUS_TREFFER = 211, + GEF_ANFORDERUNG_SW_VERSION = 212, + GEF_SW_VERSIONSMELDUNG = 213, + GEF_TECHNIK_FUNKTIONSRAUM = 219, - GEF_TEILNEHMERMODE_SETZEN = 230, - GEF_TEILNEHMERMODE_MELDUNG = 231, - GEF_TEILNEHMERMODE_ANFORDERN = 232, - GEF_TEILNEHMER_KONFIG_ANTWORT = 233, - GEF_TEILNEHMER_KONFIG_SETZEN = 234, - GEF_TEILNEHMER_KONFIG_ANFORDERN = 235, + GEF_TEILNEHMERMODE_SETZEN = 230, + GEF_TEILNEHMERMODE_MELDUNG = 231, + GEF_TEILNEHMERMODE_ANFORDERN = 232, + GEF_TEILNEHMER_KONFIG_ANTWORT = 233, + GEF_TEILNEHMER_KONFIG_SETZEN = 234, + GEF_TEILNEHMER_KONFIG_ANFORDERN = 235, - GEF_SANITAETSDIENST_INSTANDSETZUNG = 240, - GEF_BESTANDSMELDUNG_SANITAETSMATERIAL = 241, - GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN = 242, + GEF_SANITAETSDIENST_INSTANDSETZUNG = 240, + GEF_BESTANDSMELDUNG_SANITAETSMATERIAL = 241, + GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN = 242, - GEF_LASER_TARGET_DESIGNATOR_UPDATE = 214, + GEF_LASER_TARGET_DESIGNATOR_UPDATE = 214, - GEF_GEFECHTSFELDTELEGRAMM = 300 + GEF_GEFECHTSFELDTELEGRAMM = 300 }; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/Console/main.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/Console/main.cpp index 3ac38ac9f..c48ac607e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/Console/main.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/Console/main.cpp @@ -17,8 +17,7 @@ #include static QSet s_eqIds; -template -bool validEqId(const T &tele) +template bool validEqId(const T &tele) { if (!s_eqIds.isEmpty() && !s_eqIds.contains(tele.header.equipmentNumber)) return false; @@ -46,24 +45,21 @@ int main(int argc, char **argv) if (app.arguments().count() < 3) { - ERROR_LOG(logger) << "Usage: " << app.arguments().at(0) - << " "; + ERROR_LOG(logger) << "Usage: " << app.arguments().at(0) << " "; return 1; } QFile telegramFile(app.arguments().at(1)); if (!telegramFile.open(QIODevice::ReadOnly)) { - ERROR_LOG(logger) << "Error opening " << telegramFile.fileName() - << " for reading: " << telegramFile.errorString(); + ERROR_LOG(logger) << "Error opening " << telegramFile.fileName() << " for reading: " << telegramFile.errorString(); return 2; } bool bOk; int telIdToSearch = app.arguments().at(2).toUShort(&bOk); if (!bOk) { - ERROR_LOG(logger) << "Error reading telId - not a (valid) number: " - << app.arguments().at(2); + ERROR_LOG(logger) << "Error reading telId - not a (valid) number: " << app.arguments().at(2); return 3; } s_eqIds.clear(); @@ -72,8 +68,7 @@ int main(int argc, char **argv) int eqId = app.arguments().at(i).toUShort(&bOk); if (!bOk) { - ERROR_LOG(logger) << "Error reading equipId - not a (valid) number: " - << app.arguments().at(i); + ERROR_LOG(logger) << "Error reading equipId - not a (valid) number: " << app.arguments().at(i); return 4; } s_eqIds += eqId; @@ -94,97 +89,81 @@ int main(int argc, char **argv) if (telegramLength == telegramFile.read(telegramData.data(), telegramLength)) { // add the telegram to telegram-list - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol dest = (N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol) - (lh.m_Protocol & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol dest = + (N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol)(lh.m_Protocol & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - { - const QJsonObject obj = QJsonDocument::fromJson(telegramData).object(); - int telId = obj.value(QStringLiteral("typeId")).toInt(); - if (telIdToSearch != telId) - continue; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + { + const QJsonObject obj = QJsonDocument::fromJson(telegramData).object(); + int telId = obj.value(QStringLiteral("typeId")).toInt(); + if (telIdToSearch != telId) + continue; - const QJsonObject objData = obj.value(QStringLiteral("data")).toObject(); + const QJsonObject objData = obj.value(QStringLiteral("data")).toObject(); - const QByteArray tBA = formatTime(lh.m_Time); - const char *timeStr = tBA.constData(); - - switch (telId) - { - case Constraints::id(): - { - const CreateFunctionalArea tele(CreateFunctionalArea::fromJson(objData)); - if (!validEqId(tele)) - break; - fprintf(stdout, "%s, FUNKTIONSRAUM: '%s', %d, %d\n", - timeStr, - tele.name.c_str(), - tele.aesDdsId, - tele.header.equipmentNumber - ); - break; - } - case Constraints::id(): - { - const DeactivateEffectSimulation tele(DeactivateEffectSimulation::fromJson(objData)); - fprintf(stdout, "%s, DEAKTIVIERUNG_WIRKFELD: typ: %d - kennung: %d\n", - timeStr, - int(tele.aesType), - tele.aesDdsId - ); - break; - } - case Constraints::id(): - { - const PositionReport tele(PositionReport::fromJson(objData)); - if (!validEqId(tele)) - break; - if (tele.opsPosition.opsId == 0) - break; - fprintf(stdout, "%s, IPS_POSITIONSDATEN: %d - OPS: %d\n", - timeStr, - tele.header.equipmentNumber, - tele.opsPosition.opsId - ); - break; - } - case BESTAETIGUNG: - case UMGEBUNGS_MELDUNG2: - break; - default: - fprintf(stderr, "Printing telegram with id %d not implemented\n", telId); - break; - - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: - { - N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(telegramData); - gef_telegramm_id_et telId = radioTelegram.getTelID(); - if (telId == GEF_UMGEBUNGS_MELDUNG2) - { const QByteArray tBA = formatTime(lh.m_Time); const char *timeStr = tBA.constData(); - static uint16_t bci = 0xFFFF; - if (bci != radioTelegram.getBroadcastIndex()) + + switch (telId) { - if (bci > radioTelegram.getBroadcastIndex() && bci != 0xFFFF) + case Constraints::id(): { - fprintf(stdout, "BCI reset in %s at %s!\n", - qPrintable(telegramFile.fileName()), - timeStr); + const CreateFunctionalArea tele(CreateFunctionalArea::fromJson(objData)); + if (!validEqId(tele)) + break; + fprintf(stdout, "%s, FUNKTIONSRAUM: '%s', %d, %d\n", timeStr, tele.name.c_str(), tele.aesDdsId, tele.header.equipmentNumber); + break; } - fprintf(stdout, "BCI: %d\n", radioTelegram.getBroadcastIndex()); - bci = radioTelegram.getBroadcastIndex(); + case Constraints::id(): + { + const DeactivateEffectSimulation tele(DeactivateEffectSimulation::fromJson(objData)); + fprintf(stdout, "%s, DEAKTIVIERUNG_WIRKFELD: typ: %d - kennung: %d\n", timeStr, int(tele.aesType), tele.aesDdsId); + break; + } + case Constraints::id(): + { + const PositionReport tele(PositionReport::fromJson(objData)); + if (!validEqId(tele)) + break; + if (tele.opsPosition.opsId == 0) + break; + fprintf(stdout, "%s, IPS_POSITIONSDATEN: %d - OPS: %d\n", timeStr, tele.header.equipmentNumber, tele.opsPosition.opsId); + break; + } + case BESTAETIGUNG: + case UMGEBUNGS_MELDUNG2: + break; + default: + fprintf(stderr, "Printing telegram with id %d not implemented\n", telId); + break; } + break; } - break; - } - default: - break; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(telegramData); + gef_telegramm_id_et telId = radioTelegram.getTelID(); + if (telId == GEF_UMGEBUNGS_MELDUNG2) + { + const QByteArray tBA = formatTime(lh.m_Time); + const char *timeStr = tBA.constData(); + static uint16_t bci = 0xFFFF; + if (bci != radioTelegram.getBroadcastIndex()) + { + if (bci > radioTelegram.getBroadcastIndex() && bci != 0xFFFF) + { + fprintf(stdout, "BCI reset in %s at %s!\n", qPrintable(telegramFile.fileName()), timeStr); + } + fprintf(stdout, "BCI: %d\n", radioTelegram.getBroadcastIndex()); + bci = radioTelegram.getBroadcastIndex(); + } + } + break; + } + default: + break; } } } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.cpp index bd4d14a0f..adf68f0f8 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.cpp @@ -19,479 +19,492 @@ namespace N_SST { -IntegerCalculator::IntegerCalculator() - : m_OperationList({{"*", 6},{"/", 6},{"%", 6},{"+", 5},{"-", 5},{"<<", 4},{">>", 4}}) - , m_AdditionalErrorText() - , m_ParanthesisCount(0) - , m_Error(IntegerCalculator::e_Ok) -{ -} - -// --------------------------------------------------------------- -// Converts the expressen in a_calcText into a signed value. -// Returns whether an error happend in the variable a_error. -// If an error happend, the variable a_addErrorText can -// contain more informaition about the error (see E_Error for -// more information about errors). -// --------------------------------------------------------------- -int64_t IntegerCalculator::calc(const std::string& a_calcText, E_Error& a_error, std::string* a_addErrorText) -{ - std::string calcText = a_calcText; - // separate operations from variables - for (auto iter = m_OperationList.begin(); iter != m_OperationList.end(); ++iter) - replace(calcText, iter->first, " "+iter->first+" "); - - // separate paranthesis from variables - replace(calcText, "(", " ( "); - replace(calcText, ")", " ) "); - - - // now calculate the expression - m_ParanthesisCount = 0; - m_Error = e_Ok; - m_AdditionalErrorText = ""; - size_t pos = 0; - bool dummy; - int64_t value = calc(calcText, pos, dummy, "", 0, "+"); // todo: use member-variable m_CalcText - //M_INFO("calc: " << calcText << " value: " << value); - - // check the paranthesis - if (m_Error == e_Ok) + IntegerCalculator::IntegerCalculator() + : m_OperationList({{"*", 6}, {"/", 6}, {"%", 6}, {"+", 5}, {"-", 5}, {"<<", 4}, {">>", 4}}) + , m_AdditionalErrorText() + , m_ParanthesisCount(0) + , m_Error(IntegerCalculator::e_Ok) { - if (m_ParanthesisCount > 0) - { - m_Error = e_MissingRightParanthesis; - } - else if (m_ParanthesisCount < 0) - { - m_Error = e_MissingLeftParanthesis; - } - else if (pos != calcText.length()) - { - m_Error = e_UnknownError; - } } - // actions if a failure happens - a_error = m_Error; - if (a_error != e_Ok) + // --------------------------------------------------------------- + // Converts the expressen in a_calcText into a signed value. + // Returns whether an error happend in the variable a_error. + // If an error happend, the variable a_addErrorText can + // contain more informaition about the error (see E_Error for + // more information about errors). + // --------------------------------------------------------------- + int64_t IntegerCalculator::calc(const std::string &a_calcText, E_Error &a_error, std::string *a_addErrorText) { - value = 0; - if (a_addErrorText) + std::string calcText = a_calcText; + // separate operations from variables + for (auto iter = m_OperationList.begin(); iter != m_OperationList.end(); ++iter) + replace(calcText, iter->first, " " + iter->first + " "); + + // separate paranthesis from variables + replace(calcText, "(", " ( "); + replace(calcText, ")", " ) "); + + + // now calculate the expression + m_ParanthesisCount = 0; + m_Error = e_Ok; + m_AdditionalErrorText = ""; + size_t pos = 0; + bool dummy; + int64_t value = calc(calcText, pos, dummy, "", 0, "+"); // todo: use member-variable m_CalcText + //M_INFO("calc: " << calcText << " value: " << value); + + // check the paranthesis + if (m_Error == e_Ok) { - *a_addErrorText = m_AdditionalErrorText; - } - } - return value; -} - -// --------------------------------------------------------------- -// Adds or changes a case-sensitive variable to the calculator. -// --------------------------------------------------------------- -void IntegerCalculator::addVariable(const std::string& a_name, const int64_t a_value) -{ - std::map::iterator iter = m_VariableList.find(a_name); - if (iter != m_VariableList.end()) - removeVariable(a_name); - m_VariableList.insert(std::make_pair(a_name, a_value)); -} - - -// --------------------------------------------------------------- -// Removes a case-sensitive variable from the calculator. -// --------------------------------------------------------------- -void IntegerCalculator::removeVariable(const std::string& a_name) -{ - std::map::iterator iter = m_VariableList.find(a_name); - if (iter != m_VariableList.end()) - m_VariableList.erase(iter); -} - - -// --------------------------------------------------------------- -// Calculates the expression (recursive) -// --------------------------------------------------------------- -int64_t IntegerCalculator::calc(const std::string& a_calcText, size_t& a_pos, bool& a_IsEndParanthesis, - const std::string& a_prevOp, const int64_t a_prevValue, - const std::string& a_initOp) -{ - std::string operation = a_initOp; - int64_t value1 = a_prevValue; - bool isNegative = false; - std::string calcText = a_calcText; - a_IsEndParanthesis = false; - - while (a_pos < calcText.length()) - { - if (' ' == calcText[a_pos]) - { - a_pos++; - } - else if ('(' == calcText[a_pos]) - { - m_ParanthesisCount++; - bool dummy; - int64_t value2 = calcSign(calc(calcText, ++a_pos, dummy), isNegative); - value1 = doOperation(value1, operation, value2); - - // get next operation to check priority of operation - size_t tmpPos = a_pos; // do not change the position, we only pre-read - std::string nextOp = getToken(a_calcText, tmpPos); - if (isOperation(nextOp) && isOperation(a_prevOp) && !isOperationPriorityHigher(nextOp, a_prevOp)) + if (m_ParanthesisCount > 0) { - // end of higher priority operation + m_Error = e_MissingRightParanthesis; + } + else if (m_ParanthesisCount < 0) + { + m_Error = e_MissingLeftParanthesis; + } + else if (pos != calcText.length()) + { + m_Error = e_UnknownError; + } + } + + // actions if a failure happens + a_error = m_Error; + if (a_error != e_Ok) + { + value = 0; + if (a_addErrorText) + { + *a_addErrorText = m_AdditionalErrorText; + } + } + return value; + } + + // --------------------------------------------------------------- + // Adds or changes a case-sensitive variable to the calculator. + // --------------------------------------------------------------- + void IntegerCalculator::addVariable(const std::string &a_name, const int64_t a_value) + { + std::map::iterator iter = m_VariableList.find(a_name); + if (iter != m_VariableList.end()) + removeVariable(a_name); + m_VariableList.insert(std::make_pair(a_name, a_value)); + } + + + // --------------------------------------------------------------- + // Removes a case-sensitive variable from the calculator. + // --------------------------------------------------------------- + void IntegerCalculator::removeVariable(const std::string &a_name) + { + std::map::iterator iter = m_VariableList.find(a_name); + if (iter != m_VariableList.end()) + m_VariableList.erase(iter); + } + + + // --------------------------------------------------------------- + // Calculates the expression (recursive) + // --------------------------------------------------------------- + int64_t IntegerCalculator::calc(const std::string &a_calcText, + size_t &a_pos, + bool &a_IsEndParanthesis, + const std::string &a_prevOp, + const int64_t a_prevValue, + const std::string &a_initOp) + { + std::string operation = a_initOp; + int64_t value1 = a_prevValue; + bool isNegative = false; + std::string calcText = a_calcText; + a_IsEndParanthesis = false; + + while (a_pos < calcText.length()) + { + if (' ' == calcText[a_pos]) + { + a_pos++; + } + else if ('(' == calcText[a_pos]) + { + m_ParanthesisCount++; + bool dummy; + int64_t value2 = calcSign(calc(calcText, ++a_pos, dummy), isNegative); + value1 = doOperation(value1, operation, value2); + + // get next operation to check priority of operation + size_t tmpPos = a_pos; // do not change the position, we only pre-read + std::string nextOp = getToken(a_calcText, tmpPos); + if (isOperation(nextOp) && isOperation(a_prevOp) && !isOperationPriorityHigher(nextOp, a_prevOp)) + { + // end of higher priority operation + return value1; + } + + operation = ""; + } + else if (')' == calcText[a_pos]) + { + m_ParanthesisCount--; + a_pos++; + a_IsEndParanthesis = true; return value1; } - - operation = ""; - } - else if (')' == calcText[a_pos]) - { - m_ParanthesisCount--; - a_pos++; - a_IsEndParanthesis = true; - return value1; - } - else if (isDigit(calcText[a_pos])) - { - // value - // ----- - int64_t value2 = calcSign(convertValue(calcText, a_pos), isNegative); - if (calcWithPriority(calcText, a_pos, value1, operation, value2, a_prevOp)) return value1; - } - else - { - // operation or variable - // --------------------- - std::string oldOperation = operation; - operation = getToken(calcText, a_pos); - - // is it a variable? - if (!isOperation(operation)) + else if (isDigit(calcText[a_pos])) { - int64_t value2 = 0; - if (getVariableValue(operation, value2)) - { - value2 = calcSign(value2, isNegative); - if (calcWithPriority(calcText, a_pos, value1, oldOperation, value2, a_prevOp)) return value1; - operation = ""; - } - else - { - // error - m_Error = e_UnknownOperationOrVariable; - m_AdditionalErrorText = operation; - } + // value + // ----- + int64_t value2 = calcSign(convertValue(calcText, a_pos), isNegative); + if (calcWithPriority(calcText, a_pos, value1, operation, value2, a_prevOp)) + return value1; } else { - // do we have a sign? - if (oldOperation != "") + // operation or variable + // --------------------- + std::string oldOperation = operation; + operation = getToken(calcText, a_pos); + + // is it a variable? + if (!isOperation(operation)) { - if (operation == "+") + int64_t value2 = 0; + if (getVariableValue(operation, value2)) { - operation = oldOperation; - } - else if (operation == "-") - { - isNegative = !isNegative; - operation = oldOperation; + value2 = calcSign(value2, isNegative); + if (calcWithPriority(calcText, a_pos, value1, oldOperation, value2, a_prevOp)) + return value1; + operation = ""; } else { - m_Error = e_NoOperandBetweenOperators; - m_AdditionalErrorText = oldOperation + " " + operation; - return 0; + // error + m_Error = e_UnknownOperationOrVariable; + m_AdditionalErrorText = operation; + } + } + else + { + // do we have a sign? + if (oldOperation != "") + { + if (operation == "+") + { + operation = oldOperation; + } + else if (operation == "-") + { + isNegative = !isNegative; + operation = oldOperation; + } + else + { + m_Error = e_NoOperandBetweenOperators; + m_AdditionalErrorText = oldOperation + " " + operation; + return 0; + } } } } } + return value1; } - return value1; -} -// --------------------------------------------------------------- -// Calculates an operation with respecting the priority of -// operations. This will be done with recursion. -// --------------------------------------------------------------- -bool IntegerCalculator::calcWithPriority(const std::string& a_calcText, size_t& a_pos, int64_t& a_value1, std::string& a_operation, int64_t a_value2, const std::string& a_prevOp) -{ - bool isParaEnd = false; - // get next operation to check priority of operation - size_t tmpPos = a_pos; // only pre-read - std::string nextOp = getToken(a_calcText, tmpPos); - if (isOperation(a_operation) && isOperation(nextOp) && isOperationPriorityHigher(nextOp, a_operation)) + // --------------------------------------------------------------- + // Calculates an operation with respecting the priority of + // operations. This will be done with recursion. + // --------------------------------------------------------------- + bool IntegerCalculator::calcWithPriority(const std::string &a_calcText, + size_t &a_pos, + int64_t &a_value1, + std::string &a_operation, + int64_t a_value2, + const std::string &a_prevOp) { - // next operation has higher priority => calc the next operation first - a_value2 = calc(a_calcText, a_pos, isParaEnd, a_operation, a_value2); - } - a_value1 = doOperation(a_value1, a_operation, a_value2); - if (isParaEnd || (isOperation(nextOp) && isOperation(a_prevOp) && !isOperationPriorityHigher(nextOp, a_prevOp))) - { - // end of higher priority operation - return true; - } - a_operation = ""; - return false; -} - - -// --------------------------------------------------------------- -// Returns the inverted a_value if a_isNegative is true. -// a_isNegative will be false after calling this function. -// If a_isNegative is true, the NOT inverted a_value will be -// returned. -// --------------------------------------------------------------- -int64_t IntegerCalculator::calcSign(const int64_t a_value, bool& a_isNegative) -{ - if (a_isNegative) - { - a_isNegative = false; - return -a_value; - } - return a_value; -} - - -// --------------------------------------------------------------- -// Converts the value in form of text to a number. The Text -// can be decimal, hex (0x) or binary (0b). -// --------------------------------------------------------------- -int64_t IntegerCalculator::convertValue(const std::string &a_valueText, size_t& a_pos) -{ - std::string valueText = a_valueText.substr(a_pos); - int base = 10; - size_t startpos = 0; - // hex- and binary-stuff - bool isHex = (0 == valueText.find("0X")) || (0 == valueText.find("0x")); - bool isBin = (0 == valueText.find("0B")) || (0 == valueText.find("0b")); - if (isHex) - { - base = 16; - startpos = 2; - } - else if (isBin) - { - base = 2; - startpos = 2; - } - // search end of value - size_t i; - for (i=startpos; i calc the next operation first + a_value2 = calc(a_calcText, a_pos, isParaEnd, a_operation, a_value2); } - } - // check the next char, it must be a space - if (valueText.length() > i && valueText[i] != ' ') - { - m_Error = e_InvalidOperand; - int spacePos = valueText.find(' '); - m_AdditionalErrorText = valueText.substr(0, spacePos); - } - a_pos += i; - - int64_t value = 0; - std::stringstream stream; - stream.str(valueText.substr(startpos, i-startpos)); - if (2 == base) - { - // our stl is not able to read in binary-values, therefore we have to implement it ourself - const std::string binValueAsText = stream.str(); - for (const char c : binValueAsText) + a_value1 = doOperation(a_value1, a_operation, a_value2); + if (isParaEnd || (isOperation(nextOp) && isOperation(a_prevOp) && !isOperationPriorityHigher(nextOp, a_prevOp))) { - value = value << 1; - if (c == '1') - value += 1; + // end of higher priority operation + return true; } - } - else - { - stream << std::setbase(base); - stream >> value; - } - return value; -} - - -// --------------------------------------------------------------- -// Returns the next token (with space as separator). Heading -// spaces will be ignored. -// --------------------------------------------------------------- -std::string IntegerCalculator::getToken(const std::string &a_calcText, size_t& a_pos) -{ - // skip spaces at begin - while (a_pos < a_calcText.length()) - { - if (a_calcText[a_pos] == ' ') a_pos++; - else break; + a_operation = ""; + return false; } - // search until next space (or end) - size_t startPos = a_pos; - while (a_pos < a_calcText.length()) - { - if (' ' == a_calcText[a_pos]) break; - a_pos++; - } - return a_calcText.substr(startPos, a_pos-startPos); -} - -// --------------------------------------------------------------- -// returns true if a_operation is a known operation. -// --------------------------------------------------------------- -bool IntegerCalculator::isOperation(const std::string& a_operation) const -{ - std::map::const_iterator iter = m_OperationList.find(a_operation); - return (iter != m_OperationList.end()); -} - - -// --------------------------------------------------------------- -// Calculates the opeation a_operations with a_value1 as first -// and a_value2 as second operand. -// --------------------------------------------------------------- -int64_t IntegerCalculator::doOperation(const int64_t a_value1, const std::string& a_operation, const int64_t a_value2) -{ -// M_INFO("" << a_value1 << " " << a_operation << " " << a_value2); - if (("+" == a_operation) || a_operation.empty()) + // --------------------------------------------------------------- + // Returns the inverted a_value if a_isNegative is true. + // a_isNegative will be false after calling this function. + // If a_isNegative is true, the NOT inverted a_value will be + // returned. + // --------------------------------------------------------------- + int64_t IntegerCalculator::calcSign(const int64_t a_value, bool &a_isNegative) { - return a_value1 + a_value2; - } - else if ("-" == a_operation) - { - return a_value1 - a_value2; - } - else if ("*" == a_operation) - { - return a_value1 * a_value2; - } - else if ("/" == a_operation) - { - if (0 == a_value2) + if (a_isNegative) { - m_Error = e_DivisionByZero; + a_isNegative = false; + return -a_value; + } + return a_value; + } + + + // --------------------------------------------------------------- + // Converts the value in form of text to a number. The Text + // can be decimal, hex (0x) or binary (0b). + // --------------------------------------------------------------- + int64_t IntegerCalculator::convertValue(const std::string &a_valueText, size_t &a_pos) + { + std::string valueText = a_valueText.substr(a_pos); + int base = 10; + size_t startpos = 0; + // hex- and binary-stuff + bool isHex = (0 == valueText.find("0X")) || (0 == valueText.find("0x")); + bool isBin = (0 == valueText.find("0B")) || (0 == valueText.find("0b")); + if (isHex) + { + base = 16; + startpos = 2; + } + else if (isBin) + { + base = 2; + startpos = 2; + } + // search end of value + size_t i; + for (i = startpos; i < valueText.length(); i++) + { + if (!isDigit(valueText[i], isHex, isBin)) + { + break; + } + } + // check the next char, it must be a space + if (valueText.length() > i && valueText[i] != ' ') + { + m_Error = e_InvalidOperand; + int spacePos = valueText.find(' '); + m_AdditionalErrorText = valueText.substr(0, spacePos); + } + a_pos += i; + + int64_t value = 0; + std::stringstream stream; + stream.str(valueText.substr(startpos, i - startpos)); + if (2 == base) + { + // our stl is not able to read in binary-values, therefore we have to implement it ourself + const std::string binValueAsText = stream.str(); + for (const char c : binValueAsText) + { + value = value << 1; + if (c == '1') + value += 1; + } } else { - return a_value1 / a_value2; + stream << std::setbase(base); + stream >> value; } + return value; } - else if ("%" == a_operation) + + + // --------------------------------------------------------------- + // Returns the next token (with space as separator). Heading + // spaces will be ignored. + // --------------------------------------------------------------- + std::string IntegerCalculator::getToken(const std::string &a_calcText, size_t &a_pos) { - if (0 == a_value2) + // skip spaces at begin + while (a_pos < a_calcText.length()) { - m_Error = e_DivisionByZero; + if (a_calcText[a_pos] == ' ') + a_pos++; + else + break; + } + + // search until next space (or end) + size_t startPos = a_pos; + while (a_pos < a_calcText.length()) + { + if (' ' == a_calcText[a_pos]) + break; + a_pos++; + } + return a_calcText.substr(startPos, a_pos - startPos); + } + + + // --------------------------------------------------------------- + // returns true if a_operation is a known operation. + // --------------------------------------------------------------- + bool IntegerCalculator::isOperation(const std::string &a_operation) const + { + std::map::const_iterator iter = m_OperationList.find(a_operation); + return (iter != m_OperationList.end()); + } + + + // --------------------------------------------------------------- + // Calculates the opeation a_operations with a_value1 as first + // and a_value2 as second operand. + // --------------------------------------------------------------- + int64_t IntegerCalculator::doOperation(const int64_t a_value1, const std::string &a_operation, const int64_t a_value2) + { + // M_INFO("" << a_value1 << " " << a_operation << " " << a_value2); + if (("+" == a_operation) || a_operation.empty()) + { + return a_value1 + a_value2; + } + else if ("-" == a_operation) + { + return a_value1 - a_value2; + } + else if ("*" == a_operation) + { + return a_value1 * a_value2; + } + else if ("/" == a_operation) + { + if (0 == a_value2) + { + m_Error = e_DivisionByZero; + } + else + { + return a_value1 / a_value2; + } + } + else if ("%" == a_operation) + { + if (0 == a_value2) + { + m_Error = e_DivisionByZero; + } + else + { + return a_value1 % a_value2; + } + } + else if ("<<" == a_operation) + { + return a_value1 << a_value2; + } + else if (">>" == a_operation) + { + return a_value1 >> a_value2; } else { - return a_value1 % a_value2; + m_Error = e_UnknownOperationOrVariable; + m_AdditionalErrorText = a_operation; + } + return 0; + } + + + // --------------------------------------------------------------- + // returns true if priority of a_opeation1 is higher than + // priority of a_operation2. + // --------------------------------------------------------------- + bool IntegerCalculator::isOperationPriorityHigher(const std::string &a_operation1, const std::string &a_operation2) const + { + return (getPriority(a_operation1) > getPriority(a_operation2)); + } + + + // --------------------------------------------------------------- + // Returns true if the variable named a_variableName is known + // and a_value will be filled with its value. If the variable + // is not found false will be returned. + // Overload this virtual function if you want to implement + // your own variable-list. + // --------------------------------------------------------------- + bool IntegerCalculator::getVariableValue(const std::string &a_variableName, int64_t &a_value) const + { + auto iter = m_VariableList.find(a_variableName); + if (iter != m_VariableList.end()) + { + a_value = iter->second; + return true; + } + + // error + return false; + } + + + // --------------------------------------------------------------- + // Returns true if a_char is a digit. When a_isHex is true, + // also the charactes a-f will be accepted as digits. When + // a_isBin is true, only 0 and 1 will be treated as digit. + // --------------------------------------------------------------- + bool IntegerCalculator::isDigit(const char a_char, const bool a_isHex, const bool a_isBin) + { + if (a_isHex) + { + // for hex-values also A..F are 'digits' + return (a_char >= '0' && a_char <= '9') || (a_char >= 'A' && a_char <= 'F') || (a_char >= 'a' && a_char <= 'f'); + } + else if (a_isBin) + { + // for binary-values only 0 and 1 are allowed + return (a_char >= '0' && a_char <= '1'); + } + // normal digits + return (a_char >= '0' && a_char <= '9'); + } + + + // --------------------------------------------------------------- + // Returns the priority of the operation. A higher value means + // more priority. + // --------------------------------------------------------------- + int16_t IntegerCalculator::getPriority(const std::string &a_operation) const + { + std::map::const_iterator iter = m_OperationList.find(a_operation); + if (iter != m_OperationList.end()) + return iter->second; + + return -1; + } + + + // --------------------------------------------------------------- + // replaces in a_haystack all a_searchText with a_replaceText + // (not greedy). + // --------------------------------------------------------------- + void IntegerCalculator::replace(std::string &a_haystack, const std::string &a_searchText, const std::string &a_replaceText) + { + std::string::size_type searchSize = a_searchText.length(); + std::string::size_type replaceSize = a_replaceText.length(); + + std::string::size_type pos = a_haystack.find(a_searchText, 0); + while (std::string::npos != pos) + { + a_haystack.replace(pos, searchSize, a_replaceText); + pos += replaceSize; + pos = a_haystack.find(a_searchText, pos); } } - else if ("<<" == a_operation) - { - return a_value1 << a_value2; - } - else if (">>" == a_operation) - { - return a_value1 >> a_value2; - } - else - { - m_Error = e_UnknownOperationOrVariable; - m_AdditionalErrorText = a_operation; - } - return 0; -} - - -// --------------------------------------------------------------- -// returns true if priority of a_opeation1 is higher than -// priority of a_operation2. -// --------------------------------------------------------------- -bool IntegerCalculator::isOperationPriorityHigher(const std::string& a_operation1, const std::string& a_operation2) const -{ - return (getPriority(a_operation1) > getPriority(a_operation2)); -} - - -// --------------------------------------------------------------- -// Returns true if the variable named a_variableName is known -// and a_value will be filled with its value. If the variable -// is not found false will be returned. -// Overload this virtual function if you want to implement -// your own variable-list. -// --------------------------------------------------------------- -bool IntegerCalculator::getVariableValue(const std::string& a_variableName, int64_t& a_value) const -{ - auto iter = m_VariableList.find(a_variableName); - if (iter != m_VariableList.end()) - { - a_value = iter->second; - return true; - } - - // error - return false; -} - - -// --------------------------------------------------------------- -// Returns true if a_char is a digit. When a_isHex is true, -// also the charactes a-f will be accepted as digits. When -// a_isBin is true, only 0 and 1 will be treated as digit. -// --------------------------------------------------------------- -bool IntegerCalculator::isDigit(const char a_char, const bool a_isHex, const bool a_isBin) -{ - if (a_isHex) - { - // for hex-values also A..F are 'digits' - return (a_char >= '0' && a_char <= '9') || (a_char >= 'A' && a_char <= 'F') || (a_char >= 'a' && a_char <= 'f'); - } - else if (a_isBin) - { - // for binary-values only 0 and 1 are allowed - return (a_char >= '0' && a_char <= '1'); - } - // normal digits - return (a_char >= '0' && a_char <= '9'); -} - - -// --------------------------------------------------------------- -// Returns the priority of the operation. A higher value means -// more priority. -// --------------------------------------------------------------- -int16_t IntegerCalculator::getPriority(const std::string& a_operation) const -{ - std::map::const_iterator iter = m_OperationList.find(a_operation); - if (iter != m_OperationList.end()) - return iter->second; - - return -1; -} - - -// --------------------------------------------------------------- -// replaces in a_haystack all a_searchText with a_replaceText -// (not greedy). -// --------------------------------------------------------------- -void IntegerCalculator::replace(std::string& a_haystack, const std::string &a_searchText, const std::string &a_replaceText) -{ - std::string::size_type searchSize = a_searchText.length(); - std::string::size_type replaceSize = a_replaceText.length(); - - std::string::size_type pos = a_haystack.find(a_searchText, 0); - while (std::string::npos != pos) - { - a_haystack.replace(pos, searchSize, a_replaceText); - pos += replaceSize; - pos = a_haystack.find(a_searchText, pos); - } -} } // namespace N_SST diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.hpp index 1c9088eb4..10c273a81 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/IntegerCalculator.hpp @@ -34,7 +34,6 @@ namespace N_SST class IntegerCalculator { public: - /** * Describes the error happend while calculation of an expression * @@ -95,7 +94,7 @@ namespace N_SST * @param a_error * @param a_addErrorText */ - int64_t calc(const std::string& a_calcText, E_Error& a_error, std::string* a_addErrorText = nullptr); + int64_t calc(const std::string &a_calcText, E_Error &a_error, std::string *a_addErrorText = nullptr); /** * Adds or changes a case-sensitive variable to the calculator. @@ -103,17 +102,16 @@ namespace N_SST * @param a_name * @param a_value */ - void addVariable(const std::string& a_name, const int64_t a_value); + void addVariable(const std::string &a_name, const int64_t a_value); /** * Removes a case-sensitive variable from the calculator. * * @param a_name */ - void removeVariable(const std::string& a_name); + void removeVariable(const std::string &a_name); protected: - /** * Contains all supported operations */ @@ -143,9 +141,12 @@ namespace N_SST * @param a_prevValue * @param a_initOp */ - int64_t calc(const std::string& a_calcText, size_t& a_pos, bool& a_IsEndParanthesis, - const std::string& a_prevOp = std::string(), const int64_t a_prevValue = 0, - const std::string& a_initOp = std::string()); + int64_t calc(const std::string &a_calcText, + size_t &a_pos, + bool &a_IsEndParanthesis, + const std::string &a_prevOp = std::string(), + const int64_t a_prevValue = 0, + const std::string &a_initOp = std::string()); /** * Calculates an operation with respecting the priority of operations. This will @@ -158,8 +159,7 @@ namespace N_SST * @param a_value2 * @param a_prevOp */ - bool calcWithPriority(const std::string& a_calcText, size_t& a_pos, int64_t& a_value1, - std::string& a_operation, int64_t a_value2, const std::string& a_prevOp); + bool calcWithPriority(const std::string &a_calcText, size_t &a_pos, int64_t &a_value1, std::string &a_operation, int64_t a_value2, const std::string &a_prevOp); /** * Returns the inverted a_value if a_isNegative is true. a_isNegative will be @@ -169,7 +169,7 @@ namespace N_SST * @param a_value * @param a_isNegative */ - static int64_t calcSign(const int64_t a_value, bool& a_isNegative); + static int64_t calcSign(const int64_t a_value, bool &a_isNegative); /** * Converts the value in form of text to a number. The Text can be decimal, hex @@ -178,7 +178,7 @@ namespace N_SST * @param a_valueText * @param a_pos */ - int64_t convertValue(const std::string& a_valueText, size_t& a_pos); + int64_t convertValue(const std::string &a_valueText, size_t &a_pos); /** * Returns the next token (with space as separator). Heading spaces will be @@ -187,14 +187,14 @@ namespace N_SST * @param a_calcText * @param a_pos */ - static std::string getToken(const std::string& a_calcText, size_t& a_pos); + static std::string getToken(const std::string &a_calcText, size_t &a_pos); /** * returns true if a_operation is a known operation. * * @param a_operation */ - bool isOperation(const std::string& a_operation) const; + bool isOperation(const std::string &a_operation) const; /** * Calculates the opeation a_operations with a_value1 as first and a_value2 as @@ -204,7 +204,7 @@ namespace N_SST * @param a_operation * @param a_value2 */ - int64_t doOperation(const int64_t a_value1, const std::string& a_operation, const int64_t a_value2); + int64_t doOperation(const int64_t a_value1, const std::string &a_operation, const int64_t a_value2); /** * returns true if priority of a_opeation1 is higher than priority of a_operation2. @@ -213,7 +213,7 @@ namespace N_SST * @param a_operation1 * @param a_operation2 */ - bool isOperationPriorityHigher(const std::string& a_operation1, const std::string& a_operation2) const; + bool isOperationPriorityHigher(const std::string &a_operation1, const std::string &a_operation2) const; /** * Returns true if the variable named a_variableName is known and a_value will be @@ -223,7 +223,7 @@ namespace N_SST * @param a_variableName * @param a_value */ - virtual bool getVariableValue(const std::string& a_variableName, int64_t& a_value) const; + virtual bool getVariableValue(const std::string &a_variableName, int64_t &a_value) const; /** * Returns true if a_char is a digit. When a_isHex is true, also the charactes a-f @@ -241,7 +241,7 @@ namespace N_SST * * @param a_operation */ - int16_t getPriority(const std::string& a_operation) const; + int16_t getPriority(const std::string &a_operation) const; /** * replaces in a_haystack all a_searchText with a_replaceText (not greedy). @@ -250,8 +250,7 @@ namespace N_SST * @param a_searchText * @param a_replaceText */ - static void replace(std::string& a_haystack, const std::string& a_searchText, const std::string& a_replaceText); - + static void replace(std::string &a_haystack, const std::string &a_searchText, const std::string &a_replaceText); }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.cpp index 4ec34f960..3e719893e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.cpp @@ -13,29 +13,29 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewBooleanEdit::LogViewBooleanEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly) - : QCheckBox (a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) -{ - const QString valueText = a_field->value(0); - - setChecked(valueText.toInt() == 1); - setEnabled(!a_readonly); -} - -// --------------------------------------------------------------- -bool LogViewBooleanEdit::saveContent(LogViewTelegram* a_telegram) -{ - if (m_Valid) + // --------------------------------------------------------------- + LogViewBooleanEdit::LogViewBooleanEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly) + : QCheckBox(a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) { - if (a_telegram->isJsonTelegram()) - a_telegram->setJsonValue(m_Field->jsonPath(), isChecked()); - else - a_telegram->setUIntX(getSize(), isChecked()); - return true; + const QString valueText = a_field->value(0); + + setChecked(valueText.toInt() == 1); + setEnabled(!a_readonly); + } + + // --------------------------------------------------------------- + bool LogViewBooleanEdit::saveContent(LogViewTelegram *a_telegram) + { + if (m_Valid) + { + if (a_telegram->isJsonTelegram()) + a_telegram->setJsonValue(m_Field->jsonPath(), isChecked()); + else + a_telegram->setUIntX(getSize(), isChecked()); + return true; + } + return false; } - return false; -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.hpp index 3cb68a018..c5646e959 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewBooleanEdit.hpp @@ -13,12 +13,14 @@ namespace N_LogView { - class LogViewBooleanEdit : public QCheckBox, public LogViewWidget + class LogViewBooleanEdit + : public QCheckBox + , public LogViewWidget { Q_OBJECT public: - LogViewBooleanEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly); - bool saveContent(LogViewTelegram* a_telegram) override; + LogViewBooleanEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly); + bool saveContent(LogViewTelegram *a_telegram) override; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.cpp index 096538f11..31b2f0e6a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewDateTimeEdit.hpp" #include @@ -20,67 +20,65 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewDateTimeEdit::LogViewDateTimeEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly) - : QDateTimeEdit(a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) -{ - if (a_readonly) + // --------------------------------------------------------------- + LogViewDateTimeEdit::LogViewDateTimeEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly) + : QDateTimeEdit(a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) { - setReadOnly(true); - setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); + if (a_readonly) + { + setReadOnly(true); + setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); + } + + // date-time-field + qint64 unixTime = 0; + if (a_field->hasContent()) + { + if (a_field->isMSecsField()) + unixTime = a_field->value(0, true).toLongLong(); + else + unixTime = a_field->value(0, true).toInt() * 1000LL; + } + // take actual date and time if time is 0 + if (0 == unixTime && !a_readonly) + unixTime = ::time(nullptr) * 1000LL; + + //valueWidget = new QDateTimeEdit(dateTime); + setDateTime(QDateTime::fromMSecsSinceEpoch(unixTime)); + setDisplayFormat(QLatin1String("dd MMM yyyy hh:mm:ss")); + setCalendarPopup(true); + updateToolTip(QString::number(unixTime)); + //setToolTip(a_field->getToolTipText()); + // checkAndOvertakeContent(); + + connect(this, &LogViewDateTimeEdit::editingFinished, this, &LogViewDateTimeEdit::checkAndOvertakeContent); } - // date-time-field - qint64 unixTime = 0; - if (a_field->hasContent()) + + // --------------------------------------------------------------- + void LogViewDateTimeEdit::checkAndOvertakeContent() { - if (a_field->isMSecsField()) - unixTime = a_field->value(0, true).toLongLong(); + updateToolTip(QString::number(dateTime().toMSecsSinceEpoch() / 1000)); + } + + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewDateTimeEdit::saveContent(LogViewTelegram *a_telegram) + { + if (a_telegram->isJsonTelegram()) + { + a_telegram->setJsonValue(m_Field->jsonPath(), dateTime().toMSecsSinceEpoch()); + } else - unixTime = a_field->value(0, true).toInt() * 1000LL; + { + a_telegram->setNextFieldAsGpsTimeField(); // fixme: muss noch der feldname auf GPS Zeit geprüft werden? + a_telegram->setUIntX(getSize(), dateTime().toMSecsSinceEpoch() / 1000); + } + return true; } - // take actual date and time if time is 0 - if (0 == unixTime && !a_readonly) - unixTime = ::time(nullptr) * 1000LL; - - //valueWidget = new QDateTimeEdit(dateTime); - setDateTime(QDateTime::fromMSecsSinceEpoch(unixTime)); - setDisplayFormat(QLatin1String("dd MMM yyyy hh:mm:ss")); - setCalendarPopup(true); - updateToolTip(QString::number(unixTime)); - //setToolTip(a_field->getToolTipText()); - // checkAndOvertakeContent(); - - connect(this, &LogViewDateTimeEdit::editingFinished, - this, &LogViewDateTimeEdit::checkAndOvertakeContent); -} - - -// --------------------------------------------------------------- -void LogViewDateTimeEdit::checkAndOvertakeContent() -{ - updateToolTip(QString::number(dateTime().toMSecsSinceEpoch() / 1000)); -} - - -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewDateTimeEdit::saveContent(LogViewTelegram* a_telegram) -{ - if (a_telegram->isJsonTelegram()) - { - a_telegram->setJsonValue(m_Field->jsonPath(), dateTime().toMSecsSinceEpoch()); - } - else - { - a_telegram->setNextFieldAsGpsTimeField(); // fixme: muss noch der feldname auf GPS Zeit geprüft werden? - a_telegram->setUIntX(getSize(), dateTime().toMSecsSinceEpoch() / 1000); - } - return true; -} } // namespace N_LogView - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.hpp index cb1f297c9..2c72f4cce 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewDateTimeEdit.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewWidget.hpp" @@ -25,7 +25,9 @@ namespace N_LogView * @version 1.0 * @created 20-Mai-2010 17:41:28 */ - class LogViewDateTimeEdit : public QDateTimeEdit, public LogViewWidget + class LogViewDateTimeEdit + : public QDateTimeEdit + , public LogViewWidget { Q_OBJECT public: @@ -35,7 +37,7 @@ namespace N_LogView * @param a_parent * @param a_readonly */ - LogViewDateTimeEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly); + LogViewDateTimeEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly); /** * Writes the content into telegram. @@ -43,11 +45,10 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; public slots: void checkAndOvertakeContent(); - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.cpp index 477914745..5763d6459 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewEnumEdit.hpp" #include "LogViewXdrStruct.hpp" @@ -23,83 +23,82 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewEnumEdit::LogViewEnumEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly, const int a_index) - : QComboBox(a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) -{ - QString value = a_field->value(a_index); - - // show the tool-tip with special-case for TETRA bitfields - setToolTip(a_field->toolTipText()); - - // fill combobox - bool bCurrentIndexSet = false; - int i = 0; - while (LogViewXdrValue* child = (static_cast(a_field->xdrElement()))->getChildAsValue(i++)) + // --------------------------------------------------------------- + LogViewEnumEdit::LogViewEnumEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly, const int a_index) + : QComboBox(a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) { - QString enumText = LogViewField::makeClean(child->getName()); - if (!a_readonly || enumText == value) + QString value = a_field->value(a_index); + + // show the tool-tip with special-case for TETRA bitfields + setToolTip(a_field->toolTipText()); + + // fill combobox + bool bCurrentIndexSet = false; + int i = 0; + while (LogViewXdrValue *child = (static_cast(a_field->xdrElement()))->getChildAsValue(i++)) { - addItem(QStringLiteral("%1 (%2)").arg(enumText).arg(child->getValue()), QVariant::fromValue(child->getValue())); - if (a_readonly) + QString enumText = LogViewField::makeClean(child->getName()); + if (!a_readonly || enumText == value) + { + addItem(QStringLiteral("%1 (%2)").arg(enumText).arg(child->getValue()), QVariant::fromValue(child->getValue())); + if (a_readonly) + bCurrentIndexSet = true; + } + + if (enumText == value) + { + setCurrentIndex(a_readonly ? 0 : i - 1); bCurrentIndexSet = true; + if (!a_readonly || (0 != a_index)) + updateToolTip(itemData(currentIndex()).toString()); + } } - if (enumText == value) + if (!bCurrentIndexSet) { - setCurrentIndex(a_readonly ? 0 : i - 1); - bCurrentIndexSet = true; - if (!a_readonly || (0 != a_index)) - updateToolTip(itemData(currentIndex()).toString()); + addItem(value); + setCurrentIndex(findText(value)); } + + // connect signals + connect(this, QOverload::of(&LogViewEnumEdit::currentIndexChanged), this, &LogViewEnumEdit::checkAndOvertakeContent); } - if (!bCurrentIndexSet) + + // --------------------------------------------------------------- + uint16_t LogViewEnumEdit::getSize() const { - addItem(value); - setCurrentIndex(findText(value)); + // todo: check ob wirklich ein struct + const LogViewXdrStruct *xdrStruct = static_cast(m_Field->xdrElement()); + return xdrStruct->getEnumSize(); } - // connect signals - connect(this, QOverload::of(&LogViewEnumEdit::currentIndexChanged), - this, &LogViewEnumEdit::checkAndOvertakeContent); -} - -// --------------------------------------------------------------- -uint16_t LogViewEnumEdit::getSize() const -{ - // todo: check ob wirklich ein struct - const LogViewXdrStruct* xdrStruct = static_cast(m_Field->xdrElement()); - return xdrStruct->getEnumSize(); -} - - -// --------------------------------------------------------------- -void LogViewEnumEdit::checkAndOvertakeContent() -{ - updateToolTip(itemData(currentIndex()).toString()); -} - - -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewEnumEdit::saveContent(LogViewTelegram* a_telegram) -{ - bool ok; - int value = itemData(currentIndex()).toInt(&ok); - if (ok) + // --------------------------------------------------------------- + void LogViewEnumEdit::checkAndOvertakeContent() { - if (a_telegram->isJsonTelegram()) - a_telegram->setJsonValue(m_Field->jsonPath(), value); - else - a_telegram->setUIntX(getSize(), value); - return true; + updateToolTip(itemData(currentIndex()).toString()); + } + + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewEnumEdit::saveContent(LogViewTelegram *a_telegram) + { + bool ok; + int value = itemData(currentIndex()).toInt(&ok); + if (ok) + { + if (a_telegram->isJsonTelegram()) + a_telegram->setJsonValue(m_Field->jsonPath(), value); + else + a_telegram->setUIntX(getSize(), value); + return true; + } + return false; // failure while conversion } - return false; // failure while conversion -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.hpp index 8bb05b8f0..9300d15bf 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewEnumEdit.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewWidget.hpp" @@ -25,7 +25,9 @@ namespace N_LogView * @version 1.0 * @created 21-Mai-2010 09:31:16 */ - class LogViewEnumEdit : public QComboBox, public LogViewWidget + class LogViewEnumEdit + : public QComboBox + , public LogViewWidget { Q_OBJECT public: @@ -36,7 +38,7 @@ namespace N_LogView * @param a_readonly * @param a_index the array-index */ - LogViewEnumEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly, const int a_index); + LogViewEnumEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly, const int a_index); uint16_t getSize() const override; @@ -47,11 +49,10 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; protected slots: void checkAndOvertakeContent(); - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.cpp index d62d7244b..69eb57ca1 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewField.hpp" #include #include @@ -20,257 +20,260 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewField::LogViewField(const QString& a_name, const E_FieldKind a_kind, const LogViewXdrElement* a_xdrElement) - : m_logger(getLogger("LogViewField")), - m_Name(a_name), - m_IsRightAligned(false), - m_Offset(0), - m_Size(0), - m_MaxArraySize(0), - m_IsDynamicArray(false), - m_HasContent(true), - m_bDeleteXdr(false), - m_Kind(a_kind), - m_XdrElement(a_xdrElement) -{ -} - -// --------------------------------------------------------------- -LogViewField::~LogViewField() -{ - for (LogViewField *f : std::as_const(m_Child)) - delete f; - if (m_bDeleteXdr) - delete m_XdrElement; -} - -LogViewField *LogViewField::clone(int arrayIdx) const -{ - LogViewField *f = new LogViewField(*this); - f->m_Child.clear(); - f->m_bDeleteXdr = false; - for (auto * c : m_Child) + // --------------------------------------------------------------- + LogViewField::LogViewField(const QString &a_name, const E_FieldKind a_kind, const LogViewXdrElement *a_xdrElement) + : m_logger(getLogger("LogViewField")) + , m_Name(a_name) + , m_IsRightAligned(false) + , m_Offset(0) + , m_Size(0) + , m_MaxArraySize(0) + , m_IsDynamicArray(false) + , m_HasContent(true) + , m_bDeleteXdr(false) + , m_Kind(a_kind) + , m_XdrElement(a_xdrElement) { - auto *clonedChild = c->clone(-1); - if (arrayIdx >= 0) + } + + // --------------------------------------------------------------- + LogViewField::~LogViewField() + { + for (LogViewField *f : std::as_const(m_Child)) + delete f; + if (m_bDeleteXdr) + delete m_XdrElement; + } + + LogViewField *LogViewField::clone(int arrayIdx) const + { + LogViewField *f = new LogViewField(*this); + f->m_Child.clear(); + f->m_bDeleteXdr = false; + for (auto *c : m_Child) { - QStringList sl = clonedChild->jsonPath(); - if (sl.size() > 1 && sl.at(sl.size() - 2).startsWith(QStringLiteral("index: "))) + auto *clonedChild = c->clone(-1); + if (arrayIdx >= 0) { - sl[sl.size() - 2] = QStringLiteral("index: %1").arg(arrayIdx); - clonedChild->setJsonPath(sl); + QStringList sl = clonedChild->jsonPath(); + if (sl.size() > 1 && sl.at(sl.size() - 2).startsWith(QStringLiteral("index: "))) + { + sl[sl.size() - 2] = QStringLiteral("index: %1").arg(arrayIdx); + clonedChild->setJsonPath(sl); + } } + f->addChild(clonedChild); } - f->addChild(clonedChild); + for (auto &val : f->m_ValueList) + val.clear(); + return f; } - for (auto &val : f->m_ValueList) - val.clear(); - return f; -} -// --------------------------------------------------------------- -void LogViewField::addChild(LogViewField* a_child) -{ - if (a_child) - m_Child.push_back(a_child); -} - -// --------------------------------------------------------------- -void LogViewField::removeLastChild() -{ - if (m_Child.empty()) - return; - delete m_Child.takeLast(); -} - - -// --------------------------------------------------------------- -LogViewField* LogViewField::child(int arrayIdx) -{ - if (m_Child.size() > arrayIdx) - return m_Child.at(arrayIdx); - return nullptr; -} - -// --------------------------------------------------------------- -void LogViewField::addValue(const QString &value) -{ - m_ValueList.append(value); -} - -// --------------------------------------------------------------- -void LogViewField::addValueBinaryHex(const QString &value) -{ - const QByteArray ba = QByteArray::fromHex(value.toLatin1()); - for (const char c : ba) - m_ValueList.append(QString::number(static_cast(c))); -} - - -// --------------------------------------------------------------- -// Returns the value at position a_index converted to a string. -// If the field is a date-time-field, the returned value is -// converted to a string containing date and time, execpt when -// a_doNotMakeSpecialConversions is set to true, the unix-time -// will be returned as value. -// --------------------------------------------------------------- -QString LogViewField::value(int arrayIdx, const bool a_doNotMakeSpecialConversions) const -{ - if (m_ValueList.size() > arrayIdx) + // --------------------------------------------------------------- + void LogViewField::addChild(LogViewField *a_child) { - const QString &ret = m_ValueList.at(arrayIdx); - if (!a_doNotMakeSpecialConversions) + if (a_child) + m_Child.push_back(a_child); + } + + // --------------------------------------------------------------- + void LogViewField::removeLastChild() + { + if (m_Child.empty()) + return; + delete m_Child.takeLast(); + } + + + // --------------------------------------------------------------- + LogViewField *LogViewField::child(int arrayIdx) + { + if (m_Child.size() > arrayIdx) + return m_Child.at(arrayIdx); + return nullptr; + } + + // --------------------------------------------------------------- + void LogViewField::addValue(const QString &value) + { + m_ValueList.append(value); + } + + // --------------------------------------------------------------- + void LogViewField::addValueBinaryHex(const QString &value) + { + const QByteArray ba = QByteArray::fromHex(value.toLatin1()); + for (const char c : ba) + m_ValueList.append(QString::number(static_cast(c))); + } + + + // --------------------------------------------------------------- + // Returns the value at position a_index converted to a string. + // If the field is a date-time-field, the returned value is + // converted to a string containing date and time, execpt when + // a_doNotMakeSpecialConversions is set to true, the unix-time + // will be returned as value. + // --------------------------------------------------------------- + QString LogViewField::value(int arrayIdx, const bool a_doNotMakeSpecialConversions) const + { + if (m_ValueList.size() > arrayIdx) { - if (isDateTimeField()) - return QDateTime::fromMSecsSinceEpoch(ret.toLongLong() * 1000).toString(QStringLiteral("dd.mm.yy hh:mm:ss.zzz")); - if (isMSecsField()) - return QDateTime::fromMSecsSinceEpoch(ret.toLongLong()).toString(QStringLiteral("dd.mm.yy hh:mm:ss.zzz")); + const QString &ret = m_ValueList.at(arrayIdx); + if (!a_doNotMakeSpecialConversions) + { + if (isDateTimeField()) + return QDateTime::fromMSecsSinceEpoch(ret.toLongLong() * 1000).toString(QStringLiteral("dd.mm.yy hh:mm:ss.zzz")); + if (isMSecsField()) + return QDateTime::fromMSecsSinceEpoch(ret.toLongLong()).toString(QStringLiteral("dd.mm.yy hh:mm:ss.zzz")); + } + return ret; } - return ret; + return QString(); } - return QString(); -} -// --------------------------------------------------------------- -int64_t LogViewField::getHighestValue() const -{ - switch (m_XdrElement->getKind()) + // --------------------------------------------------------------- + int64_t LogViewField::getHighestValue() const { - case LogViewXdrElement::e_KindStandardType: - { - int64_t highest = 1; - //const LogViewXdrStandardType* xdrStandardType = static_cast(m_XdrElement); - uint16_t bitSize = 8*static_cast(m_XdrElement)->getEditSize(); - // fixme: mache configurierbar - if ((0 == m_Name.compare(QLatin1String("utm nordwert"), Qt::CaseInsensitive)) || - (0 == m_Name.compare(QLatin1String("utm ostwert"), Qt::CaseInsensitive))) - bitSize -= 8; + switch (m_XdrElement->getKind()) + { + case LogViewXdrElement::e_KindStandardType: + { + int64_t highest = 1; + //const LogViewXdrStandardType* xdrStandardType = static_cast(m_XdrElement); + uint16_t bitSize = 8 * static_cast(m_XdrElement)->getEditSize(); + // fixme: mache configurierbar + if ((0 == m_Name.compare(QLatin1String("utm nordwert"), Qt::CaseInsensitive)) || (0 == m_Name.compare(QLatin1String("utm ostwert"), Qt::CaseInsensitive))) + bitSize -= 8; - switch (static_cast(m_XdrElement)->getValueKind()) { - case LogViewXdrStandardType::e_Boolean: - return 1; - case LogViewXdrStandardType::e_Signed: - bitSize--; - Q_FALLTHROUGH(); - case LogViewXdrStandardType::e_Unsigned: - case LogViewXdrStandardType::e_Data: - highest = highest << bitSize; - highest--; - break; - default: - highest = 0; - break; + switch (static_cast(m_XdrElement)->getValueKind()) + { + case LogViewXdrStandardType::e_Boolean: + return 1; + case LogViewXdrStandardType::e_Signed: + bitSize--; + Q_FALLTHROUGH(); + case LogViewXdrStandardType::e_Unsigned: + case LogViewXdrStandardType::e_Data: + highest = highest << bitSize; + highest--; + break; + default: + highest = 0; + break; + } + return highest; + } + default: + ERROR_LOG(m_logger) << "Case not implemented"; } - return highest; + return 0; } - default: - ERROR_LOG(m_logger) << "Case not implemented"; - } - return 0; -} -// --------------------------------------------------------------- -int64_t LogViewField::getLowestValue() const -{ - switch (m_XdrElement->getKind()) + // --------------------------------------------------------------- + int64_t LogViewField::getLowestValue() const { - case LogViewXdrElement::e_KindStandardType: - { - int64_t lowest = 0; - //const LogViewXdrStandardType* xdrStandardType = static_cast(a_field->getXdrElement()); - switch (static_cast(m_XdrElement)->getValueKind()) { - case LogViewXdrStandardType::e_Boolean: - return 0; - case LogViewXdrStandardType::e_Signed: - lowest = getHighestValue() + 1; - lowest = -lowest; - break; - default: - break; + switch (m_XdrElement->getKind()) + { + case LogViewXdrElement::e_KindStandardType: + { + int64_t lowest = 0; + //const LogViewXdrStandardType* xdrStandardType = static_cast(a_field->getXdrElement()); + switch (static_cast(m_XdrElement)->getValueKind()) + { + case LogViewXdrStandardType::e_Boolean: + return 0; + case LogViewXdrStandardType::e_Signed: + lowest = getHighestValue() + 1; + lowest = -lowest; + break; + default: + break; + } + return lowest; + } + default: + ERROR_LOG(m_logger) << "Case not implemented"; + break; } - return lowest; + return 0; } - default: - ERROR_LOG(m_logger) << "Case not implemented"; - break; - } - return 0; -} -// --------------------------------------------------------------- -void LogViewField::dump(const QString &a_indent) const -{ - INFO_LOG(m_logger) << a_indent << "["; - INFO_LOG(m_logger) << a_indent << "Field[" << m_Name << "]: m_Kind=" << m_Kind << " m_Offset=" << m_Offset << " m_Size=" << m_Size << " m_MaxArraySize=" << m_MaxArraySize << " m_IsRightAligned=" << m_IsRightAligned << " m_IsDynamicArray=" << m_IsDynamicArray << " m_ToolTipText=" << m_ToolTipText; -// m_XdrElement->dump(); - for (int i=0; i pretty for human readable. -// It does following: -// - generates umlaute (ä, ö, ü) -// - removes _rt at end -// - replaces _ with space -// - uppercase of every word -// --------------------------------------------------------------- -QString LogViewField::makeClean(const QString &text) -{ - QString a_uncleanText = text; - // remove _rt at end - if (a_uncleanText.endsWith(QLatin1String("_rt"))) - a_uncleanText = a_uncleanText.left(a_uncleanText.length() - 3); - - // replace _ with space - a_uncleanText = a_uncleanText.replace(QLatin1Char('_'), QLatin1Char(' ')); - - // first character of every word must be uppercase - int pos = 0; - while (a_uncleanText.length() > pos) + // --------------------------------------------------------------- + void LogViewField::dump(const QString &a_indent) const { - a_uncleanText[pos] = a_uncleanText[pos].toUpper(); - pos = a_uncleanText.indexOf(QLatin1Char(' '), pos + 1); - if (-1 == pos) - break; - pos++; + INFO_LOG(m_logger) << a_indent << "["; + INFO_LOG(m_logger) << a_indent << "Field[" << m_Name << "]: m_Kind=" << m_Kind << " m_Offset=" << m_Offset << " m_Size=" << m_Size + << " m_MaxArraySize=" << m_MaxArraySize << " m_IsRightAligned=" << m_IsRightAligned << " m_IsDynamicArray=" << m_IsDynamicArray + << " m_ToolTipText=" << m_ToolTipText; + // m_XdrElement->dump(); + for (int i = 0; i < m_ValueList.size(); i++) + INFO_LOG(m_logger) << a_indent << "m_Value[" << i << "]=" << m_ValueList[i]; + + for (auto *c : m_Child) + c->dump(a_indent + QLatin1Char(' ')); + + INFO_LOG(m_logger) << a_indent << "]"; } - return a_uncleanText; -} + + // --------------------------------------------------------------- + // Makes the text pretty for human readable. + // It does following: + // - generates umlaute (ä, ö, ü) + // - removes _rt at end + // - replaces _ with space + // - uppercase of every word + // --------------------------------------------------------------- + QString LogViewField::makeClean(const QString &text) + { + QString a_uncleanText = text; + // remove _rt at end + if (a_uncleanText.endsWith(QLatin1String("_rt"))) + a_uncleanText = a_uncleanText.left(a_uncleanText.length() - 3); + + // replace _ with space + a_uncleanText = a_uncleanText.replace(QLatin1Char('_'), QLatin1Char(' ')); + + // first character of every word must be uppercase + int pos = 0; + while (a_uncleanText.length() > pos) + { + a_uncleanText[pos] = a_uncleanText[pos].toUpper(); + pos = a_uncleanText.indexOf(QLatin1Char(' '), pos + 1); + if (-1 == pos) + break; + pos++; + } + + return a_uncleanText; + } -// --------------------------------------------------------------- -// returns true if the field is a date-time -// --------------------------------------------------------------- -bool LogViewField::isDateTimeField() const -{ - QString name = m_Name.toLower(); - return name == QLatin1String("gps_zeit"); -} + // --------------------------------------------------------------- + // returns true if the field is a date-time + // --------------------------------------------------------------- + bool LogViewField::isDateTimeField() const + { + QString name = m_Name.toLower(); + return name == QLatin1String("gps_zeit"); + } -bool LogViewField::isMSecsField() const -{ - QString name = m_Name.toLower(); - return (name == QLatin1String("timestamp")) || (name == QLatin1String("effectstart")); -} + bool LogViewField::isMSecsField() const + { + QString name = m_Name.toLower(); + return (name == QLatin1String("timestamp")) || (name == QLatin1String("effectstart")); + } -// --------------------------------------------------------------- -void LogViewField::setMaxArraySize(uint16_t newVal, const bool a_isDynamic) -{ - m_MaxArraySize = newVal; - m_IsDynamicArray = a_isDynamic; -} + // --------------------------------------------------------------- + void LogViewField::setMaxArraySize(uint16_t newVal, const bool a_isDynamic) + { + m_MaxArraySize = newVal; + m_IsDynamicArray = a_isDynamic; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.hpp index 6f38965d1..5310cfae0 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewField.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -34,7 +34,7 @@ namespace N_LogView }; - LogViewField(const QString& a_name, const E_FieldKind a_kind, const LogViewXdrElement* a_xdrElement); + LogViewField(const QString &a_name, const E_FieldKind a_kind, const LogViewXdrElement *a_xdrElement); virtual ~LogViewField(); LogViewField *clone(int arrayIdx) const; @@ -44,7 +44,7 @@ namespace N_LogView void setName(const QString &newVal) { m_Name = newVal; } - void addChild(LogViewField* a_child); + void addChild(LogViewField *a_child); void removeLastChild(); LogViewField *child(int arrayIdx); int childCount() const { return m_Child.size(); } @@ -103,7 +103,7 @@ namespace N_LogView void setSize(int newVal) { m_Size = newVal; } - const LogViewXdrElement* xdrElement() const { return m_XdrElement; } + const LogViewXdrElement *xdrElement() const { return m_XdrElement; } /** * returns true if the field is a date-time @@ -130,7 +130,6 @@ namespace N_LogView QStringList jsonPath() const { return m_jsonPath; } protected: - NGL::INGLLogger &m_logger; QString m_Name; @@ -148,7 +147,7 @@ namespace N_LogView bool m_IsDynamicArray; bool m_HasContent; bool m_bDeleteXdr; - QVector m_Child; + QVector m_Child; E_FieldKind m_Kind; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.cpp index 951c01bc7..87a7651a8 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.cpp @@ -50,959 +50,945 @@ namespace N_LogView { -// static member initialization -const QLatin1String LogViewGui::WINDOW_GROUP("MainWindow"); -const QLatin1String LogViewGui::SIZE("Size"); -const QLatin1String LogViewGui::SCREEN("Screen"); -const QLatin1String LogViewGui::POS("Pos"); -const QLatin1String LogViewGui::SPLITTPOS("SplittPos"); -const QLatin1String LogViewGui::TOOLBOXINDEX("ToolBoxIndex"); + // static member initialization + const QLatin1String LogViewGui::WINDOW_GROUP("MainWindow"); + const QLatin1String LogViewGui::SIZE("Size"); + const QLatin1String LogViewGui::SCREEN("Screen"); + const QLatin1String LogViewGui::POS("Pos"); + const QLatin1String LogViewGui::SPLITTPOS("SplittPos"); + const QLatin1String LogViewGui::TOOLBOXINDEX("ToolBoxIndex"); -// --------------------------------------------------------------- + // --------------------------------------------------------------- -// --------------------------------------------------------------- -LogViewGui::LogViewGui(QWidget* a_parent) - : QMainWindow(a_parent) - , RADIO_BUTTON_ICON_SIZE(16, 16) - , m_LogfileSize(0) - , m_DoReload(false) - , m_EditTelegramController(new TelegramEdit(this)) - , m_TailTimer(nullptr) - , m_InjectionThread(nullptr) - , m_replayTimer(new QTimer(this)) - , m_currentReplayRow(-1) - , m_logger(getLogger("LogViewGui")) -{ - setWindowIcon(QIcon(QLatin1String(":icons/16x16/rde_16x16.png"))); - - QSettings settings; - settings.beginGroup(WINDOW_GROUP); - - // status-bar - m_InjectionStatus = new QLabel(this); - m_InjectionStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); - statusBar()->addPermanentWidget(m_InjectionStatus); - m_ParticipantStatus = new QLabel(this); - m_ParticipantStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); - statusBar()->addPermanentWidget(m_ParticipantStatus); - m_TelegramStatus = new QLabel(this); - m_TelegramStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); - statusBar()->addPermanentWidget(m_TelegramStatus); - - // tool-bar - // -------- - QToolBar* toolBar = addToolBar(tr("Datei")); - toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - // tool-bar: new logfile - QString tipText; - QAction* action = new QAction(tr("Neue Log-Datei"), this); - action->setIcon(QIcon(QLatin1String(":icons/16x16/document-new.png"))); - action->setShortcut(tr("Ctrl+N")); - tipText = tr("Eine neue Telegram-Log-Datei anzeigen (Ctrl-N)"); - action->setStatusTip(tipText); - action->setToolTip(tipText); - connect(action, &QAction::triggered, this, &LogViewGui::newTelegramFile); - toolBar->addAction(action); - // tool-bar: add logfile - action = new QAction(tr("Log-Datei hinzu"), this); - action->setIcon(QIcon(QLatin1String(":icons/16x16/document-import.png"))); - action->setShortcut(tr("Ctrl+O")); - tipText = tr("Eine weitere Telegramm-Log-Datei anzeigen (Ctrl-O)"); - action->setStatusTip(tipText); - action->setToolTip(tipText); - connect(action, &QAction::triggered, this, &LogViewGui::loadTelegramFile); - toolBar->addAction(action); - // tool-bar: reload - m_reloadAction = new QAction(tr("&Reload"), this); - m_reloadAction->setCheckable(true); - m_reloadAction->setChecked(m_DoReload); - m_reloadAction->setIcon(QIcon(QLatin1String(":icons/16x16/edit-redo.png"))); - m_reloadAction->setShortcut(tr("Ctrl+R")); - tipText = tr("Reload des Logfiles ein-/ausschalten (Ctrl-R)"); - m_reloadAction->setStatusTip(tipText); - m_reloadAction->setToolTip(tipText); - connect(m_reloadAction, &QAction::triggered, this, &LogViewGui::reloadOnOff); - toolBar->addAction(m_reloadAction); - // tool-bar: settings - action = new QAction(tr("&Einstellungen"), this); - action->setIcon(QIcon(QLatin1String(":icons/16x16/configure.png"))); - action->setShortcut(tr("Ctrl+E")); - tipText = tr("Verhalten des Programmes einstellen (Ctrl-E)"); - action->setStatusTip(tipText); - action->setToolTip(tipText); - connect(action, &QAction::triggered, this, &LogViewGui::changeSettings); - toolBar->addAction(action); - // tool-bar: exit - toolBar->addSeparator(); - action = new QAction(tr("&Beenden"), this); - action->setIcon(QIcon(QLatin1String(":icons/16x16/edit-delete.png"))); - action->setShortcut(tr("Alt-F4")); - tipText = tr("LogView beenden (Alt-F4)"); - action->setStatusTip(tipText); - action->setToolTip(tipText); - connect(action, &QAction::triggered, this, &LogViewGui::close); - toolBar->addAction(action); - - createCentralSelectionWidget(); - createTetraSelectionWidget(); - createWlsSelectionWidget(); - - // participant-selection - // --------------------- - m_ParticipantTableView = new QTableView(this); - m_participantProxyModel = new QSortFilterProxyModel(this); - m_participantModel = new ParticipantModel(this); - m_participantProxyModel->setSourceModel(m_participantModel); - m_ParticipantTableView->setModel(m_participantProxyModel); - m_ParticipantTableView->setAlternatingRowColors(true); - m_ParticipantTableView->setSelectionBehavior(QAbstractItemView::SelectRows); - m_ParticipantTableView->setSelectionMode(QAbstractItemView::MultiSelection); - m_ParticipantTableView->setSortingEnabled(true); - m_ParticipantTableView->setTabKeyNavigation(false); - m_ParticipantTableView->verticalHeader()->hide(); - m_ParticipantTableView->verticalHeader()->setMinimumSectionSize(QApplication::font().pointSize() * 2.5); - m_ParticipantTableView->verticalHeader()->setDefaultSectionSize(QApplication::font().pointSize() * 2.5); - m_ParticipantTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - m_ParticipantTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); - connect(m_ParticipantTableView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &LogViewGui::selectedParticipantChanged); - QVBoxLayout* participantBox = new QVBoxLayout; - participantBox->addWidget(m_ParticipantTableView); - m_ParticipantSelectionGroup = new QGroupBox(tr("Teilnehmer-Filter &aktivieren"), this); - m_ParticipantSelectionGroup->setCheckable(true); - m_ParticipantSelectionGroup->setChecked(false); - m_ParticipantSelectionGroup->setLayout(participantBox); - connect(m_ParticipantSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::selectedParticipantChanged); - - // left side (filters) - m_ToolBox = new QToolBox(this); - m_ToolBox->addItem(m_CentralSelectionGroup, QIcon(QLatin1String(":/image/Central.png")), tr("&Zentral-Telegramm-Filter")); - m_ToolBox->addItem(m_TetraSelectionGroup, QIcon(QLatin1String(":/image/Tetra.png")), tr("TET&RA-Telegramm-Filter")); - m_ToolBox->addItem(m_WlsSelectionGroup, QIcon(QLatin1String(":/image/Wls.png")), tr("&WLS-Telegramm-Filter")); - m_ToolBox->addItem(m_ParticipantSelectionGroup, QIcon(QLatin1String(":/image/TNE.png")), tr("Teilnehmer-&Filter")); - m_ToolBox->addItem(m_EditTelegramController->tableView(), QIcon(QLatin1String(":icons/16x16/document-edit.png")), tr("&Edit && Sende Telegramme")); - m_ToolBox->setCurrentIndex(settings.value(TOOLBOXINDEX).toInt()); - - // right side (logged telegrams) - // ----------------------------- - m_logTelegramView = new QTableView(this); - m_logTelegramView->setAlternatingRowColors(true); - m_logTelegramView->setSelectionBehavior(QAbstractItemView::SelectRows); - m_logTelegramView->setSelectionMode(QAbstractItemView::ContiguousSelection); - m_logTelegramView->verticalHeader()->hide(); - m_logTelegramView->verticalHeader()->setMinimumSectionSize(QApplication::font().pointSize() * 2.5); - m_logTelegramView->verticalHeader()->setDefaultSectionSize(QApplication::font().pointSize() * 2.5); - m_logTelegramView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); - m_logTelegramView->setContextMenuPolicy(Qt::CustomContextMenu); //Custom Contextmenu enabled - connect(m_logTelegramView, &QTableView::customContextMenuRequested, - this, &LogViewGui::customMenuRequested); //connect table to contextmenu - m_telegramModel = new TelegramModel(m_logTelegramView); - m_telegramProxyModel = new TelegramProxyModel(m_logTelegramView); - m_telegramProxyModel->setSourceModel(m_telegramModel); - m_logTelegramView->setModel(m_telegramProxyModel); - connect(m_logTelegramView, &QTableView::doubleClicked, - this, &LogViewGui::onLogTelegramViewDoubleClicked); - m_logTelegramView->horizontalHeader()->setSortIndicatorShown(true); - m_logTelegramView->horizontalHeader()->setSortIndicator(3, Qt::AscendingOrder); - m_logTelegramView->setSortingEnabled(true); - - QVBoxLayout* telegramBox = new QVBoxLayout; - telegramBox->addWidget(m_logTelegramView); - QGroupBox* telegramGroup = new QGroupBox(tr("&Log-Telegramme"), this); - telegramGroup->setLayout(telegramBox); - - // splitter between toolbox and log-telegram-list - m_Splitter = new QSplitter(Qt::Horizontal, this); - m_Splitter->addWidget(m_ToolBox); - m_Splitter->addWidget(telegramGroup); - const QList splitterSizesAsVariant = settings.value(SPLITTPOS).toList(); - QList splitterSizes; - splitterSizes.reserve(splitterSizesAsVariant.size()); - if (splitterSizesAsVariant.isEmpty()) + // --------------------------------------------------------------- + LogViewGui::LogViewGui(QWidget *a_parent) + : QMainWindow(a_parent) + , RADIO_BUTTON_ICON_SIZE(16, 16) + , m_LogfileSize(0) + , m_DoReload(false) + , m_EditTelegramController(new TelegramEdit(this)) + , m_TailTimer(nullptr) + , m_InjectionThread(nullptr) + , m_replayTimer(new QTimer(this)) + , m_currentReplayRow(-1) + , m_logger(getLogger("LogViewGui")) { - splitterSizes << 235 << 1000; - } - else - { - for (const QVariant &item : splitterSizesAsVariant) - splitterSizes << item.toInt(); - } - m_Splitter->setSizes(splitterSizes); - setCentralWidget(m_Splitter); + setWindowIcon(QIcon(QLatin1String(":icons/16x16/rde_16x16.png"))); - // initialize the telegram-filters (this should be done before load of telegrams, otherwise the telegram-list - // will be shown several times and this could be slow when the telegram-list is slow) - m_CentralSelectionGroup->setChecked(true); - m_ackCentralTelCheckBox->setChecked(true); - m_ackCentralTelCheckBox->setChecked(false); - m_PosCentralTelCheckBox->setChecked(true); - m_PosCentralTelCheckBox->setChecked(false); - m_SentCentralTelCheckBox->setChecked(true); - m_ReceivedCentralTelCheckBox->setChecked(true); + QSettings settings; + settings.beginGroup(WINDOW_GROUP); - m_TetraSelectionGroup->setChecked(true); - m_SentTetraTelCheckBox->setChecked(true); - m_ReceivedTetraTelCheckBox->setChecked(true); - m_PosTetraTelCheckBox->setChecked(true); - m_PosTetraTelCheckBox->setChecked(false); - m_FragmentedTetraTelCheckBox->setChecked(true); - m_LoginTetraTelCheckBox->setChecked(true); - m_RegisterTetraTelCheckBox->setChecked(true); - m_ReportTetraTelCheckBox->setChecked(false); - m_AirInterfaceLoadTetraTelCheckBox->setChecked(false); + // status-bar + m_InjectionStatus = new QLabel(this); + m_InjectionStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); + statusBar()->addPermanentWidget(m_InjectionStatus); + m_ParticipantStatus = new QLabel(this); + m_ParticipantStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); + statusBar()->addPermanentWidget(m_ParticipantStatus); + m_TelegramStatus = new QLabel(this); + m_TelegramStatus->setFrameStyle(QFrame::Panel | QFrame::Sunken); + statusBar()->addPermanentWidget(m_TelegramStatus); - m_WlsSelectionGroup->setChecked(true); - m_PosWlsTelCheckBox->setChecked(true); - m_PosWlsTelCheckBox->setChecked(false); - m_SentWlsTelCheckBox->setChecked(true); - m_ReceivedWlsTelCheckBox->setChecked(true); + // tool-bar + // -------- + QToolBar *toolBar = addToolBar(tr("Datei")); + toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + // tool-bar: new logfile + QString tipText; + QAction *action = new QAction(tr("Neue Log-Datei"), this); + action->setIcon(QIcon(QLatin1String(":icons/16x16/document-new.png"))); + action->setShortcut(tr("Ctrl+N")); + tipText = tr("Eine neue Telegram-Log-Datei anzeigen (Ctrl-N)"); + action->setStatusTip(tipText); + action->setToolTip(tipText); + connect(action, &QAction::triggered, this, &LogViewGui::newTelegramFile); + toolBar->addAction(action); + // tool-bar: add logfile + action = new QAction(tr("Log-Datei hinzu"), this); + action->setIcon(QIcon(QLatin1String(":icons/16x16/document-import.png"))); + action->setShortcut(tr("Ctrl+O")); + tipText = tr("Eine weitere Telegramm-Log-Datei anzeigen (Ctrl-O)"); + action->setStatusTip(tipText); + action->setToolTip(tipText); + connect(action, &QAction::triggered, this, &LogViewGui::loadTelegramFile); + toolBar->addAction(action); + // tool-bar: reload + m_reloadAction = new QAction(tr("&Reload"), this); + m_reloadAction->setCheckable(true); + m_reloadAction->setChecked(m_DoReload); + m_reloadAction->setIcon(QIcon(QLatin1String(":icons/16x16/edit-redo.png"))); + m_reloadAction->setShortcut(tr("Ctrl+R")); + tipText = tr("Reload des Logfiles ein-/ausschalten (Ctrl-R)"); + m_reloadAction->setStatusTip(tipText); + m_reloadAction->setToolTip(tipText); + connect(m_reloadAction, &QAction::triggered, this, &LogViewGui::reloadOnOff); + toolBar->addAction(m_reloadAction); + // tool-bar: settings + action = new QAction(tr("&Einstellungen"), this); + action->setIcon(QIcon(QLatin1String(":icons/16x16/configure.png"))); + action->setShortcut(tr("Ctrl+E")); + tipText = tr("Verhalten des Programmes einstellen (Ctrl-E)"); + action->setStatusTip(tipText); + action->setToolTip(tipText); + connect(action, &QAction::triggered, this, &LogViewGui::changeSettings); + toolBar->addAction(action); + // tool-bar: exit + toolBar->addSeparator(); + action = new QAction(tr("&Beenden"), this); + action->setIcon(QIcon(QLatin1String(":icons/16x16/edit-delete.png"))); + action->setShortcut(tr("Alt-F4")); + tipText = tr("LogView beenden (Alt-F4)"); + action->setStatusTip(tipText); + action->setToolTip(tipText); + connect(action, &QAction::triggered, this, &LogViewGui::close); + toolBar->addAction(action); - // set the size and position of main-window - QSize size = settings.value(SIZE, sizeHint()).toSize(); - resize(size.isNull() ? QSize(1280, 768) : size); - move(settings.value(POS, QPoint(0, 0)).toPoint()); - settings.endGroup(); + createCentralSelectionWidget(); + createTetraSelectionWidget(); + createWlsSelectionWidget(); - connect(m_replayTimer, &QTimer::timeout, this, &LogViewGui::onReplayTimerTimeout); + // participant-selection + // --------------------- + m_ParticipantTableView = new QTableView(this); + m_participantProxyModel = new QSortFilterProxyModel(this); + m_participantModel = new ParticipantModel(this); + m_participantProxyModel->setSourceModel(m_participantModel); + m_ParticipantTableView->setModel(m_participantProxyModel); + m_ParticipantTableView->setAlternatingRowColors(true); + m_ParticipantTableView->setSelectionBehavior(QAbstractItemView::SelectRows); + m_ParticipantTableView->setSelectionMode(QAbstractItemView::MultiSelection); + m_ParticipantTableView->setSortingEnabled(true); + m_ParticipantTableView->setTabKeyNavigation(false); + m_ParticipantTableView->verticalHeader()->hide(); + m_ParticipantTableView->verticalHeader()->setMinimumSectionSize(QApplication::font().pointSize() * 2.5); + m_ParticipantTableView->verticalHeader()->setDefaultSectionSize(QApplication::font().pointSize() * 2.5); + m_ParticipantTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + m_ParticipantTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); + connect(m_ParticipantTableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &LogViewGui::selectedParticipantChanged); + QVBoxLayout *participantBox = new QVBoxLayout; + participantBox->addWidget(m_ParticipantTableView); + m_ParticipantSelectionGroup = new QGroupBox(tr("Teilnehmer-Filter &aktivieren"), this); + m_ParticipantSelectionGroup->setCheckable(true); + m_ParticipantSelectionGroup->setChecked(false); + m_ParticipantSelectionGroup->setLayout(participantBox); + connect(m_ParticipantSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::selectedParticipantChanged); - QTimer::singleShot(0, this, &LogViewGui::loadSpecificationFiles); + // left side (filters) + m_ToolBox = new QToolBox(this); + m_ToolBox->addItem(m_CentralSelectionGroup, QIcon(QLatin1String(":/image/Central.png")), tr("&Zentral-Telegramm-Filter")); + m_ToolBox->addItem(m_TetraSelectionGroup, QIcon(QLatin1String(":/image/Tetra.png")), tr("TET&RA-Telegramm-Filter")); + m_ToolBox->addItem(m_WlsSelectionGroup, QIcon(QLatin1String(":/image/Wls.png")), tr("&WLS-Telegramm-Filter")); + m_ToolBox->addItem(m_ParticipantSelectionGroup, QIcon(QLatin1String(":/image/TNE.png")), tr("Teilnehmer-&Filter")); + m_ToolBox->addItem(m_EditTelegramController->tableView(), QIcon(QLatin1String(":icons/16x16/document-edit.png")), tr("&Edit && Sende Telegramme")); + m_ToolBox->setCurrentIndex(settings.value(TOOLBOXINDEX).toInt()); - startInjectionThread(); -} + // right side (logged telegrams) + // ----------------------------- + m_logTelegramView = new QTableView(this); + m_logTelegramView->setAlternatingRowColors(true); + m_logTelegramView->setSelectionBehavior(QAbstractItemView::SelectRows); + m_logTelegramView->setSelectionMode(QAbstractItemView::ContiguousSelection); + m_logTelegramView->verticalHeader()->hide(); + m_logTelegramView->verticalHeader()->setMinimumSectionSize(QApplication::font().pointSize() * 2.5); + m_logTelegramView->verticalHeader()->setDefaultSectionSize(QApplication::font().pointSize() * 2.5); + m_logTelegramView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); + m_logTelegramView->setContextMenuPolicy(Qt::CustomContextMenu); //Custom Contextmenu enabled + connect(m_logTelegramView, &QTableView::customContextMenuRequested, this, &LogViewGui::customMenuRequested); //connect table to contextmenu + m_telegramModel = new TelegramModel(m_logTelegramView); + m_telegramProxyModel = new TelegramProxyModel(m_logTelegramView); + m_telegramProxyModel->setSourceModel(m_telegramModel); + m_logTelegramView->setModel(m_telegramProxyModel); + connect(m_logTelegramView, &QTableView::doubleClicked, this, &LogViewGui::onLogTelegramViewDoubleClicked); + m_logTelegramView->horizontalHeader()->setSortIndicatorShown(true); + m_logTelegramView->horizontalHeader()->setSortIndicator(3, Qt::AscendingOrder); + m_logTelegramView->setSortingEnabled(true); -void LogViewGui::createCentralSelectionWidget() -{ - // send-checkbox - m_SentCentralTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/P2C.png")); - // received-checkbox - m_ReceivedCentralTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/C2P.png")); - // pos-checkbox - m_PosCentralTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/CentralPos.png")); - // ack-checkbox - m_ackCentralTelCheckBox = createRadioButton(tr("&Bestaetigungstelegramme"), QLatin1String(":/image/CentralAck.png")); + QVBoxLayout *telegramBox = new QVBoxLayout; + telegramBox->addWidget(m_logTelegramView); + QGroupBox *telegramGroup = new QGroupBox(tr("&Log-Telegramme"), this); + telegramGroup->setLayout(telegramBox); - QVBoxLayout* centralFilterBox = new QVBoxLayout; - centralFilterBox->addWidget(m_SentCentralTelCheckBox); - centralFilterBox->addWidget(m_ReceivedCentralTelCheckBox); - centralFilterBox->addWidget(m_PosCentralTelCheckBox); - centralFilterBox->addWidget(m_ackCentralTelCheckBox); - centralFilterBox->addStretch(1); - - m_CentralSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); - m_CentralSelectionGroup->setCheckable(true); - m_CentralSelectionGroup->setChecked(false); - m_CentralSelectionGroup->setLayout(centralFilterBox); - connect(m_CentralSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); -} - -void LogViewGui::createTetraSelectionWidget() -{ - // sent-checkbox - m_SentTetraTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/T2P.png")); - // received-checkbox - m_ReceivedTetraTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/P2T.png")); - // pos-checkbox - m_PosTetraTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/TetraPos.png")); - // fragmented-checkbox - m_FragmentedTetraTelCheckBox = createRadioButton(tr("&Fragmentierte Meldungen"), QLatin1String(":/image/TetraFragmented.png")); - // login-checkbox - m_LoginTetraTelCheckBox = createRadioButton(tr("&Loginmeldungen"), QLatin1String(":/image/TetraLogin.png")); - // register-checkbox - m_RegisterTetraTelCheckBox = createRadioButton(tr("&Registermeldungen"), QLatin1String(":/image/TetraRegister.png")); - // report-checkbox - m_ReportTetraTelCheckBox = createRadioButton(tr("&Reportmeldungen"), QLatin1String(":/image/TetraReport.png")); - // air-interface-load-checkbox - m_AirInterfaceLoadTetraTelCheckBox = createRadioButton(tr("&Air-Load Meldungen"), QLatin1String(":/image/TetraAirInterface.png")); - - QVBoxLayout* tetraFilterBox = new QVBoxLayout; - tetraFilterBox->addWidget(m_SentTetraTelCheckBox); - tetraFilterBox->addWidget(m_ReceivedTetraTelCheckBox); - tetraFilterBox->addWidget(m_PosTetraTelCheckBox); - tetraFilterBox->addWidget(m_FragmentedTetraTelCheckBox); - tetraFilterBox->addWidget(m_LoginTetraTelCheckBox); - tetraFilterBox->addWidget(m_RegisterTetraTelCheckBox); - tetraFilterBox->addWidget(m_ReportTetraTelCheckBox); - tetraFilterBox->addWidget(m_AirInterfaceLoadTetraTelCheckBox); - tetraFilterBox->addStretch(1); - - m_TetraSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); - m_TetraSelectionGroup->setCheckable(true); - m_TetraSelectionGroup->setChecked(false); - m_TetraSelectionGroup->setLayout(tetraFilterBox); - connect(m_TetraSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); -} - -void LogViewGui::createWlsSelectionWidget() -{ - // send-checkbox - m_SentWlsTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/P2W.png")); - // received-checkbox - m_ReceivedWlsTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/W2P.png")); - // pos-checkbox - m_PosWlsTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/WlsPos.png")); - - QVBoxLayout* wlsFilterBox = new QVBoxLayout; - wlsFilterBox->addWidget(m_SentWlsTelCheckBox); - wlsFilterBox->addWidget(m_ReceivedWlsTelCheckBox); - wlsFilterBox->addWidget(m_PosWlsTelCheckBox); - wlsFilterBox->addStretch(1); - - m_WlsSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); - m_WlsSelectionGroup->setCheckable(true); - m_WlsSelectionGroup->setChecked(false); - m_WlsSelectionGroup->setLayout(wlsFilterBox); - connect(m_WlsSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); -} - - -// --------------------------------------------------------------- -void LogViewGui::customMenuRequested(const QPoint &pos) -{ - //create Menu with Actions - QMenu menu(this); - menu.addAction(tr("Add Telegram to EditList"), this, &LogViewGui::addTelegramToEdit); - menu.addAction(tr("Show HexData"), this, &LogViewGui::showHexData); - menu.addAction(tr("Export as CSV file"), this, &LogViewGui::exportAsCsv); - menu.addAction(tr("Export as JSon file"), this, &LogViewGui::exportAsJson); -#ifdef LTS_DEBUG - if (m_EditTelegramController && m_EditTelegramController->isInjectionPossible()) - { - const QString str = m_replayTimer->isActive() ? tr("Stop replay") : tr("Start Replay from here"); - menu.addAction(str, this, &LogViewGui::onStartLogReplay); - } -#endif - menu.exec(m_logTelegramView->viewport()->mapToGlobal(pos)); -} - - -// --------------------------------------------------------------- -void LogViewGui::addTelegramToEdit() -{ - for (const QModelIndex &orig: m_logTelegramView->selectionModel()->selectedRows()) - { - const QModelIndex idx = m_telegramProxyModel->mapToSource(orig); - QSharedPointer tele = m_telegramModel->telegram(idx.row()); - if (!tele) - continue; - m_EditTelegramController->appendTelegram(tele); - } -} - - -// --------------------------------------------------------------- -void LogViewGui::showHexData() -{ - const QModelIndex idx = m_telegramProxyModel->mapToSource(m_logTelegramView->currentIndex()); - QSharedPointer tele = m_telegramModel->telegram(idx.row()); - if (!tele) - return; - - LogViewTelegramDialog* showTelegramDialog = new LogViewTelegramDialog(this, true); - showTelegramDialog->showDataDump(tele, false); -} - -// --------------------------------------------------------------- -void LogViewGui::exportAsCsv() -{ - const int idx = m_ActualLogfile.lastIndexOf(QLatin1Char('.')); - const QString suggestion = m_ActualLogfile.left(idx) + QLatin1String(".csv"); - const QString fn = QFileDialog::getSaveFileName(this, tr("Export logdata as CSV"), suggestion, tr("CSV file (*.csv)")); - if (fn.isEmpty()) - return; - QFile f(fn); - if (!f.open(QIODevice::WriteOnly)) - return; - for (int c = 0; c < m_telegramProxyModel->columnCount(); ++c) - { - f.write(m_telegramProxyModel->headerData(c, Qt::Horizontal).toString().toUtf8()); - f.write(";"); - } - f.write("ISSI\n"); - const int rc = m_telegramProxyModel->rowCount(); - for (int r = 0; r < rc; ++r) - { - QSharedPointer tele = m_telegramProxyModel->telegram(r); - if (!tele) - continue; - f.write(QByteArray::number(tele->getDestination())); - f.write(";"); - f.write(tele->getName().toUtf8()); - f.write(";"); - f.write(QByteArray::number(tele->getParticipantId())); - f.write(";"); - f.write(QByteArray::number(tele->getLogTimeMsec())); - f.write(";"); - f.write(QByteArray::number(tele->getGpsTime())); - f.write(";"); - f.write(QByteArray::number(tele->getDelay())); - f.write(";"); - f.write(QByteArray::number(tele->getISSI())); - f.write("\n"); - } - f.close(); -}// --------------------------------------------------------------- - -void LogViewGui::exportAsJson() -{ - const int idx = m_ActualLogfile.lastIndexOf(QLatin1Char('.')); - const QString suggestion = m_ActualLogfile.left(idx) + QLatin1String(".csv"); - const QString fn = QFileDialog::getSaveFileName(this, tr("Export logdata as Json"), suggestion, tr("JSon file (*.json)")); - if (fn.isEmpty()) - return; - QFile f(fn); - if (!f.open(QIODevice::WriteOnly)) - return; - QJsonArray arr; - const int rc = m_telegramProxyModel->rowCount(); - for (int r = 0; r < rc; ++r) - { - QSharedPointer tele = m_telegramProxyModel->telegram(r); - if (!tele) - continue; - if (tele->jsonData().isEmpty()) - continue; - arr += tele->jsonData(); - } - f.write(QJsonDocument(arr).toJson(QJsonDocument::Indented)); - f.close(); -} - -// --------------------------------------------------------------- -void LogViewGui::onStartLogReplay() -{ -#ifndef LTS_DEBUG - return; -#endif - if (m_replayTimer->isActive()) - { - m_replayTimer->stop(); - return; - } - m_reloadAction->setChecked(false); - m_PosCentralTelCheckBox->setChecked(true); - if (!m_EditTelegramController || !m_EditTelegramController->isInjectionPossible()) - return; - m_currentReplayRow = m_telegramProxyModel->mapToSource(m_logTelegramView->currentIndex()).row(); - if (m_currentReplayRow < 0) - return; - m_replayTimer->start(0); -} - -void LogViewGui::onReplayTimerTimeout() -{ - auto findNextCentralTelegram = [&]() - { - static constexpr auto sendToCentralBits = N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral | - N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend; - auto tele = m_telegramModel->telegram(m_currentReplayRow); - while (tele && (tele->getDestination() != sendToCentralBits || - tele->getTelId() == GEF_BESTAETIGUNG)) - tele = m_telegramModel->telegram(++m_currentReplayRow); - return tele; - }; - - QSharedPointer tele = findNextCentralTelegram(); - auto checkTele = [&]() - { - if (!tele) + // splitter between toolbox and log-telegram-list + m_Splitter = new QSplitter(Qt::Horizontal, this); + m_Splitter->addWidget(m_ToolBox); + m_Splitter->addWidget(telegramGroup); + const QList splitterSizesAsVariant = settings.value(SPLITTPOS).toList(); + QList splitterSizes; + splitterSizes.reserve(splitterSizesAsVariant.size()); + if (splitterSizesAsVariant.isEmpty()) { - m_replayTimer->stop(); - m_currentReplayRow = -1; - QMessageBox::information(this, tr("Sending finished"), tr("No more telegrams to send - stopping")); - return false; - } - return true; - }; - - if (!checkTele()) - return; - const uint64_t curSendTime = tele->getLogTimeMsec(); - auto teleCopy = QSharedPointer(new LogViewTelegram(*(tele.data()))); - teleCopy->actualizeGpsTime(); - m_InjectionThread->sendTelegram(teleCopy.data(), true); - ++m_currentReplayRow; - tele = findNextCentralTelegram(); - if (!checkTele()) - return; - - uint64_t nextSendTime = (tele->getLogTimeMsec() - curSendTime); // micro -> milli - DEBUG_LOG(m_logger) << "Next SendTime: " << nextSendTime - << ", telId: " << tele->getTelId() - << ", next row: " << m_currentReplayRow - << ", equipNo: " << tele->getParticipantId(); - QModelIndex idx = m_telegramModel->index(m_currentReplayRow, 0, QModelIndex()); - m_logTelegramView->setCurrentIndex(m_telegramProxyModel->mapFromSource(idx)); - m_replayTimer->start(nextSendTime); -} - -// --------------------------------------------------------------- -void LogViewGui::loadSpecificationFiles() -{ - QSettings settings; - settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); - - // load central-protocol spezification - QString defString = QCoreApplication::applicationDirPath() + QLatin1String("/training_area_telegrams.h"); - QString filename = settings.value(LogViewOptionDialog::P0_FILENAME, defString).toString(); - INFO_LOG(m_logger) << "Load central-protocol spezification-file: " << filename.toStdString(); - if (!QFile::exists(filename)) - { - QMessageBox::warning(this, tr("LogView"), tr("Die Spezifikations-Datei \'%1\' fuer Zentral-Telegramme existiert nicht!

Werde die Default-Datei verwenden...").arg(filename)); - filename = defString; - } - LogViewTelegram::jsonParser()->parse(filename); - - // load tetra-protocol spezification - defString = QCoreApplication::applicationDirPath() + QLatin1String("/zsksxd_tetraForLogView.x"); - filename = settings.value(LogViewOptionDialog::P5_FILENAME, defString).toString(); - INFO_LOG(m_logger) << "Load tetra-protocol spezification-file: " << filename.toStdString(); - if (!QFile::exists(filename)) - { - QMessageBox::warning(this, tr("LogView"), tr("Die Spezifikations-Datei \'%1\' fuer TETRA-Telegramme existiert nicht!

Werde die Default-Datei verwenden...").arg(filename)); - filename = defString; - } - - LogViewTelegram::tetraParser()->parseX_File(filename); - - INFO_LOG(m_logger) << "Browse telegram-log-file"; - newTelegramFile(); -} - - -// --------------------------------------------------------------- -void LogViewGui::newTelegramFile() -{ - if (m_TailTimer) m_TailTimer->stop(); - // delete all participants - m_participantModel->clearParticipants(); - m_telegramModel->clearTelegrams(); - m_participantListTelCount.clear(); - m_participantListIssi.clear(); - m_ParticipantStatus->setText(tr("0 Teilnehmer")); - // load a telegram-file - loadTelegramFile(); -} - - -// --------------------------------------------------------------- -void LogViewGui::loadTelegramFile() -{ - const QLatin1String DIR("Dir"); - QSettings settings; - settings.beginGroup(QLatin1String("LogFiles")); - - QString filename = QFileDialog::getOpenFileName(this, tr("Bitte eine Log-Datei auswaehlen"), settings.value(DIR).toString(), LogViewOptionDialog::KRLOG_FILES/*tr("Log-Dateien (*.krlog)")*/); - if (filename.isEmpty()) - return; - - QDir dir; - settings.setValue(DIR, dir.filePath(filename)); - - readTelegramsFromLogFile(filename); - showTelegramTable(); - startInjectionThread(); - m_logTelegramView->resizeColumnsToContents(); - m_ParticipantTableView->resizeColumnsToContents(); - - // start the time for checking whether new entries were added to the log-file - if (!m_TailTimer) - m_TailTimer = new QTimer(this); - connect(m_TailTimer, &QTimer::timeout, this, &LogViewGui::updateLogfile, Qt::QueuedConnection); - m_TailTimer->setInterval(1000); - m_TailTimer->start(); -} - - -// --------------------------------------------------------------- -// Checks whether the size of actual logfile has changed. If -// yes, the new log-entries will be read and shown within -// table. -// --------------------------------------------------------------- -void LogViewGui::updateLogfile() -{ - if(!m_DoReload) - return; - m_TailTimer->stop(); - QFileInfo fileInfo = QFileInfo(m_ActualLogfile); - if (fileInfo.exists()) - { - if (fileInfo.size() > m_LogfileSize) - { - try - { - readTelegramsFromLogFile(m_ActualLogfile, m_LogfileSize); - } - catch (const std::exception& e) - { - WARNING_LOG(m_logger) << "Error: " << e.what(); - // simply read the telegram in the next update - } + splitterSizes << 235 << 1000; } else { - //check if one newer file exists and load it - QString dateFromFile; - const QString format = QStringLiteral("yyMMdd_hh"); - for (int iterator = fileInfo.baseName().size() - format.size(); iterator < fileInfo.baseName().size(); ++iterator) - dateFromFile.append(fileInfo.baseName().at(iterator)); + for (const QVariant &item : splitterSizesAsVariant) + splitterSizes << item.toInt(); + } + m_Splitter->setSizes(splitterSizes); + setCentralWidget(m_Splitter); - QDateTime nextDateCalc = QDateTime::fromString(dateFromFile, format); - nextDateCalc = nextDateCalc.addYears(100); - nextDateCalc = nextDateCalc.addSecs(3600); - QString nextDate = nextDateCalc.toString(format); - nextDateCalc = nextDateCalc.addSecs(3600); - QString checkDate = nextDateCalc.toString(format); + // initialize the telegram-filters (this should be done before load of telegrams, otherwise the telegram-list + // will be shown several times and this could be slow when the telegram-list is slow) + m_CentralSelectionGroup->setChecked(true); + m_ackCentralTelCheckBox->setChecked(true); + m_ackCentralTelCheckBox->setChecked(false); + m_PosCentralTelCheckBox->setChecked(true); + m_PosCentralTelCheckBox->setChecked(false); + m_SentCentralTelCheckBox->setChecked(true); + m_ReceivedCentralTelCheckBox->setChecked(true); - QString filePath(fileInfo.absolutePath() + QLatin1Char('/')); - const QString baseName = fileInfo.baseName(); - const QVector parts = baseName.split(QLatin1Char('_')); + m_TetraSelectionGroup->setChecked(true); + m_SentTetraTelCheckBox->setChecked(true); + m_ReceivedTetraTelCheckBox->setChecked(true); + m_PosTetraTelCheckBox->setChecked(true); + m_PosTetraTelCheckBox->setChecked(false); + m_FragmentedTetraTelCheckBox->setChecked(true); + m_LoginTetraTelCheckBox->setChecked(true); + m_RegisterTetraTelCheckBox->setChecked(true); + m_ReportTetraTelCheckBox->setChecked(false); + m_AirInterfaceLoadTetraTelCheckBox->setChecked(false); - for (int iterator = 0; iterator < parts.size() - 2; ++iterator) - filePath += parts.at(iterator) + QLatin1Char('_'); + m_WlsSelectionGroup->setChecked(true); + m_PosWlsTelCheckBox->setChecked(true); + m_PosWlsTelCheckBox->setChecked(false); + m_SentWlsTelCheckBox->setChecked(true); + m_ReceivedWlsTelCheckBox->setChecked(true); - QString nextFile(filePath + nextDate + QLatin1Char('.') + fileInfo.completeSuffix()); - QString checkFile(filePath + checkDate + QLatin1Char('.') + fileInfo.completeSuffix()); + // set the size and position of main-window + QSize size = settings.value(SIZE, sizeHint()).toSize(); + resize(size.isNull() ? QSize(1280, 768) : size); + move(settings.value(POS, QPoint(0, 0)).toPoint()); + settings.endGroup(); - QFileInfo infoNextFile(nextFile); - QFileInfo infoCheckFile(checkFile); - if (infoNextFile.exists() && infoNextFile.isFile() && !infoCheckFile.exists()) - { - m_LogfileSize = 0; - readTelegramsFromLogFile(nextFile, m_LogfileSize); - } + connect(m_replayTimer, &QTimer::timeout, this, &LogViewGui::onReplayTimerTimeout); + + QTimer::singleShot(0, this, &LogViewGui::loadSpecificationFiles); + + startInjectionThread(); + } + + void LogViewGui::createCentralSelectionWidget() + { + // send-checkbox + m_SentCentralTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/P2C.png")); + // received-checkbox + m_ReceivedCentralTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/C2P.png")); + // pos-checkbox + m_PosCentralTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/CentralPos.png")); + // ack-checkbox + m_ackCentralTelCheckBox = createRadioButton(tr("&Bestaetigungstelegramme"), QLatin1String(":/image/CentralAck.png")); + + QVBoxLayout *centralFilterBox = new QVBoxLayout; + centralFilterBox->addWidget(m_SentCentralTelCheckBox); + centralFilterBox->addWidget(m_ReceivedCentralTelCheckBox); + centralFilterBox->addWidget(m_PosCentralTelCheckBox); + centralFilterBox->addWidget(m_ackCentralTelCheckBox); + centralFilterBox->addStretch(1); + + m_CentralSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); + m_CentralSelectionGroup->setCheckable(true); + m_CentralSelectionGroup->setChecked(false); + m_CentralSelectionGroup->setLayout(centralFilterBox); + connect(m_CentralSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); + } + + void LogViewGui::createTetraSelectionWidget() + { + // sent-checkbox + m_SentTetraTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/T2P.png")); + // received-checkbox + m_ReceivedTetraTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/P2T.png")); + // pos-checkbox + m_PosTetraTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/TetraPos.png")); + // fragmented-checkbox + m_FragmentedTetraTelCheckBox = createRadioButton(tr("&Fragmentierte Meldungen"), QLatin1String(":/image/TetraFragmented.png")); + // login-checkbox + m_LoginTetraTelCheckBox = createRadioButton(tr("&Loginmeldungen"), QLatin1String(":/image/TetraLogin.png")); + // register-checkbox + m_RegisterTetraTelCheckBox = createRadioButton(tr("&Registermeldungen"), QLatin1String(":/image/TetraRegister.png")); + // report-checkbox + m_ReportTetraTelCheckBox = createRadioButton(tr("&Reportmeldungen"), QLatin1String(":/image/TetraReport.png")); + // air-interface-load-checkbox + m_AirInterfaceLoadTetraTelCheckBox = createRadioButton(tr("&Air-Load Meldungen"), QLatin1String(":/image/TetraAirInterface.png")); + + QVBoxLayout *tetraFilterBox = new QVBoxLayout; + tetraFilterBox->addWidget(m_SentTetraTelCheckBox); + tetraFilterBox->addWidget(m_ReceivedTetraTelCheckBox); + tetraFilterBox->addWidget(m_PosTetraTelCheckBox); + tetraFilterBox->addWidget(m_FragmentedTetraTelCheckBox); + tetraFilterBox->addWidget(m_LoginTetraTelCheckBox); + tetraFilterBox->addWidget(m_RegisterTetraTelCheckBox); + tetraFilterBox->addWidget(m_ReportTetraTelCheckBox); + tetraFilterBox->addWidget(m_AirInterfaceLoadTetraTelCheckBox); + tetraFilterBox->addStretch(1); + + m_TetraSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); + m_TetraSelectionGroup->setCheckable(true); + m_TetraSelectionGroup->setChecked(false); + m_TetraSelectionGroup->setLayout(tetraFilterBox); + connect(m_TetraSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); + } + + void LogViewGui::createWlsSelectionWidget() + { + // send-checkbox + m_SentWlsTelCheckBox = createRadioButton(tr("&gesendete Telegramme"), QLatin1String(":/image/P2W.png")); + // received-checkbox + m_ReceivedWlsTelCheckBox = createRadioButton(tr("&empfangene Telegramme"), QLatin1String(":/image/W2P.png")); + // pos-checkbox + m_PosWlsTelCheckBox = createRadioButton(tr("&Positionsmeldungen"), QLatin1String(":/image/WlsPos.png")); + + QVBoxLayout *wlsFilterBox = new QVBoxLayout; + wlsFilterBox->addWidget(m_SentWlsTelCheckBox); + wlsFilterBox->addWidget(m_ReceivedWlsTelCheckBox); + wlsFilterBox->addWidget(m_PosWlsTelCheckBox); + wlsFilterBox->addStretch(1); + + m_WlsSelectionGroup = new QGroupBox(tr("Telegramme anzeigen"), this); + m_WlsSelectionGroup->setCheckable(true); + m_WlsSelectionGroup->setChecked(false); + m_WlsSelectionGroup->setLayout(wlsFilterBox); + connect(m_WlsSelectionGroup, &QGroupBox::toggled, this, &LogViewGui::showTelegramTable); + } + + + // --------------------------------------------------------------- + void LogViewGui::customMenuRequested(const QPoint &pos) + { + //create Menu with Actions + QMenu menu(this); + menu.addAction(tr("Add Telegram to EditList"), this, &LogViewGui::addTelegramToEdit); + menu.addAction(tr("Show HexData"), this, &LogViewGui::showHexData); + menu.addAction(tr("Export as CSV file"), this, &LogViewGui::exportAsCsv); + menu.addAction(tr("Export as JSon file"), this, &LogViewGui::exportAsJson); +#ifdef LTS_DEBUG + if (m_EditTelegramController && m_EditTelegramController->isInjectionPossible()) + { + const QString str = m_replayTimer->isActive() ? tr("Stop replay") : tr("Start Replay from here"); + menu.addAction(str, this, &LogViewGui::onStartLogReplay); + } +#endif + menu.exec(m_logTelegramView->viewport()->mapToGlobal(pos)); + } + + + // --------------------------------------------------------------- + void LogViewGui::addTelegramToEdit() + { + for (const QModelIndex &orig : m_logTelegramView->selectionModel()->selectedRows()) + { + const QModelIndex idx = m_telegramProxyModel->mapToSource(orig); + QSharedPointer tele = m_telegramModel->telegram(idx.row()); + if (!tele) + continue; + m_EditTelegramController->appendTelegram(tele); } } - m_TailTimer->start(); -} -// --------------------------------------------------------------- -void LogViewGui::readTelegramsFromLogFile(const QString& a_fileName, const qint64 a_filePos) -{ - // open the log-file - QFile telegramFile(a_fileName); - if (telegramFile.open(QIODevice::ReadOnly)) + // --------------------------------------------------------------- + void LogViewGui::showHexData() { - m_ActualLogfile = a_fileName; - telegramFile.seek(a_filePos); - setWindowTitle(QFileInfo(m_ActualLogfile).baseName()); - m_logTelegramView->blockSignals(true); - m_logTelegramView->setUpdatesEnabled(false); - QVector > newTelegrams; - // read the header of telegram-entry - N_CoPrtCnv::CoPrtCnvLogHeader lh; - while (true) + const QModelIndex idx = m_telegramProxyModel->mapToSource(m_logTelegramView->currentIndex()); + QSharedPointer tele = m_telegramModel->telegram(idx.row()); + if (!tele) + return; + + LogViewTelegramDialog *showTelegramDialog = new LogViewTelegramDialog(this, true); + showTelegramDialog->showDataDump(tele, false); + } + + // --------------------------------------------------------------- + void LogViewGui::exportAsCsv() + { + const int idx = m_ActualLogfile.lastIndexOf(QLatin1Char('.')); + const QString suggestion = m_ActualLogfile.left(idx) + QLatin1String(".csv"); + const QString fn = QFileDialog::getSaveFileName(this, tr("Export logdata as CSV"), suggestion, tr("CSV file (*.csv)")); + if (fn.isEmpty()) + return; + QFile f(fn); + if (!f.open(QIODevice::WriteOnly)) + return; + for (int c = 0; c < m_telegramProxyModel->columnCount(); ++c) { - if (sizeof(lh) == telegramFile.read((char*)&lh, sizeof(lh))) + f.write(m_telegramProxyModel->headerData(c, Qt::Horizontal).toString().toUtf8()); + f.write(";"); + } + f.write("ISSI\n"); + const int rc = m_telegramProxyModel->rowCount(); + for (int r = 0; r < rc; ++r) + { + QSharedPointer tele = m_telegramProxyModel->telegram(r); + if (!tele) + continue; + f.write(QByteArray::number(tele->getDestination())); + f.write(";"); + f.write(tele->getName().toUtf8()); + f.write(";"); + f.write(QByteArray::number(tele->getParticipantId())); + f.write(";"); + f.write(QByteArray::number(tele->getLogTimeMsec())); + f.write(";"); + f.write(QByteArray::number(tele->getGpsTime())); + f.write(";"); + f.write(QByteArray::number(tele->getDelay())); + f.write(";"); + f.write(QByteArray::number(tele->getISSI())); + f.write("\n"); + } + f.close(); + } // --------------------------------------------------------------- + + void LogViewGui::exportAsJson() + { + const int idx = m_ActualLogfile.lastIndexOf(QLatin1Char('.')); + const QString suggestion = m_ActualLogfile.left(idx) + QLatin1String(".csv"); + const QString fn = QFileDialog::getSaveFileName(this, tr("Export logdata as Json"), suggestion, tr("JSon file (*.json)")); + if (fn.isEmpty()) + return; + QFile f(fn); + if (!f.open(QIODevice::WriteOnly)) + return; + QJsonArray arr; + const int rc = m_telegramProxyModel->rowCount(); + for (int r = 0; r < rc; ++r) + { + QSharedPointer tele = m_telegramProxyModel->telegram(r); + if (!tele) + continue; + if (tele->jsonData().isEmpty()) + continue; + arr += tele->jsonData(); + } + f.write(QJsonDocument(arr).toJson(QJsonDocument::Indented)); + f.close(); + } + + // --------------------------------------------------------------- + void LogViewGui::onStartLogReplay() + { +#ifndef LTS_DEBUG + return; +#endif + if (m_replayTimer->isActive()) + { + m_replayTimer->stop(); + return; + } + m_reloadAction->setChecked(false); + m_PosCentralTelCheckBox->setChecked(true); + if (!m_EditTelegramController || !m_EditTelegramController->isInjectionPossible()) + return; + m_currentReplayRow = m_telegramProxyModel->mapToSource(m_logTelegramView->currentIndex()).row(); + if (m_currentReplayRow < 0) + return; + m_replayTimer->start(0); + } + + void LogViewGui::onReplayTimerTimeout() + { + auto findNextCentralTelegram = [&]() + { + static constexpr auto sendToCentralBits = N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral | N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend; + auto tele = m_telegramModel->telegram(m_currentReplayRow); + while (tele && (tele->getDestination() != sendToCentralBits || tele->getTelId() == GEF_BESTAETIGUNG)) + tele = m_telegramModel->telegram(++m_currentReplayRow); + return tele; + }; + + QSharedPointer tele = findNextCentralTelegram(); + auto checkTele = [&]() + { + if (!tele) { - if (lh.m_Version == 3 || lh.m_Version == 4) + m_replayTimer->stop(); + m_currentReplayRow = -1; + QMessageBox::information(this, tr("Sending finished"), tr("No more telegrams to send - stopping")); + return false; + } + return true; + }; + + if (!checkTele()) + return; + const uint64_t curSendTime = tele->getLogTimeMsec(); + auto teleCopy = QSharedPointer(new LogViewTelegram(*(tele.data()))); + teleCopy->actualizeGpsTime(); + m_InjectionThread->sendTelegram(teleCopy.data(), true); + ++m_currentReplayRow; + tele = findNextCentralTelegram(); + if (!checkTele()) + return; + + uint64_t nextSendTime = (tele->getLogTimeMsec() - curSendTime); // micro -> milli + DEBUG_LOG(m_logger) << "Next SendTime: " << nextSendTime << ", telId: " << tele->getTelId() << ", next row: " << m_currentReplayRow + << ", equipNo: " << tele->getParticipantId(); + QModelIndex idx = m_telegramModel->index(m_currentReplayRow, 0, QModelIndex()); + m_logTelegramView->setCurrentIndex(m_telegramProxyModel->mapFromSource(idx)); + m_replayTimer->start(nextSendTime); + } + + // --------------------------------------------------------------- + void LogViewGui::loadSpecificationFiles() + { + QSettings settings; + settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); + + // load central-protocol spezification + QString defString = QCoreApplication::applicationDirPath() + QLatin1String("/training_area_telegrams.h"); + QString filename = settings.value(LogViewOptionDialog::P0_FILENAME, defString).toString(); + INFO_LOG(m_logger) << "Load central-protocol spezification-file: " << filename.toStdString(); + if (!QFile::exists(filename)) + { + QMessageBox::warning(this, + tr("LogView"), + tr("Die Spezifikations-Datei \'%1\' fuer Zentral-Telegramme existiert nicht!

Werde die Default-Datei verwenden...").arg(filename)); + filename = defString; + } + LogViewTelegram::jsonParser()->parse(filename); + + // load tetra-protocol spezification + defString = QCoreApplication::applicationDirPath() + QLatin1String("/zsksxd_tetraForLogView.x"); + filename = settings.value(LogViewOptionDialog::P5_FILENAME, defString).toString(); + INFO_LOG(m_logger) << "Load tetra-protocol spezification-file: " << filename.toStdString(); + if (!QFile::exists(filename)) + { + QMessageBox::warning(this, + tr("LogView"), + tr("Die Spezifikations-Datei \'%1\' fuer TETRA-Telegramme existiert nicht!

Werde die Default-Datei verwenden...").arg(filename)); + filename = defString; + } + + LogViewTelegram::tetraParser()->parseX_File(filename); + + INFO_LOG(m_logger) << "Browse telegram-log-file"; + newTelegramFile(); + } + + + // --------------------------------------------------------------- + void LogViewGui::newTelegramFile() + { + if (m_TailTimer) + m_TailTimer->stop(); + // delete all participants + m_participantModel->clearParticipants(); + m_telegramModel->clearTelegrams(); + m_participantListTelCount.clear(); + m_participantListIssi.clear(); + m_ParticipantStatus->setText(tr("0 Teilnehmer")); + // load a telegram-file + loadTelegramFile(); + } + + + // --------------------------------------------------------------- + void LogViewGui::loadTelegramFile() + { + const QLatin1String DIR("Dir"); + QSettings settings; + settings.beginGroup(QLatin1String("LogFiles")); + + QString filename = QFileDialog::getOpenFileName(this, + tr("Bitte eine Log-Datei auswaehlen"), + settings.value(DIR).toString(), + LogViewOptionDialog::KRLOG_FILES /*tr("Log-Dateien (*.krlog)")*/); + if (filename.isEmpty()) + return; + + QDir dir; + settings.setValue(DIR, dir.filePath(filename)); + + readTelegramsFromLogFile(filename); + showTelegramTable(); + startInjectionThread(); + m_logTelegramView->resizeColumnsToContents(); + m_ParticipantTableView->resizeColumnsToContents(); + + // start the time for checking whether new entries were added to the log-file + if (!m_TailTimer) + m_TailTimer = new QTimer(this); + connect(m_TailTimer, &QTimer::timeout, this, &LogViewGui::updateLogfile, Qt::QueuedConnection); + m_TailTimer->setInterval(1000); + m_TailTimer->start(); + } + + + // --------------------------------------------------------------- + // Checks whether the size of actual logfile has changed. If + // yes, the new log-entries will be read and shown within + // table. + // --------------------------------------------------------------- + void LogViewGui::updateLogfile() + { + if (!m_DoReload) + return; + m_TailTimer->stop(); + QFileInfo fileInfo = QFileInfo(m_ActualLogfile); + if (fileInfo.exists()) + { + if (fileInfo.size() > m_LogfileSize) + { + try { - // read the telegram itself - qint64 telegramLength = lh.m_Length - sizeof(lh); - QByteArray buf(telegramLength, Qt::Uninitialized); - if (telegramLength == telegramFile.read(buf.data(), telegramLength)) - { - m_LogfileSize = telegramFile.pos(); - - if (lh.m_Version == 4) - buf = qUncompress(buf); - - // add the telegram to telegram-list - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol protocol = - static_cast(lh.m_Protocol); - QSharedPointer telegram(new LogViewTelegram(protocol, lh.m_Time, buf)); - // this checks the telegram and raises a messagebox if the telegram is wrong - if (!telegram->isValid()) - { - ERROR_LOG(m_logger) << "Trying to read/parse unknown data from logfile '" << a_fileName - << "' at position " << telegramFile.pos() - (telegramLength + sizeof(lh)); - continue; - } - newTelegrams.push_back(telegram); - - // add the pariticipant to the participant-list - addToParticipantList(telegram); - } + readTelegramsFromLogFile(m_ActualLogfile, m_LogfileSize); } - else + catch (const std::exception &e) { - QMessageBox::warning(this, tr("Falsche Version"), tr("LogViewer kann Telegramm-Logs der Version %1 nicht einlesen").arg(lh.m_Version)); - ERROR_LOG(m_logger) << "Trying to read/parse unknown data from logfile '" << a_fileName - << "' at position " << telegramFile.pos() - sizeof(lh); + WARNING_LOG(m_logger) << "Error: " << e.what(); + // simply read the telegram in the next update } } else { - break; + //check if one newer file exists and load it + QString dateFromFile; + const QString format = QStringLiteral("yyMMdd_hh"); + for (int iterator = fileInfo.baseName().size() - format.size(); iterator < fileInfo.baseName().size(); ++iterator) + dateFromFile.append(fileInfo.baseName().at(iterator)); + + QDateTime nextDateCalc = QDateTime::fromString(dateFromFile, format); + nextDateCalc = nextDateCalc.addYears(100); + nextDateCalc = nextDateCalc.addSecs(3600); + QString nextDate = nextDateCalc.toString(format); + nextDateCalc = nextDateCalc.addSecs(3600); + QString checkDate = nextDateCalc.toString(format); + + QString filePath(fileInfo.absolutePath() + QLatin1Char('/')); + const QString baseName = fileInfo.baseName(); + const QVector parts = baseName.split(QLatin1Char('_')); + + for (int iterator = 0; iterator < parts.size() - 2; ++iterator) + filePath += parts.at(iterator) + QLatin1Char('_'); + + QString nextFile(filePath + nextDate + QLatin1Char('.') + fileInfo.completeSuffix()); + QString checkFile(filePath + checkDate + QLatin1Char('.') + fileInfo.completeSuffix()); + + QFileInfo infoNextFile(nextFile); + QFileInfo infoCheckFile(checkFile); + if (infoNextFile.exists() && infoNextFile.isFile() && !infoCheckFile.exists()) + { + m_LogfileSize = 0; + readTelegramsFromLogFile(nextFile, m_LogfileSize); + } } } - syncParticipantList(); - - m_telegramModel->appendTelegrams(newTelegrams); - m_ParticipantStatus->setText(tr("%1 Teilnehmer").arg(m_participantModel->rowCount())); - m_logTelegramView->setUpdatesEnabled(true); - m_logTelegramView->blockSignals(false); - - statusBar()->showMessage(tr("%1 Telegramme eingelesen").arg(m_telegramModel->rowCount())); + m_TailTimer->start(); } - else + + + // --------------------------------------------------------------- + void LogViewGui::readTelegramsFromLogFile(const QString &a_fileName, const qint64 a_filePos) { - QMessageBox::warning(this, tr("Dateifehler"), tr("Konnte die Datei %1 nicht oeffnen").arg(a_fileName)); + // open the log-file + QFile telegramFile(a_fileName); + if (telegramFile.open(QIODevice::ReadOnly)) + { + m_ActualLogfile = a_fileName; + telegramFile.seek(a_filePos); + setWindowTitle(QFileInfo(m_ActualLogfile).baseName()); + m_logTelegramView->blockSignals(true); + m_logTelegramView->setUpdatesEnabled(false); + QVector> newTelegrams; + // read the header of telegram-entry + N_CoPrtCnv::CoPrtCnvLogHeader lh; + while (true) + { + if (sizeof(lh) == telegramFile.read((char *)&lh, sizeof(lh))) + { + if (lh.m_Version == 3 || lh.m_Version == 4) + { + // read the telegram itself + qint64 telegramLength = lh.m_Length - sizeof(lh); + QByteArray buf(telegramLength, Qt::Uninitialized); + if (telegramLength == telegramFile.read(buf.data(), telegramLength)) + { + m_LogfileSize = telegramFile.pos(); + + if (lh.m_Version == 4) + buf = qUncompress(buf); + + // add the telegram to telegram-list + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol protocol = static_cast(lh.m_Protocol); + QSharedPointer telegram(new LogViewTelegram(protocol, lh.m_Time, buf)); + // this checks the telegram and raises a messagebox if the telegram is wrong + if (!telegram->isValid()) + { + ERROR_LOG(m_logger) << "Trying to read/parse unknown data from logfile '" << a_fileName << "' at position " + << telegramFile.pos() - (telegramLength + sizeof(lh)); + continue; + } + newTelegrams.push_back(telegram); + + // add the pariticipant to the participant-list + addToParticipantList(telegram); + } + } + else + { + QMessageBox::warning(this, tr("Falsche Version"), tr("LogViewer kann Telegramm-Logs der Version %1 nicht einlesen").arg(lh.m_Version)); + ERROR_LOG(m_logger) << "Trying to read/parse unknown data from logfile '" << a_fileName << "' at position " << telegramFile.pos() - sizeof(lh); + } + } + else + { + break; + } + } + syncParticipantList(); + + m_telegramModel->appendTelegrams(newTelegrams); + m_ParticipantStatus->setText(tr("%1 Teilnehmer").arg(m_participantModel->rowCount())); + m_logTelegramView->setUpdatesEnabled(true); + m_logTelegramView->blockSignals(false); + + statusBar()->showMessage(tr("%1 Telegramme eingelesen").arg(m_telegramModel->rowCount())); + } + else + { + QMessageBox::warning(this, tr("Dateifehler"), tr("Konnte die Datei %1 nicht oeffnen").arg(a_fileName)); + } + telegramFile.close(); } - telegramFile.close(); -} -// --------------------------------------------------------------- -void LogViewGui::selectedParticipantChanged() -{ - std::set selectedParticipantIds; - - const QModelIndexList selectedParticipants = m_ParticipantTableView->selectionModel()->selectedRows(0); - for (const QModelIndex &participantIdx : selectedParticipants) + // --------------------------------------------------------------- + void LogViewGui::selectedParticipantChanged() { - // row 0 -> eqId - const QModelIndex idx = m_participantProxyModel->mapToSource(participantIdx); - selectedParticipantIds.insert(m_participantModel->data(idx).toInt()); - } - m_telegramProxyModel->setAllowedEquipmentIds(selectedParticipantIds); - showTelegramTable(); -} + std::set selectedParticipantIds; -static void updateFilteredPosTelegramIds(std::set &teleIds, bool bEnable) -{ - if (bEnable) + const QModelIndexList selectedParticipants = m_ParticipantTableView->selectionModel()->selectedRows(0); + for (const QModelIndex &participantIdx : selectedParticipants) + { + // row 0 -> eqId + const QModelIndex idx = m_participantProxyModel->mapToSource(participantIdx); + selectedParticipantIds.insert(m_participantModel->data(idx).toInt()); + } + m_telegramProxyModel->setAllowedEquipmentIds(selectedParticipantIds); + showTelegramTable(); + } + + static void updateFilteredPosTelegramIds(std::set &teleIds, bool bEnable) { - teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG); - teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_LFZ); - teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_MIT_TEILNEHMER); - teleIds.erase(TrainingAreaBase::TetraIcd::IPS_POSITIONSDATEN); + if (bEnable) + { + teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG); + teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_LFZ); + teleIds.erase(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_MIT_TEILNEHMER); + teleIds.erase(TrainingAreaBase::TetraIcd::IPS_POSITIONSDATEN); + } + else + { + teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG); + teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_LFZ); + teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_MIT_TEILNEHMER); + teleIds.insert(TrainingAreaBase::TetraIcd::IPS_POSITIONSDATEN); + } } - else + + // --------------------------------------------------------------- + void LogViewGui::showTelegramTable() { - teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG); - teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_LFZ); - teleIds.insert(TrainingAreaBase::TetraIcd::POSITIONS_MELDUNG_MIT_TEILNEHMER); - teleIds.insert(TrainingAreaBase::TetraIcd::IPS_POSITIONSDATEN); + updateFilteredPosTelegramIds(m_CentralTelegramFilterList, m_PosCentralTelCheckBox->isChecked()); + updateFilteredPosTelegramIds(m_TetraTelegramFilterList, m_PosTetraTelCheckBox->isChecked()); + updateFilteredPosTelegramIds(m_WlsTelegramFilterList, m_PosWlsTelCheckBox->isChecked()); + if (m_ackCentralTelCheckBox->isChecked()) + m_CentralTelegramFilterList.erase(TrainingAreaBase::TetraIcd::BESTAETIGUNG); + else + m_CentralTelegramFilterList.insert(TrainingAreaBase::TetraIcd::BESTAETIGUNG); + m_telegramProxyModel->setFilteredCentralTelegramIds(m_CentralTelegramFilterList); + m_telegramProxyModel->setFilteredTetraTelegramIds(m_TetraTelegramFilterList); + m_telegramProxyModel->setFilteredWlsTelegramIds(m_WlsTelegramFilterList); + + m_telegramProxyModel->setFilterByEquipmentIds(m_ParticipantSelectionGroup->isChecked()); + + m_PosCentralTelCheckBox->setEnabled(m_SentCentralTelCheckBox->isChecked() && m_CentralSelectionGroup->isChecked()); + m_PosTetraTelCheckBox->setEnabled(m_SentTetraTelCheckBox->isChecked() && m_TetraSelectionGroup->isChecked()); + m_PosWlsTelCheckBox->setEnabled(m_ReceivedWlsTelCheckBox->isChecked() && m_WlsSelectionGroup->isChecked()); + + const bool bShowCentralTelegrams = m_CentralSelectionGroup->isChecked(); + m_telegramProxyModel->setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, !m_SentCentralTelCheckBox->isChecked() || !bShowCentralTelegrams); + m_telegramProxyModel->setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, !m_ReceivedCentralTelCheckBox->isChecked() || !bShowCentralTelegrams); + + const bool bShowTetraTelegrams = m_TetraSelectionGroup->isChecked(); + m_telegramProxyModel->setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, !m_SentTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, !m_ReceivedTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd, !m_RegisterTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp, !m_RegisterTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq, !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq, !m_ReportTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq, + !m_AirInterfaceLoadTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirLoadHyterra, + !m_AirInterfaceLoadTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraLogin(!m_LoginTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + m_telegramProxyModel->setFilterTetraFragmented(!m_FragmentedTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); + + const bool bShowWlsTelegrams = m_WlsSelectionGroup->isChecked(); + m_telegramProxyModel->setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, !m_SentWlsTelCheckBox->isChecked() || !bShowWlsTelegrams); + m_telegramProxyModel->setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, !m_ReceivedWlsTelCheckBox->isChecked() || !bShowWlsTelegrams); + + m_TelegramStatus->setText(tr("%1 telegrams (unfiltered: %2)").arg(m_telegramProxyModel->rowCount()).arg(m_telegramModel->rowCount())); } -} - -// --------------------------------------------------------------- -void LogViewGui::showTelegramTable() -{ - updateFilteredPosTelegramIds(m_CentralTelegramFilterList, m_PosCentralTelCheckBox->isChecked()); - updateFilteredPosTelegramIds(m_TetraTelegramFilterList, m_PosTetraTelCheckBox->isChecked()); - updateFilteredPosTelegramIds(m_WlsTelegramFilterList, m_PosWlsTelCheckBox->isChecked()); - if (m_ackCentralTelCheckBox->isChecked()) - m_CentralTelegramFilterList.erase(TrainingAreaBase::TetraIcd::BESTAETIGUNG); - else - m_CentralTelegramFilterList.insert(TrainingAreaBase::TetraIcd::BESTAETIGUNG); - m_telegramProxyModel->setFilteredCentralTelegramIds(m_CentralTelegramFilterList); - m_telegramProxyModel->setFilteredTetraTelegramIds(m_TetraTelegramFilterList); - m_telegramProxyModel->setFilteredWlsTelegramIds(m_WlsTelegramFilterList); - - m_telegramProxyModel->setFilterByEquipmentIds(m_ParticipantSelectionGroup->isChecked()); - - m_PosCentralTelCheckBox->setEnabled(m_SentCentralTelCheckBox->isChecked() && m_CentralSelectionGroup->isChecked()); - m_PosTetraTelCheckBox->setEnabled(m_SentTetraTelCheckBox->isChecked() && m_TetraSelectionGroup->isChecked()); - m_PosWlsTelCheckBox->setEnabled(m_ReceivedWlsTelCheckBox->isChecked() && m_WlsSelectionGroup->isChecked()); - - const bool bShowCentralTelegrams = m_CentralSelectionGroup->isChecked(); - m_telegramProxyModel->setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, - !m_SentCentralTelCheckBox->isChecked() || !bShowCentralTelegrams); - m_telegramProxyModel->setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, - !m_ReceivedCentralTelCheckBox->isChecked() || !bShowCentralTelegrams); - - const bool bShowTetraTelegrams = m_TetraSelectionGroup->isChecked(); - m_telegramProxyModel->setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, - !m_SentTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, - !m_ReceivedTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd, - !m_RegisterTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp, - !m_RegisterTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq, - !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq, - !m_ReportTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq, - !m_AirInterfaceLoadTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirLoadHyterra, - !m_AirInterfaceLoadTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraLogin(!m_LoginTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - m_telegramProxyModel->setFilterTetraFragmented(!m_FragmentedTetraTelCheckBox->isChecked() || !bShowTetraTelegrams); - - const bool bShowWlsTelegrams = m_WlsSelectionGroup->isChecked(); - m_telegramProxyModel->setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend, - !m_SentWlsTelCheckBox->isChecked() || !bShowWlsTelegrams); - m_telegramProxyModel->setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive, - !m_ReceivedWlsTelCheckBox->isChecked() || !bShowWlsTelegrams); - - m_TelegramStatus->setText(tr("%1 telegrams (unfiltered: %2)") - .arg(m_telegramProxyModel->rowCount()) - .arg(m_telegramModel->rowCount())); -} -void LogViewGui::addToParticipantList(const QSharedPointer &a_telegram) -{ - int partId = a_telegram->getParticipantId(); - m_participantListTelCount[partId]++; - auto &issi = m_participantListIssi[partId]; - if (issi == 0) - issi = a_telegram->getISSI(); -} - -void LogViewGui::syncParticipantList() -{ - QVector eqIds; - QVector issis; - QVector numberOfTelegrams; - eqIds.reserve(m_participantListTelCount.size()); - issis.reserve(m_participantListTelCount.size()); - numberOfTelegrams.reserve(m_participantListTelCount.size()); - for (auto it = m_participantListTelCount.constBegin(); it != m_participantListTelCount.constEnd(); ++it) + void LogViewGui::addToParticipantList(const QSharedPointer &a_telegram) { - eqIds.push_back(it.key()); - issis.push_back(m_participantListIssi.value(it.key())); - numberOfTelegrams.push_back(it.value()); + int partId = a_telegram->getParticipantId(); + m_participantListTelCount[partId]++; + auto &issi = m_participantListIssi[partId]; + if (issi == 0) + issi = a_telegram->getISSI(); } - m_participantModel->addUpdateParticipants(eqIds, issis, numberOfTelegrams); -} -// --------------------------------------------------------------- -void LogViewGui::changeSettings() -{ - LogViewOptionDialog optionDialog(this); - - connect(&optionDialog, &LogViewOptionDialog::settingsChanged, this, &LogViewGui::onSettingsChanged); - - optionDialog.exec(); -} - - -// --------------------------------------------------------------- -QCheckBox* LogViewGui::createRadioButton(const QString& a_buttonName, const QString& a_iconName) -{ - QCheckBox* checkBox = new QCheckBox(a_buttonName, this); - checkBox->setIcon(QIcon(a_iconName)); - checkBox->setIconSize(RADIO_BUTTON_ICON_SIZE); - connect(checkBox, &QCheckBox::toggled, this, &LogViewGui::showTelegramTable); - return checkBox; -} - - -// --------------------------------------------------------------- -// starts the thread, which trys to connect to the injection- -// server of PrtCnv -// --------------------------------------------------------------- -void LogViewGui::startInjectionThread() -{ - if (m_InjectionThread) + void LogViewGui::syncParticipantList() { - m_InjectionThread->quit(); - m_InjectionThread->wait(); - delete m_InjectionThread; + QVector eqIds; + QVector issis; + QVector numberOfTelegrams; + eqIds.reserve(m_participantListTelCount.size()); + issis.reserve(m_participantListTelCount.size()); + numberOfTelegrams.reserve(m_participantListTelCount.size()); + for (auto it = m_participantListTelCount.constBegin(); it != m_participantListTelCount.constEnd(); ++it) + { + eqIds.push_back(it.key()); + issis.push_back(m_participantListIssi.value(it.key())); + numberOfTelegrams.push_back(it.value()); + } + m_participantModel->addUpdateParticipants(eqIds, issis, numberOfTelegrams); } - m_InjectionThread = new LogViewInjectionThread(); - - QSettings settings; - settings.beginGroup(QLatin1String("LogFiles")); - QString filePath = settings.value(QLatin1String("Dir")).toString(); - QString exerciseName; - QVector parts = filePath.split(QLatin1Char('/')); - if (parts.size() >= 2) - exerciseName = QLatin1Char('_') + parts.at(parts.size() - 2); - - QString portFilePath = QCoreApplication::applicationDirPath() + QDir::separator() + QLatin1String("PrtCnv") + exerciseName + QLatin1String(".dat"); - QFileInfo checkPortFile(portFilePath); - if(checkPortFile.exists() && checkPortFile.isFile()) + // --------------------------------------------------------------- + void LogViewGui::changeSettings() { - QSettings portSetting(portFilePath, QSettings::IniFormat); - m_InjectionThread->setPort(portSetting.value(QLatin1String("Injection/Port")).toInt()); + LogViewOptionDialog optionDialog(this); + + connect(&optionDialog, &LogViewOptionDialog::settingsChanged, this, &LogViewGui::onSettingsChanged); + + optionDialog.exec(); } - m_EditTelegramController->setInjectionThread(m_InjectionThread); - connect(m_InjectionThread, &LogViewInjectionThread::updateStatus, - this, &LogViewGui::updateInjectionStatus); - m_InjectionThread->start(); -} + // --------------------------------------------------------------- + QCheckBox *LogViewGui::createRadioButton(const QString &a_buttonName, const QString &a_iconName) + { + QCheckBox *checkBox = new QCheckBox(a_buttonName, this); + checkBox->setIcon(QIcon(a_iconName)); + checkBox->setIconSize(RADIO_BUTTON_ICON_SIZE); + connect(checkBox, &QCheckBox::toggled, this, &LogViewGui::showTelegramTable); + return checkBox; + } -// --------------------------------------------------------------- -// Toggles whether the logfile must be periodically checked -// for changes -// --------------------------------------------------------------- -void LogViewGui::reloadOnOff() -{ - m_DoReload = !m_DoReload; -} + // --------------------------------------------------------------- + // starts the thread, which trys to connect to the injection- + // server of PrtCnv + // --------------------------------------------------------------- + void LogViewGui::startInjectionThread() + { + if (m_InjectionThread) + { + m_InjectionThread->quit(); + m_InjectionThread->wait(); + delete m_InjectionThread; + } + + m_InjectionThread = new LogViewInjectionThread(); + + QSettings settings; + settings.beginGroup(QLatin1String("LogFiles")); + QString filePath = settings.value(QLatin1String("Dir")).toString(); + QString exerciseName; + QVector parts = filePath.split(QLatin1Char('/')); + if (parts.size() >= 2) + exerciseName = QLatin1Char('_') + parts.at(parts.size() - 2); + + QString portFilePath = QCoreApplication::applicationDirPath() + QDir::separator() + QLatin1String("PrtCnv") + exerciseName + QLatin1String(".dat"); + QFileInfo checkPortFile(portFilePath); + if (checkPortFile.exists() && checkPortFile.isFile()) + { + QSettings portSetting(portFilePath, QSettings::IniFormat); + m_InjectionThread->setPort(portSetting.value(QLatin1String("Injection/Port")).toInt()); + } + + m_EditTelegramController->setInjectionThread(m_InjectionThread); + connect(m_InjectionThread, &LogViewInjectionThread::updateStatus, this, &LogViewGui::updateInjectionStatus); + + m_InjectionThread->start(); + } -// --------------------------------------------------------------- -void LogViewGui::closeEvent(QCloseEvent* a_closeEvent) -{ - QSettings settings; - settings.beginGroup(WINDOW_GROUP); + // --------------------------------------------------------------- + // Toggles whether the logfile must be periodically checked + // for changes + // --------------------------------------------------------------- + void LogViewGui::reloadOnOff() + { + m_DoReload = !m_DoReload; + } - // store the actual toolbox selection - settings.setValue(TOOLBOXINDEX, m_ToolBox->currentIndex()); - // store the actual size - settings.setValue(SIZE, size()); - QPoint position = pos(); - settings.setValue(POS, position); - QScreen *scr = QGuiApplication::screenAt(position); - int screenNbr = QGuiApplication::screens().indexOf(scr); - settings.setValue(SCREEN, screenNbr); + // --------------------------------------------------------------- + void LogViewGui::closeEvent(QCloseEvent *a_closeEvent) + { + QSettings settings; + settings.beginGroup(WINDOW_GROUP); - // store the splitter-position - const QList splitterSizes = m_Splitter->sizes(); - QList splitterSizesAsVariant; - splitterSizesAsVariant.reserve(splitterSizes.size()); - for (int item : splitterSizes) - splitterSizesAsVariant << QVariant(item); + // store the actual toolbox selection + settings.setValue(TOOLBOXINDEX, m_ToolBox->currentIndex()); - settings.setValue(SPLITTPOS, splitterSizesAsVariant); + // store the actual size + settings.setValue(SIZE, size()); + QPoint position = pos(); + settings.setValue(POS, position); + QScreen *scr = QGuiApplication::screenAt(position); + int screenNbr = QGuiApplication::screens().indexOf(scr); + settings.setValue(SCREEN, screenNbr); - settings.endGroup(); + // store the splitter-position + const QList splitterSizes = m_Splitter->sizes(); + QList splitterSizesAsVariant; + splitterSizesAsVariant.reserve(splitterSizes.size()); + for (int item : splitterSizes) + splitterSizesAsVariant << QVariant(item); - QMainWindow::closeEvent(a_closeEvent); -} + settings.setValue(SPLITTPOS, splitterSizesAsVariant); -// --------------------------------------------------------------- -void LogViewGui::updateInjectionStatus(const QString& a_picName, const QString& a_toopTipText) -{ - m_InjectionStatus->setPixmap(QPixmap(a_picName)); - m_InjectionStatus->setToolTip(a_toopTipText); -} + settings.endGroup(); -// --------------------------------------------------------------- -void LogViewGui::onLogTelegramViewDoubleClicked(const QModelIndex &index) -{ - if (!m_telegramProxyModel || !m_telegramModel) - return; - QModelIndex idx = m_telegramProxyModel->mapToSource(index); - if (!idx.isValid()) - return; - QSharedPointer telegram = m_telegramModel->telegram(idx.row()); - if (!telegram) - return; - LogViewTelegramDialog* showTelegramDialog = new LogViewTelegramDialog(this, true); - showTelegramDialog->showDialog(telegram); -} + QMainWindow::closeEvent(a_closeEvent); + } -void LogViewGui::onSettingsChanged(uint32_t changedFlags) -{ - if ((changedFlags & LogViewOptionDialog::SpecFilesGroup) == LogViewOptionDialog::SpecFilesGroup) - loadSpecificationFiles(); + // --------------------------------------------------------------- + void LogViewGui::updateInjectionStatus(const QString &a_picName, const QString &a_toopTipText) + { + m_InjectionStatus->setPixmap(QPixmap(a_picName)); + m_InjectionStatus->setToolTip(a_toopTipText); + } - if ((changedFlags & LogViewOptionDialog::InjectionGroup) == LogViewOptionDialog::InjectionGroup) - startInjectionThread(); -} + // --------------------------------------------------------------- + void LogViewGui::onLogTelegramViewDoubleClicked(const QModelIndex &index) + { + if (!m_telegramProxyModel || !m_telegramModel) + return; + QModelIndex idx = m_telegramProxyModel->mapToSource(index); + if (!idx.isValid()) + return; + QSharedPointer telegram = m_telegramModel->telegram(idx.row()); + if (!telegram) + return; + LogViewTelegramDialog *showTelegramDialog = new LogViewTelegramDialog(this, true); + showTelegramDialog->showDialog(telegram); + } + + void LogViewGui::onSettingsChanged(uint32_t changedFlags) + { + if ((changedFlags & LogViewOptionDialog::SpecFilesGroup) == LogViewOptionDialog::SpecFilesGroup) + loadSpecificationFiles(); + + if ((changedFlags & LogViewOptionDialog::InjectionGroup) == LogViewOptionDialog::InjectionGroup) + startInjectionThread(); + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.hpp index dacb75b18..0a851712e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewGui.hpp @@ -23,7 +23,7 @@ namespace N_LogView { -class LogViewTelegram; + class LogViewTelegram; } class QTableView; @@ -38,164 +38,163 @@ class QToolBox; namespace N_LogView { -class LogViewInjectionThread; -class TelegramEdit; + class LogViewInjectionThread; + class TelegramEdit; -/** + /** * @author alois.wismer * @version 1.0 * @created 03-Feb-2010 16:44:53 */ -class LogViewGui : public QMainWindow -{ - Q_OBJECT -public: + class LogViewGui : public QMainWindow + { + Q_OBJECT + public: + explicit LogViewGui(QWidget *a_parent); - explicit LogViewGui(QWidget* a_parent); + static const QLatin1String WINDOW_GROUP; + static const QLatin1String SCREEN; - static const QLatin1String WINDOW_GROUP; - static const QLatin1String SCREEN; + protected: + const QSize RADIO_BUTTON_ICON_SIZE; + static const QLatin1String SIZE; + static const QLatin1String POS; + static const QLatin1String SPLITTPOS; + static const QLatin1String TOOLBOXINDEX; + // Central + QGroupBox *m_CentralSelectionGroup; + std::set m_CentralTelegramFilterList; + QCheckBox *m_SentCentralTelCheckBox; + QCheckBox *m_ReceivedCentralTelCheckBox; + QCheckBox *m_PosCentralTelCheckBox; + QCheckBox *m_ackCentralTelCheckBox; + // Tetra + QGroupBox *m_TetraSelectionGroup; + std::set m_TetraTelegramFilterList; + QCheckBox *m_SentTetraTelCheckBox; + QCheckBox *m_ReceivedTetraTelCheckBox; + QCheckBox *m_PosTetraTelCheckBox; + QCheckBox *m_LoginTetraTelCheckBox; + QCheckBox *m_RegisterTetraTelCheckBox; + QCheckBox *m_ReportTetraTelCheckBox; + QCheckBox *m_FragmentedTetraTelCheckBox; + QCheckBox *m_AirInterfaceLoadTetraTelCheckBox; + // Wls + QGroupBox *m_WlsSelectionGroup; + std::set m_WlsTelegramFilterList; + QCheckBox *m_SentWlsTelCheckBox; + QCheckBox *m_ReceivedWlsTelCheckBox; + QCheckBox *m_PosWlsTelCheckBox; + QCheckBox *m_ackWlsTelCheckBox; -protected: + QString m_ActualLogfile; + qint64 m_LogfileSize; + bool m_DoReload; + QToolBox *m_ToolBox; + QTableView *m_ParticipantTableView; + ParticipantModel *m_participantModel; + QSortFilterProxyModel *m_participantProxyModel; - const QSize RADIO_BUTTON_ICON_SIZE; - static const QLatin1String SIZE; - static const QLatin1String POS; - static const QLatin1String SPLITTPOS; - static const QLatin1String TOOLBOXINDEX; - // Central - QGroupBox *m_CentralSelectionGroup; - std::set m_CentralTelegramFilterList; - QCheckBox* m_SentCentralTelCheckBox; - QCheckBox* m_ReceivedCentralTelCheckBox; - QCheckBox* m_PosCentralTelCheckBox; - QCheckBox* m_ackCentralTelCheckBox; - // Tetra - QGroupBox *m_TetraSelectionGroup; - std::set m_TetraTelegramFilterList; - QCheckBox* m_SentTetraTelCheckBox; - QCheckBox* m_ReceivedTetraTelCheckBox; - QCheckBox* m_PosTetraTelCheckBox; - QCheckBox* m_LoginTetraTelCheckBox; - QCheckBox* m_RegisterTetraTelCheckBox; - QCheckBox* m_ReportTetraTelCheckBox; - QCheckBox* m_FragmentedTetraTelCheckBox; - QCheckBox* m_AirInterfaceLoadTetraTelCheckBox; - // Wls - QGroupBox *m_WlsSelectionGroup; - std::set m_WlsTelegramFilterList; - QCheckBox* m_SentWlsTelCheckBox; - QCheckBox* m_ReceivedWlsTelCheckBox; - QCheckBox* m_PosWlsTelCheckBox; - QCheckBox* m_ackWlsTelCheckBox; + QTableView *m_logTelegramView; + TelegramModel *m_telegramModel; + TelegramProxyModel *m_telegramProxyModel; - QString m_ActualLogfile; - qint64 m_LogfileSize; - bool m_DoReload; - QToolBox* m_ToolBox; - QTableView *m_ParticipantTableView; - ParticipantModel *m_participantModel; - QSortFilterProxyModel *m_participantProxyModel; + QLabel *m_TelegramStatus; - QTableView *m_logTelegramView; - TelegramModel *m_telegramModel; - TelegramProxyModel *m_telegramProxyModel; + QLabel *m_ParticipantStatus; - QLabel *m_TelegramStatus; + QGroupBox *m_ParticipantSelectionGroup; - QLabel *m_ParticipantStatus; + TelegramEdit *m_EditTelegramController; - QGroupBox *m_ParticipantSelectionGroup; + QTimer *m_TailTimer; - TelegramEdit *m_EditTelegramController; + QSplitter *m_Splitter; - QTimer *m_TailTimer; + LogViewInjectionThread *m_InjectionThread; - QSplitter *m_Splitter; + QLabel *m_InjectionStatus; - LogViewInjectionThread *m_InjectionThread; + // ausstg, telcount + QHash m_participantListTelCount; + // ausstg, issi + QHash m_participantListIssi; - QLabel *m_InjectionStatus; + QAction *m_reloadAction; + QTimer *m_replayTimer; + int m_currentReplayRow; - // ausstg, telcount - QHash m_participantListTelCount; - // ausstg, issi - QHash m_participantListIssi; + protected: + void readTelegramsFromLogFile(const QString &a_fileName, const qint64 a_filePos = 0); - QAction *m_reloadAction; - QTimer *m_replayTimer; - int m_currentReplayRow; -protected: - void readTelegramsFromLogFile(const QString& a_fileName, const qint64 a_filePos = 0); - - /** + /** * returns true if the participant was added to the list */ - void addToParticipantList(const QSharedPointer &a_telegram); - void syncParticipantList(); - QCheckBox* createRadioButton(const QString& a_buttonName, const QString& a_iconName); + void addToParticipantList(const QSharedPointer &a_telegram); + void syncParticipantList(); + QCheckBox *createRadioButton(const QString &a_buttonName, const QString &a_iconName); - /** + /** * starts the thread, which trys to connect to the injection-server of PrtCnv */ - void startInjectionThread(); + void startInjectionThread(); - void closeEvent(QCloseEvent* a_closeEvent) override; + void closeEvent(QCloseEvent *a_closeEvent) override; - void createCentralSelectionWidget(); - void createTetraSelectionWidget(); - void createWlsSelectionWidget(); + void createCentralSelectionWidget(); + void createTetraSelectionWidget(); + void createWlsSelectionWidget(); -protected slots: - void addTelegramToEdit(); - void showHexData(); - void exportAsCsv(); - void exportAsJson(); - void onStartLogReplay(); - void onReplayTimerTimeout(); + protected slots: + void addTelegramToEdit(); + void showHexData(); + void exportAsCsv(); + void exportAsJson(); + void onStartLogReplay(); + void onReplayTimerTimeout(); - void loadSpecificationFiles(); + void loadSpecificationFiles(); - void newTelegramFile(); + void newTelegramFile(); - void loadTelegramFile(); + void loadTelegramFile(); - /** + /** * Checks whether the size of actual logfile has changed. If yes, the new log- * entries will be read and shown within table. */ - void updateLogfile(); + void updateLogfile(); - void selectedParticipantChanged(); + void selectedParticipantChanged(); - void showTelegramTable(); + void showTelegramTable(); - //SLOT for creating the ContextMenu - void customMenuRequested(const QPoint &pos); + //SLOT for creating the ContextMenu + void customMenuRequested(const QPoint &pos); - void changeSettings(); + void changeSettings(); - /** + /** * Toggles whether the logfile must be periodically checked for changes */ - void reloadOnOff(); + void reloadOnOff(); - /** + /** * * @param a_picName * @param a_toopTipText */ - void updateInjectionStatus(const QString& a_picName, const QString& a_toopTipText); + void updateInjectionStatus(const QString &a_picName, const QString &a_toopTipText); - void onLogTelegramViewDoubleClicked(const QModelIndex &index); + void onLogTelegramViewDoubleClicked(const QModelIndex &index); -private: - NGL::INGLLogger &m_logger; + private: + NGL::INGLLogger &m_logger; -private slots: - void onSettingsChanged(uint32_t changedFlags); -}; + private slots: + void onSettingsChanged(uint32_t changedFlags); + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.cpp index e2979c490..14869272d 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewInjectionThread.hpp" @@ -23,121 +23,118 @@ namespace N_LogView { -LogViewInjectionThread::LogViewInjectionThread() - : m_logger(getLogger("LogViewInjectionThread")) - , m_DoStartConnection(false) - , m_SendingPossible(false) - , m_Socket(nullptr) - , m_Timer(nullptr) -{ - // load the settings (and write default-values if not defined) - QSettings settings; - settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); - m_Hostname = settings.value(LogViewOptionDialog::INJECTION_HOSTNAME).toString(); - if (m_Hostname.isEmpty()) + LogViewInjectionThread::LogViewInjectionThread() + : m_logger(getLogger("LogViewInjectionThread")) + , m_DoStartConnection(false) + , m_SendingPossible(false) + , m_Socket(nullptr) + , m_Timer(nullptr) { - // set default-hostname if nothing was set - m_Hostname = QLatin1String("localhost"); - settings.setValue(LogViewOptionDialog::INJECTION_HOSTNAME, m_Hostname); + // load the settings (and write default-values if not defined) + QSettings settings; + settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); + m_Hostname = settings.value(LogViewOptionDialog::INJECTION_HOSTNAME).toString(); + if (m_Hostname.isEmpty()) + { + // set default-hostname if nothing was set + m_Hostname = QLatin1String("localhost"); + settings.setValue(LogViewOptionDialog::INJECTION_HOSTNAME, m_Hostname); + } + m_Port = settings.value(LogViewOptionDialog::INJECTION_PORT).toInt(); + if (0 == m_Port || m_Port > 65535) + { + m_Port = 46666; + settings.setValue(LogViewOptionDialog::INJECTION_PORT, m_Port); + } } - m_Port = settings.value(LogViewOptionDialog::INJECTION_PORT).toInt(); - if (0 == m_Port || m_Port > 65535) + + // --------------------------------------------------------------- + void LogViewInjectionThread::run() { - m_Port = 46666; + emit updateStatus(QLatin1String(":/image/RedLamp.png"), tr("LogView ist nicht mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); + QTimer::singleShot(100, this, &LogViewInjectionThread::tryToConnect); + + exec(); + } + + + // --------------------------------------------------------------- + void LogViewInjectionThread::setPort(uint16_t port) + { + m_Port = port; + QSettings settings; + settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); settings.setValue(LogViewOptionDialog::INJECTION_PORT, m_Port); } -} - -// --------------------------------------------------------------- -void LogViewInjectionThread::run() -{ - emit updateStatus(QLatin1String(":/image/RedLamp.png"), - tr("LogView ist nicht mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); - QTimer::singleShot(100, this, &LogViewInjectionThread::tryToConnect); - - exec(); -} -// --------------------------------------------------------------- -void LogViewInjectionThread::setPort(uint16_t port) -{ - m_Port = port; - QSettings settings; - settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); - settings.setValue(LogViewOptionDialog::INJECTION_PORT, m_Port); -} - - -// --------------------------------------------------------------- -bool LogViewInjectionThread::isSendingPossible() const -{ - return m_SendingPossible; -} - - -// --------------------------------------------------------------- -void LogViewInjectionThread::tryToConnect() -{ - //m_Timer->setInterval(3000); - if (!m_Socket) + // --------------------------------------------------------------- + bool LogViewInjectionThread::isSendingPossible() const { - m_Socket = new QTcpSocket(this); - connect(m_Socket, &QTcpSocket::connected, this, &LogViewInjectionThread::doConnect); - connect(m_Socket, &QTcpSocket::disconnected, this, &LogViewInjectionThread::doDisconnect); + return m_SendingPossible; } - // we need a timer for retrying connection - if (!m_Timer) + + // --------------------------------------------------------------- + void LogViewInjectionThread::tryToConnect() { - m_Timer = new QTimer(this); - connect(m_Timer, &QTimer::timeout, this, &LogViewInjectionThread::tryToConnect); + //m_Timer->setInterval(3000); + if (!m_Socket) + { + m_Socket = new QTcpSocket(this); + connect(m_Socket, &QTcpSocket::connected, this, &LogViewInjectionThread::doConnect); + connect(m_Socket, &QTcpSocket::disconnected, this, &LogViewInjectionThread::doDisconnect); + } + + // we need a timer for retrying connection + if (!m_Timer) + { + m_Timer = new QTimer(this); + connect(m_Timer, &QTimer::timeout, this, &LogViewInjectionThread::tryToConnect); + } + m_Timer->setInterval(3000); + m_Timer->start(); + + INFO_LOG(m_logger) << "Try to connect to injection-server of TETRA-If (" << m_Hostname << ":" << m_Port << ")"; + m_Socket->connectToHost(m_Hostname, m_Port); } - m_Timer->setInterval(3000); - m_Timer->start(); - - INFO_LOG(m_logger) << "Try to connect to injection-server of TETRA-If (" << m_Hostname << ":" << m_Port << ")"; - m_Socket->connectToHost(m_Hostname, m_Port); -} -// --------------------------------------------------------------- -void LogViewInjectionThread::doConnect() -{ - INFO_LOG(m_logger) << "LogView has successful connected to injection-server of TETRA-If"; - m_SendingPossible = true; - m_Timer->stop(); - emit updateStatus(QLatin1String(":/image/GreenLamp.png"), - tr("LogView ist mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); -} - - -// --------------------------------------------------------------- -void LogViewInjectionThread::doDisconnect() -{ - INFO_LOG(m_logger) << "LogView was disconnected from injection-server of TETRA-If"; - m_SendingPossible = false; - emit updateStatus(QLatin1String(":/image/RedLamp.png"), - tr("LogView ist nicht mehr mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); - tryToConnect(); -} - - -// --------------------------------------------------------------- -void LogViewInjectionThread::sendTelegram(LogViewTelegram* a_telegram, const bool a_doSendAsCentralTelegram) -{ - INFO_LOG(m_logger) << "inject " << (a_doSendAsCentralTelegram ? "central" : "Tetra") << " telegram"; - if (!m_Socket || m_Socket->state() != QAbstractSocket::ConnectedState) + // --------------------------------------------------------------- + void LogViewInjectionThread::doConnect() { - ERROR_LOG(m_logger) << "Try to write a telegramm but we are not connected"; - return; + INFO_LOG(m_logger) << "LogView has successful connected to injection-server of TETRA-If"; + m_SendingPossible = true; + m_Timer->stop(); + emit updateStatus(QLatin1String(":/image/GreenLamp.png"), tr("LogView ist mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); + } + + + // --------------------------------------------------------------- + void LogViewInjectionThread::doDisconnect() + { + INFO_LOG(m_logger) << "LogView was disconnected from injection-server of TETRA-If"; + m_SendingPossible = false; + emit updateStatus(QLatin1String(":/image/RedLamp.png"), tr("LogView ist nicht mehr mit TETRA-If-Injection-Server (%1:%2) verbunden").arg(m_Hostname).arg(m_Port)); + tryToConnect(); + } + + + // --------------------------------------------------------------- + void LogViewInjectionThread::sendTelegram(LogViewTelegram *a_telegram, const bool a_doSendAsCentralTelegram) + { + INFO_LOG(m_logger) << "inject " << (a_doSendAsCentralTelegram ? "central" : "Tetra") << " telegram"; + if (!m_Socket || m_Socket->state() != QAbstractSocket::ConnectedState) + { + ERROR_LOG(m_logger) << "Try to write a telegramm but we are not connected"; + return; + } + N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader; + injectionHeader.m_Kind = a_doSendAsCentralTelegram ? N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral : N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio; + const QByteArray &data = a_telegram->getData(); + injectionHeader.m_Size = data.size(); + m_Socket->write((char *)(&injectionHeader), sizeof(injectionHeader)); + m_Socket->write(data); } - N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader; - injectionHeader.m_Kind = a_doSendAsCentralTelegram ? N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral : N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio; - const QByteArray &data = a_telegram->getData(); - injectionHeader.m_Size = data.size(); - m_Socket->write((char*)(&injectionHeader), sizeof(injectionHeader)); - m_Socket->write(data); -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.hpp index ab42ae4dc..a9f885d13 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewInjectionThread.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -33,7 +33,6 @@ namespace N_LogView { Q_OBJECT public: - LogViewInjectionThread(); void run(); @@ -47,10 +46,9 @@ namespace N_LogView * @param a_telegram * @param a_doSendAsCentralTelegram */ - void sendTelegram(LogViewTelegram* a_telegram, const bool a_doSendAsCentralTelegram); + void sendTelegram(LogViewTelegram *a_telegram, const bool a_doSendAsCentralTelegram); protected: - NGL::INGLLogger &m_logger; bool m_DoStartConnection; bool m_SendingPossible; @@ -78,8 +76,7 @@ namespace N_LogView * @param a_picName * @param a_toolTipText */ - void updateStatus(const QString& a_picName, const QString& a_toolTipText); - + void updateStatus(const QString &a_picName, const QString &a_toolTipText); }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewMain.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewMain.cpp index 5841c9c1e..82373682e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewMain.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewMain.cpp @@ -4,7 +4,7 @@ #include #include #ifndef WIN32 - #include +#include #endif #include "LogViewGui.hpp" #include "logger.h" @@ -21,10 +21,13 @@ int main(int argc, char *argv[]) s << "/proc/" << getpid() << "/exe"; char buf[1024]; ssize_t len = readlink(s.str().c_str(), buf, 1024); - if(len > 0) { + if (len > 0) + { buf[len] = '\0'; dir = buf; - } else { + } + else + { // fallback dir = argv[0]; } @@ -32,7 +35,8 @@ int main(int argc, char *argv[]) std::string::size_type pos = dir.find_last_of('/'); if (std::string::npos != pos) - logConfigFileName += dir.substr(0, pos + 1);; + logConfigFileName += dir.substr(0, pos + 1); + ; logConfigFileName += "LogView_log4cxx.props"; qputenv("TDS_DEVEL", QByteArray::number(1)); @@ -49,8 +53,9 @@ int main(int argc, char *argv[]) settings.endGroup(); QScreen *screen = QGuiApplication::screens().value(screenNbr, QGuiApplication::primaryScreen()); - N_LogView::LogViewGui* logViewGui = new N_LogView::LogViewGui(nullptr); - if (logViewGui->windowHandle()) { + N_LogView::LogViewGui *logViewGui = new N_LogView::LogViewGui(nullptr); + if (logViewGui->windowHandle()) + { logViewGui->windowHandle()->setScreen(screen); } logViewGui->show(); @@ -59,4 +64,3 @@ int main(int argc, char *argv[]) delete logViewGui; return ret; } - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.cpp index 2e7bc24f0..286270880 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.cpp @@ -15,572 +15,562 @@ namespace N_LogView { -// --------------------------------------------------------------- -// --------------------------------------------------------------- -int ParticipantModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : m_particpants.size(); -} - -// --------------------------------------------------------------- -int ParticipantModel::columnCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : 3; -} - -// --------------------------------------------------------------- -QVariant ParticipantModel::data(const QModelIndex &index, int role) const -{ - if (index.isValid() && index.row() < m_particpants.size()) + // --------------------------------------------------------------- + // --------------------------------------------------------------- + int ParticipantModel::rowCount(const QModelIndex &parent) const { - const auto &p = m_particpants.at(index.row()); - if (role == Qt::DisplayRole) + return parent.isValid() ? 0 : m_particpants.size(); + } + + // --------------------------------------------------------------- + int ParticipantModel::columnCount(const QModelIndex &parent) const + { + return parent.isValid() ? 0 : 3; + } + + // --------------------------------------------------------------- + QVariant ParticipantModel::data(const QModelIndex &index, int role) const + { + if (index.isValid() && index.row() < m_particpants.size()) { - switch (index.column()) + const auto &p = m_particpants.at(index.row()); + if (role == Qt::DisplayRole) { - case 0: - return p.first; - case 1: - return p.second; - case 2: - return m_particpantMap.value(p.first); - default: - break; + switch (index.column()) + { + case 0: + return p.first; + case 1: + return p.second; + case 2: + return m_particpantMap.value(p.first); + default: + break; + } + } + if (role == Qt::ToolTipRole) + { + switch (index.column()) + { + case 0: + return tr("hex: 0x%1").arg(p.first, 4, 16, QLatin1Char('0')); + case 1: + return tr("hex: 0x%1").arg(p.second, 4, 16, QLatin1Char('0')); + default: + break; + } + } + if (role == Qt::BackgroundRole) + { + if (p.first == 0) + return QVariant(); // 0 aussen vor lassen + if (m_participantHeatmap.isEmpty()) + updateHeatMap(); + return m_participantHeatmap.value(p.first); } } - if (role == Qt::ToolTipRole) - { - switch (index.column()) - { - case 0: - return tr("hex: 0x%1").arg(p.first, 4, 16, QLatin1Char('0')); - case 1: - return tr("hex: 0x%1").arg(p.second, 4, 16, QLatin1Char('0')); - default: - break; - } - } - if (role == Qt::BackgroundRole) - { - if (p.first == 0) - return QVariant(); // 0 aussen vor lassen - if (m_participantHeatmap.isEmpty()) - updateHeatMap(); - return m_participantHeatmap.value(p.first); - } - } - return QVariant(); -} - -// --------------------------------------------------------------- -QVariant ParticipantModel::headerData(int section, - Qt::Orientation orientation, - int role) const -{ - if (role == Qt::DisplayRole && orientation == Qt::Horizontal) - { - switch (section) - { - case 0: - return tr("Equip. No."); - case 1: - return tr("ISSI"); - case 2: - return tr("#"); - default: - break; - } - } - return QAbstractTableModel::headerData(section, orientation, role); -} - -// --------------------------------------------------------------- -void ParticipantModel::clearParticipants() -{ - beginResetModel(); - m_particpantMap.clear(); - m_particpants.clear(); - m_participantHeatmap.clear(); - endResetModel(); -} - -// --------------------------------------------------------------- -bool ParticipantModel::addUpdateParticipants(const QVector &eqIds, - const QVector &issis, - const QVector &numberOfTelegrams) -{ - QVector > newParticpants; - for (int i = 0; i < eqIds.size(); ++i) - { - const int eqId = eqIds.at(i); - const int issi = issis.at(i); - const int cntTelegrams = numberOfTelegrams.at(i); - auto it = m_particpantMap.find(eqId); - if (it != m_particpantMap.end()) - { - it.value() = cntTelegrams; - continue; - } - newParticpants.push_back(qMakePair(eqId, issi)); - m_particpantMap[eqId] = cntTelegrams; + return QVariant(); } - if (!newParticpants.isEmpty()) + // --------------------------------------------------------------- + QVariant ParticipantModel::headerData(int section, Qt::Orientation orientation, int role) const { - beginInsertRows(QModelIndex(), m_particpants.size(), m_particpants.size() + newParticpants.size() - 1); - m_particpants.append(newParticpants); - endInsertRows(); - } - m_participantHeatmap.clear(); - return true; -} - -// --------------------------------------------------------------- -void ParticipantModel::updateHeatMap() const -{ - int maxNumberOfTelegrams = 0; - for (auto it = m_particpantMap.begin(); it != m_particpantMap.end(); ++it) - { - if (it.key() == 0) // EqId 0 aussen vor lassen - continue; - maxNumberOfTelegrams = std::max(it.value(), maxNumberOfTelegrams); - } - - const QColor backgroundColor = QGuiApplication::palette().base().color(); - const QColor redColor = Qt::red; - for (auto it = m_particpantMap.begin(); it != m_particpantMap.end(); ++it) - { - const int eqId = it.key(); - if (eqId == 0) // EqId 0 aussen vor lassen - continue; - - const int nbrTelegrams = it.value(); - QColor curColor; - double percent = static_cast(nbrTelegrams) / maxNumberOfTelegrams; - curColor.setRed(backgroundColor.red() - ((backgroundColor.red() - redColor.red()) * percent)); - curColor.setGreen(backgroundColor.green() - ((backgroundColor.green() - redColor.green()) * percent)); - curColor.setBlue(backgroundColor.blue() - ((backgroundColor.blue() - redColor.blue()) * percent)); - m_participantHeatmap[eqId] = curColor; - } -} - -// --------------------------------------------------------------- -// --------------------------------------------------------------- -int TelegramModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : m_telegrams.size(); -} - -// --------------------------------------------------------------- -int TelegramModel::columnCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : 6; -} - -// --------------------------------------------------------------- -QVariant TelegramModel::data(const QModelIndex &index, int role) const -{ - if (index.isValid() && index.row() < m_telegrams.size()) - { - if (role == Qt::DisplayRole) - { - const QSharedPointer &telegram = m_telegrams.at(index.row()); - switch (index.column()) - { - case 0: - return telegram->getDestinationText(); - case 1: - return telegram->getName(); - case 2: - return telegram->getParticipantId(); - case 3: - return telegram->getLogTimeText(); - case 4: - return telegram->getGpsTimeText(); - case 5: - return telegram->getDelay(); - } - } - if (role == Qt::DecorationRole) - { - const QSharedPointer telegram = m_telegrams.at(index.row()); - switch (index.column()) - { - case 0: - return telegram->getIcon(); - default: - break; - } - } - if (role == Qt::ToolTipRole) - { - const QSharedPointer telegram = m_telegrams.at(index.row()); - switch (index.column()) - { - case 1: - return telegram->getToolTipText(LogViewTelegram::e_ColName); - case 3: - return telegram->getToolTipText(LogViewTelegram::e_ColLogTime); - case 4: - return telegram->getToolTipText(LogViewTelegram::e_ColGpsTime); - default: - break; - } - } - } - return QVariant(); -} - -// --------------------------------------------------------------- -QVariant TelegramModel::headerData(int section, - Qt::Orientation orientation, - int role) const -{ - if (orientation == Qt::Horizontal) - { - if (role == Qt::DisplayRole) + if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { + case 0: + return tr("Equip. No."); + case 1: + return tr("ISSI"); + case 2: + return tr("#"); + default: + break; + } + } + return QAbstractTableModel::headerData(section, orientation, role); + } + + // --------------------------------------------------------------- + void ParticipantModel::clearParticipants() + { + beginResetModel(); + m_particpantMap.clear(); + m_particpants.clear(); + m_participantHeatmap.clear(); + endResetModel(); + } + + // --------------------------------------------------------------- + bool ParticipantModel::addUpdateParticipants(const QVector &eqIds, const QVector &issis, const QVector &numberOfTelegrams) + { + QVector> newParticpants; + for (int i = 0; i < eqIds.size(); ++i) + { + const int eqId = eqIds.at(i); + const int issi = issis.at(i); + const int cntTelegrams = numberOfTelegrams.at(i); + auto it = m_particpantMap.find(eqId); + if (it != m_particpantMap.end()) + { + it.value() = cntTelegrams; + continue; + } + newParticpants.push_back(qMakePair(eqId, issi)); + m_particpantMap[eqId] = cntTelegrams; + } + + if (!newParticpants.isEmpty()) + { + beginInsertRows(QModelIndex(), m_particpants.size(), m_particpants.size() + newParticpants.size() - 1); + m_particpants.append(newParticpants); + endInsertRows(); + } + m_participantHeatmap.clear(); + return true; + } + + // --------------------------------------------------------------- + void ParticipantModel::updateHeatMap() const + { + int maxNumberOfTelegrams = 0; + for (auto it = m_particpantMap.begin(); it != m_particpantMap.end(); ++it) + { + if (it.key() == 0) // EqId 0 aussen vor lassen + continue; + maxNumberOfTelegrams = std::max(it.value(), maxNumberOfTelegrams); + } + + const QColor backgroundColor = QGuiApplication::palette().base().color(); + const QColor redColor = Qt::red; + for (auto it = m_particpantMap.begin(); it != m_particpantMap.end(); ++it) + { + const int eqId = it.key(); + if (eqId == 0) // EqId 0 aussen vor lassen + continue; + + const int nbrTelegrams = it.value(); + QColor curColor; + double percent = static_cast(nbrTelegrams) / maxNumberOfTelegrams; + curColor.setRed(backgroundColor.red() - ((backgroundColor.red() - redColor.red()) * percent)); + curColor.setGreen(backgroundColor.green() - ((backgroundColor.green() - redColor.green()) * percent)); + curColor.setBlue(backgroundColor.blue() - ((backgroundColor.blue() - redColor.blue()) * percent)); + m_participantHeatmap[eqId] = curColor; + } + } + + // --------------------------------------------------------------- + // --------------------------------------------------------------- + int TelegramModel::rowCount(const QModelIndex &parent) const + { + return parent.isValid() ? 0 : m_telegrams.size(); + } + + // --------------------------------------------------------------- + int TelegramModel::columnCount(const QModelIndex &parent) const + { + return parent.isValid() ? 0 : 6; + } + + // --------------------------------------------------------------- + QVariant TelegramModel::data(const QModelIndex &index, int role) const + { + if (index.isValid() && index.row() < m_telegrams.size()) + { + if (role == Qt::DisplayRole) + { + const QSharedPointer &telegram = m_telegrams.at(index.row()); + switch (index.column()) + { + case 0: + return telegram->getDestinationText(); + case 1: + return telegram->getName(); + case 2: + return telegram->getParticipantId(); + case 3: + return telegram->getLogTimeText(); + case 4: + return telegram->getGpsTimeText(); + case 5: + return telegram->getDelay(); + } + } + if (role == Qt::DecorationRole) + { + const QSharedPointer telegram = m_telegrams.at(index.row()); + switch (index.column()) + { + case 0: + return telegram->getIcon(); + default: + break; + } + } + if (role == Qt::ToolTipRole) + { + const QSharedPointer telegram = m_telegrams.at(index.row()); + switch (index.column()) + { + case 1: + return telegram->getToolTipText(LogViewTelegram::e_ColName); + case 3: + return telegram->getToolTipText(LogViewTelegram::e_ColLogTime); + case 4: + return telegram->getToolTipText(LogViewTelegram::e_ColGpsTime); + default: + break; + } + } + } + return QVariant(); + } + + // --------------------------------------------------------------- + QVariant TelegramModel::headerData(int section, Qt::Orientation orientation, int role) const + { + if (orientation == Qt::Horizontal) + { + if (role == Qt::DisplayRole) + { + switch (section) + { + case 0: + return tr("Dest."); + case 1: + return tr("Description"); + case 2: + return tr("Equip. No."); + case 3: + return tr("Send/Recieve time"); + case 4: + return tr("GPS time"); + case 5: + return tr("Delay"); + default: + break; + } + } + } + return QAbstractTableModel::headerData(section, orientation, role); + } + + // --------------------------------------------------------------- + void TelegramModel::clearTelegrams() + { + beginResetModel(); + m_telegrams.clear(); + endResetModel(); + } + + // --------------------------------------------------------------- + void TelegramModel::appendTelegrams(const QVector> &telegrams) + { + if (telegrams.isEmpty()) + return; + beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size() + telegrams.size() - 1); + m_telegrams += telegrams; + endInsertRows(); + } + + // --------------------------------------------------------------- + void TelegramModel::appendTelegram(const QSharedPointer &telegram) + { + beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size()); + m_telegrams.push_back(telegram); + endInsertRows(); + } + + // --------------------------------------------------------------- + QSharedPointer TelegramModel::telegram(int row) const + { + if (row >= 0 && row < m_telegrams.size()) + return m_telegrams.at(row); + return QSharedPointer(); + } + + // --------------------------------------------------------------- + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterByEquipmentIds(bool bFilterByEquipmentIds) + { + if (m_bFilterByEquipmentIds == bFilterByEquipmentIds) + return; + m_bFilterByEquipmentIds = bFilterByEquipmentIds; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setAllowedEquipmentIds(const std::set &allowedEquipmentIds) + { + if (m_allowedEquipmentIds == allowedEquipmentIds) + return; + m_allowedEquipmentIds = allowedEquipmentIds; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilteredCentralTelegramIds(const std::set &filteredCentralTelegramIds) + { + if (m_filteredCentralTelegramIds == filteredCentralTelegramIds) + return; + m_filteredCentralTelegramIds = filteredCentralTelegramIds; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilteredTetraTelegramIds(const std::set &filteredTetraTelegramIds) + { + if (m_filteredTetraTelegramIds == filteredTetraTelegramIds) + return; + m_filteredTetraTelegramIds = filteredTetraTelegramIds; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilteredWlsTelegramIds(const std::set &filteredWlsTelegramIds) + { + if (m_filteredWlsTelegramIds == filteredWlsTelegramIds) + return; + m_filteredWlsTelegramIds = filteredWlsTelegramIds; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter) + { + std::set curFilter = m_filterCentralTelegrams; + if (bFilter) + curFilter.insert(direction); + else + curFilter.erase(direction); + if (curFilter == m_filterCentralTelegrams) + return; + m_filterCentralTelegrams = curFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter) + { + std::set curFilter = m_filterTetraTelegrams; + if (bFilter) + curFilter.insert(direction); + else + curFilter.erase(direction); + if (curFilter == m_filterTetraTelegrams) + return; + m_filterTetraTelegrams = curFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType, bool bFilter) + { + std::set curFilter = m_filterTetraPDU; + if (bFilter) + curFilter.insert(pduType); + else + curFilter.erase(pduType); + if (curFilter == m_filterTetraPDU) + return; + m_filterTetraPDU = curFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + void TelegramProxyModel::setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter) + { + std::set curFilter = m_filterWlsTelegrams; + if (bFilter) + curFilter.insert(direction); + else + curFilter.erase(direction); + if (curFilter == m_filterWlsTelegrams) + return; + m_filterWlsTelegrams = curFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterTetraLogin(bool bFilter) + { + if (m_bFilterLoginTelegrams == bFilter) + return; + m_bFilterLoginTelegrams = bFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + void TelegramProxyModel::setFilterTetraFragmented(bool bFilter) + { + if (m_bFilterFragmentedTelegrams == bFilter) + return; + m_bFilterFragmentedTelegrams = bFilter; + // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the + // documented replacement (re-filters the model) + beginFilterChange(); + endFilterChange(); + } + + // --------------------------------------------------------------- + QSharedPointer TelegramProxyModel::telegram(int row) const + { + const TelegramModel *tm = qobject_cast(sourceModel()); + if (!tm) + return {}; + const int srcRow = mapToSource(index(row, 0)).row(); + return tm->telegram(srcRow); + } + + // --------------------------------------------------------------- + bool TelegramProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const + { + if (left.column() != right.column()) + return QSortFilterProxyModel::lessThan(left, right); + const TelegramModel *tm = qobject_cast(sourceModel()); + if (!tm) + return QSortFilterProxyModel::lessThan(left, right); + QSharedPointer teleLeft = tm->telegram(left.row()); + QSharedPointer teleRight = tm->telegram(right.row()); + if (!teleLeft || !teleRight) + return QSortFilterProxyModel::lessThan(left, right); + + switch (left.column()) + { case 0: - return tr("Dest."); + return teleLeft->getDestination() < teleRight->getDestination(); case 1: - return tr("Description"); + return teleLeft->getName() < teleRight->getName(); case 2: - return tr("Equip. No."); + return teleLeft->getParticipantId() < teleRight->getParticipantId(); case 3: - return tr("Send/Recieve time"); + return teleLeft->getLogTime() < teleRight->getLogTime(); case 4: - return tr("GPS time"); + return teleLeft->getGpsTime() < teleRight->getGpsTime(); case 5: - return tr("Delay"); - default: + return teleLeft->getDelay() < teleRight->getDelay(); + } + return QSortFilterProxyModel::lessThan(left, right); + } + + // --------------------------------------------------------------- + bool TelegramProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const + { + // TODO: optimize + const TelegramModel *tm = qobject_cast(sourceModel()); + if (!tm) + return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); + + QSharedPointer tele = tm->telegram(source_row); + if (!tele) + return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); + + if (m_bFilterByEquipmentIds) + { + int equipId = tele->getParticipantId(); + if (m_allowedEquipmentIds.find(equipId) == m_allowedEquipmentIds.end()) + return false; + } + switch (tele->getProtocol()) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + if (!m_filteredCentralTelegramIds.empty()) + { + const int telegramId = tele->getTelId(); + if (m_filteredCentralTelegramIds.find(telegramId) != m_filteredCentralTelegramIds.end()) + return false; + } + if (!m_filterCentralTelegrams.empty()) + { + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); + if (m_filterCentralTelegrams.find(direction) != m_filterCentralTelegrams.end()) + return false; + } + break; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + if (!m_filteredTetraTelegramIds.empty()) + { + const int telegramId = tele->getTelId(); + if (m_filteredTetraTelegramIds.find(telegramId) != m_filteredTetraTelegramIds.end()) + return false; + } + if (!m_filterTetraTelegrams.empty()) + { + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); + if (m_filterTetraTelegrams.find(direction) != m_filterTetraTelegrams.end()) + return false; + } + const N_CoPrtCnv::CoPrtCnvRadioTelegram *tetraTelegram = tele->getTetraTelegram(); + if (tetraTelegram) + { + if (!m_filterTetraPDU.empty()) + { + N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType = tetraTelegram->getPDU_Type(); + if (m_filterTetraPDU.find(pduType) != m_filterTetraPDU.end()) + return false; + } + if (m_bFilterLoginTelegrams) + { + if (tetraTelegram->isLoginTelegram()) + return false; + } + if (m_bFilterFragmentedTelegrams) + { + if (!tetraTelegram->isLoginTelegram() && !tetraTelegram->isNormalTelegram()) + return false; + } + } break; } + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + if (!m_filteredWlsTelegramIds.empty()) + { + const int telegramId = tele->getTelId(); + if (m_filteredWlsTelegramIds.find(telegramId) != m_filteredWlsTelegramIds.end()) + return false; + } + if (!m_filterWlsTelegrams.empty()) + { + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); + if (m_filterWlsTelegrams.find(direction) != m_filterWlsTelegrams.end()) + return false; + } + break; + default: + break; } + return true; } - return QAbstractTableModel::headerData(section, orientation, role); -} - -// --------------------------------------------------------------- -void TelegramModel::clearTelegrams() -{ - beginResetModel(); - m_telegrams.clear(); - endResetModel(); -} - -// --------------------------------------------------------------- -void TelegramModel::appendTelegrams(const QVector > &telegrams) -{ - if (telegrams.isEmpty()) - return; - beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size() + telegrams.size() - 1); - m_telegrams += telegrams; - endInsertRows(); -} - -// --------------------------------------------------------------- -void TelegramModel::appendTelegram(const QSharedPointer &telegram) -{ - beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size()); - m_telegrams.push_back(telegram); - endInsertRows(); -} - -// --------------------------------------------------------------- -QSharedPointer TelegramModel::telegram(int row) const -{ - if (row >= 0 && row < m_telegrams.size()) - return m_telegrams.at(row); - return QSharedPointer(); -} - -// --------------------------------------------------------------- -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterByEquipmentIds(bool bFilterByEquipmentIds) -{ - if (m_bFilterByEquipmentIds == bFilterByEquipmentIds) - return; - m_bFilterByEquipmentIds = bFilterByEquipmentIds; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setAllowedEquipmentIds(const std::set &allowedEquipmentIds) -{ - if (m_allowedEquipmentIds == allowedEquipmentIds) - return; - m_allowedEquipmentIds = allowedEquipmentIds; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilteredCentralTelegramIds(const std::set &filteredCentralTelegramIds) -{ - if (m_filteredCentralTelegramIds == filteredCentralTelegramIds) - return; - m_filteredCentralTelegramIds = filteredCentralTelegramIds; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilteredTetraTelegramIds(const std::set &filteredTetraTelegramIds) -{ - if (m_filteredTetraTelegramIds == filteredTetraTelegramIds) - return; - m_filteredTetraTelegramIds = filteredTetraTelegramIds; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilteredWlsTelegramIds(const std::set &filteredWlsTelegramIds) -{ - if (m_filteredWlsTelegramIds == filteredWlsTelegramIds) - return; - m_filteredWlsTelegramIds = filteredWlsTelegramIds; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, - bool bFilter) -{ - std::set curFilter = m_filterCentralTelegrams; - if (bFilter) - curFilter.insert(direction); - else - curFilter.erase(direction); - if (curFilter == m_filterCentralTelegrams) - return; - m_filterCentralTelegrams = curFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, - bool bFilter) -{ - std::set curFilter = m_filterTetraTelegrams; - if (bFilter) - curFilter.insert(direction); - else - curFilter.erase(direction); - if (curFilter == m_filterTetraTelegrams) - return; - m_filterTetraTelegrams = curFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType, - bool bFilter) -{ - std::set curFilter = m_filterTetraPDU; - if (bFilter) - curFilter.insert(pduType); - else - curFilter.erase(pduType); - if (curFilter == m_filterTetraPDU) - return; - m_filterTetraPDU = curFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -void TelegramProxyModel::setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, - bool bFilter) -{ - std::set curFilter = m_filterWlsTelegrams; - if (bFilter) - curFilter.insert(direction); - else - curFilter.erase(direction); - if (curFilter == m_filterWlsTelegrams) - return; - m_filterWlsTelegrams = curFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterTetraLogin(bool bFilter) -{ - if (m_bFilterLoginTelegrams == bFilter) - return; - m_bFilterLoginTelegrams = bFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -void TelegramProxyModel::setFilterTetraFragmented(bool bFilter) -{ - if (m_bFilterFragmentedTelegrams == bFilter) - return; - m_bFilterFragmentedTelegrams = bFilter; - // invalidateFilter() is deprecated in Qt6 - begin/endFilterChange() is the - // documented replacement (re-filters the model) - beginFilterChange(); - endFilterChange(); -} - -// --------------------------------------------------------------- -QSharedPointer TelegramProxyModel::telegram(int row) const -{ - const TelegramModel *tm = qobject_cast(sourceModel()); - if (!tm) - return {}; - const int srcRow = mapToSource(index(row, 0)).row(); - return tm->telegram(srcRow); -} - -// --------------------------------------------------------------- -bool TelegramProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const -{ - if (left.column() != right.column()) - return QSortFilterProxyModel::lessThan(left, right); - const TelegramModel *tm = qobject_cast(sourceModel()); - if (!tm) - return QSortFilterProxyModel::lessThan(left, right); - QSharedPointer teleLeft = tm->telegram(left.row()); - QSharedPointer teleRight = tm->telegram(right.row()); - if (!teleLeft || !teleRight) - return QSortFilterProxyModel::lessThan(left, right); - - switch (left.column()) - { - case 0: - return teleLeft->getDestination() < teleRight->getDestination(); - case 1: - return teleLeft->getName() < teleRight->getName(); - case 2: - return teleLeft->getParticipantId() < teleRight->getParticipantId(); - case 3: - return teleLeft->getLogTime() < teleRight->getLogTime(); - case 4: - return teleLeft->getGpsTime() < teleRight->getGpsTime(); - case 5: - return teleLeft->getDelay() < teleRight->getDelay(); - } - return QSortFilterProxyModel::lessThan(left, right); -} - -// --------------------------------------------------------------- -bool TelegramProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const -{ - // TODO: optimize - const TelegramModel *tm = qobject_cast(sourceModel()); - if (!tm) - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - - QSharedPointer tele = tm->telegram(source_row); - if (!tele) - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - - if (m_bFilterByEquipmentIds) - { - int equipId = tele->getParticipantId(); - if (m_allowedEquipmentIds.find(equipId) == m_allowedEquipmentIds.end()) - return false; - } - switch (tele->getProtocol()) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - if (!m_filteredCentralTelegramIds.empty()) - { - const int telegramId = tele->getTelId(); - if (m_filteredCentralTelegramIds.find(telegramId) != m_filteredCentralTelegramIds.end()) - return false; - } - if (!m_filterCentralTelegrams.empty()) - { - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); - if (m_filterCentralTelegrams.find(direction) != m_filterCentralTelegrams.end()) - return false; - } - break; - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: - { - if (!m_filteredTetraTelegramIds.empty()) - { - const int telegramId = tele->getTelId(); - if (m_filteredTetraTelegramIds.find(telegramId) != m_filteredTetraTelegramIds.end()) - return false; - } - if (!m_filterTetraTelegrams.empty()) - { - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); - if (m_filterTetraTelegrams.find(direction) != m_filterTetraTelegrams.end()) - return false; - } - const N_CoPrtCnv::CoPrtCnvRadioTelegram *tetraTelegram = tele->getTetraTelegram(); - if (tetraTelegram) - { - if (!m_filterTetraPDU.empty()) - { - N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType = tetraTelegram->getPDU_Type(); - if (m_filterTetraPDU.find(pduType) != m_filterTetraPDU.end()) - return false; - } - if (m_bFilterLoginTelegrams) - { - if (tetraTelegram->isLoginTelegram()) - return false; - } - if (m_bFilterFragmentedTelegrams) - { - if (!tetraTelegram->isLoginTelegram() && !tetraTelegram->isNormalTelegram()) - return false; - } - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: - if (!m_filteredWlsTelegramIds.empty()) - { - const int telegramId = tele->getTelId(); - if (m_filteredWlsTelegramIds.find(telegramId) != m_filteredWlsTelegramIds.end()) - return false; - } - if (!m_filterWlsTelegrams.empty()) - { - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction = tele->getDirection(); - if (m_filterWlsTelegrams.find(direction) != m_filterWlsTelegrams.end()) - return false; - } - break; - default: - break; - } - return true; -} } // namespace N_LogView; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.hpp index 53ca4c133..634193d68 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewModels.hpp @@ -21,94 +21,95 @@ namespace N_LogView { -class ParticipantModel final : public QAbstractTableModel -{ - Q_OBJECT -public: - using QAbstractTableModel::QAbstractTableModel; + class ParticipantModel final : public QAbstractTableModel + { + Q_OBJECT + public: + using QAbstractTableModel::QAbstractTableModel; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - void clearParticipants(); - bool addUpdateParticipants(const QVector &eqIds, - const QVector &issis, - const QVector &numberOfTelegrams); -protected: - void updateHeatMap() const; -protected: - // eqId , issi - QVector > m_particpants; - // eqid, count telegrams - QHash m_particpantMap; - // eqId, QColor for heatmap - mutable QHash m_participantHeatmap; -}; + void clearParticipants(); + bool addUpdateParticipants(const QVector &eqIds, const QVector &issis, const QVector &numberOfTelegrams); -class TelegramModel final : public QAbstractTableModel -{ - Q_OBJECT -public: - using QAbstractTableModel::QAbstractTableModel; + protected: + void updateHeatMap() const; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + protected: + // eqId , issi + QVector> m_particpants; + // eqid, count telegrams + QHash m_particpantMap; + // eqId, QColor for heatmap + mutable QHash m_participantHeatmap; + }; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + class TelegramModel final : public QAbstractTableModel + { + Q_OBJECT + public: + using QAbstractTableModel::QAbstractTableModel; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; - void clearTelegrams(); - void appendTelegrams(const QVector > &telegrams); - void appendTelegram(const QSharedPointer &telegram); - QSharedPointer telegram(int row) const; -protected: - QVector > m_telegrams; -}; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; -class TelegramProxyModel final : public QSortFilterProxyModel -{ - Q_OBJECT -public: - using QSortFilterProxyModel::QSortFilterProxyModel; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - void setFilterByEquipmentIds(bool bFilterByEquipmentIds); - void setAllowedEquipmentIds(const std::set &allowedEquipmentIds); + void clearTelegrams(); + void appendTelegrams(const QVector> &telegrams); + void appendTelegram(const QSharedPointer &telegram); + QSharedPointer telegram(int row) const; - void setFilteredCentralTelegramIds(const std::set &filteredCentralTelegramIds); - void setFilteredTetraTelegramIds(const std::set &filteredTetraTelegramIds); - void setFilteredWlsTelegramIds(const std::set &filteredWlsTelegramIds); + protected: + QVector> m_telegrams; + }; - void setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); - void setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); - void setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType, bool bFilter); - void setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); + class TelegramProxyModel final : public QSortFilterProxyModel + { + Q_OBJECT + public: + using QSortFilterProxyModel::QSortFilterProxyModel; - void setFilterTetraLogin(bool bFilter); - void setFilterTetraFragmented(bool bFilter); + void setFilterByEquipmentIds(bool bFilterByEquipmentIds); + void setAllowedEquipmentIds(const std::set &allowedEquipmentIds); - QSharedPointer telegram(int row) const; -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; - bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; -protected: - std::set m_allowedEquipmentIds; - std::set m_filteredCentralTelegramIds; - std::set m_filteredTetraTelegramIds; - std::set m_filteredWlsTelegramIds; - bool m_bFilterByEquipmentIds = false; - bool m_bFilterLoginTelegrams = false; - bool m_bFilterFragmentedTelegrams = false; - std::set m_filterCentralTelegrams; - std::set m_filterTetraTelegrams; - std::set m_filterWlsTelegrams; - std::set m_filterTetraPDU; -}; + void setFilteredCentralTelegramIds(const std::set &filteredCentralTelegramIds); + void setFilteredTetraTelegramIds(const std::set &filteredTetraTelegramIds); + void setFilteredWlsTelegramIds(const std::set &filteredWlsTelegramIds); + + void setFilterCentralTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); + void setFilterTetraTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); + void setFilterTetraPDU(N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type pduType, bool bFilter); + void setFilterWlsTelegrams(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol direction, bool bFilter); + + void setFilterTetraLogin(bool bFilter); + void setFilterTetraFragmented(bool bFilter); + + QSharedPointer telegram(int row) const; + + protected: + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; + + protected: + std::set m_allowedEquipmentIds; + std::set m_filteredCentralTelegramIds; + std::set m_filteredTetraTelegramIds; + std::set m_filteredWlsTelegramIds; + bool m_bFilterByEquipmentIds = false; + bool m_bFilterLoginTelegrams = false; + bool m_bFilterFragmentedTelegrams = false; + std::set m_filterCentralTelegrams; + std::set m_filterTetraTelegrams; + std::set m_filterWlsTelegrams; + std::set m_filterTetraPDU; + }; } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.cpp index 8f0c06752..1b3dd134f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.cpp @@ -1,14 +1,14 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** #include "LogViewOptionDialog.hpp" @@ -28,155 +28,153 @@ namespace N_LogView { -// static member initialization -const QString LogViewOptionDialog::SPEC_FILES = tr("Spezifikations-Dateien (*.x)"); -const QString LogViewOptionDialog::KRLOG_FILES = tr("Log-Dateien (*.krlog)"); -const QLatin1String LogViewOptionDialog::SPEC_FILES_GROUP("SpecFiles"); -const QLatin1String LogViewOptionDialog::DIR("Dir"); -const QLatin1String LogViewOptionDialog::P0_FILENAME("Central2PrtCnv"); -const QLatin1String LogViewOptionDialog::P5_FILENAME("PrtCnv2TETRA"); -const QLatin1String LogViewOptionDialog::SERVER_GROUP("ServerPorts"); -const QLatin1String LogViewOptionDialog::CENTRAL_PORT("Central"); -const QLatin1String LogViewOptionDialog::TETRA_PORT("Tetra"); -const QLatin1String LogViewOptionDialog::LOG_FILENAME("LogFilename"); -const QLatin1String LogViewOptionDialog::INJECTION_GROUP("InjectionServer"); -const QLatin1String LogViewOptionDialog::INJECTION_HOSTNAME("InjectionHostname"); -const QLatin1String LogViewOptionDialog::INJECTION_PORT("InjectionPort"); + // static member initialization + const QString LogViewOptionDialog::SPEC_FILES = tr("Spezifikations-Dateien (*.x)"); + const QString LogViewOptionDialog::KRLOG_FILES = tr("Log-Dateien (*.krlog)"); + const QLatin1String LogViewOptionDialog::SPEC_FILES_GROUP("SpecFiles"); + const QLatin1String LogViewOptionDialog::DIR("Dir"); + const QLatin1String LogViewOptionDialog::P0_FILENAME("Central2PrtCnv"); + const QLatin1String LogViewOptionDialog::P5_FILENAME("PrtCnv2TETRA"); + const QLatin1String LogViewOptionDialog::SERVER_GROUP("ServerPorts"); + const QLatin1String LogViewOptionDialog::CENTRAL_PORT("Central"); + const QLatin1String LogViewOptionDialog::TETRA_PORT("Tetra"); + const QLatin1String LogViewOptionDialog::LOG_FILENAME("LogFilename"); + const QLatin1String LogViewOptionDialog::INJECTION_GROUP("InjectionServer"); + const QLatin1String LogViewOptionDialog::INJECTION_HOSTNAME("InjectionHostname"); + const QLatin1String LogViewOptionDialog::INJECTION_PORT("InjectionPort"); -// --------------------------------------------------------------- -LogViewOptionDialog::LogViewOptionDialog(QWidget* a_parent) - : QDialog(a_parent) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - - // telegram specification files - m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); - QGroupBox* groupBox = new QGroupBox(tr("Telegramm-Spezifikations-Dateien"), this); - layout->addWidget(groupBox); - - QGridLayout* groupLayout = new QGridLayout(); - - QLabel* p0Label = new QLabel(tr("&Zentrale - Protokollkonverter"), this); - groupLayout->addWidget(p0Label, 0, 0, 1, 2); - QString defString = QCoreApplication::applicationDirPath() + QLatin1String("/training_area_telegrams.h"); - m_P0Edit = new QLineEdit(m_Settings.value(P0_FILENAME, defString).toString(), this); - m_P0Edit->setMinimumWidth(400); - groupLayout->addWidget(m_P0Edit); - QPushButton* p0Browse = new QPushButton(tr("Browse"), this); - p0Label->setBuddy(p0Browse); - connect(p0Browse, &QPushButton::clicked, this, &LogViewOptionDialog::browseP0File); - groupLayout->addWidget(p0Browse, 1, 1); - - QLabel* p5Label = new QLabel(tr("Protokollkonverter - &TETRA"), this); - groupLayout->addWidget(p5Label, 2, 0, 1, 2); - defString = QCoreApplication::applicationDirPath() + QLatin1String("/zsksxd_tetraForLogView.x"); - m_P5Edit = new QLineEdit(m_Settings.value(P5_FILENAME, defString).toString(), this); - groupLayout->addWidget(m_P5Edit); - QPushButton* p5Browse = new QPushButton(tr("Browse"), this); - p5Label->setBuddy(p5Browse); - connect(p5Browse, &QPushButton::clicked, this, &LogViewOptionDialog::browseP5File); - groupLayout->addWidget(p5Browse, 3, 1); - - groupBox->setLayout(groupLayout); - m_Settings.endGroup(); - - // injection - m_Settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); - groupBox = new QGroupBox(tr("Telegram Injection Server"), this); - layout->addWidget(groupBox); - QGridLayout* injectLayout = new QGridLayout(); - - QLabel* injectPortLabel = new QLabel(tr("Port"), this); - injectLayout->addWidget(injectPortLabel, 1, 0); - m_InjectPortEdit = new QLineEdit(m_Settings.value(INJECTION_PORT).toString(), this); - QIntValidator* validator = new QIntValidator(1024, 65535, this); - m_InjectPortEdit->setValidator(validator); - injectLayout->addWidget(m_InjectPortEdit, 1, 1); - - QLabel* injectHostnameLabel = new QLabel(tr("Hostname"), this); - injectLayout->addWidget(injectHostnameLabel, 0, 0); - m_InjectHostnameEdit = new QLineEdit(m_Settings.value(INJECTION_HOSTNAME).toString(), this); - injectLayout->addWidget(m_InjectHostnameEdit, 0, 1); - - groupBox->setLayout(injectLayout); - m_Settings.endGroup(); - - // buttons - layout->addStretch(); - QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, &QDialogButtonBox::accepted, this, &LogViewOptionDialog::save); - connect(buttonBox, &QDialogButtonBox::rejected, this, &LogViewOptionDialog::reject); - layout->addWidget(buttonBox); - - //setLayout(layout); -} - - -// --------------------------------------------------------------- -void LogViewOptionDialog::browseP0File() -{ - QString newFilename = QFileDialog::getOpenFileName(this, - tr("Zentrale - Protokollkonverter Spezifikations-Datei"), - m_Settings.value(DIR).toString(), - tr("TrainingArea Telegram Headerdatei (training_area_telegrams.h)")); - if (!newFilename.isEmpty()) + // --------------------------------------------------------------- + LogViewOptionDialog::LogViewOptionDialog(QWidget *a_parent) + : QDialog(a_parent) { - m_P0Edit->setText(newFilename); - QDir dir; + QVBoxLayout *layout = new QVBoxLayout(this); + + // telegram specification files m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); - m_Settings.setValue(DIR, dir.filePath(newFilename)); + QGroupBox *groupBox = new QGroupBox(tr("Telegramm-Spezifikations-Dateien"), this); + layout->addWidget(groupBox); + + QGridLayout *groupLayout = new QGridLayout(); + + QLabel *p0Label = new QLabel(tr("&Zentrale - Protokollkonverter"), this); + groupLayout->addWidget(p0Label, 0, 0, 1, 2); + QString defString = QCoreApplication::applicationDirPath() + QLatin1String("/training_area_telegrams.h"); + m_P0Edit = new QLineEdit(m_Settings.value(P0_FILENAME, defString).toString(), this); + m_P0Edit->setMinimumWidth(400); + groupLayout->addWidget(m_P0Edit); + QPushButton *p0Browse = new QPushButton(tr("Browse"), this); + p0Label->setBuddy(p0Browse); + connect(p0Browse, &QPushButton::clicked, this, &LogViewOptionDialog::browseP0File); + groupLayout->addWidget(p0Browse, 1, 1); + + QLabel *p5Label = new QLabel(tr("Protokollkonverter - &TETRA"), this); + groupLayout->addWidget(p5Label, 2, 0, 1, 2); + defString = QCoreApplication::applicationDirPath() + QLatin1String("/zsksxd_tetraForLogView.x"); + m_P5Edit = new QLineEdit(m_Settings.value(P5_FILENAME, defString).toString(), this); + groupLayout->addWidget(m_P5Edit); + QPushButton *p5Browse = new QPushButton(tr("Browse"), this); + p5Label->setBuddy(p5Browse); + connect(p5Browse, &QPushButton::clicked, this, &LogViewOptionDialog::browseP5File); + groupLayout->addWidget(p5Browse, 3, 1); + + groupBox->setLayout(groupLayout); m_Settings.endGroup(); + + // injection + m_Settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); + groupBox = new QGroupBox(tr("Telegram Injection Server"), this); + layout->addWidget(groupBox); + QGridLayout *injectLayout = new QGridLayout(); + + QLabel *injectPortLabel = new QLabel(tr("Port"), this); + injectLayout->addWidget(injectPortLabel, 1, 0); + m_InjectPortEdit = new QLineEdit(m_Settings.value(INJECTION_PORT).toString(), this); + QIntValidator *validator = new QIntValidator(1024, 65535, this); + m_InjectPortEdit->setValidator(validator); + injectLayout->addWidget(m_InjectPortEdit, 1, 1); + + QLabel *injectHostnameLabel = new QLabel(tr("Hostname"), this); + injectLayout->addWidget(injectHostnameLabel, 0, 0); + m_InjectHostnameEdit = new QLineEdit(m_Settings.value(INJECTION_HOSTNAME).toString(), this); + injectLayout->addWidget(m_InjectHostnameEdit, 0, 1); + + groupBox->setLayout(injectLayout); + m_Settings.endGroup(); + + // buttons + layout->addStretch(); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, &QDialogButtonBox::accepted, this, &LogViewOptionDialog::save); + connect(buttonBox, &QDialogButtonBox::rejected, this, &LogViewOptionDialog::reject); + layout->addWidget(buttonBox); + + //setLayout(layout); } -} -// --------------------------------------------------------------- -void LogViewOptionDialog::browseP5File() -{ - QString newFilename = QFileDialog::getOpenFileName(this, tr("Protokollkonverter - TETRA Spezifikations-Datei"), m_Settings.value(DIR).toString(), SPEC_FILES); - if (!newFilename.isEmpty()) + // --------------------------------------------------------------- + void LogViewOptionDialog::browseP0File() { - m_P5Edit->setText(newFilename); - QDir dir; + QString newFilename = QFileDialog::getOpenFileName(this, + tr("Zentrale - Protokollkonverter Spezifikations-Datei"), + m_Settings.value(DIR).toString(), + tr("TrainingArea Telegram Headerdatei (training_area_telegrams.h)")); + if (!newFilename.isEmpty()) + { + m_P0Edit->setText(newFilename); + QDir dir; + m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); + m_Settings.setValue(DIR, dir.filePath(newFilename)); + m_Settings.endGroup(); + } + } + + + // --------------------------------------------------------------- + void LogViewOptionDialog::browseP5File() + { + QString newFilename = QFileDialog::getOpenFileName(this, tr("Protokollkonverter - TETRA Spezifikations-Datei"), m_Settings.value(DIR).toString(), SPEC_FILES); + if (!newFilename.isEmpty()) + { + m_P5Edit->setText(newFilename); + QDir dir; + m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); + m_Settings.setValue(DIR, dir.filePath(newFilename)); + m_Settings.endGroup(); + } + } + + // --------------------------------------------------------------- + void LogViewOptionDialog::save() + { + uint32_t changedFlags = 0; + + // check group wise for changes + // specification files m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); - m_Settings.setValue(DIR, dir.filePath(newFilename)); + QString string = m_Settings.value(P0_FILENAME).toString(); + if ((string != m_P0Edit->text()) || (m_Settings.value(P5_FILENAME).toString() != m_P5Edit->text())) + { + m_Settings.setValue(P0_FILENAME, m_P0Edit->text()); + m_Settings.setValue(P5_FILENAME, m_P5Edit->text()); + changedFlags |= SpecFilesGroup; + } m_Settings.endGroup(); + + // injection settings + m_Settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); + if ((m_Settings.value(INJECTION_HOSTNAME).toString() != m_InjectHostnameEdit->text()) || (m_Settings.value(INJECTION_PORT).toString() != m_InjectPortEdit->text())) + { + m_Settings.setValue(INJECTION_HOSTNAME, m_InjectHostnameEdit->text()); + m_Settings.setValue(INJECTION_PORT, m_InjectPortEdit->text()); + changedFlags |= InjectionGroup; + } + m_Settings.endGroup(); + + emit settingsChanged(changedFlags); + + accept(); } -} - -// --------------------------------------------------------------- -void LogViewOptionDialog::save() -{ - uint32_t changedFlags = 0; - - // check group wise for changes - // specification files - m_Settings.beginGroup(LogViewOptionDialog::SPEC_FILES_GROUP); - QString string = m_Settings.value(P0_FILENAME).toString(); - if ((string != m_P0Edit->text()) || - (m_Settings.value(P5_FILENAME).toString() != m_P5Edit->text())) - { - m_Settings.setValue(P0_FILENAME, m_P0Edit->text()); - m_Settings.setValue(P5_FILENAME, m_P5Edit->text()); - changedFlags |= SpecFilesGroup; - } - m_Settings.endGroup(); - - // injection settings - m_Settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP); - if ((m_Settings.value(INJECTION_HOSTNAME).toString() != m_InjectHostnameEdit->text()) || - (m_Settings.value(INJECTION_PORT).toString() != m_InjectPortEdit->text())) - { - m_Settings.setValue(INJECTION_HOSTNAME, m_InjectHostnameEdit->text()); - m_Settings.setValue(INJECTION_PORT, m_InjectPortEdit->text()); - changedFlags |= InjectionGroup; - } - m_Settings.endGroup(); - - emit settingsChanged(changedFlags); - - accept(); -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.hpp index d891bfb7a..e8e775e38 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewOptionDialog.hpp @@ -20,65 +20,64 @@ class QLineEdit; namespace N_LogView { -/** + /** * This class lets the user view and change the settings of the application * * @author alois.wismer * @version 1.0 * @created 09-Mrz-2010 14:49:40 */ -class LogViewOptionDialog : public QDialog -{ - Q_OBJECT -public: + class LogViewOptionDialog : public QDialog + { + Q_OBJECT + public: + enum SettingsChangedFlag + { + SpecFilesGroup = 0x01, + ServerGroup = 0x02, + InjectionGroup = 0x04 + }; - enum SettingsChangedFlag { - SpecFilesGroup = 0x01, - ServerGroup = 0x02, - InjectionGroup = 0x04 - }; - - static const QString KRLOG_FILES; - static const QLatin1String SPEC_FILES_GROUP; - static const QLatin1String P0_FILENAME; - static const QLatin1String P5_FILENAME; - static const QLatin1String SERVER_GROUP; - static const QLatin1String CENTRAL_PORT; - static const QLatin1String TETRA_PORT; - static const QLatin1String SIZE; - static const QLatin1String POS; - static const QLatin1String CENTRAL_IS_SERVER; - static const QLatin1String CENTRAL_HOSTNAME; - static const QLatin1String LOG_FILENAME; - static const QLatin1String INJECTION_GROUP; - static const QLatin1String INJECTION_HOSTNAME; - static const QLatin1String INJECTION_PORT; + static const QString KRLOG_FILES; + static const QLatin1String SPEC_FILES_GROUP; + static const QLatin1String P0_FILENAME; + static const QLatin1String P5_FILENAME; + static const QLatin1String SERVER_GROUP; + static const QLatin1String CENTRAL_PORT; + static const QLatin1String TETRA_PORT; + static const QLatin1String SIZE; + static const QLatin1String POS; + static const QLatin1String CENTRAL_IS_SERVER; + static const QLatin1String CENTRAL_HOSTNAME; + static const QLatin1String LOG_FILENAME; + static const QLatin1String INJECTION_GROUP; + static const QLatin1String INJECTION_HOSTNAME; + static const QLatin1String INJECTION_PORT; - /** + /** * * @param a_parent a_parent */ - explicit LogViewOptionDialog(QWidget* a_parent); + explicit LogViewOptionDialog(QWidget *a_parent); -signals: - void settingsChanged(uint32_t changed); // bitfield of SettingsChangedFlag enum + signals: + void settingsChanged(uint32_t changed); // bitfield of SettingsChangedFlag enum -protected: + protected: + static const QString SPEC_FILES; + static const QLatin1String DIR; + bool m_IsServer; + QLineEdit *m_P0Edit; + QLineEdit *m_P5Edit; + QSettings m_Settings; + QLineEdit *m_InjectHostnameEdit; + QLineEdit *m_InjectPortEdit; - static const QString SPEC_FILES; - static const QLatin1String DIR; - bool m_IsServer; - QLineEdit *m_P0Edit; - QLineEdit *m_P5Edit; - QSettings m_Settings; - QLineEdit *m_InjectHostnameEdit; - QLineEdit *m_InjectPortEdit; - -protected slots: - void browseP0File(); - void browseP5File(); - void save(); -}; + protected slots: + void browseP0File(); + void browseP5File(); + void save(); + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.cpp index fce5a09c6..c72bf2725 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.cpp @@ -1,59 +1,58 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewSpinBox.hpp" #include "LogViewField.hpp" namespace N_LogView { -// --------------------------------------------------------------- -LogViewSpinBox::LogViewSpinBox(LogViewField* a_field, QWidget* a_parent, const int a_value) - : QSpinBox(a_parent) - , LogViewWidget(a_field, this, a_parent, false) -{ - // set range - uint16_t maxArraySize = a_field->maxArraySize(); - setRange(0, maxArraySize); + // --------------------------------------------------------------- + LogViewSpinBox::LogViewSpinBox(LogViewField *a_field, QWidget *a_parent, const int a_value) + : QSpinBox(a_parent) + , LogViewWidget(a_field, this, a_parent, false) + { + // set range + uint16_t maxArraySize = a_field->maxArraySize(); + setRange(0, maxArraySize); - // set the actual value - setValue(a_value); + // set the actual value + setValue(a_value); - // set tooltip-text - setToolTip(tr("Wertebereich: 0..%1").arg(maxArraySize)); + // set tooltip-text + setToolTip(tr("Wertebereich: 0..%1").arg(maxArraySize)); - // connect - connect(this, &LogViewSpinBox::editingFinished, - this, &LogViewSpinBox::finishEditing); -} + // connect + connect(this, &LogViewSpinBox::editingFinished, this, &LogViewSpinBox::finishEditing); + } -// --------------------------------------------------------------- -void LogViewSpinBox::finishEditing() -{ - emit valueEditingFinished(text().toInt()); -} + // --------------------------------------------------------------- + void LogViewSpinBox::finishEditing() + { + emit valueEditingFinished(text().toInt()); + } -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewSpinBox::saveContent(LogViewTelegram* a_telegram) -{ - Q_UNUSED(a_telegram); - // not yet implemented - return false; -} + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewSpinBox::saveContent(LogViewTelegram *a_telegram) + { + Q_UNUSED(a_telegram); + // not yet implemented + return false; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.hpp index 98c7fcee9..803da0bf0 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewSpinBox.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -25,7 +25,9 @@ namespace N_LogView * @version 1.0 * @created 25-Mai-2010 10:39:45 */ - class LogViewSpinBox : public QSpinBox, public LogViewWidget + class LogViewSpinBox + : public QSpinBox + , public LogViewWidget { Q_OBJECT public: @@ -35,7 +37,7 @@ namespace N_LogView * @param a_parent * @param a_value */ - LogViewSpinBox(LogViewField* a_field, QWidget* a_parent, const int a_value); + LogViewSpinBox(LogViewField *a_field, QWidget *a_parent, const int a_value); /** * Writes the content into telegram. @@ -43,7 +45,7 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; protected slots: void finishEditing(); @@ -54,7 +56,6 @@ namespace N_LogView * @param a_newValue */ void valueEditingFinished(int a_newValue); - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.cpp index 61b8a7352..03a44ef5e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.cpp @@ -1,14 +1,14 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** #include "LogViewTabWidget.hpp" @@ -25,116 +25,116 @@ namespace N_LogView { -LogViewTabWidget::LogViewTabWidget(LogViewField* a_field, LogViewTelegramDialog* a_parent, LogViewSpinBox* a_spinBox, NGL::INGLLogger& logger) - : QTabWidget(a_parent) - , LogViewWidget(a_field, this, a_parent, false) - , m_TelegramDialog(a_parent) - , m_SpinBox(a_spinBox) - , m_logger(logger) -{ - setVisible(false); -} - - -// --------------------------------------------------------------- -void LogViewTabWidget::changeSize(const int a_newSize) -{ - // add new tabs - for (int i = count(); i < a_newSize; i++) - addTab(m_Field, true, i); - - // remove old tabs - while (count() > a_newSize) + LogViewTabWidget::LogViewTabWidget(LogViewField *a_field, LogViewTelegramDialog *a_parent, LogViewSpinBox *a_spinBox, NGL::INGLLogger &logger) + : QTabWidget(a_parent) + , LogViewWidget(a_field, this, a_parent, false) + , m_TelegramDialog(a_parent) + , m_SpinBox(a_spinBox) + , m_logger(logger) { - QStringList path = m_Field->jsonPath(); - path += QStringLiteral("index: %1").arg(count() - 1); - m_TelegramDialog->removeItemsFromEditInfoList(path); - removeTab(count() - 1); + setVisible(false); } - while (m_Field->childCount() > a_newSize) - m_Field->removeLastChild(); - setVisible(a_newSize > 0); - m_TelegramDialog->makePretty(); // fixme: funktioniert so nicht, muss als signal realisiert werden -} + // --------------------------------------------------------------- + void LogViewTabWidget::changeSize(const int a_newSize) + { + // add new tabs + for (int i = count(); i < a_newSize; i++) + addTab(m_Field, true, i); + + // remove old tabs + while (count() > a_newSize) + { + QStringList path = m_Field->jsonPath(); + path += QStringLiteral("index: %1").arg(count() - 1); + m_TelegramDialog->removeItemsFromEditInfoList(path); + removeTab(count() - 1); + } + while (m_Field->childCount() > a_newSize) + m_Field->removeLastChild(); -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewTabWidget::saveContent(LogViewTelegram* a_telegram) -{ - if (a_telegram->isJsonTelegram()) + setVisible(a_newSize > 0); + m_TelegramDialog->makePretty(); // fixme: funktioniert so nicht, muss als signal realisiert werden + } + + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewTabWidget::saveContent(LogViewTelegram *a_telegram) + { + if (a_telegram->isJsonTelegram()) + return true; + // if m_SpinBox is NULL, we have a static array => no size has to be stored + if (m_SpinBox) + { + if (!isValid()) + return false; + a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, count()); + } return true; - // if m_SpinBox is NULL, we have a static array => no size has to be stored - if (m_SpinBox) - { - if (!isValid()) - return false; - a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, count()); - } - return true; -} - - -// --------------------------------------------------------------- -void LogViewTabWidget::addTab(LogViewField* a_field, const bool a_isEmpty, int arrayIdx) -{ - if (arrayIdx < 0) - { - WARNING_LOG(m_logger) << "Invalid array index given: " << arrayIdx; - return; } - QFrame *frame = new QFrame; - QGridLayout *box = new QGridLayout(frame); - QTabWidget::addTab(frame, QStringLiteral("%1 %2").arg(a_field->cleanName()).arg(count()+1)); - if (a_isEmpty) - a_field->setHasContent(false); - auto *childTree = a_field->child(arrayIdx); - while (!childTree) + + // --------------------------------------------------------------- + void LogViewTabWidget::addTab(LogViewField *a_field, const bool a_isEmpty, int arrayIdx) { - const auto *first = a_field->child(0); - if (first) + if (arrayIdx < 0) { - LogViewField *fNew = first->clone(arrayIdx); - a_field->addChild(fNew); - childTree = a_field->child(arrayIdx); + WARNING_LOG(m_logger) << "Invalid array index given: " << arrayIdx; + return; } - else + + QFrame *frame = new QFrame; + QGridLayout *box = new QGridLayout(frame); + QTabWidget::addTab(frame, QStringLiteral("%1 %2").arg(a_field->cleanName()).arg(count() + 1)); + if (a_isEmpty) + a_field->setHasContent(false); + auto *childTree = a_field->child(arrayIdx); + while (!childTree) { - LogViewTetraTelegramsParser *p = LogViewTelegram::jsonParser(); - const StructInformation si = p->structFromType(a_field->type()); - if (si.type != a_field->type()) + const auto *first = a_field->child(0); + if (first) { - WARNING_LOG(m_logger) << "Could not find type '" << a_field->type() << "' - can not add substructure"; - return; + LogViewField *fNew = first->clone(arrayIdx); + a_field->addChild(fNew); + childTree = a_field->child(arrayIdx); + } + else + { + LogViewTetraTelegramsParser *p = LogViewTelegram::jsonParser(); + const StructInformation si = p->structFromType(a_field->type()); + if (si.type != a_field->type()) + { + WARNING_LOG(m_logger) << "Could not find type '" << a_field->type() << "' - can not add substructure"; + return; + } + LogViewField *tc = new LogViewField(a_field->name() + QStringLiteral("TabChild"), LogViewField::e_FieldKindTabChild, a_field->xdrElement()); + tc->setJsonPath(a_field->jsonPath()); + a_field->addChild(tc); + const QString path(QStringLiteral("index: %1")); + LogViewTelegram::addFieldTreeStruct(QJsonObject(), tc, si, path.arg(arrayIdx), m_logger); + childTree = a_field->child(arrayIdx); } - LogViewField *tc = new LogViewField(a_field->name() + QStringLiteral("TabChild"), LogViewField::e_FieldKindTabChild, a_field->xdrElement()); - tc->setJsonPath(a_field->jsonPath()); - a_field->addChild(tc); - const QString path(QStringLiteral("index: %1")); - LogViewTelegram::addFieldTreeStruct(QJsonObject(), tc, si, path.arg(arrayIdx), m_logger); - childTree = a_field->child(arrayIdx); } + m_TelegramDialog->showTree(childTree, box); + + // todo: sind nach dem dyn. array noch weitere Felder, so wird addTab nicht richtig funktionieren, weil die + // neuen Felder des Tabs am Ende von m_EditInfoList hinzugefügt werden => diese müssen mittendrin (an der richtigen + // position) eingefügt werden. + + // update spinbox + if (m_SpinBox) + { + int spinValue = m_SpinBox->value(); + if (spinValue < count()) + m_SpinBox->setValue(count()); + } + + setVisible(true); } - m_TelegramDialog->showTree(childTree, box); - - // todo: sind nach dem dyn. array noch weitere Felder, so wird addTab nicht richtig funktionieren, weil die - // neuen Felder des Tabs am Ende von m_EditInfoList hinzugefügt werden => diese müssen mittendrin (an der richtigen - // position) eingefügt werden. - - // update spinbox - if (m_SpinBox) - { - int spinValue = m_SpinBox->value(); - if (spinValue < count()) - m_SpinBox->setValue(count()); - } - - setVisible(true); -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.hpp index a957a066d..14460cf17 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTabWidget.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -30,15 +30,16 @@ namespace N_LogView * @version 1.0 * @created 26-Mai-2010 17:12:30 */ - class LogViewTabWidget : public QTabWidget, public LogViewWidget + class LogViewTabWidget + : public QTabWidget + , public LogViewWidget { Q_OBJECT public: + LogViewTabWidget(LogViewField *a_field, LogViewTelegramDialog *a_parent, LogViewSpinBox *a_spinBox, NGL::INGLLogger &logger); - LogViewTabWidget(LogViewField* a_field, LogViewTelegramDialog* a_parent, LogViewSpinBox* a_spinBox, NGL::INGLLogger& logger); - - bool saveContent(LogViewTelegram* a_telegram) override; - void addTab(LogViewField* a_field, const bool a_isEmpty, int arrayIdx); + bool saveContent(LogViewTelegram *a_telegram) override; + void addTab(LogViewField *a_field, const bool a_isEmpty, int arrayIdx); public slots: /** @@ -48,11 +49,9 @@ namespace N_LogView void changeSize(const int a_newSize); protected: - - LogViewTelegramDialog* m_TelegramDialog; - LogViewSpinBox* m_SpinBox; - NGL::INGLLogger& m_logger; - + LogViewTelegramDialog *m_TelegramDialog; + LogViewSpinBox *m_SpinBox; + NGL::INGLLogger &m_logger; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.cpp index 2f7383408..d1b4a094d 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewTableWidget.hpp" #include "LogViewField.hpp" @@ -24,289 +24,290 @@ namespace N_LogView { -LogViewTableWidget::LogViewTableWidget(LogViewField* a_field, QWidget* a_parent, const bool a_readonly, NGL::INGLLogger& logger) - : QTableWidget(0, 2, a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) - , m_IsFloat(false) - , m_IsEnum(false) - , m_logger(logger) -{ - switch (m_Field->xdrElement()->getKind()) + LogViewTableWidget::LogViewTableWidget(LogViewField *a_field, QWidget *a_parent, const bool a_readonly, NGL::INGLLogger &logger) + : QTableWidget(0, 2, a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) + , m_IsFloat(false) + , m_IsEnum(false) + , m_logger(logger) { - case LogViewXdrElement::e_KindEnum: - m_IsEnum = true; - break; - default: - m_IsFloat = LogViewXdrStandardType::e_Float == static_cast(m_Field->xdrElement())->getValueKind(); - } - if (!m_IsFloat) - setColumnCount(3); - if (m_IsEnum) - setColumnCount(1); - - setHorizontalHeaderItem(0, new QTableWidgetItem(m_IsEnum ? tr("Enum") : tr("Dez"))); - if (!m_IsEnum) - { - setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Hex"))); + switch (m_Field->xdrElement()->getKind()) + { + case LogViewXdrElement::e_KindEnum: + m_IsEnum = true; + break; + default: + m_IsFloat = LogViewXdrStandardType::e_Float == static_cast(m_Field->xdrElement())->getValueKind(); + } if (!m_IsFloat) - { - setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Bin"))); - } - } - setAlternatingRowColors(true); - - // make pretty -// horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); - - updateToolTip(); - - // for debugging only -// INFO_LOG(m_logger) << "type=" << static_cast(a_field->getXdrElement())->getValueKind(); -// INFO_LOG(m_logger) << "name=" << static_cast(a_field->getXdrElement())->getName().toStdString(); -// a_field->getXdrElement()->dump(); - - // fill in the values - // fixme: implementiere den Fall isHasContent() false - int nbrOfRows = a_field->valueListSize(); - setRowCount(nbrOfRows); - for (int i = 0; i < nbrOfRows; i++) - changeRow(i, a_field->value(i)); - - makePretty(); - - // connect signals - connect(this, &LogViewTableWidget::itemChanged, - this, &LogViewTableWidget::checkAndOvertakeContent); -} - - -// --------------------------------------------------------------- -void LogViewTableWidget::changeSize(const int a_newSize) -{ - setRowCount(a_newSize); - - disconnect(this, &LogViewTableWidget::itemChanged, - this, &LogViewTableWidget::checkAndOvertakeContent); - // check and set the new fields - for (int i = 0; i < a_newSize; i++) - changeRow(i, QLatin1String("0")); - - connect(this, &LogViewTableWidget::itemChanged, - this, &LogViewTableWidget::checkAndOvertakeContent); - - makePretty(); - - m_Valid = true; -} - - -// --------------------------------------------------------------- -void LogViewTableWidget::changeRow(const int a_rowIndex, const QString& a_value) -{ -// INFO_LOG(m_logger) << "a_rowIndex=" << a_rowIndex << " a_value=" << a_value.toStdString(); - - if (m_IsEnum) - { - // enum - QWidget* enumItem = cellWidget(a_rowIndex, 0); - if (!enumItem) - setCellWidget(a_rowIndex, 0, new LogViewEnumEdit(m_Field, this, m_Readonly, a_rowIndex)); - } - else - { - QFont font; - font.setStyleHint(QFont::TypeWriter); - font.setFamily(QString()); - // decimal - QTableWidgetItem* decItem = item(a_rowIndex, 0); - if (!decItem) - { - decItem = new QTableWidgetItem(); - //decItem->setData(Qt::DisplayRole, 0); - decItem->setText(a_value); - decItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - if (!m_Readonly) - { - decItem->setFlags(decItem->flags() | Qt::ItemIsEditable); - } - decItem->setFont(font); - decItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); - setItem(a_rowIndex, 0, decItem); - } - - // hexadecimal - QTableWidgetItem* hexItem = item(a_rowIndex, 1); - if (!hexItem) - { - hexItem = new QTableWidgetItem(); - hexItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - hexItem->setFont(font); - hexItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); - setItem(a_rowIndex, 1, hexItem); - } - - // binary - if (!m_IsFloat) - { - QTableWidgetItem* binItem = item(a_rowIndex, 2); - if (!binItem) - { - binItem = new QTableWidgetItem(); - binItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - binItem->setFont(font); - binItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); - setItem(a_rowIndex, 2, binItem); - } - } - - // set the values - checkAndOvertakeContent(decItem); - makePretty(); - } -} - - -// --------------------------------------------------------------- -void LogViewTableWidget::checkAndOvertakeContent(QTableWidgetItem* a_changedItem) -{ - if (a_changedItem->column() != 0) return; - - int row = a_changedItem->row(); - QString text = a_changedItem->text(); - - - bool ok; - int64_t intValue = 0; - double floatValue = 0.0; - - // get the calculated and checked value - if (m_IsFloat) - floatValue = getFloat(text, (uint64_t&)intValue, ok, true); - else - intValue = getInteger(text, ok); - - // handle errors - if (!ok) - { - setFocus(); -// selectAll(); - setCurrentCell(row, 0); // todo: funktioniert nicht - return; - } - - // set the decimal value - QTableWidgetItem* decField = item(row, 0); - if (decField) decField->setText(QString::number(m_IsFloat ? floatValue : intValue)); - - // set the hex value - QTableWidgetItem* hexField = item(row, 1); - if (hexField) hexField->setText(toHex(intValue)); - - // set the binary value - if (!m_IsFloat) - { - QTableWidgetItem* binField = item(row, 2); - if (binField) binField->setText(toBin(intValue)); - } -} - - -// --------------------------------------------------------------- -void LogViewTableWidget::makePretty() -{ - //horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); - resizeColumnsToContents(); - resizeRowsToContents(); - - // set the height of table-widget -//// QWidget* cellWdg = tableWidget->cellWidget(0, 0); -// int showRows = 7; -// if (m_Field->getValueListSize() < (showRows-1)) -// { -// showRows = m_Field->getValueListSize()+1; -// setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); -// } -// else -// { -// setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); -// } -// setFixedHeight(showRows*tableWidget->rowHeight(0)); -} - - -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewTableWidget::saveContent(LogViewTelegram* a_telegram) -{ - if (!isValid()) - return false; - - if (a_telegram->isJsonTelegram()) - { - if (m_Field->kind() == LogViewField::e_FieldKindPodArray) - { - QJsonArray arr; - for (int i = 0; i < rowCount(); ++i) - arr += item(i, 0)->text().toInt(); - a_telegram->setJsonValue(m_Field->jsonPath(), arr); - } - else - { - QString value; - value.reserve(rowCount() * 2); - for (int i = 0; i < rowCount(); ++i) - { - int val = item(i, 0)->text().toInt(); - value += QStringLiteral("%1").arg(val, 2, 16, QLatin1Char('0')); - } - a_telegram->setJsonValue(m_Field->jsonPath(), value); - } - return true; - } - - uint16_t arraySize; - if (m_Field->isDynamicArray()) - { - arraySize = rowCount(); - a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize); - // fixme: bei vielen Telegrammen muss Länge auf die Länge des Textes gesetzt werden. Dies kann nicht automatisch gemacht werden. Aber vielleicht kann man schauen, ob vor dem dyn. Array ein Feld Länge vorkommt, oder hartcodieren, oder konfigurierbaren - } - else - { - // todo: teste mit opaque[] - arraySize = m_Field->maxArraySize(); - } - // copy the data - INFO_LOG(m_logger) << "arraySize=" << arraySize; - for (int i = 0; i < arraySize; i++) - { + setColumnCount(3); if (m_IsEnum) + setColumnCount(1); + + setHorizontalHeaderItem(0, new QTableWidgetItem(m_IsEnum ? tr("Enum") : tr("Dez"))); + if (!m_IsEnum) { - LogViewEnumEdit *enumEdit = dynamic_cast(cellWidget(i,0)); - enumEdit->saveContent(a_telegram); - } - else - { - uint16_t size = getSize(); - QString text = item(i, 0)->text(); + setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Hex"))); if (!m_IsFloat) { - a_telegram->setUIntX(size, text.toULong()); + setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Bin"))); + } + } + setAlternatingRowColors(true); + + // make pretty + // horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); + + updateToolTip(); + + // for debugging only + // INFO_LOG(m_logger) << "type=" << static_cast(a_field->getXdrElement())->getValueKind(); + // INFO_LOG(m_logger) << "name=" << static_cast(a_field->getXdrElement())->getName().toStdString(); + // a_field->getXdrElement()->dump(); + + // fill in the values + // fixme: implementiere den Fall isHasContent() false + int nbrOfRows = a_field->valueListSize(); + setRowCount(nbrOfRows); + for (int i = 0; i < nbrOfRows; i++) + changeRow(i, a_field->value(i)); + + makePretty(); + + // connect signals + connect(this, &LogViewTableWidget::itemChanged, this, &LogViewTableWidget::checkAndOvertakeContent); + } + + + // --------------------------------------------------------------- + void LogViewTableWidget::changeSize(const int a_newSize) + { + setRowCount(a_newSize); + + disconnect(this, &LogViewTableWidget::itemChanged, this, &LogViewTableWidget::checkAndOvertakeContent); + // check and set the new fields + for (int i = 0; i < a_newSize; i++) + changeRow(i, QLatin1String("0")); + + connect(this, &LogViewTableWidget::itemChanged, this, &LogViewTableWidget::checkAndOvertakeContent); + + makePretty(); + + m_Valid = true; + } + + + // --------------------------------------------------------------- + void LogViewTableWidget::changeRow(const int a_rowIndex, const QString &a_value) + { + // INFO_LOG(m_logger) << "a_rowIndex=" << a_rowIndex << " a_value=" << a_value.toStdString(); + + if (m_IsEnum) + { + // enum + QWidget *enumItem = cellWidget(a_rowIndex, 0); + if (!enumItem) + setCellWidget(a_rowIndex, 0, new LogViewEnumEdit(m_Field, this, m_Readonly, a_rowIndex)); + } + else + { + QFont font; + font.setStyleHint(QFont::TypeWriter); + font.setFamily(QString()); + // decimal + QTableWidgetItem *decItem = item(a_rowIndex, 0); + if (!decItem) + { + decItem = new QTableWidgetItem(); + //decItem->setData(Qt::DisplayRole, 0); + decItem->setText(a_value); + decItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + if (!m_Readonly) + { + decItem->setFlags(decItem->flags() | Qt::ItemIsEditable); + } + decItem->setFont(font); + decItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); + setItem(a_rowIndex, 0, decItem); + } + + // hexadecimal + QTableWidgetItem *hexItem = item(a_rowIndex, 1); + if (!hexItem) + { + hexItem = new QTableWidgetItem(); + hexItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + hexItem->setFont(font); + hexItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); + setItem(a_rowIndex, 1, hexItem); + } + + // binary + if (!m_IsFloat) + { + QTableWidgetItem *binItem = item(a_rowIndex, 2); + if (!binItem) + { + binItem = new QTableWidgetItem(); + binItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + binItem->setFont(font); + binItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); + setItem(a_rowIndex, 2, binItem); + } + } + + // set the values + checkAndOvertakeContent(decItem); + makePretty(); + } + } + + + // --------------------------------------------------------------- + void LogViewTableWidget::checkAndOvertakeContent(QTableWidgetItem *a_changedItem) + { + if (a_changedItem->column() != 0) + return; + + int row = a_changedItem->row(); + QString text = a_changedItem->text(); + + + bool ok; + int64_t intValue = 0; + double floatValue = 0.0; + + // get the calculated and checked value + if (m_IsFloat) + floatValue = getFloat(text, (uint64_t &)intValue, ok, true); + else + intValue = getInteger(text, ok); + + // handle errors + if (!ok) + { + setFocus(); + // selectAll(); + setCurrentCell(row, 0); // todo: funktioniert nicht + return; + } + + // set the decimal value + QTableWidgetItem *decField = item(row, 0); + if (decField) + decField->setText(QString::number(m_IsFloat ? floatValue : intValue)); + + // set the hex value + QTableWidgetItem *hexField = item(row, 1); + if (hexField) + hexField->setText(toHex(intValue)); + + // set the binary value + if (!m_IsFloat) + { + QTableWidgetItem *binField = item(row, 2); + if (binField) + binField->setText(toBin(intValue)); + } + } + + + // --------------------------------------------------------------- + void LogViewTableWidget::makePretty() + { + //horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); + resizeColumnsToContents(); + resizeRowsToContents(); + + // set the height of table-widget + //// QWidget* cellWdg = tableWidget->cellWidget(0, 0); + // int showRows = 7; + // if (m_Field->getValueListSize() < (showRows-1)) + // { + // showRows = m_Field->getValueListSize()+1; + // setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + // } + // else + // { + // setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + // } + // setFixedHeight(showRows*tableWidget->rowHeight(0)); + } + + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewTableWidget::saveContent(LogViewTelegram *a_telegram) + { + if (!isValid()) + return false; + + if (a_telegram->isJsonTelegram()) + { + if (m_Field->kind() == LogViewField::e_FieldKindPodArray) + { + QJsonArray arr; + for (int i = 0; i < rowCount(); ++i) + arr += item(i, 0)->text().toInt(); + a_telegram->setJsonValue(m_Field->jsonPath(), arr); } else { - const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); - LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder(); - uint64_t hex; - getFloat(text, hex, m_Valid); - a_telegram->setUIntX(size, hex, byteOrder); + QString value; + value.reserve(rowCount() * 2); + for (int i = 0; i < rowCount(); ++i) + { + int val = item(i, 0)->text().toInt(); + value += QStringLiteral("%1").arg(val, 2, 16, QLatin1Char('0')); + } + a_telegram->setJsonValue(m_Field->jsonPath(), value); + } + return true; + } + + uint16_t arraySize; + if (m_Field->isDynamicArray()) + { + arraySize = rowCount(); + a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize); + // fixme: bei vielen Telegrammen muss Länge auf die Länge des Textes gesetzt werden. Dies kann nicht automatisch gemacht werden. Aber vielleicht kann man schauen, ob vor dem dyn. Array ein Feld Länge vorkommt, oder hartcodieren, oder konfigurierbaren + } + else + { + // todo: teste mit opaque[] + arraySize = m_Field->maxArraySize(); + } + // copy the data + INFO_LOG(m_logger) << "arraySize=" << arraySize; + for (int i = 0; i < arraySize; i++) + { + if (m_IsEnum) + { + LogViewEnumEdit *enumEdit = dynamic_cast(cellWidget(i, 0)); + enumEdit->saveContent(a_telegram); + } + else + { + uint16_t size = getSize(); + QString text = item(i, 0)->text(); + if (!m_IsFloat) + { + a_telegram->setUIntX(size, text.toULong()); + } + else + { + const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); + LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder(); + uint64_t hex; + getFloat(text, hex, m_Valid); + a_telegram->setUIntX(size, hex, byteOrder); + } } } + + return true; } - return true; -} - } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.hpp index 5eccbef8f..458e4cd8f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTableWidget.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -26,11 +26,13 @@ namespace N_LogView * @version 1.0 * @created 25-Mai-2010 09:34:24 */ - class LogViewTableWidget : public QTableWidget, public LogViewWidget + class LogViewTableWidget + : public QTableWidget + , public LogViewWidget { Q_OBJECT public: - LogViewTableWidget(LogViewField* a_field, QWidget* a_parent, const bool a_readonly, NGL::INGLLogger& logger); + LogViewTableWidget(LogViewField *a_field, QWidget *a_parent, const bool a_readonly, NGL::INGLLogger &logger); /** * Writes the content into telegram. @@ -38,20 +40,20 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; public slots: void changeSize(const int a_newSize); protected: - void changeRow(const int a_rowIndex, const QString& a_value); + void changeRow(const int a_rowIndex, const QString &a_value); void makePretty(); protected slots: - void checkAndOvertakeContent(QTableWidgetItem* a_changedItem); + void checkAndOvertakeContent(QTableWidgetItem *a_changedItem); private: bool m_IsFloat; bool m_IsEnum; - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.cpp index 2c5878a8f..9316aacb1 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.cpp @@ -36,153 +36,148 @@ namespace N_LogView { -// static member initialization -const LogViewXdrParser* LogViewTelegram::m_Parser = nullptr; -const uint16_t LogViewTelegram::START_OFFSET_CENTRAL = 12; -const uint16_t LogViewTelegram::POS_CENTRAL_COUNTER = 4; -const uint16_t LogViewTelegram::POS_CENTRAL_TELID = 8; -const uint16_t LogViewTelegram::POS_CENTRAL_PARTICIPANTID = 12; -const uint16_t LogViewTelegram::START_OFFSET_TETRA_REGISTER = 5; -const uint16_t LogViewTelegram::START_OFFSET_TETRA_AIRLOAD = 5; -const uint16_t LogViewTelegram::START_OFFSET_TETRA_DATA = 28; -const uint16_t LogViewTelegram::START_OFFSET_TETRA_LOGIN = 27; -const uint16_t LogViewTelegram::START_OFFSET_TETRA_FRAGMENT = 26; -const uint16_t LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE = 4; + // static member initialization + const LogViewXdrParser *LogViewTelegram::m_Parser = nullptr; + const uint16_t LogViewTelegram::START_OFFSET_CENTRAL = 12; + const uint16_t LogViewTelegram::POS_CENTRAL_COUNTER = 4; + const uint16_t LogViewTelegram::POS_CENTRAL_TELID = 8; + const uint16_t LogViewTelegram::POS_CENTRAL_PARTICIPANTID = 12; + const uint16_t LogViewTelegram::START_OFFSET_TETRA_REGISTER = 5; + const uint16_t LogViewTelegram::START_OFFSET_TETRA_AIRLOAD = 5; + const uint16_t LogViewTelegram::START_OFFSET_TETRA_DATA = 28; + const uint16_t LogViewTelegram::START_OFFSET_TETRA_LOGIN = 27; + const uint16_t LogViewTelegram::START_OFFSET_TETRA_FRAGMENT = 26; + const uint16_t LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE = 4; -// --------------------------------------------------------------- -// Copy ctor -// --------------------------------------------------------------- -LogViewTelegram::LogViewTelegram(const LogViewTelegram &o) - : m_Name(o.m_Name) - , m_ToolTipText(o.m_ToolTipText) - , m_WaitTime(o.m_WaitTime) - , m_ParticipantId(o.m_ParticipantId) - , m_ISSI(o.m_ISSI) - , m_AllocatedSize(o.m_AllocatedSize) - , m_ActOffset(o.m_ActOffset) - , m_GpsFieldOffset(o.m_GpsFieldOffset) - , m_TelId(o.m_TelId) - , m_LastUnsignedValue(o.m_LastUnsignedValue) - , m_MaxArraySize(o.m_MaxArraySize) - , m_DynArraySizeMethod(o.m_DynArraySizeMethod) - , m_Destination(o.m_Destination) - , m_Validity(o.m_Validity) - , m_Protocol(o.m_Protocol) - , m_LogTime(o.m_LogTime) - , m_logTimeText(o.m_logTimeText) - , m_GpsTime(o.m_GpsTime) - , m_data(o.m_data) - , m_json(o.m_json) - , m_TetraTelegram(nullptr) - , m_logger(o.m_logger) -{ - if (!m_data.isEmpty()) - m_TetraTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(m_data); -} - -// --------------------------------------------------------------- -// Constructor for new telegrams (only receive central- -// telegrams are allowed), which will be edited -// --------------------------------------------------------------- -LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, - int telegramId) - : m_WaitTime(1000) - , m_ParticipantId(0) - , m_ISSI(0) - , m_AllocatedSize(0) - , m_ActOffset(0) - , m_GpsFieldOffset(QVector()) - , m_TelId(telegramId) - , m_LastUnsignedValue(0) - , m_MaxArraySize(0) - , m_DynArraySizeMethod(LogViewXdrStandardType::e_DynArrayMsgLength) - , m_Destination(a_destination) - , m_Validity(e_NotYetEvaluated) - , m_Protocol(static_cast(a_destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask)) - , m_LogTime(0) - , m_GpsTime(0) - , m_TetraTelegram(nullptr) - , m_logger(N_LogView::getLogger("LogViewTelegram")) -{ - const uint32_t &waitTime = qgetenv("LogViewWaitTime").toUInt(); - if (waitTime > 0) - m_WaitTime = waitTime; - m_ToolTipText.resize(e_ColMax); - switch (m_Protocol) + // --------------------------------------------------------------- + // Copy ctor + // --------------------------------------------------------------- + LogViewTelegram::LogViewTelegram(const LogViewTelegram &o) + : m_Name(o.m_Name) + , m_ToolTipText(o.m_ToolTipText) + , m_WaitTime(o.m_WaitTime) + , m_ParticipantId(o.m_ParticipantId) + , m_ISSI(o.m_ISSI) + , m_AllocatedSize(o.m_AllocatedSize) + , m_ActOffset(o.m_ActOffset) + , m_GpsFieldOffset(o.m_GpsFieldOffset) + , m_TelId(o.m_TelId) + , m_LastUnsignedValue(o.m_LastUnsignedValue) + , m_MaxArraySize(o.m_MaxArraySize) + , m_DynArraySizeMethod(o.m_DynArraySizeMethod) + , m_Destination(o.m_Destination) + , m_Validity(o.m_Validity) + , m_Protocol(o.m_Protocol) + , m_LogTime(o.m_LogTime) + , m_logTimeText(o.m_logTimeText) + , m_GpsTime(o.m_GpsTime) + , m_data(o.m_data) + , m_json(o.m_json) + , m_TetraTelegram(nullptr) + , m_logger(o.m_logger) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - { - m_Name = jsonParser()->nameFromTelegramId(m_TelId); - m_json[QStringLiteral("type")] = m_Name; - m_json[QStringLiteral("typeId")] = m_TelId; - break; + if (!m_data.isEmpty()) + m_TetraTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(m_data); } - default: - showMessageBox(QObject::tr("Nur Zentral-Telegramme sind erlaubt")); - } -} - -// --------------------------------------------------------------- -// Constructor for existing telegrams -// --------------------------------------------------------------- -LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, - const quint64 a_unixTime, - const QByteArray &a_telegramData) - : m_WaitTime(1000) - , m_ParticipantId(0) - , m_ISSI(0) - , m_AllocatedSize(0) - , m_ActOffset(0) - , m_GpsFieldOffset(QVector()) - , m_TelId(0) - , m_LastUnsignedValue(0) - , m_MaxArraySize(0) - , m_DynArraySizeMethod(LogViewXdrStandardType::e_DynArrayMsgLength) - , m_Destination(a_destination) - , m_Validity(e_NotYetEvaluated) - , m_Protocol(static_cast(a_destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask)) - , m_LogTime(a_unixTime) - , m_GpsTime(0) - , m_data(a_telegramData) - , m_TetraTelegram(nullptr) - , m_logger(N_LogView::getLogger("LogViewTelegram")) -{ - const uint32_t &waitTime = qgetenv("LogViewWaitTime").toUInt(); - if (waitTime > 0) - m_WaitTime = waitTime; - m_ToolTipText.resize(e_ColMax); - // log-time - switch (m_Protocol) + // --------------------------------------------------------------- + // Constructor for new telegrams (only receive central- + // telegrams are allowed), which will be edited + // --------------------------------------------------------------- + LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, int telegramId) + : m_WaitTime(1000) + , m_ParticipantId(0) + , m_ISSI(0) + , m_AllocatedSize(0) + , m_ActOffset(0) + , m_GpsFieldOffset(QVector()) + , m_TelId(telegramId) + , m_LastUnsignedValue(0) + , m_MaxArraySize(0) + , m_DynArraySizeMethod(LogViewXdrStandardType::e_DynArrayMsgLength) + , m_Destination(a_destination) + , m_Validity(e_NotYetEvaluated) + , m_Protocol(static_cast(a_destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask)) + , m_LogTime(0) + , m_GpsTime(0) + , m_TetraTelegram(nullptr) + , m_logger(N_LogView::getLogger("LogViewTelegram")) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + const uint32_t &waitTime = qgetenv("LogViewWaitTime").toUInt(); + if (waitTime > 0) + m_WaitTime = waitTime; + m_ToolTipText.resize(e_ColMax); + switch (m_Protocol) { - m_json = QJsonDocument::fromJson(a_telegramData).object(); - m_TelId = m_json.value(QLatin1String("typeId")).toInt();//getUInt32(POS_CENTRAL_TELID); -// INFO_LOG(m_logger) << "m_TelId=" << m_TelId; - //m_Name = m_Parser[m_Protocol]->getTelegramName(getTelId()); - m_Name = m_json.value(QLatin1String("type")).toString(); - switch (getTelId()) + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: { - case TrainingAreaBase::TetraIcd::BESTAETIGUNG: - break; - default: - // the participant-id can not be taken out of xyData.header.identitaet without knowing the exact Wrapper, - // because in some (unclear) cases an unknown 4-byte value is on expected position (maybe some C++ alignment stuff) - //m_ParticipantId = getUInt32(POS_CENTRAL_PARTICIPANTID); - m_ParticipantId = m_json.value(QLatin1String("data")) - .toObject().value(QLatin1String("header")) - .toObject().value(QLatin1String("equipmentNumber")).toInt(); - break; + m_Name = jsonParser()->nameFromTelegramId(m_TelId); + m_json[QStringLiteral("type")] = m_Name; + m_json[QStringLiteral("typeId")] = m_TelId; + break; } - break; + default: + showMessageBox(QObject::tr("Nur Zentral-Telegramme sind erlaubt")); } + } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + + // --------------------------------------------------------------- + // Constructor for existing telegrams + // --------------------------------------------------------------- + LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, const quint64 a_unixTime, const QByteArray &a_telegramData) + : m_WaitTime(1000) + , m_ParticipantId(0) + , m_ISSI(0) + , m_AllocatedSize(0) + , m_ActOffset(0) + , m_GpsFieldOffset(QVector()) + , m_TelId(0) + , m_LastUnsignedValue(0) + , m_MaxArraySize(0) + , m_DynArraySizeMethod(LogViewXdrStandardType::e_DynArrayMsgLength) + , m_Destination(a_destination) + , m_Validity(e_NotYetEvaluated) + , m_Protocol(static_cast(a_destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask)) + , m_LogTime(a_unixTime) + , m_GpsTime(0) + , m_data(a_telegramData) + , m_TetraTelegram(nullptr) + , m_logger(N_LogView::getLogger("LogViewTelegram")) + { + const uint32_t &waitTime = qgetenv("LogViewWaitTime").toUInt(); + if (waitTime > 0) + m_WaitTime = waitTime; + m_ToolTipText.resize(e_ColMax); + // log-time + switch (m_Protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + m_json = QJsonDocument::fromJson(a_telegramData).object(); + m_TelId = m_json.value(QLatin1String("typeId")).toInt(); //getUInt32(POS_CENTRAL_TELID); + // INFO_LOG(m_logger) << "m_TelId=" << m_TelId; + //m_Name = m_Parser[m_Protocol]->getTelegramName(getTelId()); + m_Name = m_json.value(QLatin1String("type")).toString(); + switch (getTelId()) + { + case TrainingAreaBase::TetraIcd::BESTAETIGUNG: + break; + default: + // the participant-id can not be taken out of xyData.header.identitaet without knowing the exact Wrapper, + // because in some (unclear) cases an unknown 4-byte value is on expected position (maybe some C++ alignment stuff) + //m_ParticipantId = getUInt32(POS_CENTRAL_PARTICIPANTID); + m_ParticipantId = m_json.value(QLatin1String("data")).toObject().value(QLatin1String("header")).toObject().value(QLatin1String("equipmentNumber")).toInt(); + break; + } + break; + } + + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: { m_TetraTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(m_data); -// NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, m_Data, m_Size); + // NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, m_Data, m_Size); switch (m_TetraTelegram->getPDU_Type()) { case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd: @@ -193,7 +188,8 @@ LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnv m_Name = QObject::tr("TETRA-Register-Response"); break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: { + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: + { if (m_TetraTelegram->isLoginTelegram()) { m_Name = QObject::tr("TETRA-Login-Telegramm"); @@ -218,7 +214,7 @@ LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnv default: gpsTimeOffset = 2; // without telID } - m_GpsTime = getUInt32(START_OFFSET_TETRA_DATA+gpsTimeOffset); + m_GpsTime = getUInt32(START_OFFSET_TETRA_DATA + gpsTimeOffset); } } else @@ -231,7 +227,7 @@ LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnv m_ParticipantId = m_TetraTelegram->getIdentity(); break; case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment: - m_Name = QObject::tr("%1.-letztes Fragment eines TETRA-Telegrammes").arg(m_TetraTelegram->getFragmentCounter()+1); + m_Name = QObject::tr("%1.-letztes Fragment eines TETRA-Telegrammes").arg(m_TetraTelegram->getFragmentCounter() + 1); // fixme: get participantid over ISSI break; case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment: @@ -283,368 +279,362 @@ LogViewTelegram::LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnv } break; - default: - showMessageBox(QObject::tr("Unknown protocol %1!").arg(m_Protocol), QObject::tr("Unknown protocol")); - m_Validity = e_Invalid; - break; - + default: + showMessageBox(QObject::tr("Unknown protocol %1!").arg(m_Protocol), QObject::tr("Unknown protocol")); + m_Validity = e_Invalid; + break; + } } -} -LogViewTelegram::~LogViewTelegram() -{ - delete m_TetraTelegram; -} - -// --------------------------------------------------------------- -// Writes a_value with size a_size at actual position of -// m_Data (given with m_ActOffset). m_ActOffset will be -// updated after writing data. -// If the size of m_Data is not big enough, it will be made -// bigger. -// --------------------------------------------------------------- -void LogViewTelegram::setUIntX(const uint8_t a_size, quint64 a_value, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) -{ - // check whether m_Data is big enough - if (m_ActOffset + a_size > m_data.size()) - m_data.resize(m_ActOffset + a_size); - - // write the data - if (a_byteOrder == LogViewXdrStandardType::e_ByteOrderBigEndian) + LogViewTelegram::~LogViewTelegram() { - for (int i = a_size - 1; i >= 0; i--) + delete m_TetraTelegram; + } + + // --------------------------------------------------------------- + // Writes a_value with size a_size at actual position of + // m_Data (given with m_ActOffset). m_ActOffset will be + // updated after writing data. + // If the size of m_Data is not big enough, it will be made + // bigger. + // --------------------------------------------------------------- + void LogViewTelegram::setUIntX(const uint8_t a_size, quint64 a_value, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) + { + // check whether m_Data is big enough + if (m_ActOffset + a_size > m_data.size()) + m_data.resize(m_ActOffset + a_size); + + // write the data + if (a_byteOrder == LogViewXdrStandardType::e_ByteOrderBigEndian) { - setData(m_ActOffset+i, a_value & 0x000000FF); - a_value = a_value >> 8; - } - } - else - { - for (int i = 0; i < a_size; i++) - { - setData(m_ActOffset + i, a_value & 0x000000FF); - a_value = a_value >> 8; - } - } - m_ActOffset += a_size; -} - - -// --------------------------------------------------------------- -// Returns true if a_data could be written. -// Returns false if a_offset is outside of range and therefore -// a_data could not be written. -// --------------------------------------------------------------- -bool LogViewTelegram::setData(const uint16_t a_offset, const uint8_t a_data) -{ - if (a_offset < m_data.size()) - { - m_data[a_offset] = a_data; - return true; - } - - return false; -} - -quint64 LogViewTelegram::getLogTimeMsec() const -{ - const quint64 logTimeSec = m_LogTime >> 32; - const quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; - return (logTimeSec * 1000 + logTimeMicroSec / 1000); -} - -// --------------------------------------------------------------- -// Returns the log-time of the telegram as pretty formatted -// text -// --------------------------------------------------------------- -QString LogViewTelegram::getLogTimeText() const -{ - if (m_logTimeText.isEmpty()) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(getLogTimeMsec())); - m_logTimeText = dt.toString(QLatin1String("ddd, MMM dd, yyyy hh:mm:ss.zzz")); - } - return m_logTimeText; -} - -// --------------------------------------------------------------- -QString LogViewTelegram::getDestinationText() const -{ - auto protocol = static_cast - (m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); - auto dest = static_cast - (m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); - switch (protocol) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return QLatin1String("C > P"); - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return QLatin1String("P > C"); - default: - break; - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return QLatin1String("W > C"); - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return QLatin1String("C > W"); - default: - break; - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return QLatin1String("P > T"); - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return QLatin1String("T > P"); - default: - break; - } - break; - } - default: - break; - } - return QStringLiteral("<%1>").arg(m_Destination); -} - - -// --------------------------------------------------------------- -// Returns the GPS-time of the telegram as pretty formatted -// text. Only telegrams from TETRA to central have a GPS-time, -// for all other telegrams an empty string will be returned. -// --------------------------------------------------------------- -QString LogViewTelegram::getGpsTimeText() const -{ - if (m_GpsTime != 0) - return QDateTime::fromMSecsSinceEpoch(m_GpsTime * 1000LL).toString(QLatin1String("hh:mm:ss")); - - return QString(); -} - - -// --------------------------------------------------------------- -// Returns the difference between GPS-time and log-time in -// seconds. Only telegrams from TETRA to central have a GPS- -// time (and therefore only for this telegrams a time- -// difference can be calculated), for all other telegrams 0 -// will be returned. -// --------------------------------------------------------------- -int32_t LogViewTelegram::getDelay() const -{ - if (m_GpsTime != 0) - { - quint64 logTimeSec = m_LogTime >> 32; - return logTimeSec - m_GpsTime; - } - return 0; -} - - -// --------------------------------------------------------------- -// Returns the tool-tip text for the with a_col defined column -// for this telegram. Its content depends on the type and -// subtype of telegram. -// --------------------------------------------------------------- -QString LogViewTelegram::getToolTipText(const E_Column a_col) -{ - if (a_col < e_ColMax) - { - if(a_col == e_ColName && m_ToolTipText[e_ColName].isNull()) - createToolTipTextForColName(); - if(a_col == e_ColLogTime && m_ToolTipText[e_ColLogTime].isNull()) { - quint64 logTimeSec = m_LogTime >> 32; - quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; - m_ToolTipText[e_ColLogTime] = QStringLiteral("%1.%2 s") - .arg(logTimeSec) - .arg(logTimeMicroSec); - } - if(a_col == e_ColGpsTime && m_ToolTipText[e_ColGpsTime].isNull()) { - if(m_GpsTime == 0) { - m_ToolTipText[e_ColGpsTime] = QLatin1String(""); // wichtig damit isNull() false ist! - } else { - const QDateTime dtGpsTime(QDateTime::fromMSecsSinceEpoch(m_GpsTime * 1000LL)); - m_ToolTipText[e_ColGpsTime] = QStringLiteral("%1
Unixzeit: %2 0x%3") - .arg(dtGpsTime.toString(QLatin1String("ddd, MMM dd, yyyy hh:mm:ss"))) - .arg(m_GpsTime) - .arg(m_GpsTime, 8, 16, QLatin1Char('0')); + for (int i = a_size - 1; i >= 0; i--) + { + setData(m_ActOffset + i, a_value & 0x000000FF); + a_value = a_value >> 8; } } - return m_ToolTipText[a_col]; - } - return QString(); -} - - -// --------------------------------------------------------------- -void LogViewTelegram::createToolTipTextForColName() -{ - switch (m_Protocol) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: - { - const QString jsonStr = QString::fromUtf8(QJsonDocument(m_json).toJson(QJsonDocument::JsonFormat::Indented)); - // set the tool-tip-text - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Telegram Id"), getTelId()) - + formatToolTipLine(QObject::tr("Counter"), getUInt32(POS_CENTRAL_COUNTER)) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + formatToolTipLine(QObject::tr("Json Data"), jsonStr, jsonStr.size()) - + QLatin1String("
"); - break; - } - - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: - { - switch (m_TetraTelegram->getPDU_Type()) + else { - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd: - // set the tool-tip-text - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Host ISSI"), m_TetraTelegram->getSrcISSI()) - + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + QLatin1String("
"); - break; - - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Registration Status"), m_TetraTelegram->getRegistrationStatusAsText(), m_TetraTelegram->getRegistrationStatus()) - + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + QLatin1String("
"); - break; - - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: { - int frameSize = 1; - if(m_TetraTelegram->getWithCrc()) - frameSize += 2; - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Source ISSI"), m_TetraTelegram->getSrcISSI()) - + formatToolTipLine(QObject::tr("Destination ISSI"), m_TetraTelegram->getDestISSI()) - + formatToolTipLine(QObject::tr("Protocol Identifier"), m_TetraTelegram->getProtocolIdentifierAsText(), m_TetraTelegram->getProtocolIdentifier()) - + formatToolTipLine(QObject::tr("Message Reference"), m_TetraTelegram->getMessageReference()) - + formatToolTipLine(QObject::tr("Area Selection"), m_TetraTelegram->getAreaSelection()) - + formatToolTipLine(QObject::tr("Validity Period"), m_TetraTelegram->getValidityPeriod()) - + formatToolTipLine(QObject::tr("Forward Address"), m_TetraTelegram->getForwardAddress()) - + formatToolTipLine(QObject::tr("Flags"), m_TetraTelegram->getFlagsAsText(), m_TetraTelegram->getFlags()) - + formatToolTipLine(QObject::tr("Complete Payload in Bits"), m_TetraTelegram->getLengthInBits()) - + formatToolTipLine(QObject::tr("Real Payload in Bytes"), m_TetraTelegram->getLengthInBytes() - frameSize) - + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + QLatin1String("
"); - break; + for (int i = 0; i < a_size; i++) + { + setData(m_ActOffset + i, a_value & 0x000000FF); + a_value = a_value >> 8; + } } - - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Source ISSI"), m_TetraTelegram->getSrcISSI()) - + formatToolTipLine(QObject::tr("Destination ISSI"), m_TetraTelegram->getDestISSI()) - + formatToolTipLine(QObject::tr("Protocol Identifier"), m_TetraTelegram->getProtocolIdentifierAsText(), m_TetraTelegram->getProtocolIdentifier()) - + formatToolTipLine(QObject::tr("Message Reference"), m_TetraTelegram->getMessageReference()) - + formatToolTipLine(QObject::tr("Area Selection"), m_TetraTelegram->getAreaSelection()) - + formatToolTipLine(QObject::tr("Delivery"), m_TetraTelegram->getDeliveryAsText(), m_TetraTelegram->getDelivery()) - + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + QLatin1String("
"); - break; - - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: - default: - m_ToolTipText[e_ColName] = QLatin1String("") - + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) - + formatToolTipLine(QObject::tr("Size"), m_data.size()) - + QLatin1String("
"); - break; - } - break; + m_ActOffset += a_size; } - default: - break; - } -} -union convertHackDouble -{ - quint64 i; - double d; -}; - -union convertHackFloat -{ - uint32_t i; - float f; -}; - -double LogViewTelegram::xdrToDouble(quint64 in) -{ - convertHackDouble c; - c.i = in; - return c.d; -} - -float LogViewTelegram::xdrToFloat(uint32_t in) -{ - convertHackFloat c; - c.i = in; - return c.f; -} - -quint64 LogViewTelegram::doubleToXdr(double in) -{ - convertHackDouble c; - c.d = in; - return c.i; -} - -uint32_t LogViewTelegram::floatToXdr(float in) -{ - convertHackFloat c; - c.f = in; - return c.i; -} - - -// --------------------------------------------------------------- -void LogViewTelegram::resetOffset() -{ - switch (m_Protocol) + // --------------------------------------------------------------- + // Returns true if a_data could be written. + // Returns false if a_offset is outside of range and therefore + // a_data could not be written. + // --------------------------------------------------------------- + bool LogViewTelegram::setData(const uint16_t a_offset, const uint8_t a_data) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - m_ActOffset = START_OFFSET_CENTRAL; - break; - default: - ERROR_LOG(m_logger) << "resetOffset is only for Central-Protocol implemented"; - } -} - - -// --------------------------------------------------------------- -LogViewField* LogViewTelegram::getFieldTree() -{ -// INFO_LOG(m_logger) << "type=" << getStructName().toStdString(); - switch (m_Protocol) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + if (a_offset < m_data.size()) { - resetOffset(); - const QString type = m_json.value(QStringLiteral("type")).toString(); - QStringList objPath = {QStringLiteral("data")}; - return getFieldTreeJson(m_json.value(QStringLiteral("data")), - type, jsonParser()->structFromType(type), objPath); + m_data[a_offset] = a_data; + return true; } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + return false; + } + + quint64 LogViewTelegram::getLogTimeMsec() const + { + const quint64 logTimeSec = m_LogTime >> 32; + const quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; + return (logTimeSec * 1000 + logTimeMicroSec / 1000); + } + + // --------------------------------------------------------------- + // Returns the log-time of the telegram as pretty formatted + // text + // --------------------------------------------------------------- + QString LogViewTelegram::getLogTimeText() const + { + if (m_logTimeText.isEmpty()) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(getLogTimeMsec())); + m_logTimeText = dt.toString(QLatin1String("ddd, MMM dd, yyyy hh:mm:ss.zzz")); + } + return m_logTimeText; + } + + // --------------------------------------------------------------- + QString LogViewTelegram::getDestinationText() const + { + auto protocol = static_cast(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); + auto dest = static_cast(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); + switch (protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return QLatin1String("C > P"); + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return QLatin1String("P > C"); + default: + break; + } + break; + } + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return QLatin1String("W > C"); + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return QLatin1String("C > W"); + default: + break; + } + break; + } + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return QLatin1String("P > T"); + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return QLatin1String("T > P"); + default: + break; + } + break; + } + default: + break; + } + return QStringLiteral("<%1>").arg(m_Destination); + } + + + // --------------------------------------------------------------- + // Returns the GPS-time of the telegram as pretty formatted + // text. Only telegrams from TETRA to central have a GPS-time, + // for all other telegrams an empty string will be returned. + // --------------------------------------------------------------- + QString LogViewTelegram::getGpsTimeText() const + { + if (m_GpsTime != 0) + return QDateTime::fromMSecsSinceEpoch(m_GpsTime * 1000LL).toString(QLatin1String("hh:mm:ss")); + + return QString(); + } + + + // --------------------------------------------------------------- + // Returns the difference between GPS-time and log-time in + // seconds. Only telegrams from TETRA to central have a GPS- + // time (and therefore only for this telegrams a time- + // difference can be calculated), for all other telegrams 0 + // will be returned. + // --------------------------------------------------------------- + int32_t LogViewTelegram::getDelay() const + { + if (m_GpsTime != 0) + { + quint64 logTimeSec = m_LogTime >> 32; + return logTimeSec - m_GpsTime; + } + return 0; + } + + + // --------------------------------------------------------------- + // Returns the tool-tip text for the with a_col defined column + // for this telegram. Its content depends on the type and + // subtype of telegram. + // --------------------------------------------------------------- + QString LogViewTelegram::getToolTipText(const E_Column a_col) + { + if (a_col < e_ColMax) + { + if (a_col == e_ColName && m_ToolTipText[e_ColName].isNull()) + createToolTipTextForColName(); + if (a_col == e_ColLogTime && m_ToolTipText[e_ColLogTime].isNull()) + { + quint64 logTimeSec = m_LogTime >> 32; + quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; + m_ToolTipText[e_ColLogTime] = QStringLiteral("%1.%2 s").arg(logTimeSec).arg(logTimeMicroSec); + } + if (a_col == e_ColGpsTime && m_ToolTipText[e_ColGpsTime].isNull()) + { + if (m_GpsTime == 0) + { + m_ToolTipText[e_ColGpsTime] = QLatin1String(""); // wichtig damit isNull() false ist! + } + else + { + const QDateTime dtGpsTime(QDateTime::fromMSecsSinceEpoch(m_GpsTime * 1000LL)); + m_ToolTipText[e_ColGpsTime] = QStringLiteral("%1
Unixzeit: %2 0x%3") + .arg(dtGpsTime.toString(QLatin1String("ddd, MMM dd, yyyy hh:mm:ss"))) + .arg(m_GpsTime) + .arg(m_GpsTime, 8, 16, QLatin1Char('0')); + } + } + return m_ToolTipText[a_col]; + } + return QString(); + } + + + // --------------------------------------------------------------- + void LogViewTelegram::createToolTipTextForColName() + { + switch (m_Protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + const QString jsonStr = QString::fromUtf8(QJsonDocument(m_json).toJson(QJsonDocument::JsonFormat::Indented)); + // set the tool-tip-text + m_ToolTipText[e_ColName] = QLatin1String("") + formatToolTipLine(QObject::tr("Telegram Id"), getTelId()) + + formatToolTipLine(QObject::tr("Counter"), getUInt32(POS_CENTRAL_COUNTER)) + formatToolTipLine(QObject::tr("Size"), m_data.size()) + + formatToolTipLine(QObject::tr("Json Data"), jsonStr, jsonStr.size()) + QLatin1String("
"); + break; + } + + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + switch (m_TetraTelegram->getPDU_Type()) + { + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd: + // set the tool-tip-text + m_ToolTipText[e_ColName] = QLatin1String("") + formatToolTipLine(QObject::tr("Host ISSI"), m_TetraTelegram->getSrcISSI()) + + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) + formatToolTipLine(QObject::tr("Size"), m_data.size()) + + QLatin1String("
"); + break; + + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: + m_ToolTipText[e_ColName] = + QLatin1String("") + + formatToolTipLine(QObject::tr("Registration Status"), m_TetraTelegram->getRegistrationStatusAsText(), m_TetraTelegram->getRegistrationStatus()) + + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) + formatToolTipLine(QObject::tr("Size"), m_data.size()) + QLatin1String("
"); + break; + + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: + { + int frameSize = 1; + if (m_TetraTelegram->getWithCrc()) + frameSize += 2; + m_ToolTipText[e_ColName] = + QLatin1String("") + formatToolTipLine(QObject::tr("Source ISSI"), m_TetraTelegram->getSrcISSI()) + + formatToolTipLine(QObject::tr("Destination ISSI"), m_TetraTelegram->getDestISSI()) + + formatToolTipLine(QObject::tr("Protocol Identifier"), m_TetraTelegram->getProtocolIdentifierAsText(), m_TetraTelegram->getProtocolIdentifier()) + + formatToolTipLine(QObject::tr("Message Reference"), m_TetraTelegram->getMessageReference()) + + formatToolTipLine(QObject::tr("Area Selection"), m_TetraTelegram->getAreaSelection()) + + formatToolTipLine(QObject::tr("Validity Period"), m_TetraTelegram->getValidityPeriod()) + + formatToolTipLine(QObject::tr("Forward Address"), m_TetraTelegram->getForwardAddress()) + + formatToolTipLine(QObject::tr("Flags"), m_TetraTelegram->getFlagsAsText(), m_TetraTelegram->getFlags()) + + formatToolTipLine(QObject::tr("Complete Payload in Bits"), m_TetraTelegram->getLengthInBits()) + + formatToolTipLine(QObject::tr("Real Payload in Bytes"), m_TetraTelegram->getLengthInBytes() - frameSize) + + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) + formatToolTipLine(QObject::tr("Size"), m_data.size()) + QLatin1String("
"); + break; + } + + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: + m_ToolTipText[e_ColName] = + QLatin1String("") + formatToolTipLine(QObject::tr("Source ISSI"), m_TetraTelegram->getSrcISSI()) + + formatToolTipLine(QObject::tr("Destination ISSI"), m_TetraTelegram->getDestISSI()) + + formatToolTipLine(QObject::tr("Protocol Identifier"), m_TetraTelegram->getProtocolIdentifierAsText(), m_TetraTelegram->getProtocolIdentifier()) + + formatToolTipLine(QObject::tr("Message Reference"), m_TetraTelegram->getMessageReference()) + + formatToolTipLine(QObject::tr("Area Selection"), m_TetraTelegram->getAreaSelection()) + + formatToolTipLine(QObject::tr("Delivery"), m_TetraTelegram->getDeliveryAsText(), m_TetraTelegram->getDelivery()) + + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) + formatToolTipLine(QObject::tr("Size"), m_data.size()) + QLatin1String("
"); + break; + + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: + default: + m_ToolTipText[e_ColName] = QLatin1String("") + formatToolTipLine(QObject::tr("Counter"), m_TetraTelegram->zaehler()) + + formatToolTipLine(QObject::tr("Size"), m_data.size()) + QLatin1String("
"); + break; + } + break; + } + + default: + break; + } + } + + union convertHackDouble + { + quint64 i; + double d; + }; + + union convertHackFloat + { + uint32_t i; + float f; + }; + + double LogViewTelegram::xdrToDouble(quint64 in) + { + convertHackDouble c; + c.i = in; + return c.d; + } + + float LogViewTelegram::xdrToFloat(uint32_t in) + { + convertHackFloat c; + c.i = in; + return c.f; + } + + quint64 LogViewTelegram::doubleToXdr(double in) + { + convertHackDouble c; + c.d = in; + return c.i; + } + + uint32_t LogViewTelegram::floatToXdr(float in) + { + convertHackFloat c; + c.f = in; + return c.i; + } + + + // --------------------------------------------------------------- + void LogViewTelegram::resetOffset() + { + switch (m_Protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + m_ActOffset = START_OFFSET_CENTRAL; + break; + default: + ERROR_LOG(m_logger) << "resetOffset is only for Central-Protocol implemented"; + } + } + + + // --------------------------------------------------------------- + LogViewField *LogViewTelegram::getFieldTree() + { + // INFO_LOG(m_logger) << "type=" << getStructName().toStdString(); + switch (m_Protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + resetOffset(); + const QString type = m_json.value(QStringLiteral("type")).toString(); + QStringList objPath = {QStringLiteral("data")}; + return getFieldTreeJson(m_json.value(QStringLiteral("data")), type, jsonParser()->structFromType(type), objPath); + } + + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: { QString structName; switch (m_TetraTelegram->getPDU_Type()) @@ -675,10 +665,8 @@ LogViewField* LogViewTelegram::getFieldTree() if (centralTelegram) { // create a temporary central-telegram for getting the field-tree - LogViewTelegram* tmpCentralTelegram = new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, - m_LogTime, - centralTelegram->data()); - LogViewField* fieldTree = tmpCentralTelegram->getFieldTree(); + LogViewTelegram *tmpCentralTelegram = new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, m_LogTime, centralTelegram->data()); + LogViewField *fieldTree = tmpCentralTelegram->getFieldTree(); delete tmpCentralTelegram; delete centralTelegram; return fieldTree; @@ -736,1038 +724,1053 @@ LogViewField* LogViewTelegram::getFieldTree() } return getFieldTree(structName, structName, 1); } - default: - break; + default: + break; + } + return nullptr; } - return nullptr; -} -static inline QStringList objectPath(const LogViewField *parent, const QString &name, const QString &nameOverride) -{ - auto ret = parent->jsonPath(); - if (!nameOverride.isEmpty()) - ret += nameOverride; - if (!name.isEmpty()) - ret += name; - return ret; -} - -LogViewField *LogViewTelegram::getFieldTreeJson(const QJsonValue &data, - const QString &name, - const StructInformation &si, - const QStringList &objectPathBase) -{ - auto xdr = new LogViewXdrStruct(name, LogViewXdrElement::e_KindStructElement); - LogViewField *f = new LogViewField(name, LogViewField::e_FieldKindBorder, xdr); - f->setJsonPath(objectPathBase); - f->setDeleteXdr(true); - addFieldTreeStruct(data.toObject(), f, si, QString(), m_logger); - return f; -} - -void LogViewTelegram::addFieldTreeStruct(const QJsonObject &parentObject, - LogViewField *parent, - const StructInformation &si, - const QString &objectNameArrayHint, - NGL::INGLLogger &logger) -{ - DEBUG_LOG(logger) << "getFieldTreeJson for struct " << si.type << " with #members: " << si.member.size(); - auto parser = jsonParser(); - - for (const MemberInformation &mi : si.member) + static inline QStringList objectPath(const LogViewField *parent, const QString &name, const QString &nameOverride) { - if (!mi.isVisible) - continue; - const QJsonValue val = parentObject.value(mi.name); - if (mi.isString || mi.isBinary) - { - addFieldTreeJsonString(val, parent, mi.name, mi.isBinary, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); - continue; - } - if (mi.isPod) - { - addFieldTreeJsonPod(val, parent, mi.name, mi.type, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); - continue; - } - if (mi.isEnum) - { - addFieldTreeJsonEnum(val, parent, mi.name, mi.type, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); - continue; - } - if (mi.isStruct) - { - const StructInformation si = parser->structFromType(mi.type); - auto xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindStructElement); - LogViewField *f = new LogViewField(mi.name, LogViewField::e_FieldKindBorder, xdr); - f->setJsonPath(objectPath(parent, mi.name, objectNameArrayHint)); - f->setDeleteXdr(true); - addFieldTreeStruct(val.toObject(), f, si, objectNameArrayHint, logger); - parent->addChild(f); - continue; - } - if (mi.isArray) - { - const QString innerType = LogViewTetraTelegramsParser::getInnerType(mi.type); - const bool isPod = parser->isPod(innerType); - const bool isEnum = isPod ? false : parser->isEnum(innerType); - const bool isStruct = (isPod || isEnum) ? false : (parser->isStruct(mi.type) || parser->isStruct(innerType)); + auto ret = parent->jsonPath(); + if (!nameOverride.isEmpty()) + ret += nameOverride; + if (!name.isEmpty()) + ret += name; + return ret; + } - LogViewXdrElement *xdr; - if (isStruct) + LogViewField *LogViewTelegram::getFieldTreeJson(const QJsonValue &data, const QString &name, const StructInformation &si, const QStringList &objectPathBase) + { + auto xdr = new LogViewXdrStruct(name, LogViewXdrElement::e_KindStructElement); + LogViewField *f = new LogViewField(name, LogViewField::e_FieldKindBorder, xdr); + f->setJsonPath(objectPathBase); + f->setDeleteXdr(true); + addFieldTreeStruct(data.toObject(), f, si, QString(), m_logger); + return f; + } + + void LogViewTelegram::addFieldTreeStruct(const QJsonObject &parentObject, + LogViewField *parent, + const StructInformation &si, + const QString &objectNameArrayHint, + NGL::INGLLogger &logger) + { + DEBUG_LOG(logger) << "getFieldTreeJson for struct " << si.type << " with #members: " << si.member.size(); + auto parser = jsonParser(); + + for (const MemberInformation &mi : si.member) + { + if (!mi.isVisible) + continue; + const QJsonValue val = parentObject.value(mi.name); + if (mi.isString || mi.isBinary) { - xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindStruct); + addFieldTreeJsonString(val, parent, mi.name, mi.isBinary, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); + continue; } - else if (isEnum) + if (mi.isPod) { - xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindEnum, 16); + addFieldTreeJsonPod(val, parent, mi.name, mi.type, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); + continue; } - else // isPod + if (mi.isEnum) { - const PodInformation pod = jsonParser()->podFromType(innerType); - - auto stdType = LogViewXdrStandardType::e_Float; - if (pod.isBoolean) - stdType = LogViewXdrStandardType::e_Boolean; - else if (pod.isIntegral) - stdType = pod.isSigned ? LogViewXdrStandardType::e_Signed : LogViewXdrStandardType::e_Unsigned; - - xdr = new LogViewXdrStandardType(mi.name, - pod.byteLen, - pod.byteLen, - stdType, - LogViewXdrStandardType::e_DynArrayMsgLength, - LogViewXdrStandardType::e_ByteOrderLittleEndian); + addFieldTreeJsonEnum(val, parent, mi.name, mi.type, objectNameArrayHint, LogViewField::e_FieldKindEdit, logger); + continue; } - - LogViewField *f = new LogViewField(mi.name, isStruct ? LogViewField::e_FieldKindTab : LogViewField::e_FieldKindPodArray, xdr); - const QString fieldName = isStruct ? QStringLiteral("array: ") + mi.name : mi.name; - f->setJsonPath(objectPath(parent, fieldName, objectNameArrayHint)); - f->setDeleteXdr(true); - f->setMaxArraySize(200, true); - f->setType(LogViewTetraTelegramsParser::getInnerType(mi.type)); - - const QJsonArray arr = val.toArray(); - const QString path(QStringLiteral("index: %1")); - if (isStruct) + if (mi.isStruct) { - auto si = parser->structFromType(mi.type); // custom struct - if (si.type.isEmpty()) - si = parser->structFromType(innerType); // pod? - for (int i = 0; i < arr.size(); ++i) + const StructInformation si = parser->structFromType(mi.type); + auto xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindStructElement); + LogViewField *f = new LogViewField(mi.name, LogViewField::e_FieldKindBorder, xdr); + f->setJsonPath(objectPath(parent, mi.name, objectNameArrayHint)); + f->setDeleteXdr(true); + addFieldTreeStruct(val.toObject(), f, si, objectNameArrayHint, logger); + parent->addChild(f); + continue; + } + if (mi.isArray) + { + const QString innerType = LogViewTetraTelegramsParser::getInnerType(mi.type); + const bool isPod = parser->isPod(innerType); + const bool isEnum = isPod ? false : parser->isEnum(innerType); + const bool isStruct = (isPod || isEnum) ? false : (parser->isStruct(mi.type) || parser->isStruct(innerType)); + + LogViewXdrElement *xdr; + if (isStruct) { - LogViewField *tc = new LogViewField(mi.name + QStringLiteral("TabChild"), LogViewField::e_FieldKindTabChild, xdr); - tc->setJsonPath(f->jsonPath()); - f->addChild(tc); - addFieldTreeStruct(arr.at(i).toObject(), tc, si, path.arg(i), logger); + xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindStruct); } + else if (isEnum) + { + xdr = new LogViewXdrStruct(mi.name, LogViewXdrElement::e_KindEnum, 16); + } + else // isPod + { + const PodInformation pod = jsonParser()->podFromType(innerType); + + auto stdType = LogViewXdrStandardType::e_Float; + if (pod.isBoolean) + stdType = LogViewXdrStandardType::e_Boolean; + else if (pod.isIntegral) + stdType = pod.isSigned ? LogViewXdrStandardType::e_Signed : LogViewXdrStandardType::e_Unsigned; + + xdr = new LogViewXdrStandardType(mi.name, + pod.byteLen, + pod.byteLen, + stdType, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderLittleEndian); + } + + LogViewField *f = new LogViewField(mi.name, isStruct ? LogViewField::e_FieldKindTab : LogViewField::e_FieldKindPodArray, xdr); + const QString fieldName = isStruct ? QStringLiteral("array: ") + mi.name : mi.name; + f->setJsonPath(objectPath(parent, fieldName, objectNameArrayHint)); + f->setDeleteXdr(true); + f->setMaxArraySize(200, true); + f->setType(LogViewTetraTelegramsParser::getInnerType(mi.type)); + + const QJsonArray arr = val.toArray(); + const QString path(QStringLiteral("index: %1")); + if (isStruct) + { + auto si = parser->structFromType(mi.type); // custom struct + if (si.type.isEmpty()) + si = parser->structFromType(innerType); // pod? + for (int i = 0; i < arr.size(); ++i) + { + LogViewField *tc = new LogViewField(mi.name + QStringLiteral("TabChild"), LogViewField::e_FieldKindTabChild, xdr); + tc->setJsonPath(f->jsonPath()); + f->addChild(tc); + addFieldTreeStruct(arr.at(i).toObject(), tc, si, path.arg(i), logger); + } + } + else if (isPod) + { + for (const auto &ele : arr) + f->addValue(QString::number(ele.toInt())); + } + else if (isEnum) + { + for (const auto &ele : arr) + addFieldTreeJsonEnum(ele, f, QString(), innerType, objectNameArrayHint, LogViewField::e_FieldKindPodArrayChild, logger); + } + else + { + // assume string + for (int i = 0; i < arr.size(); ++i) + addFieldTreeJsonString(arr.at(i), f, QString(), false, path.arg(i), LogViewField::e_FieldKindPodArrayChild, logger); + } + parent->addChild(f); } - else if (isPod) - { - for (const auto &ele : arr) - f->addValue(QString::number(ele.toInt())); - } - else if (isEnum) - { - for (const auto &ele : arr) - addFieldTreeJsonEnum(ele, f, QString(), innerType, objectNameArrayHint, LogViewField::e_FieldKindPodArrayChild, logger); - } - else - { - // assume string - for (int i = 0; i < arr.size(); ++i) - addFieldTreeJsonString(arr.at(i), f, QString(), false, path.arg(i), LogViewField::e_FieldKindPodArrayChild, logger); - } - parent->addChild(f); } } -} -// --------------------------------------------------------------- -void LogViewTelegram::addFieldTreeJsonString(const QJsonValue &val, + // --------------------------------------------------------------- + void LogViewTelegram::addFieldTreeJsonString(const QJsonValue &val, + LogViewField *parent, + const QString &name, + bool isBinary, + const QString &objectNameArrayHint, + LogViewField::E_FieldKind fieldKind, + NGL::INGLLogger &logger) + { + DEBUG_LOG(logger) << "addFieldTreeJsonString for " << name << " and value: " << val.toString(); + auto xdr = new LogViewXdrStandardType(name, + 1, + 1, + isBinary ? LogViewXdrStandardType::e_Data : LogViewXdrStandardType::e_Character, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderLittleEndian); + LogViewField *f = new LogViewField(name, fieldKind, xdr); + f->setMaxArraySize(std::numeric_limits::max(), true); + if (isBinary) + f->addValueBinaryHex(val.toString()); + else + f->addValue(val.toString()); + f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); + f->setDeleteXdr(true); + parent->addChild(f); + } + + // --------------------------------------------------------------- + void LogViewTelegram::addFieldTreeJsonPod(const QJsonValue &val, + LogViewField *parent, + const QString &name, + const QString &type, + const QString &objectNameArrayHint, + LogViewField::E_FieldKind fieldKind, + NGL::INGLLogger &logger) + { + DEBUG_LOG(logger) << "addFieldTreeJsonPod for " << name << " and value: " << val.toDouble() << ", type: " << type; + const PodInformation pod = jsonParser()->podFromType(type); + + auto stdType = LogViewXdrStandardType::e_Float; + if (pod.isBoolean) + stdType = LogViewXdrStandardType::e_Boolean; + else if (pod.isIntegral) + stdType = pod.isSigned ? LogViewXdrStandardType::e_Signed : LogViewXdrStandardType::e_Unsigned; + + auto xdr = + new LogViewXdrStandardType(name, pod.byteLen, pod.byteLen, stdType, LogViewXdrStandardType::e_DynArrayMsgLength, LogViewXdrStandardType::e_ByteOrderLittleEndian); + LogViewField *f = new LogViewField(name, fieldKind, xdr); + if (pod.isBoolean) + f->addValue(QString::number(val.toBool())); + else if (pod.isIntegral) + f->addValue(QString::number(qRound64(val.toDouble()))); + else + f->addValue(QStringLiteral("%1").arg(val.toDouble(), 0, 'f', 10)); + f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); + f->setDeleteXdr(true); + parent->addChild(f); + } + + // --------------------------------------------------------------- + void LogViewTelegram::addFieldTreeJsonEnum(const QJsonValue &val, LogViewField *parent, const QString &name, - bool isBinary, + const QString &type, const QString &objectNameArrayHint, LogViewField::E_FieldKind fieldKind, NGL::INGLLogger &logger) -{ - DEBUG_LOG(logger) << "addFieldTreeJsonString for " << name << " and value: " << val.toString(); - auto xdr = new LogViewXdrStandardType(name, - 1, - 1, - isBinary ? LogViewXdrStandardType::e_Data : LogViewXdrStandardType::e_Character, - LogViewXdrStandardType::e_DynArrayMsgLength, - LogViewXdrStandardType::e_ByteOrderLittleEndian); - LogViewField *f = new LogViewField(name, fieldKind, xdr); - f->setMaxArraySize(std::numeric_limits::max(), true); - if (isBinary) - f->addValueBinaryHex(val.toString()); - else - f->addValue(val.toString()); - f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); - f->setDeleteXdr(true); - parent->addChild(f); -} - -// --------------------------------------------------------------- -void LogViewTelegram::addFieldTreeJsonPod(const QJsonValue &val, - LogViewField *parent, - const QString &name, - const QString &type, - const QString &objectNameArrayHint, - LogViewField::E_FieldKind fieldKind, - NGL::INGLLogger &logger) -{ - DEBUG_LOG(logger) << "addFieldTreeJsonPod for " << name << " and value: " << val.toDouble() << ", type: " << type; - const PodInformation pod = jsonParser()->podFromType(type); - - auto stdType = LogViewXdrStandardType::e_Float; - if (pod.isBoolean) - stdType = LogViewXdrStandardType::e_Boolean; - else if (pod.isIntegral) - stdType = pod.isSigned ? LogViewXdrStandardType::e_Signed : LogViewXdrStandardType::e_Unsigned; - - auto xdr = new LogViewXdrStandardType(name, - pod.byteLen, - pod.byteLen, - stdType, - LogViewXdrStandardType::e_DynArrayMsgLength, - LogViewXdrStandardType::e_ByteOrderLittleEndian); - LogViewField *f = new LogViewField(name, fieldKind, xdr); - if (pod.isBoolean) - f->addValue(QString::number(val.toBool())); - else if (pod.isIntegral) - f->addValue(QString::number(qRound64(val.toDouble()))); - else - f->addValue(QStringLiteral("%1").arg(val.toDouble(), 0, 'f', 10)); - f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); - f->setDeleteXdr(true); - parent->addChild(f); -} - -// --------------------------------------------------------------- -void LogViewTelegram::addFieldTreeJsonEnum(const QJsonValue &val, - LogViewField *parent, - const QString &name, - const QString &type, - const QString &objectNameArrayHint, - LogViewField::E_FieldKind fieldKind, - NGL::INGLLogger &logger) -{ - DEBUG_LOG(logger) << "addFieldTreeJsonEnum for " << name << " and value: " << val.toDouble(); - const EnumInformation ei = jsonParser()->enumFromType(type); - if (ei.type.isEmpty()) { - WARNING_LOG(logger) << "Can not find enum information for " << type; - return; - } - - const int enumVal = val.toInt(); - auto xdr = new LogViewXdrStruct(name, LogViewXdrElement::e_KindEnum, 16); - LogViewField *f = new LogViewField(name, fieldKind, xdr); - - bool bAddedDefault = false; - for (const EnumValue &ev : ei.values) - { - xdr->addElement(ev.key, ev.value, LogViewXdrElement::e_KindEnumElement); - if (ev.value == enumVal) + DEBUG_LOG(logger) << "addFieldTreeJsonEnum for " << name << " and value: " << val.toDouble(); + const EnumInformation ei = jsonParser()->enumFromType(type); + if (ei.type.isEmpty()) { - bAddedDefault = true; - f->addValue(ev.key); + WARNING_LOG(logger) << "Can not find enum information for " << type; + return; } - } - if (!bAddedDefault) - f->addValue(QStringLiteral("Unknown (%1)").arg(enumVal)); - f->setMaxArraySize(0, false); - f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); - f->setDeleteXdr(true); - parent->addChild(f); -} + const int enumVal = val.toInt(); + auto xdr = new LogViewXdrStruct(name, LogViewXdrElement::e_KindEnum, 16); + LogViewField *f = new LogViewField(name, fieldKind, xdr); - -// --------------------------------------------------------------- -QString LogViewTelegram::typeFromStructInformation(const StructInformation &si, const QString &name) -{ - return memberFromStructInformation(si, name).type; -} - -// --------------------------------------------------------------- -MemberInformation LogViewTelegram::memberFromStructInformation(const StructInformation &si, const QString &name) -{ - for(const MemberInformation &mi : si.member) - { - if (mi.name == name) - return mi; - } - return {}; -} - -// --------------------------------------------------------------- -LogViewField* LogViewTelegram::getFieldTree(const QString& a_type, const QString& a_name, uint16_t a_arraySize, const LogViewXdrType* a_parentElement, const bool a_hasContent) -{ - DEBUG_LOG(m_logger) << "a_type=" << a_type << " a_name=" << a_name << " a_arraySize=" << a_arraySize; - const LogViewXdrElement* xdrElement = tetraParser()->getElement(a_type); - if (!xdrElement) - return nullptr; - - // xdrElement->dump(); - //INFO_LOG(m_logger) << "name=" << xdrElement->getName().toStdString() << " type=" << xdrElement->getType().toStdString() << " value=" << xdrElement->getValue() << " kind=" << xdrElement->getKind() << " hasChilds=" << xdrElement->hasChilds() << " arraySize=" << xdrElement->getArraySize(); - uint16_t maxArraySize = 0; - LogViewField* fieldTree = nullptr; - switch (xdrElement->getKind()) - { - case LogViewXdrElement::e_KindStruct: - { - // add tab for arrays or border for normal structure - if (a_arraySize == 1) + bool bAddedDefault = false; + for (const EnumValue &ev : ei.values) { - // border for normal structure - fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindBorder, xdrElement); - } - else - { - // static or dynamic array of structures => make tabs - fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindTab, xdrElement); - if (0 != a_arraySize) + xdr->addElement(ev.key, ev.value, LogViewXdrElement::e_KindEnumElement); + if (ev.value == enumVal) { - // static array of structures - fieldTree->setMaxArraySize(0, false); + bAddedDefault = true; + f->addValue(ev.key); } } + if (!bAddedDefault) + f->addValue(QStringLiteral("Unknown (%1)").arg(enumVal)); - // add the childs as struct-elements - uint32_t i = 0; - while (LogViewXdrType* child = static_cast(xdrElement)->getChildAsType(i++)) + f->setMaxArraySize(0, false); + f->setJsonPath(objectPath(parent, name, objectNameArrayHint)); + f->setDeleteXdr(true); + parent->addChild(f); + } + + + // --------------------------------------------------------------- + QString LogViewTelegram::typeFromStructInformation(const StructInformation &si, const QString &name) + { + return memberFromStructInformation(si, name).type; + } + + // --------------------------------------------------------------- + MemberInformation LogViewTelegram::memberFromStructInformation(const StructInformation &si, const QString &name) + { + for (const MemberInformation &mi : si.member) { - bool isDynArray = false; - int arraySize = child->getArraySize(); - if (0 == arraySize && !isScalar(child)) + if (mi.name == name) + return mi; + } + return {}; + } + + // --------------------------------------------------------------- + LogViewField *LogViewTelegram::getFieldTree(const QString &a_type, + const QString &a_name, + uint16_t a_arraySize, + const LogViewXdrType *a_parentElement, + const bool a_hasContent) + { + DEBUG_LOG(m_logger) << "a_type=" << a_type << " a_name=" << a_name << " a_arraySize=" << a_arraySize; + const LogViewXdrElement *xdrElement = tetraParser()->getElement(a_type); + if (!xdrElement) + return nullptr; + + // xdrElement->dump(); + //INFO_LOG(m_logger) << "name=" << xdrElement->getName().toStdString() << " type=" << xdrElement->getType().toStdString() << " value=" << xdrElement->getValue() << " kind=" << xdrElement->getKind() << " hasChilds=" << xdrElement->hasChilds() << " arraySize=" << xdrElement->getArraySize(); + uint16_t maxArraySize = 0; + LogViewField *fieldTree = nullptr; + switch (xdrElement->getKind()) + { + case LogViewXdrElement::e_KindStruct: { - INFO_LOG(m_logger) << "dyn. array of struc"; - arraySize = getDynArraySize(m_ActOffset); - isDynArray = true; + // add tab for arrays or border for normal structure + if (a_arraySize == 1) + { + // border for normal structure + fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindBorder, xdrElement); + } + else + { + // static or dynamic array of structures => make tabs + fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindTab, xdrElement); + if (0 != a_arraySize) + { + // static array of structures + fieldTree->setMaxArraySize(0, false); + } + } + + // add the childs as struct-elements + uint32_t i = 0; + while (LogViewXdrType *child = static_cast(xdrElement)->getChildAsType(i++)) + { + bool isDynArray = false; + int arraySize = child->getArraySize(); + if (0 == arraySize && !isScalar(child)) + { + INFO_LOG(m_logger) << "dyn. array of struc"; + arraySize = getDynArraySize(m_ActOffset); + isDynArray = true; + } + else + { + // do not iterate scalar types + if (isScalar(child)) + { + arraySize = 1; + } + m_MaxArraySize = child->getMaxArraySize(); + } + // INFO_LOG(m_logger) << "struct-element: name=" << child->getName().toStdString() << " arraySize=" << arraySize << " maxArraySize=" << m_DynArrayOffset; + + // handle specialcase: dyn. array of structures with actual count of 0 elements + if (0 == arraySize) + { + LogViewField *field = getFieldTree(child->getType(), child->getName(), child->getArraySize(), child); + field->setHasContent(false); + if (isDynArray) + field->setMaxArraySize(child->getMaxArraySize(), true); // fixme: kommt weiter unten nochmals + fieldTree->addChild(field); + } + // now the normal-case begins + for (int k = 0; k < arraySize; k++) + { + LogViewField *field = getFieldTree(child->getType(), /*childName*/ child->getName(), child->getArraySize(), child); + if (isDynArray) + field->setMaxArraySize(child->getMaxArraySize(), true); // fixme: kommt weiter oben auch schon + fieldTree->addChild(field); + } + } + break; + } + + case LogViewXdrElement::e_KindTypedef: + // get the size of the element (with iterating down until we get a standard-type) + if (a_arraySize != 0) // fixme: dies wird nur bei dyn. arrays von skalaren typen funktionieren + { + // INFO_LOG(m_logger) << "typedef statisch"; + a_arraySize = static_cast(xdrElement)->getArraySize(); + } + else + { + // fixme + INFO_LOG(m_logger) << "typedef dynamisch"; + } + maxArraySize = static_cast(xdrElement) + ->getMaxArraySize(); // fixme: vielleicht funktioniert das nicht in allen Fällen, funktioniert für allgemeine_nachricht + while (xdrElement->getKind() != LogViewXdrElement::e_KindStandardType) + { + xdrElement = tetraParser()->getElement(static_cast(xdrElement)->getType()); + // xdrElement->dump(); + // INFO_LOG(m_logger) << "====> typedef name=" << a_name.toStdString() << " type=" << a_type.toStdString() << " a_arraySize=" << a_arraySize << " xdr.name=" << xdrElement->getName().toStdString() << " xdr.isLeaf=" << xdrElement->isLeaf() << " kind=" << xdrElement->getKind(); + if (LogViewXdrElement::e_KindEnum == xdrElement->getKind()) + { + return getFieldTree(xdrElement->getName(), a_name, a_arraySize); + } + } + Q_FALLTHROUGH(); + case LogViewXdrElement::e_KindStandardType: + { + //INFO_LOG(m_logger) << "standardtype: add edit-field a_name=" << a_name.toStdString() << " a_arraySize=" << a_arraySize << " maxArraySize=" << maxArraySize << " m_DynArrayOffset=" << m_DynArrayOffset << " <==========================="; + if (a_hasContent) + { + fieldTree = getContent(static_cast(xdrElement), m_ActOffset, a_arraySize); + fieldTree->setName(a_name); + } + else + { + fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindEdit, xdrElement); + fieldTree->setHasContent(false); + // todo: mache test mit telegramm, welches ein dyn. array von strukture mit anzahl 0 enthält (z.B. statistik-nachforderung mit 0 teilnehmern) + } + // set the maximal size of array: static arrays => a_arraySize; dyn. arrays => maxArraySize + if (0 == a_arraySize) + { + // dynamic array + fieldTree->setMaxArraySize(0 == maxArraySize ? m_MaxArraySize : maxArraySize, true); + } + else + { + // static array or no array (== [1]) + fieldTree->setMaxArraySize(a_arraySize, false); + } + break; + } + + case LogViewXdrElement::e_KindEnum: + { + // evaluate the size + uint16_t size = static_cast(xdrElement)->getEnumSize(); + uint16_t arraySize = a_arraySize; + if (0 == arraySize) + { + arraySize = getDynArraySize(m_ActOffset); + } + + QString tooltipText; + bool isLast = true; + if (1 == arraySize) + { + uint32_t enumValue = getUIntX(m_ActOffset, size); + tooltipText = QStringLiteral("%1 0x%2 0b%3").arg(enumValue).arg(enumValue, 2, 16, QLatin1Char('0')).arg(enumValue, 8, 2, QLatin1Char('0')); + // only for Tetra and not for arrays: mask out unneeded bits (used for different bitfields within one value) + if (a_parentElement) + { + isLast = a_parentElement->maskValue(enumValue, size, tooltipText); + } + } + + // allocate a new field + fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindEdit, xdrElement); + fieldTree->setToolTipText(tooltipText); + + // get the enums + for (int i = 0; i < arraySize; i++) + { + uint32_t enumValue = getUIntX(m_ActOffset, size); + QString tmp; + if (a_parentElement) + a_parentElement->maskValue(enumValue, size, tmp); + // get the enum-text + QString enumText = QStringLiteral("<%1>").arg(enumValue); + int j = 0; + while (LogViewXdrValue *child = (static_cast(xdrElement))->getChildAsValue(j++)) + { + //INFO_LOG(m_logger) << "child name=" << child->getName().toStdString() << " type=" << child->getType().toStdString() << " value=" << child->getValue(); + if (child->getValue() == enumValue) + { + enumText = LogViewField::makeClean(child->getName()); + break; + } + } + // add the enum-array-element + fieldTree->addValue(enumText); + if (isLast) + m_ActOffset += size; + } + + + // set the maximal size of array: static arrays => a_arraySize; dyn. arrays => maxArraySize + if (0 == a_arraySize) + { + // dynamic array + fieldTree->setMaxArraySize(0 == maxArraySize ? m_MaxArraySize : maxArraySize, true); + } + else + { + // static array or no array (== [1]) + fieldTree->setMaxArraySize(a_arraySize, false); + } + break; + } + default: + break; + } + return fieldTree; + } + + + // --------------------------------------------------------------- + void LogViewTelegram::dump() const + { + //INFO_LOG(m_logger) << "m_ActOffset=" << m_ActOffset; + NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, m_data.data(), m_data.size()); + } + + + // --------------------------------------------------------------- + QString LogViewTelegram::getStructName() const + { + return isJsonTelegram() ? jsonParser()->nameFromTelegramId(getTelId()) : tetraParser()->getStructName(getTelId()); + ; + } + + + // --------------------------------------------------------------- + uint16_t LogViewTelegram::getUInt16(const uint16_t a_offset) const + { + return (uint16_t)getUIntX(a_offset, 2); + } + + + // --------------------------------------------------------------- + uint32_t LogViewTelegram::getUInt32(const uint16_t a_offset) const + { + return getUIntX(a_offset, 4); + } + + + // --------------------------------------------------------------- + int32_t LogViewTelegram::getInt32(const uint16_t a_offset) const + { + return getUInt32(a_offset); + } + + + // --------------------------------------------------------------- + quint64 LogViewTelegram::getUIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) const + { + quint64 factor = 1; // used for little endian + quint64 value = getData(a_offset); + for (int i = 1; i < a_size; i++) + { + if (LogViewXdrStandardType::e_ByteOrderBigEndian == a_byteOrder) + { + value = value << 8; + value += getData(a_offset + i); } else { - // do not iterate scalar types - if (isScalar(child)) + // little endian + factor = factor << 8; + value += factor * getData(a_offset + i); + } + } + return value; + } + + + // --------------------------------------------------------------- + int32_t LogViewTelegram::getSIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) const + { + uint32_t value = getUIntX(a_offset, a_size, a_byteOrder); + switch (a_size) + { + case 1: + if (value & 0x00000080) + value = value | 0xFFFFFF00; + break; + case 2: + if (value & 0x00008000) + value = value | 0xFFFF0000; + break; + case 3: + if (value & 0x00800000) + value = value | 0xFF000000; + break; + default: + break; + } + return value; + } + + + // --------------------------------------------------------------- + char LogViewTelegram::getChar(const uint16_t a_offset, const uint8_t a_size) const + { + char theChar = getData(a_offset + a_size - 1); + return theChar; + } + + + // --------------------------------------------------------------- + bool LogViewTelegram::isValid() + { + switch (m_Validity) + { + default: + switch (m_Protocol) { - arraySize = 1; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + const QJsonValue typeId(m_json.value(QStringLiteral("typeId"))); + const QJsonValue data(m_json.value(QStringLiteral("data"))); + const QJsonValue type(m_json.value(QStringLiteral("type"))); + if (!typeId.isDouble() || !data.isObject() || !type.isString()) + return false; + return true; + } + + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + // check whether magic-number is correct + uint8_t magicNumber = static_cast(m_TetraTelegram->getData()[0]); + if (magicNumber != 0xA5) + { + showMessageBox(QObject::tr("TETRA-Magic-Number is 0x%1 but must be 0xA5").arg(magicNumber, 2, 16, QLatin1Char('0'))); + m_Validity = e_Invalid; + return false; + } + // check telegram-length + int length = m_TetraTelegram->getSize(); + if (length != m_data.size()) + { + showMessageBox(QObject::tr("Telegram length is %1 but must be %2").arg(length + 4).arg(m_data.size())); + m_Validity = e_Invalid; + return false; + } + m_Validity = e_Valid; + return true; + } + + default: + m_Validity = e_Invalid; + return false; } - m_MaxArraySize = child->getMaxArraySize(); - } - // INFO_LOG(m_logger) << "struct-element: name=" << child->getName().toStdString() << " arraySize=" << arraySize << " maxArraySize=" << m_DynArrayOffset; + case e_Valid: + return true; - // handle specialcase: dyn. array of structures with actual count of 0 elements - if (0 == arraySize) - { - LogViewField* field = getFieldTree(child->getType(), child->getName(), child->getArraySize(), child); - field->setHasContent(false); - if (isDynArray) field->setMaxArraySize(child->getMaxArraySize(), true); // fixme: kommt weiter unten nochmals - fieldTree->addChild(field); - } - // now the normal-case begins - for (int k=0; kgetType(), /*childName*/child->getName(), child->getArraySize(), child); - if (isDynArray) field->setMaxArraySize(child->getMaxArraySize(), true); // fixme: kommt weiter oben auch schon - fieldTree->addChild(field); - } + case e_Invalid: + return false; } - break; } - case LogViewXdrElement::e_KindTypedef: - // get the size of the element (with iterating down until we get a standard-type) - if (a_arraySize != 0) // fixme: dies wird nur bei dyn. arrays von skalaren typen funktionieren - { - // INFO_LOG(m_logger) << "typedef statisch"; - a_arraySize = static_cast(xdrElement)->getArraySize(); - } - else - { - // fixme - INFO_LOG(m_logger) << "typedef dynamisch"; - } - maxArraySize = static_cast(xdrElement)->getMaxArraySize(); // fixme: vielleicht funktioniert das nicht in allen Fällen, funktioniert für allgemeine_nachricht - while (xdrElement->getKind() != LogViewXdrElement::e_KindStandardType) - { - xdrElement = tetraParser()->getElement(static_cast(xdrElement)->getType()); - // xdrElement->dump(); - // INFO_LOG(m_logger) << "====> typedef name=" << a_name.toStdString() << " type=" << a_type.toStdString() << " a_arraySize=" << a_arraySize << " xdr.name=" << xdrElement->getName().toStdString() << " xdr.isLeaf=" << xdrElement->isLeaf() << " kind=" << xdrElement->getKind(); - if (LogViewXdrElement::e_KindEnum == xdrElement->getKind()) - { - return getFieldTree(xdrElement->getName(), a_name, a_arraySize); - } - } - Q_FALLTHROUGH(); - case LogViewXdrElement::e_KindStandardType: - { - //INFO_LOG(m_logger) << "standardtype: add edit-field a_name=" << a_name.toStdString() << " a_arraySize=" << a_arraySize << " maxArraySize=" << maxArraySize << " m_DynArrayOffset=" << m_DynArrayOffset << " <==========================="; - if (a_hasContent) - { - fieldTree = getContent(static_cast(xdrElement), m_ActOffset, a_arraySize); - fieldTree->setName(a_name); - } - else - { - fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindEdit, xdrElement); - fieldTree->setHasContent(false); - // todo: mache test mit telegramm, welches ein dyn. array von strukture mit anzahl 0 enthält (z.B. statistik-nachforderung mit 0 teilnehmern) - } - // set the maximal size of array: static arrays => a_arraySize; dyn. arrays => maxArraySize - if (0 == a_arraySize) - { - // dynamic array - fieldTree->setMaxArraySize(0 == maxArraySize ? m_MaxArraySize : maxArraySize, true); - } - else - { - // static array or no array (== [1]) - fieldTree->setMaxArraySize(a_arraySize, false); - } - break; - } - case LogViewXdrElement::e_KindEnum: + // --------------------------------------------------------------- + LogViewField *LogViewTelegram::getContent(const LogViewXdrStandardType *a_standardType, uint16_t &a_offset, const uint16_t a_arraySize) { - // evaluate the size - uint16_t size = static_cast(xdrElement)->getEnumSize(); - uint16_t arraySize = a_arraySize; - if (0 == arraySize) - { - arraySize = getDynArraySize(m_ActOffset); - } - - QString tooltipText; - bool isLast = true; - if (1 == arraySize) - { - uint32_t enumValue = getUIntX(m_ActOffset, size); - tooltipText = QStringLiteral("%1 0x%2 0b%3").arg(enumValue) - .arg(enumValue, 2, 16, QLatin1Char('0')) - .arg(enumValue, 8, 2, QLatin1Char('0')); - // only for Tetra and not for arrays: mask out unneeded bits (used for different bitfields within one value) - if (a_parentElement) - { - isLast = a_parentElement->maskValue(enumValue, size, tooltipText); - } - } + // INFO_LOG(m_logger) << "name=" << a_standardType->getName() << " valueKind=" << a_standardType->getValueKind() << " valueSize=" << a_standardType->getValueSize() << " a_offset=" << a_offset << " a_arraySize=" << a_arraySize; // allocate a new field - fieldTree = new LogViewField(a_name, LogViewField::e_FieldKindEdit, xdrElement); - fieldTree->setToolTipText(tooltipText); + LogViewField *field = new LogViewField(QString(), LogViewField::e_FieldKindEdit, a_standardType); + field->setIsRightAligned(false); - // get the enums - for (int i=0; igetValueSize(); + field->setSize(size); + uint16_t arraySize = a_arraySize; + if (0 == arraySize) + arraySize = getDynArraySize(a_offset); + + // INFO_LOG(m_logger) << "name=" << a_standardType->getName().toStdString() << " size=" << size << " arraySize=" << arraySize; + switch (a_standardType->getValueKind()) { - uint32_t enumValue = getUIntX(m_ActOffset, size); - QString tmp; - if(a_parentElement) - a_parentElement->maskValue(enumValue, size, tmp); - // get the enum-text - QString enumText = QStringLiteral("<%1>").arg(enumValue); - int j=0; - while (LogViewXdrValue* child = (static_cast(xdrElement))->getChildAsValue(j++)) - { - //INFO_LOG(m_logger) << "child name=" << child->getName().toStdString() << " type=" << child->getType().toStdString() << " value=" << child->getValue(); - if (child->getValue() == enumValue) + case LogViewXdrStandardType::e_Unsigned: + // get the values { - enumText = LogViewField::makeClean(child->getName()); - break; + const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); + uint32_t value = 0; + for (int i = 0; i < arraySize; i++) + { + value = getUIntX(i * size + a_offset, size, byteOrder); + field->addValue(QString::number(value)); + } + // generate the tool-tip-text + if (arraySize <= 1) + { + if (a_standardType->getDynArraySizeMethod() == LogViewXdrStandardType::e_DynArrayIndex || + a_standardType->getDynArraySizeMethod() == LogViewXdrStandardType::e_DynArrayIndexDiv8) + { + m_DynArraySizeMethod = a_standardType->getDynArraySizeMethod(); + m_LastUnsignedValue = value; // used for dyn. array in TETRA-Protocol + } + } + field->setIsRightAligned(true); } - } - // add the enum-array-element - fieldTree->addValue(enumText); - if (isLast) m_ActOffset += size; + break; + + case LogViewXdrStandardType::e_Signed: + // get the signed values + { + const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); + for (int i = 0; i < arraySize; i++) + { + int32_t value = getSIntX(i * size + a_offset, size, byteOrder); + field->addValue(QString::number(value)); + } + field->setIsRightAligned(true); + } + break; + + case LogViewXdrStandardType::e_Float: + // get the floating-point value + { + const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); + for (int i = 0; i < arraySize; i++) + { + const quint64 value = getUIntX(i * size + a_offset, size, byteOrder); + if (8 == size) + { + field->addValue(QString::number(xdrToDouble(value))); + INFO_LOG(m_logger) << "value=" << xdrToDouble(value); + } + else + { + field->addValue(QString::number(xdrToFloat(value))); + INFO_LOG(m_logger) << "value=" << xdrToFloat(value); + } + } + field->setIsRightAligned(true); // fixme: vielleicht wird isRightAligned gar nicht benötigt... + } + break; + + case LogViewXdrStandardType::e_Character: + // generate the text + { + QByteArray text; + for (int i = 0; i < arraySize; i++) + { + char theChar = getChar(a_offset + (i * size), size); + if (0 == theChar) + break; + text += theChar; + } + field->addValue(QString::fromUtf8(text)); + } + break; + + case LogViewXdrStandardType::e_Data: + // generate the data-field + for (int i = 0; i < arraySize; i++) + field->addValue(QString::number(getData(a_offset + i))); + break; + + default: + ERROR_LOG(m_logger) << "ValueKind " << a_standardType->getValueKind() << " not implemented!"; + break; } - - - // set the maximal size of array: static arrays => a_arraySize; dyn. arrays => maxArraySize + uint16_t sizeOfContent = arraySize * size; + a_offset += sizeOfContent; + // dynamic arrays must have an overall size which is 4-byte aligned if (0 == a_arraySize) { - // dynamic array - fieldTree->setMaxArraySize(0 == maxArraySize ? m_MaxArraySize : maxArraySize, true); + uint16_t rest = sizeOfContent % 4; + if (0 != rest) + { + a_offset += (4 - rest); + // INFO_LOG(m_logger) << "align offset to " << a_offset << " because it was an dyn. array content."; + } + } + + return field; + } + + + // --------------------------------------------------------------- + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol LogViewTelegram::getDirection() const + { + return static_cast(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); + } + + // --------------------------------------------------------------- + void LogViewTelegram::setJsonValue(const QStringList &path, const QJsonValue &val) + { + m_data.clear(); + updateJsonValue(path, val, m_json); + if (path.size() && path.last() == QLatin1String("equipmentNumber")) + m_ParticipantId = m_json.value(QLatin1String("data")).toObject().value(QLatin1String("header")).toObject().value(QLatin1String("equipmentNumber")).toInt(); + } + + // --------------------------------------------------------------- + void LogViewTelegram::updateJsonValue(const QStringList &path, const QJsonValue &newVal, QJsonObject &obj) + { + if (path.isEmpty()) + return; + if (path.size() > 1) + { + QString key = path.first(); + static const QLatin1String arrayMarker(QLatin1String("array: ")); + const bool isArray = key.startsWith(arrayMarker); + if (isArray) + { + key = key.mid(arrayMarker.size()); + const QJsonValue val = obj.value(key); + QJsonArray arr = val.toArray(); + const QStringList subPath = path.mid(1); + updateJsonValue(subPath, newVal, arr); + obj[key] = arr; + } + else + { + const QJsonValue val = obj.value(key); + QJsonObject child = val.toObject(); + const QStringList subPath = path.mid(1); + updateJsonValue(subPath, newVal, child); + obj[key] = child; + } } else { - // static array or no array (== [1]) - fieldTree->setMaxArraySize(a_arraySize, false); + obj[path.first()] = newVal; } - break; } - default: - break; - } - return fieldTree; -} - -// --------------------------------------------------------------- -void LogViewTelegram::dump() const -{ - //INFO_LOG(m_logger) << "m_ActOffset=" << m_ActOffset; - NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, m_data.data(), m_data.size()); -} - - -// --------------------------------------------------------------- -QString LogViewTelegram::getStructName() const -{ - return isJsonTelegram() ? jsonParser()->nameFromTelegramId(getTelId()) - : tetraParser()->getStructName(getTelId());; -} - - -// --------------------------------------------------------------- -uint16_t LogViewTelegram::getUInt16(const uint16_t a_offset) const -{ - return (uint16_t)getUIntX(a_offset, 2); -} - - -// --------------------------------------------------------------- -uint32_t LogViewTelegram::getUInt32(const uint16_t a_offset) const -{ - return getUIntX(a_offset, 4); -} - - -// --------------------------------------------------------------- -int32_t LogViewTelegram::getInt32(const uint16_t a_offset) const -{ - return getUInt32(a_offset); -} - - -// --------------------------------------------------------------- -quint64 LogViewTelegram::getUIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) const -{ - quint64 factor = 1; // used for little endian - quint64 value = getData(a_offset); - for (int i=1; i 1) { - value = value << 8; - value += getData(a_offset+i); - } - else - { - // little endian - factor = factor << 8; - value += factor * getData(a_offset+i); - } - } - return value; -} - - -// --------------------------------------------------------------- -int32_t LogViewTelegram::getSIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) const -{ - uint32_t value = getUIntX(a_offset, a_size, a_byteOrder); - switch (a_size) - { - case 1: - if (value & 0x00000080) value = value | 0xFFFFFF00; - break; - case 2: - if (value & 0x00008000) value = value | 0xFFFF0000; - break; - case 3: - if (value & 0x00800000) value = value | 0xFF000000; - break; - default: - break; - } - return value; -} - - -// --------------------------------------------------------------- -char LogViewTelegram::getChar(const uint16_t a_offset, const uint8_t a_size) const -{ - char theChar = getData(a_offset+a_size-1); - return theChar; -} - - -// --------------------------------------------------------------- -bool LogViewTelegram::isValid() -{ - switch (m_Validity) - { - default: - switch (m_Protocol) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: - { - const QJsonValue typeId(m_json.value(QStringLiteral("typeId"))); - const QJsonValue data(m_json.value(QStringLiteral("data"))); - const QJsonValue type(m_json.value(QStringLiteral("type"))); - if (!typeId.isDouble() || !data.isObject() || !type.isString()) - return false; - return true; - } - - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: - { - // check whether magic-number is correct - uint8_t magicNumber = static_cast(m_TetraTelegram->getData()[0]); - if (magicNumber != 0xA5) - { - showMessageBox(QObject::tr("TETRA-Magic-Number is 0x%1 but must be 0xA5").arg(magicNumber, 2, 16, QLatin1Char('0'))); - m_Validity = e_Invalid; - return false; - } - // check telegram-length - int length = m_TetraTelegram->getSize(); - if (length != m_data.size()) - { - showMessageBox(QObject::tr("Telegram length is %1 but must be %2").arg(length+4).arg(m_data.size())); - m_Validity = e_Invalid; - return false; - } - m_Validity = e_Valid; - return true; - } - - default: - m_Validity = e_Invalid; - return false; - } - case e_Valid: - return true; - - case e_Invalid: - return false; - - } -} - - -// --------------------------------------------------------------- -LogViewField* LogViewTelegram::getContent(const LogViewXdrStandardType* a_standardType, uint16_t& a_offset, const uint16_t a_arraySize) -{ -// INFO_LOG(m_logger) << "name=" << a_standardType->getName() << " valueKind=" << a_standardType->getValueKind() << " valueSize=" << a_standardType->getValueSize() << " a_offset=" << a_offset << " a_arraySize=" << a_arraySize; - - // allocate a new field - LogViewField* field = new LogViewField(QString(), LogViewField::e_FieldKindEdit, a_standardType); - field->setIsRightAligned(false); - - // evaluate the size - const int size = a_standardType->getValueSize(); - field->setSize(size); - uint16_t arraySize = a_arraySize; - if (0 == arraySize) - arraySize = getDynArraySize(a_offset); - -// INFO_LOG(m_logger) << "name=" << a_standardType->getName().toStdString() << " size=" << size << " arraySize=" << arraySize; - switch (a_standardType->getValueKind()) - { - case LogViewXdrStandardType::e_Unsigned: - // get the values - { - const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); - uint32_t value = 0; - for (int i = 0; i < arraySize; i++) - { - value = getUIntX(i*size+a_offset, size, byteOrder); - field->addValue(QString::number(value)); - } - // generate the tool-tip-text - if (arraySize <= 1) - { - if (a_standardType->getDynArraySizeMethod() == LogViewXdrStandardType::e_DynArrayIndex - || a_standardType->getDynArraySizeMethod() == LogViewXdrStandardType::e_DynArrayIndexDiv8) - { - m_DynArraySizeMethod = a_standardType->getDynArraySizeMethod(); - m_LastUnsignedValue = value; // used for dyn. array in TETRA-Protocol - } - } - field->setIsRightAligned(true); - } - break; - - case LogViewXdrStandardType::e_Signed: - // get the signed values - { - const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); - for (int i = 0; i < arraySize; i++) - { - int32_t value = getSIntX(i*size+a_offset, size, byteOrder); - field->addValue(QString::number(value)); - } - field->setIsRightAligned(true); - } - break; - - case LogViewXdrStandardType::e_Float: - // get the floating-point value - { - const LogViewXdrStandardType::E_ByteOrder byteOrder = a_standardType->getByteOrder(); - for (int i = 0; i < arraySize; i++) - { - const quint64 value = getUIntX(i*size+a_offset, size, byteOrder); - if (8 == size) { - field->addValue(QString::number(xdrToDouble(value))); - INFO_LOG(m_logger) << "value=" << xdrToDouble(value); - } else { - field->addValue(QString::number(xdrToFloat(value))); - INFO_LOG(m_logger) << "value=" << xdrToFloat(value); - } - } - field->setIsRightAligned(true); // fixme: vielleicht wird isRightAligned gar nicht benötigt... - } - break; - - case LogViewXdrStandardType::e_Character: - // generate the text - { - QByteArray text; - for (int i = 0; i < arraySize; i++) - { - char theChar = getChar(a_offset+(i*size), size); - if (0 == theChar) - break; - text += theChar; - } - field->addValue(QString::fromUtf8(text)); - } - break; - - case LogViewXdrStandardType::e_Data: - // generate the data-field - for (int i = 0; i < arraySize; i++) - field->addValue(QString::number(getData(a_offset+i))); - break; - - default: - ERROR_LOG(m_logger) << "ValueKind " << a_standardType->getValueKind() << " not implemented!"; - break; - } - uint16_t sizeOfContent = arraySize * size; - a_offset += sizeOfContent; - // dynamic arrays must have an overall size which is 4-byte aligned - if (0 == a_arraySize) - { - uint16_t rest = sizeOfContent % 4; - if (0 != rest) - { - a_offset += (4 - rest); -// INFO_LOG(m_logger) << "align offset to " << a_offset << " because it was an dyn. array content."; - } - } - - return field; -} - - -// --------------------------------------------------------------- -N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol LogViewTelegram::getDirection() const -{ - return static_cast(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); -} - -// --------------------------------------------------------------- -void LogViewTelegram::setJsonValue(const QStringList &path, const QJsonValue &val) -{ - m_data.clear(); - updateJsonValue(path, val, m_json); - if (path.size() && path.last() == QLatin1String("equipmentNumber")) - m_ParticipantId = m_json.value(QLatin1String("data")) - .toObject().value(QLatin1String("header")) - .toObject().value(QLatin1String("equipmentNumber")).toInt(); -} - -// --------------------------------------------------------------- -void LogViewTelegram::updateJsonValue(const QStringList &path, const QJsonValue &newVal, QJsonObject &obj) -{ - if (path.isEmpty()) - return; - if (path.size() > 1) - { - QString key = path.first(); - static const QLatin1String arrayMarker(QLatin1String("array: ")); - const bool isArray = key.startsWith(arrayMarker); - if (isArray) - { - key = key.mid(arrayMarker.size()); - const QJsonValue val = obj.value(key); - QJsonArray arr = val.toArray(); - const QStringList subPath = path.mid(1); - updateJsonValue(subPath, newVal, arr); - obj[key] = arr; - } - else - { - const QJsonValue val = obj.value(key); - QJsonObject child = val.toObject(); + QJsonObject child = childVal.toObject(); const QStringList subPath = path.mid(1); updateJsonValue(subPath, newVal, child); - obj[key] = child; + arr[arrayIdx] = child; } - } - else - { - obj[path.first()] = newVal; - } -} - -// --------------------------------------------------------------- -void LogViewTelegram::updateJsonValue(const QStringList &path, const QJsonValue &newVal, QJsonArray &arr) -{ - if (path.isEmpty()) - return; - - const QString &key = path.first(); - static const QLatin1String indexMarker(QLatin1String("index: ")); - if (!key.startsWith(indexMarker)) - return; - - const int arrayIdx = key.mid(indexMarker.size()).toInt(); - while (arr.size() <= arrayIdx) - arr.append(QJsonValue()); - - QJsonValue childVal = arr.at(arrayIdx); - if (childVal.isObject() || path.size() > 1) - { - QJsonObject child = childVal.toObject(); - const QStringList subPath = path.mid(1); - updateJsonValue(subPath, newVal, child); - arr[arrayIdx] = child; - } - else - { - arr[arrayIdx] = newVal; - } -} - -// --------------------------------------------------------------- -QIcon LogViewTelegram::getIcon() const -{ - static const QIcon c2p(QLatin1String(":/image/C2P.png")); - static const QIcon p2c(QLatin1String(":/image/P2C.png")); - static const QIcon w2p(QLatin1String(":/image/W2P.png")); - static const QIcon p2w(QLatin1String(":/image/P2W.png")); - static const QIcon t2p(QLatin1String(":/image/T2P.png")); - static const QIcon p2t(QLatin1String(":/image/P2T.png")); - static const QIcon unk(QLatin1String(":/image/Unknown.png")); - N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol protocol, dest; - protocol =(N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol)(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); - dest = (N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol)(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); - switch (protocol) - { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return c2p; - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return p2c; - default: - break; - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return w2p; - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return p2w; - default: - break; - } - break; - } - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: { - switch (dest) { - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: - return p2t; - case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: - return t2p; - default: - break; - } - break; - } - default: - break; - } - return unk; -} - -// --------------------------------------------------------------- -bool LogViewTelegram::isScalar(const LogViewXdrType* a_xdrType) const -{ - const LogViewXdrElement* xdrElement = tetraParser()->getElement(a_xdrType->getType()); - if (xdrElement) - { - switch (xdrElement->getKind()) + else { - case LogViewXdrElement::e_KindStandardType: - case LogViewXdrElement::e_KindEnum: - return true; - case LogViewXdrElement::e_KindStruct: - return false; - case LogViewXdrElement::e_KindTypedef: - return isScalar(static_cast(xdrElement)); - /* + arr[arrayIdx] = newVal; + } + } + + // --------------------------------------------------------------- + QIcon LogViewTelegram::getIcon() const + { + static const QIcon c2p(QLatin1String(":/image/C2P.png")); + static const QIcon p2c(QLatin1String(":/image/P2C.png")); + static const QIcon w2p(QLatin1String(":/image/W2P.png")); + static const QIcon p2w(QLatin1String(":/image/P2W.png")); + static const QIcon t2p(QLatin1String(":/image/T2P.png")); + static const QIcon p2t(QLatin1String(":/image/P2T.png")); + static const QIcon unk(QLatin1String(":/image/Unknown.png")); + N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol protocol, dest; + protocol = (N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol)(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolMask); + dest = (N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol)(m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask); + switch (protocol) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return c2p; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return p2c; + default: + break; + } + break; + } + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return w2p; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return p2w; + default: + break; + } + break; + } + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra: + { + switch (dest) + { + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive: + return p2t; + case N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend: + return t2p; + default: + break; + } + break; + } + default: + break; + } + return unk; + } + + // --------------------------------------------------------------- + bool LogViewTelegram::isScalar(const LogViewXdrType *a_xdrType) const + { + const LogViewXdrElement *xdrElement = tetraParser()->getElement(a_xdrType->getType()); + if (xdrElement) + { + switch (xdrElement->getKind()) + { + case LogViewXdrElement::e_KindStandardType: + case LogViewXdrElement::e_KindEnum: + return true; + case LogViewXdrElement::e_KindStruct: + return false; + case LogViewXdrElement::e_KindTypedef: + return isScalar(static_cast(xdrElement)); + /* e_KindStructElement, e_KindEnumElement, e_KindDefine*/ - default: - ERROR_LOG(m_logger) << "name=" << xdrElement->getName().toStdString() << " kind=" << xdrElement->getKind() << " case not implemented!"; - return false; + default: + ERROR_LOG(m_logger) << "name=" << xdrElement->getName().toStdString() << " kind=" << xdrElement->getKind() << " case not implemented!"; + return false; + } } + return false; } - return false; -} -// --------------------------------------------------------------- -void LogViewTelegram::showMessageBox(const QString& a_errorText, const QString& a_title) const -{ - quint64 logTimeSec = m_LogTime >> 32; - quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(logTimeSec * 1000 + logTimeMicroSec/1000)); - const QString destStr((m_Destination&N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask)==N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend ? - QLatin1String("gesendete") : QLatin1String("gelesene")); - QMessageBox::warning(QApplication::topLevelWidgets()[0], a_title, - QString::fromUtf8("Das %5 Telegramm mit Protokoll %6 von %1 (Unix-Zeit: %2) und Länge %3 ist fehlerhaft:

%4") - .arg(dt.toString(Qt::TextDate)).arg(logTimeSec).arg(m_data.size()).arg(a_errorText, destStr).arg(m_Protocol)); -} - - -// --------------------------------------------------------------- -uint16_t LogViewTelegram::getDynArraySize(uint16_t& a_offset) const -{ - uint16_t arraySize; - if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra == m_Protocol) + // --------------------------------------------------------------- + void LogViewTelegram::showMessageBox(const QString &a_errorText, const QString &a_title) const { - switch (m_DynArraySizeMethod) { - case LogViewXdrStandardType::e_DynArrayMsgLength: - arraySize = m_data.size() - m_MaxArraySize; - break; + quint64 logTimeSec = m_LogTime >> 32; + quint64 logTimeMicroSec = m_LogTime & 0x00FFFFFFFFULL; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(logTimeSec * 1000 + logTimeMicroSec / 1000)); + const QString destStr((m_Destination & N_CoPrtCnv::CoPrtCnvLogHeader::e_DestDirectionMask) == N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend ? QLatin1String("gesendete") + : QLatin1String("gelesene")); + QMessageBox::warning(QApplication::topLevelWidgets()[0], + a_title, + QString::fromUtf8("Das %5 Telegramm mit Protokoll %6 von %1 (Unix-Zeit: %2) und Länge %3 ist fehlerhaft:

%4") + .arg(dt.toString(Qt::TextDate)) + .arg(logTimeSec) + .arg(m_data.size()) + .arg(a_errorText, destStr) + .arg(m_Protocol)); + } - case LogViewXdrStandardType::e_DynArrayIndexDiv8: - arraySize = (m_LastUnsignedValue+7)/8; - break; - default: - arraySize = m_LastUnsignedValue; - break; + // --------------------------------------------------------------- + uint16_t LogViewTelegram::getDynArraySize(uint16_t &a_offset) const + { + uint16_t arraySize; + if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra == m_Protocol) + { + switch (m_DynArraySizeMethod) + { + case LogViewXdrStandardType::e_DynArrayMsgLength: + arraySize = m_data.size() - m_MaxArraySize; + break; + + case LogViewXdrStandardType::e_DynArrayIndexDiv8: + arraySize = (m_LastUnsignedValue + 7) / 8; + break; + + default: + arraySize = m_LastUnsignedValue; + break; + } } + else + { + // dynamic array => get the next 4 bytes, which contain the lengths of the dynamic array + arraySize = getUIntX(a_offset, SIZE_CENTRAL_DYN_ARRAY_SIZE); + a_offset += SIZE_CENTRAL_DYN_ARRAY_SIZE; + } + return arraySize; } - else + + + // --------------------------------------------------------------- + QString LogViewTelegram::formatToolTipLine(const QString &a_name, const QString &a_text, const uint32_t a_value) { - // dynamic array => get the next 4 bytes, which contain the lengths of the dynamic array - arraySize = getUIntX(a_offset, SIZE_CENTRAL_DYN_ARRAY_SIZE); - a_offset += SIZE_CENTRAL_DYN_ARRAY_SIZE; + static const QString s1(QLatin1String( + "%1: %20x%30b%4")); + static const QString s2(QLatin1String("%1")); + QString num16 = s2.arg(a_value, 2, 16, QLatin1Char('0')); + QString num2 = s2.arg(a_value, 8, 2, QLatin1Char('0')); + QString ret = s1.arg(a_name, a_text, num16, num2); + ret = ret.replace(QLatin1Char('\n'), QLatin1String("
")); + return ret; } - return arraySize; -} -// --------------------------------------------------------------- -QString LogViewTelegram::formatToolTipLine(const QString& a_name, const QString& a_text, const uint32_t a_value) -{ - static const QString s1(QLatin1String("%1: %20x%30b%4")); - static const QString s2(QLatin1String("%1")); - QString num16 = s2.arg(a_value, 2, 16, QLatin1Char('0')); - QString num2 = s2.arg(a_value, 8, 2, QLatin1Char('0')); - QString ret = s1.arg(a_name, a_text, num16, num2); - ret = ret.replace(QLatin1Char('\n'), QLatin1String("
")); - return ret; -} + // --------------------------------------------------------------- + const N_CoPrtCnv::CoPrtCnvRadioTelegram *LogViewTelegram::getTetraTelegram() const + { + return m_TetraTelegram; + } -// --------------------------------------------------------------- -const N_CoPrtCnv::CoPrtCnvRadioTelegram* LogViewTelegram::getTetraTelegram() const -{ - return m_TetraTelegram; -} + // --------------------------------------------------------------- + LogViewTetraTelegramsParser *LogViewTelegram::jsonParser() + { + static LogViewTetraTelegramsParser s_parser; + return &s_parser; + } + + // --------------------------------------------------------------- + LogViewXdrParser *LogViewTelegram::tetraParser() + { + static LogViewXdrParser s_parser; + return &s_parser; + } + + // --------------------------------------------------------------- + // returns the data-byte at a_offset. Returns 0 if a_offset is + // outside of range. + // --------------------------------------------------------------- + uint8_t LogViewTelegram::getData(const uint16_t a_offset) const + { + if (a_offset < m_data.size()) + return m_data.at(a_offset); + + return 0; + } + + // --------------------------------------------------------------- + QByteArray LogViewTelegram::getData(QJsonDocument::JsonFormat format) const + { + if (m_data.isEmpty() && !m_json.isEmpty()) + return QJsonDocument(m_json).toJson(format); + + return m_data; + } -// --------------------------------------------------------------- -LogViewTetraTelegramsParser *LogViewTelegram::jsonParser() -{ - static LogViewTetraTelegramsParser s_parser; - return &s_parser; -} - -// --------------------------------------------------------------- -LogViewXdrParser *LogViewTelegram::tetraParser() -{ - static LogViewXdrParser s_parser; - return &s_parser; -} - -// --------------------------------------------------------------- -// returns the data-byte at a_offset. Returns 0 if a_offset is -// outside of range. -// --------------------------------------------------------------- -uint8_t LogViewTelegram::getData(const uint16_t a_offset) const -{ - if (a_offset < m_data.size()) - return m_data.at(a_offset); - - return 0; -} - -// --------------------------------------------------------------- -QByteArray LogViewTelegram::getData(QJsonDocument::JsonFormat format) const -{ - if (m_data.isEmpty() && !m_json.isEmpty()) - return QJsonDocument(m_json).toJson(format); - - return m_data; -} - - -// --------------------------------------------------------------- -void LogViewTelegram::setNextFieldAsGpsTimeField() -{ + // --------------------------------------------------------------- + void LogViewTelegram::setNextFieldAsGpsTimeField() + { m_GpsFieldOffset.append(m_ActOffset); -} - -// --------------------------------------------------------------- -void LogViewTelegram::actualizeGpsTime() -{ - if (m_GpsFieldOffset.size() > 0) - { - if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral == m_Protocol) - { - uint16_t savedOffset = m_ActOffset; - for (QVector::const_iterator i = m_GpsFieldOffset.cbegin(); i < m_GpsFieldOffset.cend(); ++i) - { - m_ActOffset = *i; - setUIntX(4, ::time(nullptr)); // todo nicht 4 sondern size des typs - } - m_ActOffset = savedOffset; - } } - if (!m_json.isEmpty()) + // --------------------------------------------------------------- + void LogViewTelegram::actualizeGpsTime() { - static const QString dataKey = QStringLiteral("data"); - if (dataKey.contains(dataKey)) + if (m_GpsFieldOffset.size() > 0) { - auto data = m_json.value(dataKey).toObject(); - static const QString hdrKey = QStringLiteral("header"); - if (data.contains(hdrKey)) + if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral == m_Protocol) { - auto hdr = data.value(hdrKey).toObject(); - hdr[QStringLiteral("timeStamp")] = QDateTime::currentMSecsSinceEpoch(); - data[hdrKey] = hdr; + uint16_t savedOffset = m_ActOffset; + for (QVector::const_iterator i = m_GpsFieldOffset.cbegin(); i < m_GpsFieldOffset.cend(); ++i) + { + m_ActOffset = *i; + setUIntX(4, ::time(nullptr)); // todo nicht 4 sondern size des typs + } + m_ActOffset = savedOffset; } - m_json[dataKey] = data; } - m_data.clear(); + + if (!m_json.isEmpty()) + { + static const QString dataKey = QStringLiteral("data"); + if (dataKey.contains(dataKey)) + { + auto data = m_json.value(dataKey).toObject(); + static const QString hdrKey = QStringLiteral("header"); + if (data.contains(hdrKey)) + { + auto hdr = data.value(hdrKey).toObject(); + hdr[QStringLiteral("timeStamp")] = QDateTime::currentMSecsSinceEpoch(); + data[hdrKey] = hdr; + } + m_json[dataKey] = data; + } + m_data.clear(); + } } -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.hpp index 4f93e04f7..423a79ab7 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegram.hpp @@ -49,7 +49,6 @@ namespace N_LogView class LogViewTelegram final { public: - /** * @author alois.wismer * @version 1.0 @@ -99,8 +98,7 @@ namespace N_LogView * @param a_destination * @param a_telId */ - LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, - int telegramId); + LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, int telegramId); /** * Constructor for existing telegrams @@ -110,9 +108,7 @@ namespace N_LogView * @param a_telegramData * @param a_telegramSize */ - LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, - const quint64 a_unixTime, - const QByteArray &a_telegramData); + LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, const quint64 a_unixTime, const QByteArray &a_telegramData); /** * Writes a_value with size a_size at actual position of m_Data (given with @@ -123,9 +119,7 @@ namespace N_LogView * @param a_value * @param a_byteOrder */ - void setUIntX(const uint8_t a_size, - quint64 a_value, - const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian); + void setUIntX(const uint8_t a_size, quint64 a_value, const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian); /** * Returns true if a_data could be written. @@ -188,7 +182,7 @@ namespace N_LogView void resetOffset(); - LogViewField* getFieldTree(); + LogViewField *getFieldTree(); void dump() const; @@ -216,14 +210,18 @@ namespace N_LogView bool isJsonTelegram() const { return N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral == m_Protocol; } void clearJsonData() { m_json.remove(QStringLiteral("data")); } - void rebuildJsonString() { if (!m_json.isEmpty()) m_data.clear(); } + void rebuildJsonString() + { + if (!m_json.isEmpty()) + m_data.clear(); + } void setJsonValue(const QStringList &path, const QJsonValue &val); QJsonObject jsonData() const { return m_json; } void updateJsonValue(const QStringList &path, const QJsonValue &newVal, QJsonObject &obj); void updateJsonValue(const QStringList &path, const QJsonValue &newVal, QJsonArray &arr); - const N_CoPrtCnv::CoPrtCnvRadioTelegram* getTetraTelegram() const; + const N_CoPrtCnv::CoPrtCnvRadioTelegram *getTetraTelegram() const; static LogViewTetraTelegramsParser *jsonParser(); static LogViewXdrParser *tetraParser(); @@ -275,7 +273,6 @@ namespace N_LogView static uint32_t floatToXdr(float in); protected: - /** * The name of the telegram, shown in edit-list */ @@ -297,7 +294,7 @@ namespace N_LogView * The allocated size of m_Data. (Used for optimizing of speed) */ int m_AllocatedSize; - static const LogViewXdrParser* m_Parser; + static const LogViewXdrParser *m_Parser; uint16_t m_ActOffset; QVector m_GpsFieldOffset; int m_TelId; @@ -338,15 +335,14 @@ namespace N_LogView QJsonObject m_json; N_CoPrtCnv::CoPrtCnvRadioTelegram *m_TetraTelegram; - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; - LogViewField *getFieldTree(const QString& a_type, const QString& a_name, - uint16_t a_arraySize, const LogViewXdrType* a_parentElement = nullptr, + LogViewField *getFieldTree(const QString &a_type, + const QString &a_name, + uint16_t a_arraySize, + const LogViewXdrType *a_parentElement = nullptr, const bool a_hasContent = true); - LogViewField *getFieldTreeJson(const QJsonValue &data, - const QString &name, - const StructInformation &si, - const QStringList &objectPathBase); + LogViewField *getFieldTreeJson(const QJsonValue &data, const QString &name, const StructInformation &si, const QStringList &objectPathBase); static void addFieldTreeStruct(const QJsonObject &parentObject, LogViewField *parent, @@ -402,7 +398,9 @@ namespace N_LogView * @param a_size * @param a_byteOrder */ - quint64 getUIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian) const; + quint64 getUIntX(const uint16_t a_offset, + const uint8_t a_size, + const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian) const; /** * @@ -410,7 +408,9 @@ namespace N_LogView * @param a_size * @param a_byteOrder */ - int32_t getSIntX(const uint16_t a_offset, const uint8_t a_size, const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian) const; + int32_t getSIntX(const uint16_t a_offset, + const uint8_t a_size, + const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian) const; /** * @@ -425,36 +425,33 @@ namespace N_LogView * @param a_offset * @param a_arraySize */ - LogViewField* getContent(const LogViewXdrStandardType* a_standardType, uint16_t& a_offset, const uint16_t a_arraySize); + LogViewField *getContent(const LogViewXdrStandardType *a_standardType, uint16_t &a_offset, const uint16_t a_arraySize); /** * * @param a_xdrType */ - bool isScalar(const LogViewXdrType* a_xdrType) const; + bool isScalar(const LogViewXdrType *a_xdrType) const; /** * * @param a_errorText * @param a_title */ - void showMessageBox(const QString& a_errorText, const QString& a_title = QObject::tr("Invalid telegram")) const; + void showMessageBox(const QString &a_errorText, const QString &a_title = QObject::tr("Invalid telegram")) const; /** * * @param a_offset */ - uint16_t getDynArraySize(uint16_t& a_offset) const; + uint16_t getDynArraySize(uint16_t &a_offset) const; /** * * @param a_name * @param a_value */ - static QString formatToolTipLine(const QString& a_name, const uint32_t a_value) - { - return formatToolTipLine(a_name, QString::number(a_value), a_value); - } + static QString formatToolTipLine(const QString &a_name, const uint32_t a_value) { return formatToolTipLine(a_name, QString::number(a_value), a_value); } /** * @@ -462,9 +459,9 @@ namespace N_LogView * @param a_text * @param a_value */ - static QString formatToolTipLine(const QString& a_name, const QString& a_text, const uint32_t a_value); + static QString formatToolTipLine(const QString &a_name, const QString &a_text, const uint32_t a_value); - static QString formatToolTipLine(const QString& a_name, const std::string& a_text, const uint32_t a_value) + static QString formatToolTipLine(const QString &a_name, const std::string &a_text, const uint32_t a_value) { return formatToolTipLine(a_name, QString::fromStdString(a_text), a_value); } @@ -478,6 +475,5 @@ namespace N_LogView private: friend class LogViewTabWidget; - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.cpp index 67aa056a1..222723e5e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.cpp @@ -42,461 +42,454 @@ namespace N_LogView { -// todo: -// - feld einfärben wenn geändert, wenn falsch -// - mache hartcodierte oder konfigurierbare ranges für spezielle Werte wie GPS-Position: signed 24-bit + // todo: + // - feld einfärben wenn geändert, wenn falsch + // - mache hartcodierte oder konfigurierbare ranges für spezielle Werte wie GPS-Position: signed 24-bit - - - -LogViewTelegramDialog::LogViewTelegramDialog(QWidget *a_parent, const bool a_readonly, NGL::INGLLogger& logger) - : QDialog(a_parent) - , m_ReadOnly(a_readonly) - , m_logger(logger) -{ - setAttribute(Qt::WA_DeleteOnClose); -} - -// --------------------------------------------------------------- -void LogViewTelegramDialog::showDialog(const QSharedPointer &a_telegram) -{ - delete layout(); - hide(); - - m_Telegram = a_telegram; - a_telegram->dump(); - - m_fieldTree.reset(a_telegram->getFieldTree()); - - if (m_fieldTree) + LogViewTelegramDialog::LogViewTelegramDialog(QWidget *a_parent, const bool a_readonly, NGL::INGLLogger &logger) + : QDialog(a_parent) + , m_ReadOnly(a_readonly) + , m_logger(logger) { - QGridLayout *dialogLayout = new QGridLayout; - if (!m_ReadOnly) + setAttribute(Qt::WA_DeleteOnClose); + } + + // --------------------------------------------------------------- + void LogViewTelegramDialog::showDialog(const QSharedPointer &a_telegram) + { + delete layout(); + hide(); + + m_Telegram = a_telegram; + a_telegram->dump(); + + m_fieldTree.reset(a_telegram->getFieldTree()); + + if (m_fieldTree) { - // edit wait-time - QLabel *waitTimeLabel = new QLabel(tr("Wartezeit [ms]"), this); - dialogLayout->addWidget(waitTimeLabel, dialogLayout->rowCount(), 0); - m_WaitTimeEdit = new QLineEdit(QString::number(a_telegram->getWaitTime()), this); - dialogLayout->addWidget(m_WaitTimeEdit, dialogLayout->rowCount() - 1, 1); + QGridLayout *dialogLayout = new QGridLayout; + if (!m_ReadOnly) + { + // edit wait-time + QLabel *waitTimeLabel = new QLabel(tr("Wartezeit [ms]"), this); + dialogLayout->addWidget(waitTimeLabel, dialogLayout->rowCount(), 0); + m_WaitTimeEdit = new QLineEdit(QString::number(a_telegram->getWaitTime()), this); + dialogLayout->addWidget(m_WaitTimeEdit, dialogLayout->rowCount() - 1, 1); - // edit name - QLabel *nameLabel = new QLabel(tr("Name"), this); - dialogLayout->addWidget(nameLabel, dialogLayout->rowCount(), 0); - m_NameEdit = new QLineEdit(a_telegram->getName(), this); - dialogLayout->addWidget(m_NameEdit, dialogLayout->rowCount() - 1, 1); + // edit name + QLabel *nameLabel = new QLabel(tr("Name"), this); + dialogLayout->addWidget(nameLabel, dialogLayout->rowCount(), 0); + m_NameEdit = new QLineEdit(a_telegram->getName(), this); + dialogLayout->addWidget(m_NameEdit, dialogLayout->rowCount() - 1, 1); - QFrame *f = new QFrame(this); - f->setFrameShape(QFrame::HLine); - f->setFrameShadow(QFrame::Sunken); - dialogLayout->addWidget(f, dialogLayout->rowCount(), 0, 1, 2); + QFrame *f = new QFrame(this); + f->setFrameShape(QFrame::HLine); + f->setFrameShadow(QFrame::Sunken); + dialogLayout->addWidget(f, dialogLayout->rowCount(), 0, 1, 2); + } + + //INFO_LOG(m_logger) << "--------------- create dialog " << fieldTree->getName().toStdString() << "--------------"; + //m_fieldTree->dump(); + showTree(m_fieldTree.data(), dialogLayout); + if (this->findChild() == nullptr) + dialogLayout->setRowStretch(dialogLayout->rowCount(), 1); + + // build the dialog + QVBoxLayout *mainLayout = new QVBoxLayout(this); + + // make dialog scrollable + m_contentsWidget = new QWidget; + m_contentsWidget->setLayout(dialogLayout); + + m_ScrollArea = new QScrollArea(this); + m_ScrollArea->setWidget(m_contentsWidget); + m_ScrollArea->setWidgetResizable(true); + + mainLayout->addWidget(m_ScrollArea); + + // buttons + QHBoxLayout *btnLayout = new QHBoxLayout; + btnLayout->addStretch(); + showButtons(btnLayout); + + mainLayout->addLayout(btnLayout); + + setWindowTitle(m_fieldTree->cleanName() + QStringLiteral(" (%1)").arg(a_telegram->getTelId())); + + setModal(true); + show(); + + makePretty(); } + else + showDataDump(a_telegram, true); + } - //INFO_LOG(m_logger) << "--------------- create dialog " << fieldTree->getName().toStdString() << "--------------"; - //m_fieldTree->dump(); - showTree(m_fieldTree.data(), dialogLayout); - if (this->findChild() == nullptr) - dialogLayout->setRowStretch(dialogLayout->rowCount(), 1); - // build the dialog - QVBoxLayout *mainLayout = new QVBoxLayout(this); + // --------------------------------------------------------------- + void LogViewTelegramDialog::showDataDump(const QSharedPointer &a_telegram, bool showErrorMessage) + { + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(new QLabel(tr("Telegramm-Dump"))); - // make dialog scrollable - m_contentsWidget = new QWidget; - m_contentsWidget->setLayout(dialogLayout); + if (showErrorMessage) + // show error-message in dialog + layout->addWidget(new QLabel(tr("Konnte Dialog basierend auf Struktur \'%1\' nicht generieren!").arg(a_telegram->getStructName()))); + else + layout->addWidget(new QLabel(tr("HexData from \'%1\' - telegram:").arg(a_telegram->getName()))); - m_ScrollArea = new QScrollArea(this); - m_ScrollArea->setWidget(m_contentsWidget); - m_ScrollArea->setWidgetResizable(true); + // generate the telegram-dump + QString theDump = QLatin1String(""); + const QByteArray &data = a_telegram->getData(); + for (int i = 0; i < data.size(); i++) + { + if (0 == (i % 8)) + theDump += QStringLiteral("%1:").arg(i, 4, 16, QLatin1Char('0')); - mainLayout->addWidget(m_ScrollArea); + theDump += QStringLiteral(" %1").arg(static_cast(data[i]), 2, 16, QLatin1Char('0')); + if (7 == (i % 8)) + theDump += QLatin1String("
"); + } + theDump += QLatin1String("
"); - // buttons + QTextEdit *telegramDump = new QTextEdit(theDump); + layout->addWidget(telegramDump); + QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Schliessen")); QHBoxLayout *btnLayout = new QHBoxLayout; btnLayout->addStretch(); - showButtons(btnLayout); - - mainLayout->addLayout(btnLayout); - - setWindowTitle(m_fieldTree->cleanName() + QStringLiteral(" (%1)").arg(a_telegram->getTelId())); - - setModal(true); + btnLayout->addWidget(btnClose); + layout->addLayout(btnLayout); + connect(btnClose, &QPushButton::clicked, this, &LogViewTelegramDialog::reject); + setLayout(layout); show(); - - makePretty(); } - else - showDataDump(a_telegram, true); -} -// --------------------------------------------------------------- -void LogViewTelegramDialog::showDataDump(const QSharedPointer &a_telegram, bool showErrorMessage) -{ - QVBoxLayout *layout = new QVBoxLayout; - layout->addWidget(new QLabel(tr("Telegramm-Dump"))); - - if (showErrorMessage) - // show error-message in dialog - layout->addWidget(new QLabel(tr("Konnte Dialog basierend auf Struktur \'%1\' nicht generieren!").arg(a_telegram->getStructName()))); - else - layout->addWidget(new QLabel(tr("HexData from \'%1\' - telegram:").arg(a_telegram->getName()))); - - // generate the telegram-dump - QString theDump = QLatin1String(""); - const QByteArray &data = a_telegram->getData(); - for (int i = 0; i < data.size(); i++) + // --------------------------------------------------------------- + void LogViewTelegramDialog::makePretty() { - if (0 == (i % 8)) - theDump += QStringLiteral("%1:").arg(i, 4, 16, QLatin1Char('0')); + return; + // set the size and position of dialog + int sbWidth = m_ScrollArea->width() - m_ScrollArea->viewport()->width(); + int wDiff = m_contentsWidget->width() - m_ScrollArea->width(); + int hDiff = m_contentsWidget->height() - m_ScrollArea->viewport()->height(); + const QRect screenSize = QGuiApplication::primaryScreen()->geometry(); - theDump += QStringLiteral(" %1").arg(static_cast(data[i]), 2, 16, QLatin1Char('0')); - if (7 == (i % 8)) - theDump += QLatin1String("
"); + int newWidth = std::min(width() + wDiff + sbWidth, screenSize.width() * 9 / 10); + int newHeight = std::min(height() + hDiff, screenSize.height() * 9 / 10); + //setGeometry(winGeo); + //QSize size = settings.value(SIZE, sizeHint()).toSize(); + resize(QSize(newWidth, newHeight)); + //move(settings.value(POS, QPoint(0, 0)).toPoint()); + // -------------------------------------------------------------------- } - theDump += QLatin1String("
"); - - QTextEdit *telegramDump = new QTextEdit(theDump); - layout->addWidget(telegramDump); - QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Schliessen")); - QHBoxLayout *btnLayout = new QHBoxLayout; - btnLayout->addStretch(); - btnLayout->addWidget(btnClose); - layout->addLayout(btnLayout); - connect(btnClose, &QPushButton::clicked, - this, &LogViewTelegramDialog::reject); - setLayout(layout); - show(); -} -// --------------------------------------------------------------- -void LogViewTelegramDialog::makePretty() -{ - return; - // set the size and position of dialog - int sbWidth = m_ScrollArea->width() - m_ScrollArea->viewport()->width(); - int wDiff = m_contentsWidget->width() - m_ScrollArea->width(); - int hDiff = m_contentsWidget->height() - m_ScrollArea->viewport()->height(); - const QRect screenSize = QGuiApplication::primaryScreen()->geometry(); - - int newWidth = std::min(width() + wDiff + sbWidth, screenSize.width() * 9 / 10); - int newHeight = std::min(height() + hDiff, screenSize.height() * 9 / 10); - //setGeometry(winGeo); - //QSize size = settings.value(SIZE, sizeHint()).toSize(); - resize(QSize(newWidth, newHeight)); - //move(settings.value(POS, QPoint(0, 0)).toPoint()); - // -------------------------------------------------------------------- -} - - -// --------------------------------------------------------------- -void LogViewTelegramDialog::showTree(LogViewField *a_fieldTree, QGridLayout *a_box) -{ - int i = 0; - while (LogViewField *child = a_fieldTree->child(i++)) + // --------------------------------------------------------------- + void LogViewTelegramDialog::showTree(LogViewField *a_fieldTree, QGridLayout *a_box) { - if (!a_fieldTree->hasContent()) - child->setHasContent(false); - switch (child->kind()) + int i = 0; + while (LogViewField *child = a_fieldTree->child(i++)) { - case LogViewField::e_FieldKindBorder: - { - QGroupBox *groupBox = new QGroupBox(child->cleanName()); - QGridLayout *actBox = new QGridLayout(groupBox); - a_box->addWidget(groupBox, a_box->rowCount(), 0, 1, 2); - showTree(child, actBox); - break; - } - case LogViewField::e_FieldKindTab: - showTab(child, a_box); - break; - case LogViewField::e_FieldKindTabChild: - { - QWidget *widget = new QWidget; - widget->setContentsMargins(QMargins()); - QGridLayout *actBox = new QGridLayout(widget); - a_box->addWidget(widget, a_box->rowCount(), 0, 1, 2); - showTree(child, actBox); - break; - } - case LogViewField::e_FieldKindEdit: - case LogViewField::e_FieldKindPodArray: - case LogViewField::e_FieldKindPodArrayChild: - showEditField(child, a_box); - break; - } - } -} - - -// --------------------------------------------------------------- -void LogViewTelegramDialog::fillTelegram(LogViewTelegram *a_telegram) -{ - INFO_LOG(m_logger) << "******************************************"; - - - - for (const auto ptr : std::as_const(m_EditInfoList)) - { - if (!ptr->isValid()) - { - INFO_LOG(m_logger) << ptr->field()->name() << " is invalid"; - return; // abort when a value is not vaild - } - } - - // now save the values - // ------------------- - a_telegram->resetOffset(); - a_telegram->clearJsonData(); - for (auto ptr : std::as_const(m_EditInfoList)) - { - if (!ptr->saveContent(a_telegram)) - { - QMessageBox::warning(this, tr("Error while saving telegram"), - tr("Found an invalid value - the telegram may be not saved correctly")); - } - } -} - - -// --------------------------------------------------------------- -void LogViewTelegramDialog::saveTelegram() -{ - fillTelegram(m_Telegram.data()); - - // save wait-time and name - N_SST::IntegerCalculator calculator; - N_SST::IntegerCalculator::E_Error error; - m_Telegram->setWaitTime(calculator.calc(m_WaitTimeEdit->text().toStdString(), error)); - m_Telegram->setName(m_NameEdit->text()); - - accept(); -} - -// --------------------------------------------------------------- -void LogViewTelegramDialog::sendCurrentTelegram() -{ - emit sendTelegram(m_Telegram); -} - -// --------------------------------------------------------------- -void LogViewTelegramDialog::showButtons(QLayout *a_layout) -{ - if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral == m_Telegram->getProtocol()) - { - QPushButton *btnSend = new QPushButton(QIcon(QLatin1String(":icons/16x16/mail-send.png")), tr("&Send")); - btnSend->setEnabled(true); // TODO: Status ob wirklich möglich ggf. überprüfen - connect(btnSend, &QPushButton::clicked, this, &LogViewTelegramDialog::sendCurrentTelegram); - a_layout->addWidget(btnSend); - } - - if (m_ReadOnly) - { - QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Schliessen")); - connect(btnClose, &QPushButton::clicked, this, &LogViewTelegramDialog::reject); - a_layout->addWidget(btnClose); - } - else - { - - QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Abbrechen")); - connect(btnClose, &QPushButton::clicked, this, &LogViewTelegramDialog::reject); - a_layout->addWidget(btnClose); - - QPushButton *btnOk = new QPushButton(QIcon(QLatin1String(":icons/16x16/dialog-ok-apply.png")), tr("&OK")); - btnOk->setDefault(true); - // fixme: absturz, wenn feld ungültiger wert enthält und ok gedrückt wird - connect(btnOk, &QPushButton::clicked, this, &LogViewTelegramDialog::saveTelegram); - a_layout->addWidget(btnOk); - } -} - - -// --------------------------------------------------------------- -void LogViewTelegramDialog::showEditField(LogViewField *a_logViewField, QGridLayout *a_box) -{ - // INFO_LOG(m_logger) << a_logViewField->getName() << - // << " a_logViewField->getValueListSize()=" << a_logViewField->getValueListSize() - // << " a_logViewField->isIsDynamicArray()=" << a_logViewField->isIsDynamicArray() - // << " a_logViewField->getValue(0)=" << a_logViewField->getValue(0).toStdString() - // << " a_logViewField->getXdrElement())->getValueKind()=" << (int)(static_cast(a_logViewField->getXdrElement())->getValueKind()) - // ; - switch (a_logViewField->valueListSize()) - { - case 1: - // 1 field (single or multi-line) - if (m_ReadOnly || !a_logViewField->isDynamicArray() || (LogViewXdrStandardType::e_Character == static_cast(a_logViewField->xdrElement())->getValueKind())) - { - QLabel *label = new QLabel(a_logViewField->cleanName()); - a_box->addWidget(label, a_box->rowCount(), 0); - LogViewWidget *valueWidget = nullptr; - //QString value = a_logViewField->getValue(0); - // if (-1 == value.indexOf("
") && value.length() < 80) + if (!a_fieldTree->hasContent()) + child->setHasContent(false); + switch (child->kind()) { - // single line - // ----------- - if (LogViewXdrElement::e_KindEnum == a_logViewField->xdrElement()->getKind()) + case LogViewField::e_FieldKindBorder: { - // enum => combobox - // ---------------- - valueWidget = new LogViewEnumEdit(a_logViewField, this, m_ReadOnly, 0); + QGroupBox *groupBox = new QGroupBox(child->cleanName()); + QGridLayout *actBox = new QGridLayout(groupBox); + a_box->addWidget(groupBox, a_box->rowCount(), 0, 1, 2); + showTree(child, actBox); + break; } - else + case LogViewField::e_FieldKindTab: + showTab(child, a_box); + break; + case LogViewField::e_FieldKindTabChild: { - if (a_logViewField->isDateTimeField() || a_logViewField->isMSecsField()) - { - // date-time-field - // --------------- - valueWidget = new LogViewDateTimeEdit(a_logViewField, this, m_ReadOnly); - } - else - { - switch (static_cast(a_logViewField->xdrElement())->getValueKind()) - { - case LogViewXdrStandardType::e_Boolean: - valueWidget = new LogViewBooleanEdit(a_logViewField, this, m_ReadOnly); - break; - case LogViewXdrStandardType::e_Signed: - case LogViewXdrStandardType::e_Unsigned: - case LogViewXdrStandardType::e_Float: - case LogViewXdrStandardType::e_Data: - valueWidget = new LogViewValueEdit(a_logViewField, this, m_ReadOnly); - break; - case LogViewXdrStandardType::e_Character: // Text - valueWidget = new LogViewTextEdit(a_logViewField, this, m_ReadOnly); - break; - } - } + QWidget *widget = new QWidget; + widget->setContentsMargins(QMargins()); + QGridLayout *actBox = new QGridLayout(widget); + a_box->addWidget(widget, a_box->rowCount(), 0, 1, 2); + showTree(child, actBox); + break; } - if (valueWidget) - m_EditInfoList.push_back(valueWidget); + case LogViewField::e_FieldKindEdit: + case LogViewField::e_FieldKindPodArray: + case LogViewField::e_FieldKindPodArrayChild: + showEditField(child, a_box); + break; } - // else - // { - // // ---------------------------------------------------------------- - // // fixme: not used => take away - // // multi-line - // valueWidget = new QTextEdit(value); - // static_cast(valueWidget)->setReadOnly(true); - // // make proper width of widget - // QFontMetrics fm(valueWidget->font()); - // // the 0 (at end) are here, because QFontMetrics does not understand the and tags. - // // So not the correct font will be used for calculating the width. - // // The solution here is suboptimal, but will hopefully work with a lot of fonts... - // valueWidget->setMinimumWidth(fm.width("0000: 00 00 00 00 00 00 00")*1.7); - // // ---------------------------------------------------------------- - // } - QWidget *w = dynamic_cast(valueWidget); - if (w) - a_box->addWidget(w, a_box->rowCount() - 1, 1); - else - WARNING_LOG(m_logger) << "Internal error - LogViewWidget is not derived from QWidget... !?"; - break; } - // fall through for not read-only and dyn. array - Q_FALLTHROUGH(); - case 0: + } + + + // --------------------------------------------------------------- + void LogViewTelegramDialog::fillTelegram(LogViewTelegram *a_telegram) + { + INFO_LOG(m_logger) << "******************************************"; + + + for (const auto ptr : std::as_const(m_EditInfoList)) + { + if (!ptr->isValid()) + { + INFO_LOG(m_logger) << ptr->field()->name() << " is invalid"; + return; // abort when a value is not vaild + } + } + + // now save the values + // ------------------- + a_telegram->resetOffset(); + a_telegram->clearJsonData(); + for (auto ptr : std::as_const(m_EditInfoList)) + { + if (!ptr->saveContent(a_telegram)) + { + QMessageBox::warning(this, tr("Error while saving telegram"), tr("Found an invalid value - the telegram may be not saved correctly")); + } + } + } + + + // --------------------------------------------------------------- + void LogViewTelegramDialog::saveTelegram() + { + fillTelegram(m_Telegram.data()); + + // save wait-time and name + N_SST::IntegerCalculator calculator; + N_SST::IntegerCalculator::E_Error error; + m_Telegram->setWaitTime(calculator.calc(m_WaitTimeEdit->text().toStdString(), error)); + m_Telegram->setName(m_NameEdit->text()); + + accept(); + } + + // --------------------------------------------------------------- + void LogViewTelegramDialog::sendCurrentTelegram() + { + emit sendTelegram(m_Telegram); + } + + // --------------------------------------------------------------- + void LogViewTelegramDialog::showButtons(QLayout *a_layout) + { + if (N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral == m_Telegram->getProtocol()) + { + QPushButton *btnSend = new QPushButton(QIcon(QLatin1String(":icons/16x16/mail-send.png")), tr("&Send")); + btnSend->setEnabled(true); // TODO: Status ob wirklich möglich ggf. überprüfen + connect(btnSend, &QPushButton::clicked, this, &LogViewTelegramDialog::sendCurrentTelegram); + a_layout->addWidget(btnSend); + } + if (m_ReadOnly) { - // no field - a_box->addWidget(new QLabel(tr("Keine %1").arg(a_logViewField->cleanName()))); + QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Schliessen")); + connect(btnClose, &QPushButton::clicked, this, &LogViewTelegramDialog::reject); + a_layout->addWidget(btnClose); + } + else + { + + QPushButton *btnClose = new QPushButton(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("&Abbrechen")); + connect(btnClose, &QPushButton::clicked, this, &LogViewTelegramDialog::reject); + a_layout->addWidget(btnClose); + + QPushButton *btnOk = new QPushButton(QIcon(QLatin1String(":icons/16x16/dialog-ok-apply.png")), tr("&OK")); + btnOk->setDefault(true); + // fixme: absturz, wenn feld ungültiger wert enthält und ok gedrückt wird + connect(btnOk, &QPushButton::clicked, this, &LogViewTelegramDialog::saveTelegram); + a_layout->addWidget(btnOk); + } + } + + + // --------------------------------------------------------------- + void LogViewTelegramDialog::showEditField(LogViewField *a_logViewField, QGridLayout *a_box) + { + // INFO_LOG(m_logger) << a_logViewField->getName() << + // << " a_logViewField->getValueListSize()=" << a_logViewField->getValueListSize() + // << " a_logViewField->isIsDynamicArray()=" << a_logViewField->isIsDynamicArray() + // << " a_logViewField->getValue(0)=" << a_logViewField->getValue(0).toStdString() + // << " a_logViewField->getXdrElement())->getValueKind()=" << (int)(static_cast(a_logViewField->getXdrElement())->getValueKind()) + // ; + switch (a_logViewField->valueListSize()) + { + case 1: + // 1 field (single or multi-line) + if (m_ReadOnly || !a_logViewField->isDynamicArray() || + (LogViewXdrStandardType::e_Character == static_cast(a_logViewField->xdrElement())->getValueKind())) + { + QLabel *label = new QLabel(a_logViewField->cleanName()); + a_box->addWidget(label, a_box->rowCount(), 0); + LogViewWidget *valueWidget = nullptr; + //QString value = a_logViewField->getValue(0); + // if (-1 == value.indexOf("
") && value.length() < 80) + { + // single line + // ----------- + if (LogViewXdrElement::e_KindEnum == a_logViewField->xdrElement()->getKind()) + { + // enum => combobox + // ---------------- + valueWidget = new LogViewEnumEdit(a_logViewField, this, m_ReadOnly, 0); + } + else + { + if (a_logViewField->isDateTimeField() || a_logViewField->isMSecsField()) + { + // date-time-field + // --------------- + valueWidget = new LogViewDateTimeEdit(a_logViewField, this, m_ReadOnly); + } + else + { + switch (static_cast(a_logViewField->xdrElement())->getValueKind()) + { + case LogViewXdrStandardType::e_Boolean: + valueWidget = new LogViewBooleanEdit(a_logViewField, this, m_ReadOnly); + break; + case LogViewXdrStandardType::e_Signed: + case LogViewXdrStandardType::e_Unsigned: + case LogViewXdrStandardType::e_Float: + case LogViewXdrStandardType::e_Data: + valueWidget = new LogViewValueEdit(a_logViewField, this, m_ReadOnly); + break; + case LogViewXdrStandardType::e_Character: // Text + valueWidget = new LogViewTextEdit(a_logViewField, this, m_ReadOnly); + break; + } + } + } + if (valueWidget) + m_EditInfoList.push_back(valueWidget); + } + // else + // { + // // ---------------------------------------------------------------- + // // fixme: not used => take away + // // multi-line + // valueWidget = new QTextEdit(value); + // static_cast(valueWidget)->setReadOnly(true); + // // make proper width of widget + // QFontMetrics fm(valueWidget->font()); + // // the 0 (at end) are here, because QFontMetrics does not understand the and tags. + // // So not the correct font will be used for calculating the width. + // // The solution here is suboptimal, but will hopefully work with a lot of fonts... + // valueWidget->setMinimumWidth(fm.width("0000: 00 00 00 00 00 00 00")*1.7); + // // ---------------------------------------------------------------- + // } + QWidget *w = dynamic_cast(valueWidget); + if (w) + a_box->addWidget(w, a_box->rowCount() - 1, 1); + else + WARNING_LOG(m_logger) << "Internal error - LogViewWidget is not derived from QWidget... !?"; + break; + } + // fall through for not read-only and dyn. array + Q_FALLTHROUGH(); + case 0: + if (m_ReadOnly) + { + // no field + a_box->addWidget(new QLabel(tr("Keine %1").arg(a_logViewField->cleanName()))); + break; + } + // fall through for not read-only + Q_FALLTHROUGH(); + default: + { + // show the title of table + QLabel *label = new QLabel(a_logViewField->cleanName()); + a_box->addWidget(label, a_box->rowCount(), 0); + + // show the spin-box for changing the dyn. array-size + LogViewSpinBox *spinBox = nullptr; + if (!m_ReadOnly && a_logViewField->isDynamicArray()) + { + spinBox = new LogViewSpinBox(a_logViewField, this, a_logViewField->valueListSize()); + a_box->addWidget(spinBox, a_box->rowCount() - 1, 1); + } + + + LogViewTableWidget *tableWidget = new LogViewTableWidget(a_logViewField, this, m_ReadOnly, m_logger); + m_EditInfoList.push_back(tableWidget); + a_box->addWidget(tableWidget, a_box->rowCount(), 0, 1, 2); + + // connect signals + if (spinBox) + { + connect(spinBox, &LogViewSpinBox::valueEditingFinished, tableWidget, &LogViewTableWidget::changeSize); + } + } break; } - // fall through for not read-only - Q_FALLTHROUGH(); - default: - { - // show the title of table - QLabel *label = new QLabel(a_logViewField->cleanName()); - a_box->addWidget(label, a_box->rowCount(), 0); + } - // show the spin-box for changing the dyn. array-size + + // --------------------------------------------------------------- + void LogViewTelegramDialog::showTab(LogViewField *a_logViewField, QGridLayout *a_box) + { LogViewSpinBox *spinBox = nullptr; if (!m_ReadOnly && a_logViewField->isDynamicArray()) { - spinBox = new LogViewSpinBox(a_logViewField, this, a_logViewField->valueListSize()); + // show the spin-box for changing the dyn. array-size + QLabel *label = new QLabel(a_logViewField->cleanName()); + a_box->addWidget(label, a_box->rowCount(), 0); + spinBox = new LogViewSpinBox(a_logViewField, this, 0); a_box->addWidget(spinBox, a_box->rowCount() - 1, 1); } - - LogViewTableWidget *tableWidget = new LogViewTableWidget(a_logViewField, this, m_ReadOnly, m_logger); - m_EditInfoList.push_back(tableWidget); - a_box->addWidget(tableWidget, a_box->rowCount(), 0, 1, 2); + LogViewTabWidget *a_tabWidget = new LogViewTabWidget(a_logViewField, this, spinBox, m_logger); + m_EditInfoList.push_back(dynamic_cast(a_tabWidget)); + a_box->addWidget(a_tabWidget, a_box->rowCount(), 0, 1, 2); // connect signals if (spinBox) { - connect(spinBox, &LogViewSpinBox::valueEditingFinished, - tableWidget, &LogViewTableWidget::changeSize); + connect(spinBox, &LogViewSpinBox::valueEditingFinished, a_tabWidget, &LogViewTabWidget::changeSize); } - } - break; - } -} - -// --------------------------------------------------------------- -void LogViewTelegramDialog::showTab(LogViewField *a_logViewField, QGridLayout *a_box) -{ - LogViewSpinBox *spinBox = nullptr; - if (!m_ReadOnly && a_logViewField->isDynamicArray()) - { - // show the spin-box for changing the dyn. array-size - QLabel *label = new QLabel(a_logViewField->cleanName()); - a_box->addWidget(label, a_box->rowCount(), 0); - spinBox = new LogViewSpinBox(a_logViewField, this, 0); - a_box->addWidget(spinBox, a_box->rowCount() - 1, 1); - } - - LogViewTabWidget *a_tabWidget = new LogViewTabWidget(a_logViewField, this, spinBox, m_logger); - m_EditInfoList.push_back(dynamic_cast(a_tabWidget)); - a_box->addWidget(a_tabWidget, a_box->rowCount(), 0, 1, 2); - - // connect signals - if (spinBox) - { - connect(spinBox, &LogViewSpinBox::valueEditingFinished, - a_tabWidget, &LogViewTabWidget::changeSize); - } - - // add the tab - if (a_logViewField->hasContent()) - { - for (int i = 0; i < a_logViewField->childCount(); ++i) - a_tabWidget->addTab(a_logViewField, false, i); - } -} - -// --------------------------------------------------------------- -bool LogViewTelegramDialog::removeItemsFromEditInfoList(const QStringList &jsonPath) -{ - if (m_EditInfoList.empty()) - return false; - for (int i = m_EditInfoList.size() - 1; i >= 0; --i) - { - LogViewWidget *lvw = m_EditInfoList.at(i); - const QStringList jsonPathChild = lvw->field()->jsonPath(); - if (jsonPathChild.size() < jsonPath.size()) - continue; - bool bIsChild = true; - for (int j = 0; j < jsonPath.size(); ++j) + // add the tab + if (a_logViewField->hasContent()) { - if (jsonPath.at(j) != jsonPathChild.at(j)) - { - bIsChild = false; - break; - } + for (int i = 0; i < a_logViewField->childCount(); ++i) + a_tabWidget->addTab(a_logViewField, false, i); } - if (!bIsChild) - continue; - delete m_EditInfoList.at(i); - m_EditInfoList.removeAt(i); } - m_EditInfoList.resize(m_EditInfoList.size() - 1); - return true; -} + + // --------------------------------------------------------------- + bool LogViewTelegramDialog::removeItemsFromEditInfoList(const QStringList &jsonPath) + { + if (m_EditInfoList.empty()) + return false; + for (int i = m_EditInfoList.size() - 1; i >= 0; --i) + { + LogViewWidget *lvw = m_EditInfoList.at(i); + const QStringList jsonPathChild = lvw->field()->jsonPath(); + if (jsonPathChild.size() < jsonPath.size()) + continue; + bool bIsChild = true; + for (int j = 0; j < jsonPath.size(); ++j) + { + if (jsonPath.at(j) != jsonPathChild.at(j)) + { + bIsChild = false; + break; + } + } + if (!bIsChild) + continue; + delete m_EditInfoList.at(i); + m_EditInfoList.removeAt(i); + } + m_EditInfoList.resize(m_EditInfoList.size() - 1); + return true; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.hpp index c87372698..df5658006 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramDialog.hpp @@ -25,55 +25,54 @@ class QLineEdit; namespace N_LogView { -class LogViewWidget; -class LogViewTelegram; -class LogViewField; + class LogViewWidget; + class LogViewTelegram; + class LogViewField; -/** + /** * @author alois.wismer * @version 1.0 * @created 09-Feb-2010 15:05:05 */ -class LogViewTelegramDialog : public QDialog -{ - Q_OBJECT -public: - explicit LogViewTelegramDialog(QWidget *a_parent = nullptr, const bool a_readonly = true, NGL::INGLLogger& logger = N_LogView::getLogger("LogViewTelegramDialog")); + class LogViewTelegramDialog : public QDialog + { + Q_OBJECT + public: + explicit LogViewTelegramDialog(QWidget *a_parent = nullptr, const bool a_readonly = true, NGL::INGLLogger &logger = N_LogView::getLogger("LogViewTelegramDialog")); - void showDialog(const QSharedPointer &a_telegram); - void showDataDump(const QSharedPointer &a_telegram, bool showErrorMessage); - void makePretty(); - void showTree(LogViewField *a_fieldTree, QGridLayout *a_box); + void showDialog(const QSharedPointer &a_telegram); + void showDataDump(const QSharedPointer &a_telegram, bool showErrorMessage); + void makePretty(); + void showTree(LogViewField *a_fieldTree, QGridLayout *a_box); - /** + /** * Removes the elements from m_EditInfoList matching the path */ - bool removeItemsFromEditInfoList(const QStringList &jsonPath); + bool removeItemsFromEditInfoList(const QStringList &jsonPath); -Q_SIGNALS: - void sendTelegram(const QSharedPointer &telegramToSend); -protected slots: - void saveTelegram(); + Q_SIGNALS: + void sendTelegram(const QSharedPointer &telegramToSend); + protected slots: + void saveTelegram(); - void sendCurrentTelegram(); + void sendCurrentTelegram(); -protected: + protected: + void fillTelegram(LogViewTelegram *a_telegram); + void showButtons(QLayout *a_layout); + void showEditField(LogViewField *a_logViewField, QGridLayout *a_box); + void showTab(LogViewField *a_logViewField, QGridLayout *a_box); - void fillTelegram(LogViewTelegram *a_telegram); - void showButtons(QLayout *a_layout); - void showEditField(LogViewField *a_logViewField, QGridLayout *a_box); - void showTab(LogViewField *a_logViewField, QGridLayout *a_box); - -private: - QSharedPointer m_Telegram; - QVector m_EditInfoList; - QScopedPointer m_fieldTree; - QWidget *m_contentsWidget = nullptr; - QScrollArea *m_ScrollArea = nullptr; - QLineEdit *m_NameEdit = nullptr; - QLineEdit *m_WaitTimeEdit = nullptr; - bool m_ReadOnly = false; - NGL::INGLLogger& m_logger; -}; + private: + QSharedPointer m_Telegram; + QVector m_EditInfoList; + QScopedPointer m_fieldTree; + QWidget *m_contentsWidget = nullptr; + QScrollArea *m_ScrollArea = nullptr; + QLineEdit *m_NameEdit = nullptr; + QLineEdit *m_WaitTimeEdit = nullptr; + bool m_ReadOnly = false; + NGL::INGLLogger &m_logger; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.cpp index 0ed763c7e..d9c0d4674 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.cpp @@ -29,563 +29,547 @@ namespace N_LogView { -QString TelegramEdit::s_DIR() -{ - return QStringLiteral("Dir"); -} -QString TelegramEdit::s_EDIT_TELEGRAM_GROUP() -{ - return QStringLiteral("EditTelegrams"); -} -QString TelegramEdit::s_TELEGRAMLIST_FILE_ID() -{ - return QStringLiteral("RDETGL"); -} -QString TelegramEdit::s_TELEGRAMLIST_FILES() -{ - return tr("Telegrammliste-Dateien (*.tgl);;Alle Dateien (*)"); -} - -TelegramEdit::TelegramEdit(QWidget *parent) - : QObject(parent) - , m_addTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/list-add.png")), tr("Add Telegram"), this)) - , m_editTeleAction(new QAction(QIcon(QLatin1String(":/image/Edit.png")), tr("Edit Telegram"), this)) - , m_copyTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy Telegram"), this)) - , m_pasteTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste Telegram"), this)) - , m_deleteTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/list-remove.png")), tr("Delete Telegram"), this)) - , m_moveTeleUpAction(new QAction(QIcon(QLatin1String(":icons/16x16/go-up.png")), tr("Move up"), this)) - , m_moveTeleDownAction(new QAction(QIcon(QLatin1String(":icons/16x16/go-down.png")), tr("Move down"), this)) - , m_teleListLoad(new QAction(QIcon(QLatin1String(":icons/16x16/document-open-data.png")), tr("Load Telegram list"), this)) - , m_teleListAppend(new QAction(QIcon(), tr("Telegrammliste anhaengen"), this)) - , m_teleListSave(new QAction(QIcon(QLatin1String(":icons/16x16/document-save.png")), tr("Save Telegram list"), this)) - , m_tableView(new QTableView(parent)) - , m_DoLoop(false) - , m_InjectionThread(nullptr) - , m_EditModel(new TelegramEditModel(this)) - , m_logger(getLogger("LogViewTelegramEdit")) -{ - m_addTeleAction->setShortcut(tr("Ctrl+A")); - m_editTeleAction->setShortcut(tr("Ctrl+E")); - m_copyTeleAction->setShortcut(tr("Ctrl+C")); - m_pasteTeleAction->setShortcut(tr("Ctrl+V")); - m_deleteTeleAction->setShortcut(Qt::Key_Delete); - m_moveTeleUpAction->setShortcut(tr("Ctrl+U")); - m_moveTeleDownAction->setShortcut(tr("Ctrl+D")); - m_teleListLoad->setShortcut(tr("Ctrl+L")); - m_teleListAppend->setShortcut(tr("Ctrl+K")); - m_teleListSave->setShortcut(tr("Ctrl+S")); - m_addTeleAction->setEnabled(true); - m_copyTeleAction->setEnabled(false); - m_pasteTeleAction->setEnabled(false); - m_deleteTeleAction->setEnabled(false); - m_moveTeleUpAction->setEnabled(false); - m_moveTeleDownAction->setEnabled(false); - m_teleListLoad->setEnabled(true); - m_teleListAppend->setEnabled(true); - m_teleListSave->setEnabled(false); - - connect(m_addTeleAction, &QAction::triggered, this, &TelegramEdit::addTelegram); - connect(m_editTeleAction, &QAction::triggered, this, &TelegramEdit::editTelegram); - connect(m_copyTeleAction, &QAction::triggered, this, &TelegramEdit::copy); - connect(m_pasteTeleAction, &QAction::triggered, this, &TelegramEdit::paste); - connect(m_deleteTeleAction, &QAction::triggered, this, &TelegramEdit::deleteTelegram); - connect(m_moveTeleUpAction, &QAction::triggered, this, &TelegramEdit::moveUp); - connect(m_moveTeleDownAction, &QAction::triggered, this, &TelegramEdit::moveDown); - connect(m_teleListLoad, &QAction::triggered, this, &TelegramEdit::loadTelegramListReplace); - connect(m_teleListAppend, &QAction::triggered, this, &TelegramEdit::loadTelegramListAppend); - connect(m_teleListSave, &QAction::triggered, this, &TelegramEdit::saveTelegramList); - - m_tableView->setModel(m_EditModel); - m_tableView->verticalHeader()->hide(); - m_tableView->setContextMenuPolicy(Qt::CustomContextMenu); - m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - m_tableView->setSelectionMode(QAbstractItemView::SingleSelection); - connect(m_tableView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &TelegramEdit::onSelectionChanged); - connect(m_tableView, &QTableView::doubleClicked, - this, &TelegramEdit::editTelegram); - connect(m_tableView, &QTableView::customContextMenuRequested, - this, &TelegramEdit::tableViewCustomContextMenu); - m_tableView->addAction(m_addTeleAction); - m_tableView->addAction(m_editTeleAction); - m_tableView->addAction(m_copyTeleAction); - m_tableView->addAction(m_pasteTeleAction); - m_tableView->addAction(m_deleteTeleAction); - m_tableView->addAction(m_moveTeleUpAction); - m_tableView->addAction(m_moveTeleDownAction); -} - -void TelegramEdit::setInjectionThread(LogViewInjectionThread *a_injectionThread) -{ - m_InjectionThread = a_injectionThread; -} - -void TelegramEdit::appendTelegram(const QSharedPointer &telegram) -{ - m_EditModel->appendTelegram(telegram); - m_teleListSave->setEnabled(true); -} - -void TelegramEdit::tableViewCustomContextMenu(const QPoint &pos) -{ - QMenu menu; - - // add, edit and remove telegrams - // ------------------------------ - menu.addAction(m_addTeleAction); - menu.addAction(m_editTeleAction); - menu.addAction(m_copyTeleAction); - menu.addAction(m_pasteTeleAction); - menu.addAction(m_deleteTeleAction); - - // move telegram up/down - // --------------------- - menu.addSeparator(); - menu.addAction(m_moveTeleUpAction); - menu.addAction(m_moveTeleDownAction); - - menu.addSeparator(); - - const bool itemSelected = m_tableView->currentIndex().isValid(); - // is it a central-telegram? - bool isCentral = false; - QSharedPointer tele = m_EditModel->telegram(m_tableView->currentIndex().row()); - if (tele) - isCentral = (tele->getProtocol() == N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral); - - // inject telegram - // --------------- - if (isInjectionPossible()) + QString TelegramEdit::s_DIR() { - QAction *action = menu.addAction(QIcon(QLatin1String(":/image/InjectCentral.png")), tr("Injektiere Zentral-Telegramm")); - // only central-telegrams can be injected - action->setEnabled(itemSelected && isCentral); - connect(action, &QAction::triggered, this, &TelegramEdit::injectCentralTelegram); - - action = menu.addAction(QIcon(QLatin1String(":/image/InjectTetra.png")), tr("Injektiere Tetra-Telegramm")); - // only central-telegrams can be injected - action->setEnabled(itemSelected && isCentral); - connect(action, &QAction::triggered, this, &TelegramEdit::injectTetraTelegram); - - menu.addSeparator(); - - // send and loop telegrams - // ----------------------- - action = menu.addAction(QIcon(QLatin1String(":icons/16x16/mail-send.png")), tr("Sende Telegramm")); - // only central-telegrams can be sent - action->setEnabled(itemSelected && isCentral); - connect(action, &QAction::triggered, this, &TelegramEdit::sendCurrentTelegram); - - if (m_DoLoop) - action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-playback-stop.png")), tr("Stop Loopen")); - else - { - action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-playback-start.png")), tr("Loop Telegramme")); - action->setEnabled(itemSelected); - } - connect(action, &QAction::triggered, this, &TelegramEdit::loopTelegrams); - - action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-play-normal.png")), tr("Sende Sequenz")); - action->setEnabled(itemSelected); - connect(action, &QAction::triggered, this, &TelegramEdit::sequenceTelegrams); - - // load/save telegram-list - // ----------------------- - menu.addSeparator(); + return QStringLiteral("Dir"); + } + QString TelegramEdit::s_EDIT_TELEGRAM_GROUP() + { + return QStringLiteral("EditTelegrams"); + } + QString TelegramEdit::s_TELEGRAMLIST_FILE_ID() + { + return QStringLiteral("RDETGL"); + } + QString TelegramEdit::s_TELEGRAMLIST_FILES() + { + return tr("Telegrammliste-Dateien (*.tgl);;Alle Dateien (*)"); } - menu.addAction(m_teleListLoad); - menu.addAction(m_teleListAppend); - menu.addAction(m_teleListSave); - - menu.exec(m_tableView->viewport()->mapToGlobal(pos)); -} - -// --------------------------------------------------------------- -// Adds a_telegram at a_row in table. If there is already a -// telegram it will be overwritten. -// If a_row is -1, the telegram will be added at end. -// If false is false, a_telegram will be ignored, a -// dialog for selecting an empty telegram will be shown -// instead. -// --------------------------------------------------------------- -void TelegramEdit::addTelegram() -{ - // add telegram for editing - LogViewTelegramSelectionDialog telegramSelectionDialog(m_tableView); - if (QDialog::Accepted == telegramSelectionDialog.exec()) + TelegramEdit::TelegramEdit(QWidget *parent) + : QObject(parent) + , m_addTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/list-add.png")), tr("Add Telegram"), this)) + , m_editTeleAction(new QAction(QIcon(QLatin1String(":/image/Edit.png")), tr("Edit Telegram"), this)) + , m_copyTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy Telegram"), this)) + , m_pasteTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste Telegram"), this)) + , m_deleteTeleAction(new QAction(QIcon(QLatin1String(":icons/16x16/list-remove.png")), tr("Delete Telegram"), this)) + , m_moveTeleUpAction(new QAction(QIcon(QLatin1String(":icons/16x16/go-up.png")), tr("Move up"), this)) + , m_moveTeleDownAction(new QAction(QIcon(QLatin1String(":icons/16x16/go-down.png")), tr("Move down"), this)) + , m_teleListLoad(new QAction(QIcon(QLatin1String(":icons/16x16/document-open-data.png")), tr("Load Telegram list"), this)) + , m_teleListAppend(new QAction(QIcon(), tr("Telegrammliste anhaengen"), this)) + , m_teleListSave(new QAction(QIcon(QLatin1String(":icons/16x16/document-save.png")), tr("Save Telegram list"), this)) + , m_tableView(new QTableView(parent)) + , m_DoLoop(false) + , m_InjectionThread(nullptr) + , m_EditModel(new TelegramEditModel(this)) + , m_logger(getLogger("LogViewTelegramEdit")) { - QSharedPointer newTelegram = QSharedPointer(new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, - telegramSelectionDialog.getSelectedTelegramId())); - m_curEditTelegramRow = m_EditModel->appendTelegram(newTelegram); + m_addTeleAction->setShortcut(tr("Ctrl+A")); + m_editTeleAction->setShortcut(tr("Ctrl+E")); + m_copyTeleAction->setShortcut(tr("Ctrl+C")); + m_pasteTeleAction->setShortcut(tr("Ctrl+V")); + m_deleteTeleAction->setShortcut(Qt::Key_Delete); + m_moveTeleUpAction->setShortcut(tr("Ctrl+U")); + m_moveTeleDownAction->setShortcut(tr("Ctrl+D")); + m_teleListLoad->setShortcut(tr("Ctrl+L")); + m_teleListAppend->setShortcut(tr("Ctrl+K")); + m_teleListSave->setShortcut(tr("Ctrl+S")); + m_addTeleAction->setEnabled(true); + m_copyTeleAction->setEnabled(false); + m_pasteTeleAction->setEnabled(false); + m_deleteTeleAction->setEnabled(false); + m_moveTeleUpAction->setEnabled(false); + m_moveTeleDownAction->setEnabled(false); + m_teleListLoad->setEnabled(true); + m_teleListAppend->setEnabled(true); + m_teleListSave->setEnabled(false); - // show the edit-telegram-dialog - LogViewTelegramDialog *editTelegramDialog = new LogViewTelegramDialog(m_tableView, false); - connect(editTelegramDialog, &LogViewTelegramDialog::finished, - this, &TelegramEdit::editTelegramDialogFinished); - connect(editTelegramDialog, &LogViewTelegramDialog::sendTelegram, - this, &TelegramEdit::sendTelegram); - editTelegramDialog->showDialog(newTelegram); + connect(m_addTeleAction, &QAction::triggered, this, &TelegramEdit::addTelegram); + connect(m_editTeleAction, &QAction::triggered, this, &TelegramEdit::editTelegram); + connect(m_copyTeleAction, &QAction::triggered, this, &TelegramEdit::copy); + connect(m_pasteTeleAction, &QAction::triggered, this, &TelegramEdit::paste); + connect(m_deleteTeleAction, &QAction::triggered, this, &TelegramEdit::deleteTelegram); + connect(m_moveTeleUpAction, &QAction::triggered, this, &TelegramEdit::moveUp); + connect(m_moveTeleDownAction, &QAction::triggered, this, &TelegramEdit::moveDown); + connect(m_teleListLoad, &QAction::triggered, this, &TelegramEdit::loadTelegramListReplace); + connect(m_teleListAppend, &QAction::triggered, this, &TelegramEdit::loadTelegramListAppend); + connect(m_teleListSave, &QAction::triggered, this, &TelegramEdit::saveTelegramList); + m_tableView->setModel(m_EditModel); + m_tableView->verticalHeader()->hide(); + m_tableView->setContextMenuPolicy(Qt::CustomContextMenu); + m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableView->setSelectionMode(QAbstractItemView::SingleSelection); + connect(m_tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &TelegramEdit::onSelectionChanged); + connect(m_tableView, &QTableView::doubleClicked, this, &TelegramEdit::editTelegram); + connect(m_tableView, &QTableView::customContextMenuRequested, this, &TelegramEdit::tableViewCustomContextMenu); + m_tableView->addAction(m_addTeleAction); + m_tableView->addAction(m_editTeleAction); + m_tableView->addAction(m_copyTeleAction); + m_tableView->addAction(m_pasteTeleAction); + m_tableView->addAction(m_deleteTeleAction); + m_tableView->addAction(m_moveTeleUpAction); + m_tableView->addAction(m_moveTeleDownAction); + } + + void TelegramEdit::setInjectionThread(LogViewInjectionThread *a_injectionThread) + { + m_InjectionThread = a_injectionThread; + } + + void TelegramEdit::appendTelegram(const QSharedPointer &telegram) + { + m_EditModel->appendTelegram(telegram); m_teleListSave->setEnabled(true); } -} -QSharedPointer TelegramEdit::currentSelectedTelegram() const -{ - return m_EditModel->telegram(currentSelectedIndex().row()); -} - -QModelIndex TelegramEdit::currentSelectedIndex() const -{ - return m_tableView->currentIndex(); -} - -void TelegramEdit::editTelegramDialogFinished() -{ - //model über geänderte Daten informieren - m_EditModel->emitDataChanged(m_curEditTelegramRow); -} - -// --------------------------------------------------------------- -// shows a telegram-dialog, where the telegram can be changed. -// --------------------------------------------------------------- -void TelegramEdit::editTelegram() -{ - m_curEditTelegramRow = currentSelectedIndex().row(); - if (m_curEditTelegramRow < 0) - return; - LogViewTelegramDialog *editTelegramDialog = new LogViewTelegramDialog(m_tableView, false); - connect(editTelegramDialog, &LogViewTelegramDialog::finished, this, &TelegramEdit::editTelegramDialogFinished); - editTelegramDialog->showDialog(currentSelectedTelegram()); -} - -// --------------------------------------------------------------- -// shows a non-editable telegram-dialog -// --------------------------------------------------------------- -void TelegramEdit::showTelegram() -{ - LogViewTelegramDialog *showTelegramDialog = new LogViewTelegramDialog(m_tableView, true); - showTelegramDialog->showDialog(currentSelectedTelegram()); -// -// qulonglong dataPtr = m_TelegramTableWidget->item(a_tableWidget->row(), 0)->data(Qt::UserRole).toULongLong(); -// LogViewTelegram* telegram = (LogViewTelegram*)dataPtr; -// LogViewTelegramDialog* telegramDialog = new LogViewTelegramDialog(this); -// telegramDialog->showDialog(telegram); -} - -void TelegramEdit::deleteTelegram() -{ - const QModelIndexList indexList = m_tableView->selectionModel()->selectedIndexes(); - QSet rows; - rows.reserve(indexList.size()); - for (const QModelIndex &index : indexList) - rows += index.row(); - - m_EditModel->removeTelegrams(rows); - m_teleListSave->setEnabled(m_EditModel->rowCount() > 0); -} - -void TelegramEdit::injectCentralTelegram() -{ - injectTelegram(true); -} - -void TelegramEdit::injectTetraTelegram() -{ - injectTelegram(false); -} - -void TelegramEdit::injectTelegram(bool a_bAsCentralTelegram) -{ - injectTelegram(currentSelectedTelegram(), a_bAsCentralTelegram); -} - -void TelegramEdit::injectTelegram(const QSharedPointer &a_telegram, bool a_bAsCentralTelegram) -{ - if (!isInjectionPossible()) + void TelegramEdit::tableViewCustomContextMenu(const QPoint &pos) { - WARNING_LOG(m_logger) << "Try to inject a telegramm but the injection thread is not running"; - return; + QMenu menu; + + // add, edit and remove telegrams + // ------------------------------ + menu.addAction(m_addTeleAction); + menu.addAction(m_editTeleAction); + menu.addAction(m_copyTeleAction); + menu.addAction(m_pasteTeleAction); + menu.addAction(m_deleteTeleAction); + + // move telegram up/down + // --------------------- + menu.addSeparator(); + menu.addAction(m_moveTeleUpAction); + menu.addAction(m_moveTeleDownAction); + + menu.addSeparator(); + + const bool itemSelected = m_tableView->currentIndex().isValid(); + // is it a central-telegram? + bool isCentral = false; + QSharedPointer tele = m_EditModel->telegram(m_tableView->currentIndex().row()); + if (tele) + isCentral = (tele->getProtocol() == N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral); + + // inject telegram + // --------------- + if (isInjectionPossible()) + { + QAction *action = menu.addAction(QIcon(QLatin1String(":/image/InjectCentral.png")), tr("Injektiere Zentral-Telegramm")); + // only central-telegrams can be injected + action->setEnabled(itemSelected && isCentral); + connect(action, &QAction::triggered, this, &TelegramEdit::injectCentralTelegram); + + action = menu.addAction(QIcon(QLatin1String(":/image/InjectTetra.png")), tr("Injektiere Tetra-Telegramm")); + // only central-telegrams can be injected + action->setEnabled(itemSelected && isCentral); + connect(action, &QAction::triggered, this, &TelegramEdit::injectTetraTelegram); + + menu.addSeparator(); + + // send and loop telegrams + // ----------------------- + action = menu.addAction(QIcon(QLatin1String(":icons/16x16/mail-send.png")), tr("Sende Telegramm")); + // only central-telegrams can be sent + action->setEnabled(itemSelected && isCentral); + connect(action, &QAction::triggered, this, &TelegramEdit::sendCurrentTelegram); + + if (m_DoLoop) + action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-playback-stop.png")), tr("Stop Loopen")); + else + { + action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-playback-start.png")), tr("Loop Telegramme")); + action->setEnabled(itemSelected); + } + connect(action, &QAction::triggered, this, &TelegramEdit::loopTelegrams); + + action = menu.addAction(QIcon(QLatin1String(":icons/16x16/media-play-normal.png")), tr("Sende Sequenz")); + action->setEnabled(itemSelected); + connect(action, &QAction::triggered, this, &TelegramEdit::sequenceTelegrams); + + // load/save telegram-list + // ----------------------- + menu.addSeparator(); + } + + menu.addAction(m_teleListLoad); + menu.addAction(m_teleListAppend); + menu.addAction(m_teleListSave); + + menu.exec(m_tableView->viewport()->mapToGlobal(pos)); } - if (a_telegram.isNull()) + + // --------------------------------------------------------------- + // Adds a_telegram at a_row in table. If there is already a + // telegram it will be overwritten. + // If a_row is -1, the telegram will be added at end. + // If false is false, a_telegram will be ignored, a + // dialog for selecting an empty telegram will be shown + // instead. + // --------------------------------------------------------------- + void TelegramEdit::addTelegram() { - WARNING_LOG(m_logger) << "Try to inject a telegramm but no telegramm selected"; - return; + // add telegram for editing + LogViewTelegramSelectionDialog telegramSelectionDialog(m_tableView); + if (QDialog::Accepted == telegramSelectionDialog.exec()) + { + QSharedPointer newTelegram = + QSharedPointer(new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, telegramSelectionDialog.getSelectedTelegramId())); + m_curEditTelegramRow = m_EditModel->appendTelegram(newTelegram); + + // show the edit-telegram-dialog + LogViewTelegramDialog *editTelegramDialog = new LogViewTelegramDialog(m_tableView, false); + connect(editTelegramDialog, &LogViewTelegramDialog::finished, this, &TelegramEdit::editTelegramDialogFinished); + connect(editTelegramDialog, &LogViewTelegramDialog::sendTelegram, this, &TelegramEdit::sendTelegram); + editTelegramDialog->showDialog(newTelegram); + + m_teleListSave->setEnabled(true); + } } - a_telegram->actualizeGpsTime(); - m_InjectionThread->sendTelegram(a_telegram.data(), a_bAsCentralTelegram); -} -void TelegramEdit::sendCurrentTelegram() -{ - sendTelegram(currentSelectedTelegram()); -} - -void TelegramEdit::sendTelegram(const QSharedPointer &a_telegram) -{ - injectTelegram(a_telegram, true); -} - -void TelegramEdit::loopTelegrams() -{ - //gucken ob loop schon gestartet oder nicht - if (m_DoLoop) + QSharedPointer TelegramEdit::currentSelectedTelegram() const { - m_DoLoop = false; - m_deleteTeleAction->setEnabled(m_tableView->currentIndex().isValid()); + return m_EditModel->telegram(currentSelectedIndex().row()); } - else + + QModelIndex TelegramEdit::currentSelectedIndex() const { - m_DoLoop = true; - m_deleteTeleAction->setEnabled(false); - m_currentRowToSend = currentSelectedIndex().row(); - if (m_currentRowToSend < 0) + return m_tableView->currentIndex(); + } + + void TelegramEdit::editTelegramDialogFinished() + { + //model über geänderte Daten informieren + m_EditModel->emitDataChanged(m_curEditTelegramRow); + } + + // --------------------------------------------------------------- + // shows a telegram-dialog, where the telegram can be changed. + // --------------------------------------------------------------- + void TelegramEdit::editTelegram() + { + m_curEditTelegramRow = currentSelectedIndex().row(); + if (m_curEditTelegramRow < 0) return; - QSharedPointer tele = currentSelectedTelegram(); + LogViewTelegramDialog *editTelegramDialog = new LogViewTelegramDialog(m_tableView, false); + connect(editTelegramDialog, &LogViewTelegramDialog::finished, this, &TelegramEdit::editTelegramDialogFinished); + editTelegramDialog->showDialog(currentSelectedTelegram()); + } + + // --------------------------------------------------------------- + // shows a non-editable telegram-dialog + // --------------------------------------------------------------- + void TelegramEdit::showTelegram() + { + LogViewTelegramDialog *showTelegramDialog = new LogViewTelegramDialog(m_tableView, true); + showTelegramDialog->showDialog(currentSelectedTelegram()); + // + // qulonglong dataPtr = m_TelegramTableWidget->item(a_tableWidget->row(), 0)->data(Qt::UserRole).toULongLong(); + // LogViewTelegram* telegram = (LogViewTelegram*)dataPtr; + // LogViewTelegramDialog* telegramDialog = new LogViewTelegramDialog(this); + // telegramDialog->showDialog(telegram); + } + + void TelegramEdit::deleteTelegram() + { + const QModelIndexList indexList = m_tableView->selectionModel()->selectedIndexes(); + QSet rows; + rows.reserve(indexList.size()); + for (const QModelIndex &index : indexList) + rows += index.row(); + + m_EditModel->removeTelegrams(rows); + m_teleListSave->setEnabled(m_EditModel->rowCount() > 0); + } + + void TelegramEdit::injectCentralTelegram() + { + injectTelegram(true); + } + + void TelegramEdit::injectTetraTelegram() + { + injectTelegram(false); + } + + void TelegramEdit::injectTelegram(bool a_bAsCentralTelegram) + { + injectTelegram(currentSelectedTelegram(), a_bAsCentralTelegram); + } + + void TelegramEdit::injectTelegram(const QSharedPointer &a_telegram, bool a_bAsCentralTelegram) + { + if (!isInjectionPossible()) + { + WARNING_LOG(m_logger) << "Try to inject a telegramm but the injection thread is not running"; + return; + } + if (a_telegram.isNull()) + { + WARNING_LOG(m_logger) << "Try to inject a telegramm but no telegramm selected"; + return; + } + a_telegram->actualizeGpsTime(); + m_InjectionThread->sendTelegram(a_telegram.data(), a_bAsCentralTelegram); + } + + void TelegramEdit::sendCurrentTelegram() + { + sendTelegram(currentSelectedTelegram()); + } + + void TelegramEdit::sendTelegram(const QSharedPointer &a_telegram) + { + injectTelegram(a_telegram, true); + } + + void TelegramEdit::loopTelegrams() + { + //gucken ob loop schon gestartet oder nicht + if (m_DoLoop) + { + m_DoLoop = false; + m_deleteTeleAction->setEnabled(m_tableView->currentIndex().isValid()); + } + else + { + m_DoLoop = true; + m_deleteTeleAction->setEnabled(false); + m_currentRowToSend = currentSelectedIndex().row(); + if (m_currentRowToSend < 0) + return; + QSharedPointer tele = currentSelectedTelegram(); + sendTelegram(tele); + QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::loopNextTelegram); + } + } + + void TelegramEdit::loopNextTelegram() + { + if (!m_DoLoop) + return; + ++m_currentRowToSend; + // am Ende ? + if (m_currentRowToSend >= m_tableView->model()->rowCount()) + m_currentRowToSend = 0; + + QSharedPointer tele = telegramAtRow(m_currentRowToSend); + if (!tele) + return; + sendTelegram(tele); QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::loopNextTelegram); } -} -void TelegramEdit::loopNextTelegram() -{ - if (!m_DoLoop) - return; - ++m_currentRowToSend; - // am Ende ? - if (m_currentRowToSend >= m_tableView->model()->rowCount()) - m_currentRowToSend = 0; - - QSharedPointer tele = telegramAtRow(m_currentRowToSend); - if (!tele) - return; - - sendTelegram(tele); - QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::loopNextTelegram); -} - -void TelegramEdit::sequenceTelegrams() -{ - m_currentRowToSend = currentSelectedIndex().row(); - if (m_currentRowToSend < 0) // invalid index - return; - QSharedPointer tele = currentSelectedTelegram(); - sendTelegram(tele); - QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::sequenceNextTelegram); -} - -void TelegramEdit::sequenceNextTelegram() -{ - ++m_currentRowToSend; - if (m_currentRowToSend >= m_tableView->model()->rowCount()) - return; - - QSharedPointer tele = telegramAtRow(m_currentRowToSend); - if (!tele) - return; - - sendTelegram(tele); - QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::sequenceNextTelegram); -} - -QSharedPointer TelegramEdit::telegramAtRow(int row) -{ - return m_EditModel->telegram(row); -} - -void TelegramEdit::copy() -{ - m_copyTelegram = currentSelectedTelegram(); - m_pasteTeleAction->setEnabled(m_copyTelegram != nullptr); - if (!m_copyTelegram) - return; - m_copyTelegram = QSharedPointer(new LogViewTelegram(*m_copyTelegram.data())); -} - -void TelegramEdit::paste() -{ - if (!m_copyTelegram) - return; - int row = currentSelectedIndex().row() + 1; - m_EditModel->pasteRows(row, m_copyTelegram); -} - -void TelegramEdit::moveUp() -{ - const QModelIndex idx = currentSelectedIndex(); - if (m_EditModel->moveUp(idx.row())) + void TelegramEdit::sequenceTelegrams() { - m_tableView->clearSelection(); - m_tableView->setCurrentIndex(m_EditModel->index(idx.row() - 1, idx.column(), idx.parent())); - m_moveTeleUpAction->setEnabled(idx.row() > 1); - m_moveTeleDownAction->setEnabled(true); - } -} - -void TelegramEdit::moveDown() -{ - const QModelIndex idx = currentSelectedIndex(); - if (m_EditModel->moveDown(idx.row())) - { - m_tableView->clearSelection(); - m_tableView->setCurrentIndex(m_EditModel->index(idx.row() + 1, idx.column(), idx.parent())); - m_moveTeleUpAction->setEnabled(true); - m_moveTeleDownAction->setEnabled(idx.row() < m_EditModel->rowCount() - 2); - } -} - -void TelegramEdit::saveTelegramList() -{ - // get the filename - QSettings settings; - QString newFilename = QFileDialog::getSaveFileName(m_tableView, - tr("Dateiname der Telegrammliste"), - settings.value(s_DIR()).toString(), - s_TELEGRAMLIST_FILES()); - if (!newFilename.isEmpty()) - { - if (!newFilename.contains(QLatin1Char('.'))) - newFilename += QLatin1String(".tgl"); - - // save the actual directory - QDir dir; - settings.beginGroup(s_EDIT_TELEGRAM_GROUP()); - settings.setValue(s_DIR(), dir.filePath(newFilename)); - settings.endGroup(); - - // save the telegram-list - QFile telegramFile(newFilename); - (void)telegramFile.open(QIODevice::WriteOnly); - QDataStream stream(&telegramFile); - - // write the header - uint32_t version = 1; - stream << s_TELEGRAMLIST_FILE_ID() << version; - - // write the telegrams - int rows = m_tableView->model()->rowCount(); - stream << rows; - for (int i = 0; i < rows; i++) - { - QSharedPointer telegram = telegramAtRow(i); - if (!telegram) - continue; - - const QByteArray &data = telegram->getData(); - const QString name = telegram->getName(); - const unsigned int waitTime = telegram->getWaitTime(); - - stream << waitTime - << name - << telegram->getGpsTimeField() - << data.size(); - stream.writeRawData(data.data(), data.size()); - } - telegramFile.close(); - } -} - -void TelegramEdit::loadTelegramListAppend() -{ - loadTelegramList(true); -} - -void TelegramEdit::loadTelegramListReplace() -{ - loadTelegramList(false); -} - -void TelegramEdit::loadTelegramList(bool checkAppend) -{ - // get the filename - QSettings settings; - QString newFilename = QFileDialog::getOpenFileName(m_tableView, - tr("Dateiname der Telegrammliste"), - settings.value(s_DIR()).toString(), - s_TELEGRAMLIST_FILES()); - if (!newFilename.isEmpty()) - { - // save the actual directory - QDir dir; - settings.beginGroup(s_EDIT_TELEGRAM_GROUP()); - settings.setValue(s_DIR(), dir.filePath(newFilename)); - settings.endGroup(); - - // delete the actual telegram-list - { - if (!checkAppend) - m_EditModel->clearTelegrams(); - } - - // load the telegram-list - QFile telegramFile(newFilename); - (void)telegramFile.open(QIODevice::ReadOnly); - QDataStream stream(&telegramFile); - - // read the header - QString id; - stream >> id; - if (id != s_TELEGRAMLIST_FILE_ID()) - { - QMessageBox::critical(m_tableView, tr("Error"), tr("%1 does not contain telegram data").arg(newFilename)); + m_currentRowToSend = currentSelectedIndex().row(); + if (m_currentRowToSend < 0) // invalid index return; - } - uint32_t version = 0; - stream >> version; - if (version != 1) - { - QMessageBox::critical(m_tableView, tr("Error"), tr("Wrong telegram list file version")); - return; - } + QSharedPointer tele = currentSelectedTelegram(); + sendTelegram(tele); + QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::sequenceNextTelegram); + } - // read the telegrams - int rows = 0; - QVector gpsFieldOffset; - stream >> rows; - for (int i = 0; i < rows; i++) + void TelegramEdit::sequenceNextTelegram() + { + ++m_currentRowToSend; + if (m_currentRowToSend >= m_tableView->model()->rowCount()) + return; + + QSharedPointer tele = telegramAtRow(m_currentRowToSend); + if (!tele) + return; + + sendTelegram(tele); + QTimer::singleShot(tele->getWaitTime(), this, &TelegramEdit::sequenceNextTelegram); + } + + QSharedPointer TelegramEdit::telegramAtRow(int row) + { + return m_EditModel->telegram(row); + } + + void TelegramEdit::copy() + { + m_copyTelegram = currentSelectedTelegram(); + m_pasteTeleAction->setEnabled(m_copyTelegram != nullptr); + if (!m_copyTelegram) + return; + m_copyTelegram = QSharedPointer(new LogViewTelegram(*m_copyTelegram.data())); + } + + void TelegramEdit::paste() + { + if (!m_copyTelegram) + return; + int row = currentSelectedIndex().row() + 1; + m_EditModel->pasteRows(row, m_copyTelegram); + } + + void TelegramEdit::moveUp() + { + const QModelIndex idx = currentSelectedIndex(); + if (m_EditModel->moveUp(idx.row())) { - uint32_t waitTime = 0; - QString name; - int telegramSize = 0; - stream >> waitTime >> name >> gpsFieldOffset >> telegramSize; - if (telegramSize > 0) + m_tableView->clearSelection(); + m_tableView->setCurrentIndex(m_EditModel->index(idx.row() - 1, idx.column(), idx.parent())); + m_moveTeleUpAction->setEnabled(idx.row() > 1); + m_moveTeleDownAction->setEnabled(true); + } + } + + void TelegramEdit::moveDown() + { + const QModelIndex idx = currentSelectedIndex(); + if (m_EditModel->moveDown(idx.row())) + { + m_tableView->clearSelection(); + m_tableView->setCurrentIndex(m_EditModel->index(idx.row() + 1, idx.column(), idx.parent())); + m_moveTeleUpAction->setEnabled(true); + m_moveTeleDownAction->setEnabled(idx.row() < m_EditModel->rowCount() - 2); + } + } + + void TelegramEdit::saveTelegramList() + { + // get the filename + QSettings settings; + QString newFilename = QFileDialog::getSaveFileName(m_tableView, tr("Dateiname der Telegrammliste"), settings.value(s_DIR()).toString(), s_TELEGRAMLIST_FILES()); + if (!newFilename.isEmpty()) + { + if (!newFilename.contains(QLatin1Char('.'))) + newFilename += QLatin1String(".tgl"); + + // save the actual directory + QDir dir; + settings.beginGroup(s_EDIT_TELEGRAM_GROUP()); + settings.setValue(s_DIR(), dir.filePath(newFilename)); + settings.endGroup(); + + // save the telegram-list + QFile telegramFile(newFilename); + (void)telegramFile.open(QIODevice::WriteOnly); + QDataStream stream(&telegramFile); + + // write the header + uint32_t version = 1; + stream << s_TELEGRAMLIST_FILE_ID() << version; + + // write the telegrams + int rows = m_tableView->model()->rowCount(); + stream << rows; + for (int i = 0; i < rows; i++) { - DEBUG_LOG(m_logger) << "telegramSize=" << telegramSize; - QByteArray buf(telegramSize, Qt::Uninitialized); - stream.readRawData(buf.data(), telegramSize); - NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Debug, buf); - LogViewTelegram *telegram = new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, - 0, - buf); - telegram->setWaitTime(waitTime); - telegram->setName(name); - telegram->setGpsTimeField(gpsFieldOffset); - m_EditModel->appendTelegram(QSharedPointer(telegram)); + QSharedPointer telegram = telegramAtRow(i); + if (!telegram) + continue; + + const QByteArray &data = telegram->getData(); + const QString name = telegram->getName(); + const unsigned int waitTime = telegram->getWaitTime(); + + stream << waitTime << name << telegram->getGpsTimeField() << data.size(); + stream.writeRawData(data.data(), data.size()); } + telegramFile.close(); } - telegramFile.close(); - - m_teleListSave->setEnabled(m_EditModel->rowCount() > 0); } -} -// --------------------------------------------------------------- -bool TelegramEdit::isInjectionPossible() const -{ - return m_InjectionThread ? m_InjectionThread->isSendingPossible() : false; -} + void TelegramEdit::loadTelegramListAppend() + { + loadTelegramList(true); + } -// --------------------------------------------------------------- -void TelegramEdit::onSelectionChanged() -{ - const QModelIndex idx = currentSelectedIndex(); + void TelegramEdit::loadTelegramListReplace() + { + loadTelegramList(false); + } - m_editTeleAction->setEnabled(idx.isValid()); - m_copyTeleAction->setEnabled(idx.isValid()); - m_deleteTeleAction->setEnabled(idx.isValid()); - m_moveTeleUpAction->setEnabled(idx.row() > 0); - m_moveTeleDownAction->setEnabled(idx.isValid() && idx.row() < m_EditModel->rowCount() - 1); -} + void TelegramEdit::loadTelegramList(bool checkAppend) + { + // get the filename + QSettings settings; + QString newFilename = QFileDialog::getOpenFileName(m_tableView, tr("Dateiname der Telegrammliste"), settings.value(s_DIR()).toString(), s_TELEGRAMLIST_FILES()); + if (!newFilename.isEmpty()) + { + // save the actual directory + QDir dir; + settings.beginGroup(s_EDIT_TELEGRAM_GROUP()); + settings.setValue(s_DIR(), dir.filePath(newFilename)); + settings.endGroup(); + + // delete the actual telegram-list + { + if (!checkAppend) + m_EditModel->clearTelegrams(); + } + + // load the telegram-list + QFile telegramFile(newFilename); + (void)telegramFile.open(QIODevice::ReadOnly); + QDataStream stream(&telegramFile); + + // read the header + QString id; + stream >> id; + if (id != s_TELEGRAMLIST_FILE_ID()) + { + QMessageBox::critical(m_tableView, tr("Error"), tr("%1 does not contain telegram data").arg(newFilename)); + return; + } + uint32_t version = 0; + stream >> version; + if (version != 1) + { + QMessageBox::critical(m_tableView, tr("Error"), tr("Wrong telegram list file version")); + return; + } + + // read the telegrams + int rows = 0; + QVector gpsFieldOffset; + stream >> rows; + for (int i = 0; i < rows; i++) + { + uint32_t waitTime = 0; + QString name; + int telegramSize = 0; + stream >> waitTime >> name >> gpsFieldOffset >> telegramSize; + if (telegramSize > 0) + { + DEBUG_LOG(m_logger) << "telegramSize=" << telegramSize; + QByteArray buf(telegramSize, Qt::Uninitialized); + stream.readRawData(buf.data(), telegramSize); + NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Debug, buf); + LogViewTelegram *telegram = new LogViewTelegram(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, 0, buf); + telegram->setWaitTime(waitTime); + telegram->setName(name); + telegram->setGpsTimeField(gpsFieldOffset); + m_EditModel->appendTelegram(QSharedPointer(telegram)); + } + } + telegramFile.close(); + + m_teleListSave->setEnabled(m_EditModel->rowCount() > 0); + } + } + + // --------------------------------------------------------------- + bool TelegramEdit::isInjectionPossible() const + { + return m_InjectionThread ? m_InjectionThread->isSendingPossible() : false; + } + + // --------------------------------------------------------------- + void TelegramEdit::onSelectionChanged() + { + const QModelIndex idx = currentSelectedIndex(); + + m_editTeleAction->setEnabled(idx.isValid()); + m_copyTeleAction->setEnabled(idx.isValid()); + m_deleteTeleAction->setEnabled(idx.isValid()); + m_moveTeleUpAction->setEnabled(idx.row() > 0); + m_moveTeleDownAction->setEnabled(idx.isValid() && idx.row() < m_EditModel->rowCount() - 1); + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.hpp index f9ecf70d7..861e13e0a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEdit.hpp @@ -17,110 +17,110 @@ class QTableView; namespace N_LogView { -class LogViewInjectionThread; -class TelegramEditModel; + class LogViewInjectionThread; + class TelegramEditModel; -class TelegramEdit :public QObject -{ - Q_OBJECT -public: - explicit TelegramEdit(QWidget *parent = nullptr); + class TelegramEdit : public QObject + { + Q_OBJECT + public: + explicit TelegramEdit(QWidget *parent = nullptr); - QTableView *tableView() { return m_tableView; } + QTableView *tableView() { return m_tableView; } - void appendTelegram(const QSharedPointer &telegram); + void appendTelegram(const QSharedPointer &telegram); - void setInjectionThread(LogViewInjectionThread* a_injectionThread); + void setInjectionThread(LogViewInjectionThread *a_injectionThread); - bool isInjectionPossible() const; + bool isInjectionPossible() const; -protected: - QSharedPointer m_copyTelegram; + protected: + QSharedPointer m_copyTelegram; - QSharedPointer currentSelectedTelegram() const; + QSharedPointer currentSelectedTelegram() const; - QModelIndex currentSelectedIndex() const; + QModelIndex currentSelectedIndex() const; - QSharedPointer telegramAtRow(int row); + QSharedPointer telegramAtRow(int row); - void loadTelegramList(bool checkAppend); + void loadTelegramList(bool checkAppend); -protected: - QAction *m_addTeleAction; - QAction *m_editTeleAction; - QAction *m_copyTeleAction; - QAction *m_pasteTeleAction; - QAction *m_deleteTeleAction; - QAction *m_moveTeleUpAction; - QAction *m_moveTeleDownAction; - QAction *m_teleListLoad; - QAction *m_teleListAppend; - QAction *m_teleListSave; - QTableView *m_tableView; - bool m_DoLoop; + protected: + QAction *m_addTeleAction; + QAction *m_editTeleAction; + QAction *m_copyTeleAction; + QAction *m_pasteTeleAction; + QAction *m_deleteTeleAction; + QAction *m_moveTeleUpAction; + QAction *m_moveTeleDownAction; + QAction *m_teleListLoad; + QAction *m_teleListAppend; + QAction *m_teleListSave; + QTableView *m_tableView; + bool m_DoLoop; - LogViewInjectionThread *m_InjectionThread; + LogViewInjectionThread *m_InjectionThread; - int m_currentRowToSend; + int m_currentRowToSend; - int m_curEditTelegramRow; + int m_curEditTelegramRow; - TelegramEditModel *m_EditModel; + TelegramEditModel *m_EditModel; - NGL::INGLLogger &m_logger; - static QString s_DIR(); - static QString s_EDIT_TELEGRAM_GROUP(); - static QString s_TELEGRAMLIST_FILE_ID(); - static QString s_TELEGRAMLIST_FILES(); + NGL::INGLLogger &m_logger; + static QString s_DIR(); + static QString s_EDIT_TELEGRAM_GROUP(); + static QString s_TELEGRAMLIST_FILE_ID(); + static QString s_TELEGRAMLIST_FILES(); -protected Q_SLOTS: + protected Q_SLOTS: - void addTelegram(); + void addTelegram(); - void injectTelegram(bool a_bAsCentralTelegram); + void injectTelegram(bool a_bAsCentralTelegram); - void injectTelegram(const QSharedPointer &a_telegram, bool a_bAsCentralTelegram); + void injectTelegram(const QSharedPointer &a_telegram, bool a_bAsCentralTelegram); - void sendTelegram(const QSharedPointer &a_telegram); + void sendTelegram(const QSharedPointer &a_telegram); - void sendCurrentTelegram(); + void sendCurrentTelegram(); - void tableViewCustomContextMenu(const QPoint &pos); + void tableViewCustomContextMenu(const QPoint &pos); - void editTelegram(); + void editTelegram(); - void showTelegram(); + void showTelegram(); - void deleteTelegram(); + void deleteTelegram(); - void injectCentralTelegram(); + void injectCentralTelegram(); - void injectTetraTelegram(); + void injectTetraTelegram(); - void loopTelegrams(); + void loopTelegrams(); - void loopNextTelegram(); + void loopNextTelegram(); - void sequenceTelegrams(); + void sequenceTelegrams(); - void sequenceNextTelegram(); + void sequenceNextTelegram(); - void copy(); + void copy(); - void paste(); + void paste(); - void moveUp(); + void moveUp(); - void moveDown(); + void moveDown(); - void saveTelegramList(); + void saveTelegramList(); - void loadTelegramListAppend(); + void loadTelegramListAppend(); - void loadTelegramListReplace(); + void loadTelegramListReplace(); - void editTelegramDialogFinished(); + void editTelegramDialogFinished(); - void onSelectionChanged(); -}; + void onSelectionChanged(); + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.cpp index 39ab476ad..7600c28a2 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.cpp @@ -12,157 +12,155 @@ namespace N_LogView { -// --------------------------------------------------------------- -int TelegramEditModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : m_telegrams.size(); -} - -// --------------------------------------------------------------- -int TelegramEditModel::columnCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : 3; -} - -// --------------------------------------------------------------- -QVariant TelegramEditModel::data(const QModelIndex &index, int role) const -{ - if (index.isValid() && index.row() < m_telegrams.size()) + // --------------------------------------------------------------- + int TelegramEditModel::rowCount(const QModelIndex &parent) const { - if (role == Qt::DisplayRole) + return parent.isValid() ? 0 : m_telegrams.size(); + } + + // --------------------------------------------------------------- + int TelegramEditModel::columnCount(const QModelIndex &parent) const + { + return parent.isValid() ? 0 : 3; + } + + // --------------------------------------------------------------- + QVariant TelegramEditModel::data(const QModelIndex &index, int role) const + { + if (index.isValid() && index.row() < m_telegrams.size()) { - const QSharedPointer telegram = m_telegrams.at(index.row()); - switch (index.column()) + if (role == Qt::DisplayRole) { - case 0: - return telegram->getName(); - case 1: - return telegram->getParticipantId(); - case 2: - return telegram->getWaitTime(); + const QSharedPointer telegram = m_telegrams.at(index.row()); + switch (index.column()) + { + case 0: + return telegram->getName(); + case 1: + return telegram->getParticipantId(); + case 2: + return telegram->getWaitTime(); + } + } + else if (role == Qt::ToolTipRole) + { + const QSharedPointer telegram = m_telegrams.at(index.row()); + if (telegram->isJsonTelegram()) + return telegram->getData(QJsonDocument::JsonFormat::Indented); } } - else if (role == Qt::ToolTipRole) + return QVariant(); + } + + // --------------------------------------------------------------- + QVariant TelegramEditModel::headerData(int section, Qt::Orientation orientation, int role) const + { + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - const QSharedPointer telegram = m_telegrams.at(index.row()); - if (telegram->isJsonTelegram()) - return telegram->getData(QJsonDocument::JsonFormat::Indented); + switch (section) + { + case 0: + return tr("Description"); + case 1: + return tr("Equip. No."); + case 2: + return tr("Wait Time"); + default: + break; + } + } + return QAbstractTableModel::headerData(section, orientation, role); + } + + // --------------------------------------------------------------- + void TelegramEditModel::clearTelegrams() + { + beginResetModel(); + m_telegrams.clear(); + endResetModel(); + } + + // --------------------------------------------------------------- + void TelegramEditModel::appendTelegrams(const QVector> &telegrams) + { + if (telegrams.isEmpty()) + return; + beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size() + telegrams.size() - 1); + m_telegrams += telegrams; + endInsertRows(); + } + + // --------------------------------------------------------------- + int TelegramEditModel::appendTelegram(const QSharedPointer &telegram) + { + beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size()); + m_telegrams.push_back(telegram); + telegram->rebuildJsonString(); + endInsertRows(); + return m_telegrams.size() - 1; // row + } + + // --------------------------------------------------------------- + QSharedPointer TelegramEditModel::telegram(int row) const + { + if (row >= 0 && row < m_telegrams.size()) + return m_telegrams.at(row); + return QSharedPointer(); + } + + // --------------------------------------------------------------- + bool TelegramEditModel::moveUp(int row) + { + if (row <= 0 || row >= m_telegrams.size()) + return false; + beginMoveRows(QModelIndex(), row, row, QModelIndex(), row - 1); + std::swap(m_telegrams[row], m_telegrams[row - 1]); + endMoveRows(); + return true; + } + + // --------------------------------------------------------------- + bool TelegramEditModel::moveDown(int row) + { + if (row >= (m_telegrams.size() - 1)) + return false; + beginMoveRows(QModelIndex(), row, row, QModelIndex(), row + 1); + std::swap(m_telegrams[row], m_telegrams[row + 1]); + endMoveRows(); + return true; + } + + // --------------------------------------------------------------- + void TelegramEditModel::emitDataChanged(int row) + { + QModelIndex top = createIndex(row, 0); + QModelIndex bottom = createIndex(row, columnCount() - 1); + emit dataChanged(top, bottom, {Qt::DisplayRole, Qt::ToolTipRole}); + } + + // --------------------------------------------------------------- + void TelegramEditModel::removeTelegrams(const QSet &rows) + { + QList rowList = rows.values(); + std::sort(rowList.begin(), rowList.end()); + // von oben her löschen um ein Verschieben der Indizes zu vermeiden + for (int i = rowList.size() - 1; i >= 0; --i) + { + int row = rowList.at(i); + beginRemoveRows(QModelIndex(), row, row); + m_telegrams.remove(row); + endRemoveRows(); } } - return QVariant(); -} -// --------------------------------------------------------------- -QVariant TelegramEditModel::headerData(int section, - Qt::Orientation orientation, - int role) const -{ - if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + // --------------------------------------------------------------- + void TelegramEditModel::pasteRows(int row, const QSharedPointer &tele) { - switch (section) - { - case 0: - return tr("Description"); - case 1: - return tr("Equip. No."); - case 2: - return tr("Wait Time"); - default: - break; - } + if (row < 0 || row > m_telegrams.size()) + return; + beginInsertRows(QModelIndex(), row, row); + m_telegrams.insert(row, QSharedPointer(new LogViewTelegram(*tele.data()))); + endInsertRows(); } - return QAbstractTableModel::headerData(section, orientation, role); -} - -// --------------------------------------------------------------- -void TelegramEditModel::clearTelegrams() -{ - beginResetModel(); - m_telegrams.clear(); - endResetModel(); -} - -// --------------------------------------------------------------- -void TelegramEditModel::appendTelegrams(const QVector > &telegrams) -{ - if (telegrams.isEmpty()) - return; - beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size() + telegrams.size() - 1); - m_telegrams += telegrams; - endInsertRows(); -} - -// --------------------------------------------------------------- -int TelegramEditModel::appendTelegram(const QSharedPointer &telegram) -{ - beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size()); - m_telegrams.push_back(telegram); - telegram->rebuildJsonString(); - endInsertRows(); - return m_telegrams.size() - 1; // row -} - -// --------------------------------------------------------------- -QSharedPointer TelegramEditModel::telegram(int row) const -{ - if (row >= 0 && row < m_telegrams.size()) - return m_telegrams.at(row); - return QSharedPointer(); -} - -// --------------------------------------------------------------- -bool TelegramEditModel::moveUp(int row) -{ - if (row <= 0 || row >= m_telegrams.size()) - return false; - beginMoveRows(QModelIndex(), row, row, QModelIndex(), row - 1); - std::swap(m_telegrams[row], m_telegrams[row - 1]); - endMoveRows(); - return true; -} - -// --------------------------------------------------------------- -bool TelegramEditModel::moveDown(int row) -{ - if (row >= (m_telegrams.size() - 1)) - return false; - beginMoveRows(QModelIndex(), row, row, QModelIndex(), row + 1); - std::swap(m_telegrams[row], m_telegrams[row + 1]); - endMoveRows(); - return true; -} - -// --------------------------------------------------------------- -void TelegramEditModel::emitDataChanged(int row) -{ - QModelIndex top = createIndex(row, 0); - QModelIndex bottom = createIndex(row, columnCount() - 1); - emit dataChanged(top, bottom, {Qt::DisplayRole, Qt::ToolTipRole}); -} - -// --------------------------------------------------------------- -void TelegramEditModel::removeTelegrams(const QSet &rows) -{ - QList rowList = rows.values(); - std::sort(rowList.begin(), rowList.end()); - // von oben her löschen um ein Verschieben der Indizes zu vermeiden - for (int i = rowList.size() - 1 ; i >= 0; --i) - { - int row = rowList.at(i); - beginRemoveRows(QModelIndex(), row, row); - m_telegrams.remove(row); - endRemoveRows(); - } -} - -// --------------------------------------------------------------- -void TelegramEditModel::pasteRows(int row, const QSharedPointer &tele) -{ - if (row < 0 || row > m_telegrams.size()) - return; - beginInsertRows(QModelIndex(), row, row); - m_telegrams.insert(row, QSharedPointer(new LogViewTelegram(*tele.data()))); - endInsertRows(); -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.hpp index aab522387..a78efd3e9 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramEditModel.hpp @@ -15,35 +15,34 @@ namespace N_LogView { -class TelegramEditModel final : public QAbstractTableModel -{ - Q_OBJECT -public: - using QAbstractTableModel::QAbstractTableModel; + class TelegramEditModel final : public QAbstractTableModel + { + Q_OBJECT + public: + using QAbstractTableModel::QAbstractTableModel; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - void clearTelegrams(); - void appendTelegrams(const QVector > &telegrams); - int appendTelegram(const QSharedPointer &telegram); - QSharedPointer telegram(int row) const; + void clearTelegrams(); + void appendTelegrams(const QVector> &telegrams); + int appendTelegram(const QSharedPointer &telegram); + QSharedPointer telegram(int row) const; - bool moveUp(int row); - bool moveDown(int row); + bool moveUp(int row); + bool moveDown(int row); - void emitDataChanged(int row); + void emitDataChanged(int row); - void removeTelegrams(const QSet &rows); + void removeTelegrams(const QSet &rows); - void pasteRows(int row, const QSharedPointer &tele); -protected: - QVector > m_telegrams; + void pasteRows(int row, const QSharedPointer &tele); -}; + protected: + QVector> m_telegrams; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.cpp index 091cf682c..2acec770c 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewTelegramSelectionDialog.hpp" #include #include @@ -22,41 +22,40 @@ namespace N_LogView { -static int s_currentRow = 0; -// --------------------------------------------------------------- -LogViewTelegramSelectionDialog::LogViewTelegramSelectionDialog(QWidget* a_parent) - : QDialog(a_parent) -{ - setMinimumSize(QSize(600, 500)); - QVBoxLayout* layout = new QVBoxLayout; - layout->addWidget(new QLabel(tr("Select a telegram:"))); - m_TelegramList = new QListWidget(this); - const auto telegramMap = LogViewTelegram::jsonParser()->telegramsToCreate(); - for (auto it = telegramMap.cbegin(); it != telegramMap.cend(); ++it) + static int s_currentRow = 0; + // --------------------------------------------------------------- + LogViewTelegramSelectionDialog::LogViewTelegramSelectionDialog(QWidget *a_parent) + : QDialog(a_parent) { - if (it.key() == 0) // ACK - continue; - auto lwi = new QListWidgetItem(it.value() + QStringLiteral(" (%1)").arg(it.key())); - lwi->setData(Qt::UserRole, it.key()); - m_TelegramList->addItem(lwi); + setMinimumSize(QSize(600, 500)); + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(new QLabel(tr("Select a telegram:"))); + m_TelegramList = new QListWidget(this); + const auto telegramMap = LogViewTelegram::jsonParser()->telegramsToCreate(); + for (auto it = telegramMap.cbegin(); it != telegramMap.cend(); ++it) + { + if (it.key() == 0) // ACK + continue; + auto lwi = new QListWidgetItem(it.value() + QStringLiteral(" (%1)").arg(it.key())); + lwi->setData(Qt::UserRole, it.key()); + m_TelegramList->addItem(lwi); + } + + m_TelegramList->sortItems(); + m_TelegramList->setCurrentRow(s_currentRow); + connect(m_TelegramList, &QListWidget::itemActivated, this, &LogViewTelegramSelectionDialog::selectTelegram); + layout->addWidget(m_TelegramList); + + setLayout(layout); } - m_TelegramList->sortItems(); - m_TelegramList->setCurrentRow(s_currentRow); - connect(m_TelegramList, &QListWidget::itemActivated, - this, &LogViewTelegramSelectionDialog::selectTelegram); - layout->addWidget(m_TelegramList); - setLayout(layout); -} - - -// --------------------------------------------------------------- -void LogViewTelegramSelectionDialog::selectTelegram(QListWidgetItem* a_telegramItem) -{ - s_currentRow = m_TelegramList->currentRow(); - m_SelectedTelegramId = a_telegramItem->data(Qt::UserRole).toInt(); - accept(); -} + // --------------------------------------------------------------- + void LogViewTelegramSelectionDialog::selectTelegram(QListWidgetItem *a_telegramItem) + { + s_currentRow = m_TelegramList->currentRow(); + m_SelectedTelegramId = a_telegramItem->data(Qt::UserRole).toInt(); + accept(); + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.hpp index 0fe2ceb67..f955b8262 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTelegramSelectionDialog.hpp @@ -32,7 +32,7 @@ namespace N_LogView * * @param a_parent */ - explicit LogViewTelegramSelectionDialog(QWidget* a_parent); + explicit LogViewTelegramSelectionDialog(QWidget *a_parent); int getSelectedTelegramId() const { return m_SelectedTelegramId; } @@ -42,12 +42,11 @@ namespace N_LogView * * @param a_telegramItem */ - void selectTelegram(QListWidgetItem* a_telegramItem); + void selectTelegram(QListWidgetItem *a_telegramItem); protected: - QListWidget *m_TelegramList; int m_SelectedTelegramId; -}; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.cpp index 9ecf48e58..243c61f90 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.cpp @@ -16,528 +16,518 @@ namespace N_LogView { -LogViewTetraTelegramsParser::LogViewTetraTelegramsParser() - : m_logger(getLogger("LogViewTetraTelegramsParser")) -{ - insertPod(QStringLiteral("bool"), 1, true, true, true); - insertPod(QStringLiteral("int"), 4, true, true); - insertPod(QStringLiteral("int32_t"), 4, true, true); - insertPod(QStringLiteral("qint64"), 8, true, true); - insertPod(QStringLiteral("float"), 4, true, false); - insertPod(QStringLiteral("double"), 8, true, false); -} - -EnumInformation LogViewTetraTelegramsParser::enumFromType(const QString &type) const -{ - for (const auto &ei : m_enums) + LogViewTetraTelegramsParser::LogViewTetraTelegramsParser() + : m_logger(getLogger("LogViewTetraTelegramsParser")) { - const QString fqType = ei.ns.isEmpty() ? ei.type : (ei.ns + QStringLiteral("::") + ei.type); - if (fqType == type) - return ei; + insertPod(QStringLiteral("bool"), 1, true, true, true); + insertPod(QStringLiteral("int"), 4, true, true); + insertPod(QStringLiteral("int32_t"), 4, true, true); + insertPod(QStringLiteral("qint64"), 8, true, true); + insertPod(QStringLiteral("float"), 4, true, false); + insertPod(QStringLiteral("double"), 8, true, false); } - return EnumInformation(); -} -StructInformation LogViewTetraTelegramsParser::structFromType(const QString &type) const -{ - return m_structs.value(type); -} - -PodInformation LogViewTetraTelegramsParser::podFromType(const QString &type) const -{ - return m_pods.value(type); -} - -bool LogViewTetraTelegramsParser::isEnum(const QString &type) const -{ - for (const auto &ei : m_enums) - if (ei.type == type) - return true; - return false; -} - -bool LogViewTetraTelegramsParser::isStruct(const QString &type) const -{ - return m_structs.contains(type); -} - -bool LogViewTetraTelegramsParser::isPod(const QString &type) const -{ - return m_pods.contains(type); -} - -static void fillBasemembers(StructInformation &si, const QHash &structs) -{ - if (si.baseStruct.isEmpty()) - return; - StructInformation base = structs.value(si.baseStruct); - fillBasemembers(base, structs); - si.member = (base.member + si.member); // base first -} - -bool LogViewTetraTelegramsParser::parse(const QString &filename) -{ - m_telegramIdEnum = EnumInformation(); - m_enums.clear(); - m_structs.clear(); - //m_pods.clear(); // only set once - m_visibleTelegrams.clear(); - - QFile f(filename); - if (!f.open(QIODevice::ReadOnly)) + EnumInformation LogViewTetraTelegramsParser::enumFromType(const QString &type) const { - WARNING_LOG(m_logger) << "Can not open file " << filename << " for reading: " << f.errorString(); + for (const auto &ei : m_enums) + { + const QString fqType = ei.ns.isEmpty() ? ei.type : (ei.ns + QStringLiteral("::") + ei.type); + if (fqType == type) + return ei; + } + return EnumInformation(); + } + + StructInformation LogViewTetraTelegramsParser::structFromType(const QString &type) const + { + return m_structs.value(type); + } + + PodInformation LogViewTetraTelegramsParser::podFromType(const QString &type) const + { + return m_pods.value(type); + } + + bool LogViewTetraTelegramsParser::isEnum(const QString &type) const + { + for (const auto &ei : m_enums) + if (ei.type == type) + return true; return false; } - const QString content = QString::fromUtf8(f.readAll()); - f.close(); - - const QStringList linesList = content.split(QLatin1Char('\n')); - QVector lines; - lines.reserve(linesList.size()); - for (const QString &line : linesList) - lines += line; - QVector linesTrimmed; - linesTrimmed.reserve(lines.size()); - for (const QStringView &line : lines) - linesTrimmed += line.trimmed(); - - int i = 0; - while (i < linesTrimmed.size()) + bool LogViewTetraTelegramsParser::isStruct(const QString &type) const { - const QStringView &line = linesTrimmed.at(i); - if (line.startsWith(QLatin1String("struct"))) - { - i = parseStruct(linesTrimmed, i); - if (i < 0) - return false; - } - else if (line.startsWith(QLatin1String("enum"))) - { - i = parseEnum(linesTrimmed, i, QString()); - if (i < 0) - return false; - } - else if (line.startsWith(QLatin1String("template <> struct Constraints"))) - { - i = parseConstraint(linesTrimmed, i); - if (i < 0) - return false; - } - ++i; + return m_structs.contains(type); } - const auto completeStructs = m_structs; - for (StructInformation &si : m_structs) - fillBasemembers(si, completeStructs); - return true; -} - -void LogViewTetraTelegramsParser::insertPod(const QString &type, int byteLen, bool isSigned, bool isIntegral, bool isBoolean) -{ - PodInformation pod; - pod.type = type; - pod.byteLen = byteLen; - pod.isBoolean = isBoolean; - pod.isIntegral = isIntegral; - pod.isSigned = isSigned; - m_pods[type] = pod; -} - - -int LogViewTetraTelegramsParser::parseStruct(const QVector &lines, int iStartPos) -{ - const QVector tokens = tokenize(lines.at(iStartPos)); - if (tokens.size() < 2) - return -1; - const QStringView &structType = tokens.at(1); - if (structType.endsWith(QLatin1Char(';'))) - return iStartPos; - - StructInformation si; - si.type = structType.toString(); - if (tokens.size() > 2) + bool LogViewTetraTelegramsParser::isPod(const QString &type) const { - if (tokens.at(2) != QLatin1String(":")) + return m_pods.contains(type); + } + + static void fillBasemembers(StructInformation &si, const QHash &structs) + { + if (si.baseStruct.isEmpty()) + return; + StructInformation base = structs.value(si.baseStruct); + fillBasemembers(base, structs); + si.member = (base.member + si.member); // base first + } + + bool LogViewTetraTelegramsParser::parse(const QString &filename) + { + m_telegramIdEnum = EnumInformation(); + m_enums.clear(); + m_structs.clear(); + //m_pods.clear(); // only set once + m_visibleTelegrams.clear(); + + QFile f(filename); + if (!f.open(QIODevice::ReadOnly)) { - WARNING_LOG(m_logger) << "Could not parse struct: '" << lines.at(iStartPos).toString() << "', line: " << iStartPos + 1; - return -1; + WARNING_LOG(m_logger) << "Can not open file " << filename << " for reading: " << f.errorString(); + return false; } - for (int i = 3; i < tokens.size(); ++i) + const QString content = QString::fromUtf8(f.readAll()); + f.close(); + + const QStringList linesList = content.split(QLatin1Char('\n')); + QVector lines; + lines.reserve(linesList.size()); + for (const QString &line : linesList) + lines += line; + QVector linesTrimmed; + linesTrimmed.reserve(lines.size()); + for (const QStringView &line : lines) + linesTrimmed += line.trimmed(); + + int i = 0; + while (i < linesTrimmed.size()) { - if (!si.baseStruct.isEmpty()) + const QStringView &line = linesTrimmed.at(i); + if (line.startsWith(QLatin1String("struct"))) + { + i = parseStruct(linesTrimmed, i); + if (i < 0) + return false; + } + else if (line.startsWith(QLatin1String("enum"))) + { + i = parseEnum(linesTrimmed, i, QString()); + if (i < 0) + return false; + } + else if (line.startsWith(QLatin1String("template <> struct Constraints"))) + { + i = parseConstraint(linesTrimmed, i); + if (i < 0) + return false; + } + ++i; + } + + const auto completeStructs = m_structs; + for (StructInformation &si : m_structs) + fillBasemembers(si, completeStructs); + return true; + } + + void LogViewTetraTelegramsParser::insertPod(const QString &type, int byteLen, bool isSigned, bool isIntegral, bool isBoolean) + { + PodInformation pod; + pod.type = type; + pod.byteLen = byteLen; + pod.isBoolean = isBoolean; + pod.isIntegral = isIntegral; + pod.isSigned = isSigned; + m_pods[type] = pod; + } + + + int LogViewTetraTelegramsParser::parseStruct(const QVector &lines, int iStartPos) + { + const QVector tokens = tokenize(lines.at(iStartPos)); + if (tokens.size() < 2) + return -1; + const QStringView &structType = tokens.at(1); + if (structType.endsWith(QLatin1Char(';'))) + return iStartPos; + + StructInformation si; + si.type = structType.toString(); + if (tokens.size() > 2) + { + if (tokens.at(2) != QLatin1String(":")) { WARNING_LOG(m_logger) << "Could not parse struct: '" << lines.at(iStartPos).toString() << "', line: " << iStartPos + 1; return -1; } - QStringView base = tokens.at(i); - if (base == QLatin1String("public") || - base == QLatin1String("protected") || - base == QLatin1String("private")) - continue; - if (base.endsWith(QLatin1Char(','))) - base.chop(1); - if (base.endsWith(QLatin1Char('>'))) // helper template - ignore + + for (int i = 3; i < tokens.size(); ++i) { - si.isVisible = true; + if (!si.baseStruct.isEmpty()) + { + WARNING_LOG(m_logger) << "Could not parse struct: '" << lines.at(iStartPos).toString() << "', line: " << iStartPos + 1; + return -1; + } + QStringView base = tokens.at(i); + if (base == QLatin1String("public") || base == QLatin1String("protected") || base == QLatin1String("private")) + continue; + if (base.endsWith(QLatin1Char(','))) + base.chop(1); + if (base.endsWith(QLatin1Char('>'))) // helper template - ignore + { + si.isVisible = true; + continue; + } + si.baseStruct = tokens.at(i).toString(); + } + } + + int i = iStartPos + 1; + while (i < lines.size()) + { + const QVector tokens = tokenize(lines.at(i)); + if (!validStructTokens(tokens)) + { + ++i; continue; } - si.baseStruct = tokens.at(i).toString(); + if (tokens.at(0) == QLatin1String("};")) + break; + if (tokens.at(0) == QLatin1String("enum")) + { + i = parseEnum(lines, i, si.type, &si); + if (i < 0) + return -1; + ++i; + continue; + } + + MemberInformation mi; + if (tokens.size() > 2) + { + const int parserCommentPos = tokens.at(2) == QLatin1String("=") ? 4 : 2; + if (tokens.size() > parserCommentPos) + { + const QStringView &comment = tokens.at(parserCommentPos); + DEBUG_LOG(m_logger) << "comment: " << comment.toString(); + if (comment.startsWith(QLatin1String("//@array: "))) + { + const QStringView hint = comment.mid(QLatin1String("//@array: ").size()); + QString structStr = QLatin1String("struct ") + si.type + QLatin1String("::") + tokens.at(0).toString() + QLatin1Char('\n') + hint.toString(); + structStr.replace(QLatin1Char(';'), QLatin1String(";\n")); + DEBUG_LOG(m_logger) << "structStr: " << structStr; + const QStringList structLines = structStr.split(QLatin1Char('\n')); + QVector structLinesView; + structLinesView.reserve(structLines.size()); + for (const QString &line : structLines) + structLinesView += line; + parseStruct(structLinesView, 0); + + mi.type = si.type + QLatin1String("::") + tokens.at(0).toString(); + mi.isArray = true; + } + if (comment == QLatin1String("//@invisible")) + mi.isVisible = false; + } + } + + QStringView name = tokens.at(1); + if (name.endsWith(QLatin1Char(';'))) + name.chop(1); + if (mi.type.isEmpty()) + mi.type += tokens.at(0).toString(); + categorizeMember(mi); + mi.name = name.toString(); + if (mi.isEnum && !mi.type.contains(QLatin1String("::"))) + { + + for (const auto &ei : std::as_const(m_enums)) + { + if (ei.type == mi.type) + { + if (!ei.ns.isEmpty()) + mi.type = ei.ns + QLatin1String("::") + mi.type; + break; + } + } + } + si.member.push_back(std::move(mi)); + + ++i; } + + if (m_logger.isDebugEnabled()) + { + if (si.baseStruct.isEmpty()) + DEBUG_LOG(m_logger) << "Found Struct: " << si.type; + else + DEBUG_LOG(m_logger) << "Found Struct: " << si.type << ", base: " << si.baseStruct; + for (int j = 0; j < si.member.size(); ++j) + { + const MemberInformation &mi = si.member.at(j); + DEBUG_LOG(m_logger) << "Member[" << j << "]: " << mi.type << " - " << mi.name; + } + } + + m_structs[si.type] = si; + + return i; } - int i = iStartPos + 1; - while (i < lines.size()) + int LogViewTetraTelegramsParser::parseEnum(const QVector &lines, int iStartPos, const QString &ns, StructInformation *si) { - const QVector tokens = tokenize(lines.at(i)); - if (!validStructTokens(tokens)) + const QVector tokens = tokenize(lines.at(iStartPos)); + if (tokens.size() < 2) + return -1; + QStringView enumName = tokens.at(1); + if (enumName == QLatin1String("class")) { - ++i; - continue; - } - if (tokens.at(0) == QLatin1String("};")) - break; - if (tokens.at(0) == QLatin1String("enum")) - { - i = parseEnum(lines, i, si.type, &si); - if (i < 0) + if (tokens.size() < 3) return -1; - ++i; - continue; + enumName = tokens.at(2); } + if (enumName.endsWith(QLatin1Char(';'))) // forward decl + return iStartPos; // move to next line - MemberInformation mi; - if (tokens.size() > 2) + EnumInformation ei; + ei.type = enumName.toString(); + ei.ns = ns; + + int i = iStartPos + 1; + while (i < lines.size()) { - const int parserCommentPos = tokens.at(2) == QLatin1String("=") ? 4 : 2; - if (tokens.size() > parserCommentPos) + const QVector tokens = tokenize(lines.at(i).split(QStringLiteral("//")).first()); + if (tokens.isEmpty() || (tokens.at(0) == QLatin1String("{"))) { - const QStringView &comment = tokens.at(parserCommentPos); - DEBUG_LOG(m_logger) << "comment: " << comment.toString(); - if (comment.startsWith(QLatin1String("//@array: "))) - { - const QStringView hint = comment.mid(QLatin1String("//@array: ").size()); - QString structStr = QLatin1String("struct ") + si.type + QLatin1String("::") + tokens.at(0).toString() + QLatin1Char('\n') + hint.toString(); - structStr.replace(QLatin1Char(';'), QLatin1String(";\n")); - DEBUG_LOG(m_logger) << "structStr: " << structStr; - const QStringList structLines = structStr.split(QLatin1Char('\n')); - QVector structLinesView; - structLinesView.reserve(structLines.size()); - for (const QString &line : structLines) - structLinesView += line; - parseStruct(structLinesView, 0); - - mi.type = si.type + QLatin1String("::") + tokens.at(0).toString(); - mi.isArray = true; - } - if (comment == QLatin1String("//@invisible")) - mi.isVisible = false; + ++i; + continue; } + if (tokens.at(0) == QLatin1String("};")) + break; + if ((tokens.size() != 1 && tokens.size() != 3) || (tokens.size() == 3 && tokens.at(1) != QLatin1String("="))) + { + if (tokens.size() == 4 && tokens.at(0) == QLatin1String("}") && tokens.at(3).endsWith(QLatin1Char(';')) && si) + { + // enum in struct with direct decl of member + MemberInformation mi; + if (ns.isEmpty()) + mi.type = ei.type; + else + mi.type = ns + QStringLiteral("::") + ei.type; + mi.isEnum = true; + mi.name = tokens.at(1).toString(); + si->member.push_back(std::move(mi)); + break; + } + WARNING_LOG(m_logger) << "Could not parse enum: '" << lines.at(i).toString() << "', line: " << i + 1; + return -1; + } + + EnumValue ev; + ev.key = tokens.at(0).toString(); + if (tokens.size() == 3) + { + QStringView value = tokens.at(2); + if (value.endsWith(QLatin1Char(','))) + value.chop(1); + ev.value = value.toInt(); + } + else + { + int val = ei.values.isEmpty() ? 0 : (ei.values.last().value + 1); + ev.value = val; + } + ei.values.push_back(std::move(ev)); + ++i; } - QStringView name = tokens.at(1); - if (name.endsWith(QLatin1Char(';'))) - name.chop(1); - if (mi.type.isEmpty()) - mi.type += tokens.at(0).toString(); - categorizeMember(mi); - mi.name = name.toString(); - if (mi.isEnum && !mi.type.contains(QLatin1String("::"))) + DEBUG_LOG(m_logger) << "Found Enum: " << ei.type; + for (const EnumValue &ev : std::as_const(ei.values)) + DEBUG_LOG(m_logger) << "Member[" << i << "]: " << ev.key << " = " << ev.value; + + if (ei.type == QLatin1String("TelegramId")) + m_telegramIdEnum = ei; + + m_enums.push_back(std::move(ei)); + + return i; + } + + int LogViewTetraTelegramsParser::parseConstraint(const QVector &lines, int iStartPos) + { + const QVector tokens = tokenize(lines.at(iStartPos)); + if (tokens.size() != 4) { - - for (const auto &ei : std::as_const(m_enums)) + WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(iStartPos).toString() << "'"; + return -1; + } + const QStringView &cs = tokens.at(3); + if (!cs.startsWith(QLatin1String("Constraints<")) || !cs.endsWith(QLatin1Char('>'))) + { + WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(iStartPos).toString() << "'"; + return -1; + } + QStringView structName = cs.mid(QLatin1String("Constraints<").size()); + structName.chop(1); + DEBUG_LOG(m_logger) << "Constraint: " << structName.toString(); + + int i = iStartPos + 1; + while (i < lines.size()) + { + const QVector tokens = tokenize(lines.at(i)); + if (tokens.isEmpty() || (tokens.at(0) == QLatin1String("{"))) { - if (ei.type == mi.type) + ++i; + continue; + } + if (tokens.at(0) == QLatin1String("};")) + break; + if (tokens.size() != 8 || tokens.at(2) != QLatin1String("TelegramId")) // static constexpr TelegramId id() { return TelegramId::INIT; } + { + ++i; + continue; + } + const QVector parts = tokens.at(6).split(u"::"); + if (parts.size() != 2) + { + WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(i).toString() << "'"; + return -1; + } + + QStringView enumKey = parts.at(1); + if (enumKey.endsWith(QLatin1Char(';'))) + enumKey.chop(1); + bool bFound = false; + for (const auto &v : std::as_const(m_telegramIdEnum.values)) + { + if (v.key == enumKey) { - if (!ei.ns.isEmpty()) - mi.type = ei.ns + QLatin1String("::") + mi.type; + m_visibleTelegrams.insert(v.value, structName.toString()); + bFound = true; break; } } - } - si.member.push_back(std::move(mi)); - - ++i; - } - - if (m_logger.isDebugEnabled()) - { - if (si.baseStruct.isEmpty()) - DEBUG_LOG(m_logger) << "Found Struct: " << si.type; - else - DEBUG_LOG(m_logger) << "Found Struct: " << si.type << ", base: " << si.baseStruct; - for (int j = 0; j < si.member.size(); ++j) - { - const MemberInformation &mi = si.member.at(j); - DEBUG_LOG(m_logger) << "Member[" << j << "]: " << mi.type << " - " << mi.name; - } - } - - m_structs[si.type] = si; - - return i; -} - -int LogViewTetraTelegramsParser::parseEnum(const QVector &lines, int iStartPos, const QString &ns, StructInformation *si) -{ - const QVector tokens = tokenize(lines.at(iStartPos)); - if (tokens.size() < 2) - return -1; - QStringView enumName = tokens.at(1); - if (enumName == QLatin1String("class")) - { - if (tokens.size() < 3) - return -1; - enumName = tokens.at(2); - } - if (enumName.endsWith(QLatin1Char(';'))) // forward decl - return iStartPos; // move to next line - - EnumInformation ei; - ei.type = enumName.toString(); - ei.ns = ns; - - int i = iStartPos + 1; - while (i < lines.size()) - { - const QVector tokens = tokenize(lines.at(i).split(QStringLiteral("//")).first()); - if (tokens.isEmpty() || - (tokens.at(0) == QLatin1String("{"))) - { - ++i; - continue; - } - if (tokens.at(0) == QLatin1String("};")) - break; - if ((tokens.size() != 1 && tokens.size() != 3) || - (tokens.size() == 3 && tokens.at(1) != QLatin1String("="))) - { - if (tokens.size() == 4 && tokens.at(0) == QLatin1String("}") && tokens.at(3).endsWith(QLatin1Char(';')) && si) + if (!bFound) { - // enum in struct with direct decl of member - MemberInformation mi; - if (ns.isEmpty()) - mi.type = ei.type; - else - mi.type = ns + QStringLiteral("::") + ei.type; - mi.isEnum = true; - mi.name = tokens.at(1).toString(); - si->member.push_back(std::move(mi)); - break; + WARNING_LOG(m_logger) << "Could not find enum value '" << enumKey.toString() << "' in enum TelegramId"; + return -1; } - WARNING_LOG(m_logger) << "Could not parse enum: '" << lines.at(i).toString() << "', line: " << i + 1; - return -1; - } - - EnumValue ev; - ev.key = tokens.at(0).toString(); - if (tokens.size() == 3) - { - QStringView value = tokens.at(2); - if (value.endsWith(QLatin1Char(','))) - value.chop(1); - ev.value = value.toInt(); - } - else - { - int val = ei.values.isEmpty() ? 0 : (ei.values.last().value + 1); - ev.value = val; - } - ei.values.push_back(std::move(ev)); - ++i; - } - - DEBUG_LOG(m_logger) << "Found Enum: " << ei.type; - for (const EnumValue &ev : std::as_const(ei.values)) - DEBUG_LOG(m_logger) << "Member[" << i << "]: " << ev.key << " = " << ev.value; - - if (ei.type == QLatin1String("TelegramId")) - m_telegramIdEnum = ei; - - m_enums.push_back(std::move(ei)); - - return i; -} - -int LogViewTetraTelegramsParser::parseConstraint(const QVector &lines, int iStartPos) -{ - const QVector tokens = tokenize(lines.at(iStartPos)); - if (tokens.size() != 4) - { - WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(iStartPos).toString() << "'"; - return -1; - } - const QStringView &cs = tokens.at(3); - if (!cs.startsWith(QLatin1String("Constraints<")) || !cs.endsWith(QLatin1Char('>'))) - { - WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(iStartPos).toString() << "'"; - return -1; - } - QStringView structName = cs.mid(QLatin1String("Constraints<").size()); - structName.chop(1); - DEBUG_LOG(m_logger) << "Constraint: " << structName.toString(); - - int i = iStartPos + 1; - while (i < lines.size()) - { - const QVector tokens = tokenize(lines.at(i)); - if (tokens.isEmpty() || - (tokens.at(0) == QLatin1String("{"))) - { ++i; - continue; - } - if (tokens.at(0) == QLatin1String("};")) - break; - if (tokens.size() != 8 || tokens.at(2) != QLatin1String("TelegramId")) // static constexpr TelegramId id() { return TelegramId::INIT; } - { - ++i; - continue; - } - const QVector parts = tokens.at(6).split(u"::"); - if (parts.size() != 2) - { - WARNING_LOG(m_logger) << "Could not parse constraint: '" << lines.at(i).toString() << "'"; - return -1; } - QStringView enumKey = parts.at(1); - if (enumKey.endsWith(QLatin1Char(';'))) - enumKey.chop(1); - bool bFound = false; - for (const auto &v : std::as_const(m_telegramIdEnum.values)) - { - if (v.key == enumKey) - { - m_visibleTelegrams.insert(v.value, structName.toString()); - bFound = true; - break; - } - } - if (!bFound) - { - WARNING_LOG(m_logger) << "Could not find enum value '" << enumKey.toString() << "' in enum TelegramId"; - return -1; - } - ++i; + return i; } - return i; -} - -QString LogViewTetraTelegramsParser::getInnerType(const QString &type) -{ - int idxLt = type.lastIndexOf(QLatin1Char('>')); - if (idxLt < 0) - return QString(); - int idxGt = type.indexOf(QLatin1Char('<')); - if (idxGt < 0) - return QString(); - return type.mid(idxGt + 1, idxLt - idxGt - 1); -} - -void LogViewTetraTelegramsParser::categorizeMember(MemberInformation &mi) const -{ - mi.isPod = isPod(mi.type); - mi.isEnum = mi.isPod ? false : isEnum(mi.type); - if (mi.type.startsWith(QLatin1String("std::vector<"))) - mi.isArray = true; - mi.isStruct = mi.isArray ? false : isStruct(mi.type); - mi.isString = (mi.type == QLatin1String("std::string") || mi.type == QLatin1String("QString")); - mi.isBinary = (mi.type == QLatin1String("std::vector") || mi.type == QLatin1String("QByteArray")); -} - -static inline void bracketCount(const QStringView &str, int &cntLt, int &cntGt) -{ - cntLt = 0; - cntGt = 0; - for (int i = 0; i < str.size(); ++i) + QString LogViewTetraTelegramsParser::getInnerType(const QString &type) { - if (str.at(i) == QLatin1Char('<')) - cntLt++; - else if (str.at(i) == QLatin1Char('>')) - cntGt++; + int idxLt = type.lastIndexOf(QLatin1Char('>')); + if (idxLt < 0) + return QString(); + int idxGt = type.indexOf(QLatin1Char('<')); + if (idxGt < 0) + return QString(); + return type.mid(idxGt + 1, idxLt - idxGt - 1); } -} -QVector LogViewTetraTelegramsParser::tokenize(const QStringView &line) const -{ - QVector ret = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); - - // Calculate positions for each token (Qt6 QStringView has no position() method) - QVector positions(ret.size()); - int currentPos = 0; - for (int j = 0; j < ret.size(); ++j) + void LogViewTetraTelegramsParser::categorizeMember(MemberInformation &mi) const { - // Find position of this token in the original line - positions[j] = line.indexOf(ret[j], currentPos); - currentPos = positions[j] + ret[j].size(); + mi.isPod = isPod(mi.type); + mi.isEnum = mi.isPod ? false : isEnum(mi.type); + if (mi.type.startsWith(QLatin1String("std::vector<"))) + mi.isArray = true; + mi.isStruct = mi.isArray ? false : isStruct(mi.type); + mi.isString = (mi.type == QLatin1String("std::string") || mi.type == QLatin1String("QString")); + mi.isBinary = (mi.type == QLatin1String("std::vector") || mi.type == QLatin1String("QByteArray")); } - - int i = 0; - while (i < ret.size()) + + static inline void bracketCount(const QStringView &str, int &cntLt, int &cntGt) { + cntLt = 0; + cntGt = 0; + for (int i = 0; i < str.size(); ++i) + { + if (str.at(i) == QLatin1Char('<')) + cntLt++; + else if (str.at(i) == QLatin1Char('>')) + cntGt++; + } + } + + QVector LogViewTetraTelegramsParser::tokenize(const QStringView &line) const + { + QVector ret = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); + + // Calculate positions for each token (Qt6 QStringView has no position() method) + QVector positions(ret.size()); + int currentPos = 0; + for (int j = 0; j < ret.size(); ++j) + { + // Find position of this token in the original line + positions[j] = line.indexOf(ret[j], currentPos); + currentPos = positions[j] + ret[j].size(); + } + + int i = 0; + while (i < ret.size()) + { const QStringView &token = ret.at(i); - if (token.startsWith(QLatin1String("//"))) - { - // all comment after this - merge into one + if (token.startsWith(QLatin1String("//"))) + { + // all comment after this - merge into one + if (i == ret.size() - 1) + break; + const QStringView &lastToken = ret.last(); + const QStringView newToken = line.mid(positions[i], positions.last() - positions[i] + lastToken.size()); + DEBUG_LOG(m_logger) << "New Token: " << newToken.toString(); + ret.resize(i + 1); + ret[i] = newToken; + break; + } if (i == ret.size() - 1) break; - const QStringView &lastToken = ret.last(); - const QStringView newToken = line.mid(positions[i], positions.last() - positions[i] + lastToken.size()); - DEBUG_LOG(m_logger) << "New Token: " << newToken.toString(); - ret.resize(i + 1); - ret[i] = newToken; - break; - } - if (i == ret.size() - 1) - break; - int cntLt; - int cntGt; - bracketCount(token, cntLt, cntGt); - if (cntLt == cntGt) - { - ++i; - continue; - } + int cntLt; + int cntGt; + bracketCount(token, cntLt, cntGt); + if (cntLt == cntGt) + { + ++i; + continue; + } const QStringView &nextToken = ret.at(i + 1); const QStringView newToken = line.mid(positions[i], positions[i + 1] - positions[i] + nextToken.size()); - DEBUG_LOG(m_logger) << "New Token: " << newToken.toString(); - ret.removeAt(i + 1); - ret[i] = newToken; + DEBUG_LOG(m_logger) << "New Token: " << newToken.toString(); + ret.removeAt(i + 1); + ret[i] = newToken; + } + + return ret; } - return ret; -} + bool LogViewTetraTelegramsParser::validStructTokens(const QVector &tokens) + { + if (tokens.isEmpty() || (tokens.at(0) == QLatin1String("{")) || (tokens.at(0) == QLatin1String("{}")) || (tokens.at(0) == QLatin1String("}")) || + (tokens.at(0) == QLatin1String(":")) || (tokens.at(0) == QLatin1String(",")) || (tokens.at(0) == QLatin1String("virtual"))) + return false; + + if (tokens.at(0) == QLatin1String("};") || tokens.at(0) == QLatin1String("enum")) + return true; + + const int len = tokens.last().startsWith(QLatin1String("//")) ? tokens.size() - 1 : tokens.size(); + + if (len == 2) + return true; + + if (len < 4) + return false; + + if (len >= 4 && tokens.at(2) == QLatin1String("=")) + return true; -bool LogViewTetraTelegramsParser::validStructTokens(const QVector &tokens) -{ - if (tokens.isEmpty() || - (tokens.at(0) == QLatin1String("{")) || - (tokens.at(0) == QLatin1String("{}")) || - (tokens.at(0) == QLatin1String("}")) || - (tokens.at(0) == QLatin1String(":")) || - (tokens.at(0) == QLatin1String(",")) || - (tokens.at(0) == QLatin1String("virtual"))) return false; - - if (tokens.at(0) == QLatin1String("};") || tokens.at(0) == QLatin1String("enum")) - return true; - - const int len = tokens.last().startsWith(QLatin1String("//")) ? tokens.size() - 1 : tokens.size(); - - if (len == 2) - return true; - - if (len < 4) - return false; - - if (len >= 4 && tokens.at(2) == QLatin1String("=")) - return true; - - return false; -} + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.hpp index cc866425f..2a1c57e1c 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTetraTelegramsParser.hpp @@ -16,80 +16,82 @@ namespace N_LogView { -struct MemberInformation -{ - QString name; - QString type; - bool isArray = false; - bool isBinary = false; - bool isEnum = false; - bool isPod = false; - bool isString = false; - bool isStruct = false; - bool isVisible = true; -}; + struct MemberInformation + { + QString name; + QString type; + bool isArray = false; + bool isBinary = false; + bool isEnum = false; + bool isPod = false; + bool isString = false; + bool isStruct = false; + bool isVisible = true; + }; -struct StructInformation -{ - QString type; - QString baseStruct; // we only allow one base... + struct StructInformation + { + QString type; + QString baseStruct; // we only allow one base... - QVector member; - bool isVisible = false; -}; + QVector member; + bool isVisible = false; + }; -struct EnumValue -{ - QString key; - int value = 0; -}; + struct EnumValue + { + QString key; + int value = 0; + }; -struct EnumInformation -{ - QString ns; - QString type; - QVector values; -}; + struct EnumInformation + { + QString ns; + QString type; + QVector values; + }; -struct PodInformation -{ - QString type; - int byteLen = 0; - bool isBoolean = false; - bool isIntegral = false; - bool isSigned = false; -}; + struct PodInformation + { + QString type; + int byteLen = 0; + bool isBoolean = false; + bool isIntegral = false; + bool isSigned = false; + }; -class LogViewTetraTelegramsParser -{ -public: - LogViewTetraTelegramsParser(); + class LogViewTetraTelegramsParser + { + public: + LogViewTetraTelegramsParser(); - bool parse(const QString &filename); + bool parse(const QString &filename); - EnumInformation enumFromType(const QString &type) const; - StructInformation structFromType(const QString &type) const; - PodInformation podFromType(const QString &type) const; - bool isEnum(const QString &type) const; - bool isStruct(const QString &type) const; - bool isPod(const QString &type) const; - QHash telegramsToCreate() const { return m_visibleTelegrams; } - QString nameFromTelegramId(int telId) const { return m_visibleTelegrams.value(telId); } - static QString getInnerType(const QString &type); -private: - void insertPod(const QString &type, int byteLen, bool isSigned, bool isIntegral, bool isBoolean = false); - int parseStruct(const QVector &lines, int iStartPos); - int parseEnum(const QVector &lines, int iStartPos, const QString &ns, StructInformation *si = nullptr); - int parseConstraint(const QVector &lines, int iStartPos); - void categorizeMember(MemberInformation &mi) const; - QVector tokenize(const QStringView &line) const; - static bool validStructTokens(const QVector &tokens); -private: - EnumInformation m_telegramIdEnum; - QVector m_enums; - QHash m_structs; - QHash m_pods; - QHash m_visibleTelegrams; - NGL::INGLLogger &m_logger; -}; + EnumInformation enumFromType(const QString &type) const; + StructInformation structFromType(const QString &type) const; + PodInformation podFromType(const QString &type) const; + bool isEnum(const QString &type) const; + bool isStruct(const QString &type) const; + bool isPod(const QString &type) const; + QHash telegramsToCreate() const { return m_visibleTelegrams; } + QString nameFromTelegramId(int telId) const { return m_visibleTelegrams.value(telId); } + static QString getInnerType(const QString &type); + + private: + void insertPod(const QString &type, int byteLen, bool isSigned, bool isIntegral, bool isBoolean = false); + int parseStruct(const QVector &lines, int iStartPos); + int parseEnum(const QVector &lines, int iStartPos, const QString &ns, StructInformation *si = nullptr); + int parseConstraint(const QVector &lines, int iStartPos); + void categorizeMember(MemberInformation &mi) const; + QVector tokenize(const QStringView &line) const; + static bool validStructTokens(const QVector &tokens); + + private: + EnumInformation m_telegramIdEnum; + QVector m_enums; + QHash m_structs; + QHash m_pods; + QHash m_visibleTelegrams; + NGL::INGLLogger &m_logger; + }; } // namespace LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.cpp index 299b9fe33..93b4765f7 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewTextEdit.hpp" #include "LogViewField.hpp" #include "LogViewTelegram.hpp" @@ -18,79 +18,78 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewTextEdit::LogViewTextEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly) - : QLineEdit(a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) -{ - const QString value = a_field->value(0); - setText(value); - - if (a_readonly) + // --------------------------------------------------------------- + LogViewTextEdit::LogViewTextEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly) + : QLineEdit(a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) { - setReadOnly(true); - setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); - } + const QString value = a_field->value(0); + setText(value); - // set a validator for number of chars - uint16_t maxArraySize = a_field->maxArraySize(); - setMaxLength(maxArraySize); - updateToolTip(value); + if (a_readonly) + { + setReadOnly(true); + setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); + } - // make proper width of widget - QFontMetrics fm(font()); + // set a validator for number of chars + uint16_t maxArraySize = a_field->maxArraySize(); + setMaxLength(maxArraySize); + updateToolTip(value); + + // make proper width of widget + QFontMetrics fm(font()); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - setMinimumWidth(fm.width(QLatin1Char(' ') + value + QLatin1Char(' '))); + setMinimumWidth(fm.width(QLatin1Char(' ') + value + QLatin1Char(' '))); #else - setMinimumWidth(fm.horizontalAdvance(QLatin1Char(' ') + value + QLatin1Char(' '))); + setMinimumWidth(fm.horizontalAdvance(QLatin1Char(' ') + value + QLatin1Char(' '))); #endif - // connect signals - connect(this, &LogViewTextEdit::editingFinished, - this, &LogViewTextEdit::checkAndOvertakeContent); -} - - -// --------------------------------------------------------------- -void LogViewTextEdit::checkAndOvertakeContent() -{ - updateToolTip(text()); // fixme nach jedem zeichen updaten - m_Valid = true; -} - -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewTextEdit::saveContent(LogViewTelegram* a_telegram) -{ - if (!isValid()) - return false; - if (a_telegram->isJsonTelegram()) - { - a_telegram->setJsonValue(m_Field->jsonPath(), text()); + // connect signals + connect(this, &LogViewTextEdit::editingFinished, this, &LogViewTextEdit::checkAndOvertakeContent); } - else + + + // --------------------------------------------------------------- + void LogViewTextEdit::checkAndOvertakeContent() { - uint16_t size = getSize(); - QString content = text(); - uint16_t arraySize; - if (m_Field->isDynamicArray()) + updateToolTip(text()); // fixme nach jedem zeichen updaten + m_Valid = true; + } + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewTextEdit::saveContent(LogViewTelegram *a_telegram) + { + if (!isValid()) + return false; + if (a_telegram->isJsonTelegram()) { - arraySize = content.length(); - a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize); - // fixme: bei vielen Telegrammen muss Länge auf die Länge des Textes gesetzt werden. Dies kann nicht automatisch gemacht werden. Aber vielleicht kann man schauen, ob vor dem dyn. Array ein Feld Länge vorkommt, oder hartcodieren, oder konfigurierbaren + a_telegram->setJsonValue(m_Field->jsonPath(), text()); } else { - arraySize = m_Field->maxArraySize(); - } + uint16_t size = getSize(); + QString content = text(); + uint16_t arraySize; + if (m_Field->isDynamicArray()) + { + arraySize = content.length(); + a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize); + // fixme: bei vielen Telegrammen muss Länge auf die Länge des Textes gesetzt werden. Dies kann nicht automatisch gemacht werden. Aber vielleicht kann man schauen, ob vor dem dyn. Array ein Feld Länge vorkommt, oder hartcodieren, oder konfigurierbaren + } + else + { + arraySize = m_Field->maxArraySize(); + } - // copy the text - for (int i = 0; i < arraySize; i++) - a_telegram->setUIntX(size, i < content.length() ? content[i].toLatin1() : 0); + // copy the text + for (int i = 0; i < arraySize; i++) + a_telegram->setUIntX(size, i < content.length() ? content[i].toLatin1() : 0); + } + return true; } - return true; -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.hpp index 82cb1471d..957ce6c44 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewTextEdit.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewWidget.hpp" @@ -25,7 +25,9 @@ namespace N_LogView * @version 1.0 * @created 21-Mai-2010 10:28:05 */ - class LogViewTextEdit : public QLineEdit, public LogViewWidget + class LogViewTextEdit + : public QLineEdit + , public LogViewWidget { Q_OBJECT public: @@ -35,7 +37,7 @@ namespace N_LogView * @param a_parent * @param a_readonly */ - LogViewTextEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly); + LogViewTextEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly); /** * Writes the content into telegram. @@ -43,11 +45,10 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; protected slots: void checkAndOvertakeContent(); - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.cpp index ef1fe9f83..52f05bcdf 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewValueEdit.hpp" #include "LogViewField.hpp" #include "LogViewTelegram.hpp" @@ -18,118 +18,117 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewValueEdit::LogViewValueEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly) - : QLineEdit(a_parent) - , LogViewWidget(a_field, this, a_parent, a_readonly) - , m_IsFloat(false) -{ - const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); - m_IsFloat = (LogViewXdrStandardType::e_Float == stdType->getValueKind()); + // --------------------------------------------------------------- + LogViewValueEdit::LogViewValueEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly) + : QLineEdit(a_parent) + , LogViewWidget(a_field, this, a_parent, a_readonly) + , m_IsFloat(false) + { + const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); + m_IsFloat = (LogViewXdrStandardType::e_Float == stdType->getValueKind()); - const QString valueText = a_field->value(0); + const QString valueText = a_field->value(0); - setText(valueText); + setText(valueText); - // checkAndOvertakeContent(); - updateToolTip(valueText); + // checkAndOvertakeContent(); + updateToolTip(valueText); - // make proper width of widget - QFontMetrics fm(font()); + // make proper width of widget + QFontMetrics fm(font()); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - setMinimumWidth(fm.width(QLatin1Char(' ') + valueText + QLatin1Char(' '))); + setMinimumWidth(fm.width(QLatin1Char(' ') + valueText + QLatin1Char(' '))); #else - setMinimumWidth(fm.horizontalAdvance(QLatin1Char(' ') + valueText + QLatin1Char(' '))); + setMinimumWidth(fm.horizontalAdvance(QLatin1Char(' ') + valueText + QLatin1Char(' '))); #endif - if (a_readonly) - { - setReadOnly(true); - setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); - } - else - { - connect(this, &LogViewValueEdit::editingFinished, - this, &LogViewValueEdit::checkAndOvertakeContent); - } -} - - -// --------------------------------------------------------------- -void LogViewValueEdit::checkAndOvertakeContent() -{ - bool ok; - int64_t intValue = 0; - double floatValue = 0.0; - - // get the calculated and checked value - if (m_IsFloat) - floatValue = getFloat(text(), (uint64_t&)intValue, ok); - else - intValue = getInteger(text(), ok); - - // handle errors - if (!ok) - { - setFocus(); - selectAll(); - return; // abort - } - - // update - if (m_IsFloat) - setText(QString::number(floatValue)); - else - setText(QString::number(intValue)); - - updateToolTip(text()); -} - - -// --------------------------------------------------------------- -// Writes the content into telegram. -// Returns true if successful. -// --------------------------------------------------------------- -bool LogViewValueEdit::saveContent(LogViewTelegram* a_telegram) -{ - if (m_Valid) - { - bool ok; - if (m_IsFloat) + if (a_readonly) { - // save the float or double-value - uint64_t valueAsUint64; - const double value = getFloat(text(), valueAsUint64, ok); - if (ok) - { - if (a_telegram->isJsonTelegram()) - { - a_telegram->setJsonValue(m_Field->jsonPath(), value); - } - else - { - const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); - LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder(); - a_telegram->setUIntX(getSize(), valueAsUint64, byteOrder); - } - return true; - } + setReadOnly(true); + setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft); } else { - // save the integer-value - qint64 intValue = getInteger(text(), ok); - if (ok) - { - if (a_telegram->isJsonTelegram()) - a_telegram->setJsonValue(m_Field->jsonPath(), intValue); - else - a_telegram->setUIntX(getSize(), intValue); - return true; - } + connect(this, &LogViewValueEdit::editingFinished, this, &LogViewValueEdit::checkAndOvertakeContent); } } - return false; -} + + + // --------------------------------------------------------------- + void LogViewValueEdit::checkAndOvertakeContent() + { + bool ok; + int64_t intValue = 0; + double floatValue = 0.0; + + // get the calculated and checked value + if (m_IsFloat) + floatValue = getFloat(text(), (uint64_t &)intValue, ok); + else + intValue = getInteger(text(), ok); + + // handle errors + if (!ok) + { + setFocus(); + selectAll(); + return; // abort + } + + // update + if (m_IsFloat) + setText(QString::number(floatValue)); + else + setText(QString::number(intValue)); + + updateToolTip(text()); + } + + + // --------------------------------------------------------------- + // Writes the content into telegram. + // Returns true if successful. + // --------------------------------------------------------------- + bool LogViewValueEdit::saveContent(LogViewTelegram *a_telegram) + { + if (m_Valid) + { + bool ok; + if (m_IsFloat) + { + // save the float or double-value + uint64_t valueAsUint64; + const double value = getFloat(text(), valueAsUint64, ok); + if (ok) + { + if (a_telegram->isJsonTelegram()) + { + a_telegram->setJsonValue(m_Field->jsonPath(), value); + } + else + { + const LogViewXdrStandardType *stdType = static_cast(m_Field->xdrElement()); + LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder(); + a_telegram->setUIntX(getSize(), valueAsUint64, byteOrder); + } + return true; + } + } + else + { + // save the integer-value + qint64 intValue = getInteger(text(), ok); + if (ok) + { + if (a_telegram->isJsonTelegram()) + a_telegram->setJsonValue(m_Field->jsonPath(), intValue); + else + a_telegram->setUIntX(getSize(), intValue); + return true; + } + } + } + return false; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.hpp index d293ddd4b..5a61a3a1d 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewValueEdit.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewWidget.hpp" @@ -25,7 +25,9 @@ namespace N_LogView * @version 1.0 * @created 20-Mai-2010 14:47:50 */ - class LogViewValueEdit : public QLineEdit, public LogViewWidget + class LogViewValueEdit + : public QLineEdit + , public LogViewWidget { Q_OBJECT public: @@ -35,7 +37,7 @@ namespace N_LogView * @param a_parent * @param a_readonly */ - LogViewValueEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly); + LogViewValueEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly); /** * Writes the content into telegram. @@ -43,15 +45,13 @@ namespace N_LogView * * @param a_telegram */ - bool saveContent(LogViewTelegram* a_telegram) override; + bool saveContent(LogViewTelegram *a_telegram) override; protected: - bool m_IsFloat; protected slots: void checkAndOvertakeContent(); - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.cpp index 60ce593c9..94c0090f6 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewWidget.hpp" @@ -23,208 +23,210 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewWidget::LogViewWidget(LogViewField* a_field, QWidget* a_widget, QWidget* a_parent, bool a_readonly) - : m_Readonly(a_readonly) - , m_Valid(true) - , m_Widget(a_widget) - , m_Field(a_field) - , m_Parent(a_parent) - , m_logger(getLogger("LogViewWidget")) -{ -} - -// --------------------------------------------------------------- -uint16_t LogViewWidget::getSize() const -{ - // todo: check whether really a standardtype - const LogViewXdrStandardType* xdrStandardType = static_cast(m_Field->xdrElement()); - return xdrStandardType->getValueSize(); -} - -// --------------------------------------------------------------- -void LogViewWidget::showMessageBox(const QString &a_errorText) const -{ - QMessageBox::warning(m_Parent, QObject::tr("Fehler"), a_errorText); -} - -// --------------------------------------------------------------- -void LogViewWidget::updateToolTip(const QString &a_text) -{ - bool isList = m_Field->valueListSize() > 1 || m_Field->isDynamicArray(); - switch (m_Field->xdrElement()->getKind()) + // --------------------------------------------------------------- + LogViewWidget::LogViewWidget(LogViewField *a_field, QWidget *a_widget, QWidget *a_parent, bool a_readonly) + : m_Readonly(a_readonly) + , m_Valid(true) + , m_Widget(a_widget) + , m_Field(a_field) + , m_Parent(a_parent) + , m_logger(getLogger("LogViewWidget")) { - case LogViewXdrElement::e_KindStandardType: - switch (static_cast(m_Field->xdrElement())->getValueKind()) + } + + // --------------------------------------------------------------- + uint16_t LogViewWidget::getSize() const + { + // todo: check whether really a standardtype + const LogViewXdrStandardType *xdrStandardType = static_cast(m_Field->xdrElement()); + return xdrStandardType->getValueSize(); + } + + // --------------------------------------------------------------- + void LogViewWidget::showMessageBox(const QString &a_errorText) const + { + QMessageBox::warning(m_Parent, QObject::tr("Fehler"), a_errorText); + } + + // --------------------------------------------------------------- + void LogViewWidget::updateToolTip(const QString &a_text) + { + bool isList = m_Field->valueListSize() > 1 || m_Field->isDynamicArray(); + switch (m_Field->xdrElement()->getKind()) { - case LogViewXdrStandardType::e_Character: - m_Widget->setToolTip(QObject::tr("%1 Zeichen").arg(a_text.length())); - if (!m_Readonly) - m_Widget->setToolTip(QObject::tr("%1
Maximal %2 Zeichen erlaubt").arg(m_Widget->toolTip()).arg(m_Field->maxArraySize())); - break; - case LogViewXdrStandardType::e_Data: - if (m_Readonly) - m_Widget->setToolTip(QObject::tr("%1 Bytes").arg(m_Field->valueListSize())); - break; - case LogViewXdrStandardType::e_Unsigned: - case LogViewXdrStandardType::e_Signed: - if (m_Readonly && isList) + case LogViewXdrElement::e_KindStandardType: + switch (static_cast(m_Field->xdrElement())->getValueKind()) + { + case LogViewXdrStandardType::e_Character: + m_Widget->setToolTip(QObject::tr("%1 Zeichen").arg(a_text.length())); + if (!m_Readonly) + m_Widget->setToolTip(QObject::tr("%1
Maximal %2 Zeichen erlaubt").arg(m_Widget->toolTip()).arg(m_Field->maxArraySize())); + break; + case LogViewXdrStandardType::e_Data: + if (m_Readonly) + m_Widget->setToolTip(QObject::tr("%1 Bytes").arg(m_Field->valueListSize())); + break; + case LogViewXdrStandardType::e_Unsigned: + case LogViewXdrStandardType::e_Signed: + if (m_Readonly && isList) + { + m_Widget->setToolTip(QObject::tr("%1 Elemente").arg(m_Field->valueListSize())); + } + else + { + // fixme: bei 3-byte werten werden fälschlicherweise 4 Bytes angezeigt + if (m_Field->isDateTimeField()) + { + m_Widget->setToolTip(QObject::tr("Unixzeit: %1 ").arg(a_text)); + } + else + { + m_Widget->setToolTip(QString()); + } + // actual value in hex and binary + if (!isList) + { + int64_t value = a_text.toLong(); + m_Widget->setToolTip(QStringLiteral("%1%2 %3").arg(m_Widget->toolTip(), toHex(value), toBin(value))); + } + // range + if (!m_Field->isDateTimeField() && !m_Readonly) + { + const QString sep(isList ? QString() : QStringLiteral("
")); + m_Widget->setToolTip( + QStringLiteral("%1%2Wertebereich: %3..%4").arg(m_Widget->toolTip(), sep).arg(m_Field->getLowestValue()).arg(m_Field->getHighestValue())); + } + } + break; + case LogViewXdrStandardType::e_Float: + if (4 == m_Field->size()) + m_Widget->setToolTip(QStringLiteral("Wertebereich: +/-3.4e+/-38")); + else + m_Widget->setToolTip(QStringLiteral("Wertebereich: +/-1.7e+/-308")); + break; + case LogViewXdrStandardType::e_Boolean: + m_Widget->setToolTip(QStringLiteral("true/false")); + } + break; + case LogViewXdrElement::e_KindEnum: { - m_Widget->setToolTip(QObject::tr("%1 Elemente").arg(m_Field->valueListSize())); + uint64_t enumValue = a_text.toLong(); + m_Widget->setToolTip(QStringLiteral("%1 %2 %3").arg(enumValue).arg(toHex(enumValue), toBin(enumValue))); + break; } - else + default: + ERROR_LOG(m_logger) << "Case not implemented"; + } + } + + + // --------------------------------------------------------------- + double LogViewWidget::getFloat(const QString &a_text, uint64_t &a_FloatAsData, bool &a_ok, const bool a_reverse) + { + // INFO_LOG(m_logger) << "a_text=" << a_text.toStdString(); + + //LogViewXdrStandardType::E_ByteOrder byteOrder = ((LogViewXdrStandardType*)m_Field->xdrElement())->getByteOrder(); + double value; + if (8 == getSize()) + { + value = a_text.toDouble(&a_ok); + a_FloatAsData = LogViewTelegram::doubleToXdr(value); + } + else + { + value = a_text.toFloat(&a_ok); + a_FloatAsData = LogViewTelegram::floatToXdr(value); + } + + // show error-message + // fixme zeige fehler genauer + if (!a_ok) + showMessageBox(QStringLiteral("Inalid real value: '%1'").arg(a_text)); + + m_Valid = a_ok; + + // swap for display data on table + if (a_reverse) + { + int j = getSize() - 1; + uint64_t *ptr = &a_FloatAsData; + for (int i = 0; i < getSize() / 2; i++) { - // fixme: bei 3-byte werten werden fälschlicherweise 4 Bytes angezeigt - if (m_Field->isDateTimeField()) - { - m_Widget->setToolTip(QObject::tr("Unixzeit: %1 ").arg(a_text)); - } - else - { - m_Widget->setToolTip(QString()); - } - // actual value in hex and binary - if (!isList) - { - int64_t value = a_text.toLong(); - m_Widget->setToolTip(QStringLiteral("%1%2 %3").arg(m_Widget->toolTip(), toHex(value), toBin(value))); - } - // range - if (!m_Field->isDateTimeField() && !m_Readonly) - { - const QString sep(isList ? QString() : QStringLiteral("
")); - m_Widget->setToolTip(QStringLiteral("%1%2Wertebereich: %3..%4").arg(m_Widget->toolTip(), sep).arg(m_Field->getLowestValue()).arg(m_Field->getHighestValue())); - } + uint8_t data = ((uint8_t *)ptr)[j]; + ((uint8_t *)&a_FloatAsData)[j] = ((uint8_t *)&a_FloatAsData)[i]; + ((uint8_t *)&a_FloatAsData)[i] = data; + j--; } - break; - case LogViewXdrStandardType::e_Float: - if (4 == m_Field->size()) - m_Widget->setToolTip(QStringLiteral("Wertebereich: +/-3.4e+/-38")); - else - m_Widget->setToolTip(QStringLiteral("Wertebereich: +/-1.7e+/-308")); - break; - case LogViewXdrStandardType::e_Boolean: - m_Widget->setToolTip(QStringLiteral("true/false")); - } - break; - case LogViewXdrElement::e_KindEnum: - { - uint64_t enumValue = a_text.toLong(); - m_Widget->setToolTip(QStringLiteral("%1 %2 %3").arg(enumValue).arg(toHex(enumValue), toBin(enumValue))); - break; - } - default: - ERROR_LOG(m_logger) << "Case not implemented"; - } -} - -// --------------------------------------------------------------- -double LogViewWidget::getFloat(const QString& a_text, uint64_t& a_FloatAsData, bool& a_ok, const bool a_reverse) -{ -// INFO_LOG(m_logger) << "a_text=" << a_text.toStdString(); - - //LogViewXdrStandardType::E_ByteOrder byteOrder = ((LogViewXdrStandardType*)m_Field->xdrElement())->getByteOrder(); - double value; - if (8 == getSize()) - { - value = a_text.toDouble(&a_ok); - a_FloatAsData = LogViewTelegram::doubleToXdr(value); - } else { - value = a_text.toFloat(&a_ok); - a_FloatAsData = LogViewTelegram::floatToXdr(value); - } - - // show error-message - // fixme zeige fehler genauer - if (!a_ok) - showMessageBox(QStringLiteral("Inalid real value: '%1'").arg(a_text)); - - m_Valid = a_ok; - - // swap for display data on table - if (a_reverse) - { - int j = getSize() - 1; - uint64_t* ptr = &a_FloatAsData; - for (int i = 0; i < getSize() / 2; i++) + // set the upper 4 bytes to 0 for float + if (4 == getSize()) { - uint8_t data = ((uint8_t*)ptr)[j]; - ((uint8_t*)&a_FloatAsData)[j] = ((uint8_t*)&a_FloatAsData)[i]; - ((uint8_t*)&a_FloatAsData)[i] = data; - j--; + ((uint8_t *)&a_FloatAsData)[4] = 0; + ((uint8_t *)&a_FloatAsData)[5] = 0; + ((uint8_t *)&a_FloatAsData)[6] = 0; + ((uint8_t *)&a_FloatAsData)[7] = 0; } + return value; } - // set the upper 4 bytes to 0 for float - if (4 == getSize()) - { - ((uint8_t*)&a_FloatAsData)[4] = 0; - ((uint8_t*)&a_FloatAsData)[5] = 0; - ((uint8_t*)&a_FloatAsData)[6] = 0; - ((uint8_t*)&a_FloatAsData)[7] = 0; - } - return value; -} - -// --------------------------------------------------------------- -// Converts a_text into a signed integer and returns it. The -// parameter a_ok will be true if all was successful. The -// attribute m_Valid will be set to a_ok. -// The range will be checked, if the value is out of range, an -// error will be shown as messge-box and a_ok will be false. -// The input a_text can be a calculation. -// --------------------------------------------------------------- -int64_t LogViewWidget::getInteger(const QString& a_text, bool& a_ok) -{ - // calculate the expression into a number - N_SST::IntegerCalculator calculator; - N_SST::IntegerCalculator::E_Error error; - int64_t value = calculator.calc(a_text.toStdString(), error); - m_Valid = false; - a_ok = true; - if (N_SST::IntegerCalculator::e_Ok != error) + // --------------------------------------------------------------- + // Converts a_text into a signed integer and returns it. The + // parameter a_ok will be true if all was successful. The + // attribute m_Valid will be set to a_ok. + // The range will be checked, if the value is out of range, an + // error will be shown as messge-box and a_ok will be false. + // The input a_text can be a calculation. + // --------------------------------------------------------------- + int64_t LogViewWidget::getInteger(const QString &a_text, bool &a_ok) { - // todo: show exact error-message - if (a_text != m_LastErrorValueText) + // calculate the expression into a number + N_SST::IntegerCalculator calculator; + N_SST::IntegerCalculator::E_Error error; + int64_t value = calculator.calc(a_text.toStdString(), error); + m_Valid = false; + a_ok = true; + if (N_SST::IntegerCalculator::e_Ok != error) { - showMessageBox(QString::fromUtf8("Die Berechnung '%1' ist falsch").arg(a_text)); - m_LastErrorValueText = a_text; - } - a_ok = false; - } - else - { - // check the range - int64_t highest = m_Field->getHighestValue(); - if (value > highest) - { - a_ok = false; - // fixme: dieser Trick mit m_LastErrorValueText ist für den Benutzer etwas verwirrend, da - // plötzlich keine Reaktion mehr auf Tab, Ok oder wählen eines anderen Feldes passiert... + // todo: show exact error-message if (a_text != m_LastErrorValueText) { - showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu hoch. Maximalwert: %2").arg(a_text).arg(highest)); + showMessageBox(QString::fromUtf8("Die Berechnung '%1' ist falsch").arg(a_text)); m_LastErrorValueText = a_text; } - return value; // abort - } - int64_t lowest = m_Field->getLowestValue(); - if (value < lowest) - { a_ok = false; - if (a_text != m_LastErrorValueText) - { - showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu tief. Minimalwert: %2").arg(a_text).arg(lowest)); - m_LastErrorValueText = a_text; - } - return value; // abort } - m_Valid = true; + else + { + // check the range + int64_t highest = m_Field->getHighestValue(); + if (value > highest) + { + a_ok = false; + // fixme: dieser Trick mit m_LastErrorValueText ist für den Benutzer etwas verwirrend, da + // plötzlich keine Reaktion mehr auf Tab, Ok oder wählen eines anderen Feldes passiert... + if (a_text != m_LastErrorValueText) + { + showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu hoch. Maximalwert: %2").arg(a_text).arg(highest)); + m_LastErrorValueText = a_text; + } + return value; // abort + } + int64_t lowest = m_Field->getLowestValue(); + if (value < lowest) + { + a_ok = false; + if (a_text != m_LastErrorValueText) + { + showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu tief. Minimalwert: %2").arg(a_text).arg(lowest)); + m_LastErrorValueText = a_text; + } + return value; // abort + } + m_Valid = true; + } + return value; } - return value; -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.hpp index 5e7c6ff22..2c241316a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewWidget.hpp @@ -22,54 +22,52 @@ class QFont; namespace N_LogView { -template -inline QString toHex(T num) -{ - return QStringLiteral("0x%1").arg(num, 2, 16, QLatin1Char('0')); -} -template -inline QString toBin(T num) -{ - return QStringLiteral("0b%1").arg(num, 8, 2, QLatin1Char('0')); -} + template inline QString toHex(T num) + { + return QStringLiteral("0x%1").arg(num, 2, 16, QLatin1Char('0')); + } + template inline QString toBin(T num) + { + return QStringLiteral("0b%1").arg(num, 8, 2, QLatin1Char('0')); + } -class LogViewField; -class LogViewTelegram; + class LogViewField; + class LogViewTelegram; -/** + /** * @author alois.wismer * @version 1.0 * @created 20-Mai-2010 14:51:17 */ -class LogViewWidget -{ -public: - LogViewWidget(LogViewField* a_field, QWidget* a_widget, QWidget* a_parent, bool a_readonly); - virtual ~LogViewWidget() = default; + class LogViewWidget + { + public: + LogViewWidget(LogViewField *a_field, QWidget *a_widget, QWidget *a_parent, bool a_readonly); + virtual ~LogViewWidget() = default; - virtual uint16_t getSize() const; - LogViewField* field() const { return m_Field; } - bool isValid() const { return m_Valid; } + virtual uint16_t getSize() const; + LogViewField *field() const { return m_Field; } + bool isValid() const { return m_Valid; } - /** + /** * The content if the field is a text-field */ - QString getText() const { return m_Text; } + QString getText() const { return m_Text; } - /** + /** * Writes the content into telegram. * Returns true if successful. * * @param a_telegram */ - virtual bool saveContent(LogViewTelegram* a_telegram) = 0; + virtual bool saveContent(LogViewTelegram *a_telegram) = 0; -protected: - void showMessageBox(const QString &a_errorText) const; - void updateToolTip(const QString &a_text = QString()); - double getFloat(const QString& a_text, uint64_t& a_FloatAsData, bool& a_ok, const bool a_reverse = false); + protected: + void showMessageBox(const QString &a_errorText) const; + void updateToolTip(const QString &a_text = QString()); + double getFloat(const QString &a_text, uint64_t &a_FloatAsData, bool &a_ok, const bool a_reverse = false); - /** + /** * Converts a_text into a signed integer and returns it. The parameter a_ok will * be true if all was successful. The attribute m_Valid will be set to a_ok. * The range will be checked, if the value is out of range, an error will be shown @@ -79,24 +77,24 @@ protected: * @param a_text * @param a_ok */ - int64_t getInteger(const QString& a_text, bool& a_ok); + int64_t getInteger(const QString &a_text, bool &a_ok); -protected: - bool m_Readonly; - bool m_Valid; - /** + protected: + bool m_Readonly; + bool m_Valid; + /** * The content if the field is a text-field */ - QString m_Text; - QString m_LastErrorValueText; - QWidget *m_Widget; + QString m_Text; + QString m_LastErrorValueText; + QWidget *m_Widget; - LogViewField *m_Field; + LogViewField *m_Field; - QWidget *m_Parent; + QWidget *m_Parent; - LOGGER_T m_logger; -}; + LOGGER_T m_logger; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.cpp index 29ca61294..b964c2193 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.cpp @@ -1,14 +1,14 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** #include "LogViewXdrElement.hpp" @@ -16,46 +16,46 @@ namespace N_LogView { -// --------------------------------------------------------------- -// Constructor of a struct or enum -// --------------------------------------------------------------- -LogViewXdrElement::LogViewXdrElement(const QString& a_name, const E_ElementKind a_kind, const char *loggerName) - : m_Name(a_name) - , m_Kind(a_kind) - , m_logger(getLogger(loggerName)) -{ - if (a_name.indexOf(QLatin1Char('<')) >= 0 || a_name.indexOf(QLatin1Char('[')) >= 0) - ERROR_LOG(m_logger) << "Element \'" << a_name.toStdString() << "\' has a problem"; -} - -// --------------------------------------------------------------- -void LogViewXdrElement::dump() const -{ - INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName(); -} - - -// --------------------------------------------------------------- -QString LogViewXdrElement::getKindName() const -{ - switch (getKind()) + // --------------------------------------------------------------- + // Constructor of a struct or enum + // --------------------------------------------------------------- + LogViewXdrElement::LogViewXdrElement(const QString &a_name, const E_ElementKind a_kind, const char *loggerName) + : m_Name(a_name) + , m_Kind(a_kind) + , m_logger(getLogger(loggerName)) { - case e_KindDefine: - return QLatin1String("Define"); - case e_KindEnum: - return QLatin1String("Enum"); - case e_KindEnumElement: - return QLatin1String("EnumElement"); - case e_KindStandardType: - return QLatin1String("StandardType"); - case e_KindStruct: - return QLatin1String("Struct"); - case e_KindStructElement: - return QLatin1String("StructElement"); - case e_KindTypedef: - return QLatin1String("Typedef"); + if (a_name.indexOf(QLatin1Char('<')) >= 0 || a_name.indexOf(QLatin1Char('[')) >= 0) + ERROR_LOG(m_logger) << "Element \'" << a_name.toStdString() << "\' has a problem"; + } + + // --------------------------------------------------------------- + void LogViewXdrElement::dump() const + { + INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName(); + } + + + // --------------------------------------------------------------- + QString LogViewXdrElement::getKindName() const + { + switch (getKind()) + { + case e_KindDefine: + return QLatin1String("Define"); + case e_KindEnum: + return QLatin1String("Enum"); + case e_KindEnumElement: + return QLatin1String("EnumElement"); + case e_KindStandardType: + return QLatin1String("StandardType"); + case e_KindStruct: + return QLatin1String("Struct"); + case e_KindStructElement: + return QLatin1String("StructElement"); + case e_KindTypedef: + return QLatin1String("Typedef"); + } + return QStringLiteral("Unknown (%1)").arg(getKind()); } - return QStringLiteral("Unknown (%1)").arg(getKind()); -} } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.hpp index 72765998a..106a90ef2 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrElement.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -26,7 +26,6 @@ namespace N_LogView class LogViewXdrElement { public: - /** * @author alois.wismer * @version 1.0 @@ -52,10 +51,10 @@ namespace N_LogView * @param a_name * @param a_kind */ - LogViewXdrElement(const QString& a_name, const E_ElementKind a_kind, const char *loggerName); + LogViewXdrElement(const QString &a_name, const E_ElementKind a_kind, const char *loggerName); public: - const QString& getName() const { return m_Name; } + const QString &getName() const { return m_Name; } LogViewXdrElement::E_ElementKind getKind() const { return m_Kind; } virtual void dump() const; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.cpp index a3f1c7f7c..3b36af497 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewXdrParser.hpp" #include @@ -30,345 +30,379 @@ namespace N_LogView { -LogViewXdrParser::LogViewXdrParser() - : m_WithinComment(false) - , m_LineNbr(0) - , m_DoReadUntilSemicolon(false) - , m_WordListIndex(0) - , m_ActElement(nullptr) - , m_State(e_ParseMain) - , m_logger(getLogger("LogViewXdrParser")) -{} - -LogViewXdrParser::~LogViewXdrParser() -{ - for (const auto &elem : m_ElementMap) - delete elem.second; -} - -// --------------------------------------------------------------- -void LogViewXdrParser::addStandardType(const QString& a_name, const uint16_t a_dataSize, const uint16_t a_realSize, const LogViewXdrStandardType::E_ValueKind a_kind, const LogViewXdrStandardType::E_DynArraySizeMethod a_dynArraySizeMethod, const LogViewXdrStandardType::E_ByteOrder a_byteOrder) -{ - QString name = a_name.trimmed(); - auto ptr = new LogViewXdrStandardType(name, a_dataSize, a_realSize, a_kind, a_dynArraySizeMethod, a_byteOrder); - if (!addToElementMap(name, ptr)) - delete ptr; - if ((a_dynArraySizeMethod == LogViewXdrStandardType::e_DynArrayIndex || a_dynArraySizeMethod == LogViewXdrStandardType::e_DynArrayIndexDiv8) - && a_kind != LogViewXdrStandardType::e_Unsigned) - showErrorMessage(QObject::tr("Standard-typ \'%1\': e_DynArrayIndex oder e_DynArrayIndexDiv darf nur mit e_Unsigned verwendet werden!")); -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::parseX_File(const QString& a_fileName) -{ - for (const auto &elem : m_ElementMap) - delete elem.second; - m_ElementMap.clear(); - m_DefinesMap.clear(); - m_TelegramMap.clear(); - m_LineNbr = 0; - m_WordListIndex = 0; - m_WithinComment = false; - m_ActElement = nullptr; - m_State = e_ParseMain; - - // define some (XDR-)standard-types - addStandardType(QLatin1String("unsigned short"), 4, 2, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("unsigned int"), 4, 4, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("short"), 4, 2, LogViewXdrStandardType::e_Signed); - addStandardType(QLatin1String("int"), 4, 4, LogViewXdrStandardType::e_Signed); - addStandardType(QLatin1String("u_int"), 4, 4, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("char"), 4, 2, LogViewXdrStandardType::e_Character); - addStandardType(QLatin1String("unsigned char"), 4, 1, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("unsigned long"), 4, 4, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("u_long"), 4, 4, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("u_short"), 4, 2, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("float"), 4, 4, LogViewXdrStandardType::e_Float, LogViewXdrStandardType::e_DynArrayMsgLength, LogViewXdrStandardType::e_ByteOrderBigEndian); - addStandardType(QLatin1String("double"), 8, 8, LogViewXdrStandardType::e_Float, LogViewXdrStandardType::e_DynArrayMsgLength, LogViewXdrStandardType::e_ByteOrderBigEndian); - addStandardType(QLatin1String("opaque"), 1, 1, LogViewXdrStandardType::e_Data); - addStandardType(QLatin1String("string"), 1, 1, LogViewXdrStandardType::e_Character); - - // for tetra-telegrams - addStandardType(QLatin1String("alpha"), 1, 1, LogViewXdrStandardType::e_Character); - addStandardType(QLatin1String("UInt8"), 1, 1, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("UInt16"), 2, 2, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("UInt24"), 3, 3, LogViewXdrStandardType::e_Unsigned); - addStandardType(QLatin1String("SInt8"), 1, 1, LogViewXdrStandardType::e_Signed); - addStandardType(QLatin1String("SInt16"), 2, 2, LogViewXdrStandardType::e_Signed); - addStandardType(QLatin1String("SInt24"), 3, 3, LogViewXdrStandardType::e_Signed); - // little-endian values (for TETRA-header) - addStandardType(QLatin1String("UInt16LE"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayMsgLength, LogViewXdrStandardType::e_ByteOrderLittleEndian); - addStandardType(QLatin1String("UInt32LE"), 4, 4, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayMsgLength, LogViewXdrStandardType::e_ByteOrderLittleEndian); - // index for next dyn. array (only for TETRA) - addStandardType(QLatin1String("UInt8Idx"), 1, 1, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndex); - addStandardType(QLatin1String("UInt16Idx"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndex); - addStandardType(QLatin1String("UInt16LEIdx"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndex, LogViewXdrStandardType::e_ByteOrderLittleEndian); - // index (div 8) for next dyn. array (only for TETRA) - addStandardType(QLatin1String("UInt8IdxDiv8"), 1, 1, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndexDiv8); - addStandardType(QLatin1String("UInt16IdxDiv8"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndexDiv8); - - const auto DEFINE_NAME = QLatin1String("%#define"); - - // parse the file - m_Filename = a_fileName; - m_State = e_ParseMain; - QFile xFile(a_fileName); - if (xFile.open(QIODevice::ReadOnly | QIODevice::Text)) + LogViewXdrParser::LogViewXdrParser() + : m_WithinComment(false) + , m_LineNbr(0) + , m_DoReadUntilSemicolon(false) + , m_WordListIndex(0) + , m_ActElement(nullptr) + , m_State(e_ParseMain) + , m_logger(getLogger("LogViewXdrParser")) { - QString lastLines; - uint32_t lastLinesCount = 0; - QTextStream in(&xFile); - while (!in.atEnd()) - { - m_Line = lastLines + QLatin1Char(' ') + in.readLine(); - m_Line = m_Line.simplified(); - m_LineNbr++; -// INFO_LOG(m_logger) << m_LineNbr << ": " << m_Line.toStdString(); + } - // ignore lines with % - if (m_Line.startsWith(QLatin1Char('%')) && !m_Line.startsWith(DEFINE_NAME)) - { - continue; - } + LogViewXdrParser::~LogViewXdrParser() + { + for (const auto &elem : m_ElementMap) + delete elem.second; + } - // remove comments (sourounded with /* */) - const QString cleanLine = removeComments(m_Line).simplified(); + // --------------------------------------------------------------- + void LogViewXdrParser::addStandardType(const QString &a_name, + const uint16_t a_dataSize, + const uint16_t a_realSize, + const LogViewXdrStandardType::E_ValueKind a_kind, + const LogViewXdrStandardType::E_DynArraySizeMethod a_dynArraySizeMethod, + const LogViewXdrStandardType::E_ByteOrder a_byteOrder) + { + QString name = a_name.trimmed(); + auto ptr = new LogViewXdrStandardType(name, a_dataSize, a_realSize, a_kind, a_dynArraySizeMethod, a_byteOrder); + if (!addToElementMap(name, ptr)) + delete ptr; + if ((a_dynArraySizeMethod == LogViewXdrStandardType::e_DynArrayIndex || a_dynArraySizeMethod == LogViewXdrStandardType::e_DynArrayIndexDiv8) && + a_kind != LogViewXdrStandardType::e_Unsigned) + showErrorMessage(QObject::tr("Standard-typ \'%1\': e_DynArrayIndex oder e_DynArrayIndexDiv darf nur mit e_Unsigned verwendet werden!")); + } - // ignore empty lines - if (cleanLine.isEmpty()) - { - continue; - } -// INFO_LOG(m_logger) << "w/o comment: \'" << cleanLine.toStdString() << "\'"; - // read in whole construct - if (m_DoReadUntilSemicolon && !cleanLine.endsWith(QLatin1Char(';'))) - { - lastLines = cleanLine; - m_LineNbr--; - lastLinesCount++; - continue; - } - - lastLines.clear(); - - // check whether it is the begin of a construct - if (e_ParseMain == m_State) - { - if (cleanLine.startsWith(QLatin1String("union "))) - { - m_State = e_ParseUnion; - } - else if (cleanLine.startsWith(QLatin1String("struct "))) - { - m_State = e_ParseStruct; - } - } - - // parse the line when we are within - switch (m_State) - { - case e_ParseUnion: - parseUnion(cleanLine); - break; - case e_ParseStruct: - parseStruct(cleanLine); - break; - case e_ParseEnum: - parseEnum(cleanLine); - break; - default: - if (m_Line.startsWith(DEFINE_NAME)) - { - parseDefine(m_Line.mid(DEFINE_NAME.size())); - } - else if (cleanLine.startsWith(QLatin1String("typedef "))) - { - parseTypedef(cleanLine); - } - else if (cleanLine.startsWith(QLatin1String("enum "))) - { - parseEnum(cleanLine.mid(5)); - } - else if (cleanLine.startsWith(QLatin1String("enum8 "))) - { - parseEnum(cleanLine.mid(6), 1); - } - else if (cleanLine.startsWith(QLatin1String("enum16 "))) - { - parseEnum(cleanLine.mid(7), 2); - } - } - - if (lastLinesCount > 0) - { - m_LineNbr += lastLinesCount; - lastLinesCount = 0; - } - } - xFile.close(); - // erase all parsing-values (otherwise errormessages will have wrong informations) + // --------------------------------------------------------------- + void LogViewXdrParser::parseX_File(const QString &a_fileName) + { + for (const auto &elem : m_ElementMap) + delete elem.second; + m_ElementMap.clear(); + m_DefinesMap.clear(); + m_TelegramMap.clear(); m_LineNbr = 0; - m_Line.clear(); - } - else - { - QMessageBox::warning(nullptr, QLatin1String("Dateifehler"), QStringLiteral("Konnte die Datei %1 nicht öffnen").arg(a_fileName)); - } -} + m_WordListIndex = 0; + m_WithinComment = false; + m_ActElement = nullptr; + m_State = e_ParseMain; + // define some (XDR-)standard-types + addStandardType(QLatin1String("unsigned short"), 4, 2, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("unsigned int"), 4, 4, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("short"), 4, 2, LogViewXdrStandardType::e_Signed); + addStandardType(QLatin1String("int"), 4, 4, LogViewXdrStandardType::e_Signed); + addStandardType(QLatin1String("u_int"), 4, 4, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("char"), 4, 2, LogViewXdrStandardType::e_Character); + addStandardType(QLatin1String("unsigned char"), 4, 1, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("unsigned long"), 4, 4, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("u_long"), 4, 4, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("u_short"), 4, 2, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("float"), + 4, + 4, + LogViewXdrStandardType::e_Float, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderBigEndian); + addStandardType(QLatin1String("double"), + 8, + 8, + LogViewXdrStandardType::e_Float, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderBigEndian); + addStandardType(QLatin1String("opaque"), 1, 1, LogViewXdrStandardType::e_Data); + addStandardType(QLatin1String("string"), 1, 1, LogViewXdrStandardType::e_Character); -// --------------------------------------------------------------- -QString LogViewXdrParser::removeComments(const QString& a_line) -{ - static const QChar slash(QLatin1Char('/')); - static const QChar asterik(QLatin1Char('*')); - // remove comments (sourounded with /* */) - QString cleanLine; cleanLine.reserve(a_line.size()); - QString::const_iterator iter = a_line.begin(); - QString::const_iterator end = a_line.end(); - while (iter != end) - { - if (!m_WithinComment) + // for tetra-telegrams + addStandardType(QLatin1String("alpha"), 1, 1, LogViewXdrStandardType::e_Character); + addStandardType(QLatin1String("UInt8"), 1, 1, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("UInt16"), 2, 2, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("UInt24"), 3, 3, LogViewXdrStandardType::e_Unsigned); + addStandardType(QLatin1String("SInt8"), 1, 1, LogViewXdrStandardType::e_Signed); + addStandardType(QLatin1String("SInt16"), 2, 2, LogViewXdrStandardType::e_Signed); + addStandardType(QLatin1String("SInt24"), 3, 3, LogViewXdrStandardType::e_Signed); + // little-endian values (for TETRA-header) + addStandardType(QLatin1String("UInt16LE"), + 2, + 2, + LogViewXdrStandardType::e_Unsigned, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderLittleEndian); + addStandardType(QLatin1String("UInt32LE"), + 4, + 4, + LogViewXdrStandardType::e_Unsigned, + LogViewXdrStandardType::e_DynArrayMsgLength, + LogViewXdrStandardType::e_ByteOrderLittleEndian); + // index for next dyn. array (only for TETRA) + addStandardType(QLatin1String("UInt8Idx"), 1, 1, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndex); + addStandardType(QLatin1String("UInt16Idx"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndex); + addStandardType(QLatin1String("UInt16LEIdx"), + 2, + 2, + LogViewXdrStandardType::e_Unsigned, + LogViewXdrStandardType::e_DynArrayIndex, + LogViewXdrStandardType::e_ByteOrderLittleEndian); + // index (div 8) for next dyn. array (only for TETRA) + addStandardType(QLatin1String("UInt8IdxDiv8"), 1, 1, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndexDiv8); + addStandardType(QLatin1String("UInt16IdxDiv8"), 2, 2, LogViewXdrStandardType::e_Unsigned, LogViewXdrStandardType::e_DynArrayIndexDiv8); + + const auto DEFINE_NAME = QLatin1String("%#define"); + + // parse the file + m_Filename = a_fileName; + m_State = e_ParseMain; + QFile xFile(a_fileName); + if (xFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - // does comment begin? - if (slash == *iter) + QString lastLines; + uint32_t lastLinesCount = 0; + QTextStream in(&xFile); + while (!in.atEnd()) { - if (++iter != end) + m_Line = lastLines + QLatin1Char(' ') + in.readLine(); + m_Line = m_Line.simplified(); + m_LineNbr++; + // INFO_LOG(m_logger) << m_LineNbr << ": " << m_Line.toStdString(); + + // ignore lines with % + if (m_Line.startsWith(QLatin1Char('%')) && !m_Line.startsWith(DEFINE_NAME)) { - if (asterik == *iter) + continue; + } + + // remove comments (sourounded with /* */) + const QString cleanLine = removeComments(m_Line).simplified(); + + // ignore empty lines + if (cleanLine.isEmpty()) + { + continue; + } + + // INFO_LOG(m_logger) << "w/o comment: \'" << cleanLine.toStdString() << "\'"; + // read in whole construct + if (m_DoReadUntilSemicolon && !cleanLine.endsWith(QLatin1Char(';'))) + { + lastLines = cleanLine; + m_LineNbr--; + lastLinesCount++; + continue; + } + + lastLines.clear(); + + // check whether it is the begin of a construct + if (e_ParseMain == m_State) + { + if (cleanLine.startsWith(QLatin1String("union "))) { - // yes, comment begins - m_WithinComment = true; + m_State = e_ParseUnion; + } + else if (cleanLine.startsWith(QLatin1String("struct "))) + { + m_State = e_ParseStruct; + } + } + + // parse the line when we are within + switch (m_State) + { + case e_ParseUnion: + parseUnion(cleanLine); + break; + case e_ParseStruct: + parseStruct(cleanLine); + break; + case e_ParseEnum: + parseEnum(cleanLine); + break; + default: + if (m_Line.startsWith(DEFINE_NAME)) + { + parseDefine(m_Line.mid(DEFINE_NAME.size())); + } + else if (cleanLine.startsWith(QLatin1String("typedef "))) + { + parseTypedef(cleanLine); + } + else if (cleanLine.startsWith(QLatin1String("enum "))) + { + parseEnum(cleanLine.mid(5)); + } + else if (cleanLine.startsWith(QLatin1String("enum8 "))) + { + parseEnum(cleanLine.mid(6), 1); + } + else if (cleanLine.startsWith(QLatin1String("enum16 "))) + { + parseEnum(cleanLine.mid(7), 2); + } + } + + if (lastLinesCount > 0) + { + m_LineNbr += lastLinesCount; + lastLinesCount = 0; + } + } + xFile.close(); + // erase all parsing-values (otherwise errormessages will have wrong informations) + m_LineNbr = 0; + m_Line.clear(); + } + else + { + QMessageBox::warning(nullptr, QLatin1String("Dateifehler"), QStringLiteral("Konnte die Datei %1 nicht öffnen").arg(a_fileName)); + } + } + + + // --------------------------------------------------------------- + QString LogViewXdrParser::removeComments(const QString &a_line) + { + static const QChar slash(QLatin1Char('/')); + static const QChar asterik(QLatin1Char('*')); + // remove comments (sourounded with /* */) + QString cleanLine; + cleanLine.reserve(a_line.size()); + QString::const_iterator iter = a_line.begin(); + QString::const_iterator end = a_line.end(); + while (iter != end) + { + if (!m_WithinComment) + { + // does comment begin? + if (slash == *iter) + { + if (++iter != end) + { + if (asterik == *iter) + { + // yes, comment begins + m_WithinComment = true; + } + else + { + // no comment begin + cleanLine.append(slash); + cleanLine.append(*iter); + } } else { - // no comment begin + // end of line cleanLine.append(slash); - cleanLine.append(*iter); } } else { - // end of line - cleanLine.append(slash); + // no + cleanLine.append(*iter); } } else { - // no - cleanLine.append(*iter); + // does comment end? + if (asterik == *iter) + { + if (++iter != end) + { + if (slash == *iter) + { + m_WithinComment = false; + } + } + } + } + if (iter != end) + ++iter; + } + return cleanLine; + } + + + // --------------------------------------------------------------- + void LogViewXdrParser::parseTypedef(const QString &a_line) + { + fillWordList(a_line); + + // typedef: "typedef telegramm_id_int_et telegramm_id_et;" + // ------- + // keyword 'typedef' + if (isNextWord("typedef")) + { + // get type + bool ok; + QString type = getNextType(ok); + // fixme: make boolean for structure wrong and gray out telegrams with wrong struct + getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure + // get name + QString name = getNextWord("Name"); + if (name.isEmpty()) + return; + if (!isNextWord(";")) + return; + // all ok + uint16_t dynArrayOffset; + uint16_t arraySize = parseArray(name, dynArrayOffset); + LogViewXdrType *typedefElement = new LogViewXdrType(name, type, arraySize, dynArrayOffset, LogViewXdrElement::e_KindTypedef); + if (!addToElementMap(name, typedefElement)) + delete typedefElement; + } + } + + + // --------------------------------------------------------------- + void LogViewXdrParser::parseDefine(const QString &a_line) + { + const QString line = a_line.trimmed(); + int sepPos = line.indexOf(QLatin1Char(' ')); + if (sepPos >= 0) + { + const QString name = line.left(sepPos).trimmed(); + QStringView substitution = line.mid(sepPos).trimmed(); + sepPos = substitution.indexOf(QLatin1Char(' ')); + if (sepPos >= 0) + substitution = substitution.left(sepPos).trimmed(); + + // convert to number + bool ok = false; + const int64_t value = calcValue(substitution.toString(), ok); + if (ok) + { + //INFO_LOG(m_logger) << "Define: name=" << name.toStdString() << " subst=" << substitution.toStdString() << " value=" << value; + m_DefinesMap.insert(std::make_pair(name, LogViewXdrValue(name, value, LogViewXdrElement::e_KindDefine))); } } else { - // does comment end? - if (asterik == *iter) + showErrorMessage(QObject::tr("Space zwischen define-name und substitution nicht gefunden")); + } + } + + + // --------------------------------------------------------------- + void LogViewXdrParser::parseEnum(const QString &a_line, const uint16_t a_enumSize) + { + if (QLatin1String("};") != a_line) + { + switch (m_State) { - if (++iter != end) - { - if (slash == *iter) + default: + // first line of enum containing the name + // i.e.: "enum telegramm_id_int_et {" + if (a_line.endsWith(QLatin1String(" {"))) { - m_WithinComment = false; + m_State = e_ParseEnum; + const QString name = a_line.left(a_line.length() - 2).trimmed(); + m_ActElement = new LogViewXdrStruct(name, LogViewXdrElement::e_KindEnum, a_enumSize); + if (!addToElementMap(name, m_ActElement)) + { + delete m_ActElement; + m_ActElement = nullptr; + return; + } } - } - } - } - if (iter != end) - ++iter; - } - return cleanLine; -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::parseTypedef(const QString &a_line) -{ - fillWordList(a_line); - - // typedef: "typedef telegramm_id_int_et telegramm_id_et;" - // ------- - // keyword 'typedef' - if (isNextWord("typedef")) - { - // get type - bool ok; - QString type = getNextType(ok); - // fixme: make boolean for structure wrong and gray out telegrams with wrong struct - getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure - // get name - QString name = getNextWord("Name"); - if (name.isEmpty()) return; - if (!isNextWord(";")) return; - // all ok - uint16_t dynArrayOffset; - uint16_t arraySize = parseArray(name, dynArrayOffset); - LogViewXdrType* typedefElement = new LogViewXdrType(name, type, arraySize, dynArrayOffset, LogViewXdrElement::e_KindTypedef); - if (!addToElementMap(name, typedefElement)) - delete typedefElement; - } -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::parseDefine(const QString &a_line) -{ - const QString line = a_line.trimmed(); - int sepPos = line.indexOf(QLatin1Char(' ')); - if (sepPos >= 0) - { - const QString name = line.left(sepPos).trimmed(); - QStringView substitution = line.mid(sepPos).trimmed(); - sepPos = substitution.indexOf(QLatin1Char(' ')); - if (sepPos >= 0) - substitution = substitution.left(sepPos).trimmed(); - - // convert to number - bool ok = false; - const int64_t value = calcValue(substitution.toString(), ok); - if (ok) - { - //INFO_LOG(m_logger) << "Define: name=" << name.toStdString() << " subst=" << substitution.toStdString() << " value=" << value; - m_DefinesMap.insert(std::make_pair(name, LogViewXdrValue(name, value, LogViewXdrElement::e_KindDefine))); - } - } - else - { - showErrorMessage(QObject::tr("Space zwischen define-name und substitution nicht gefunden")); - } -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::parseEnum(const QString &a_line, const uint16_t a_enumSize) -{ - if (QLatin1String("};") != a_line) - { - switch(m_State) - { - default: - // first line of enum containing the name - // i.e.: "enum telegramm_id_int_et {" - if (a_line.endsWith(QLatin1String(" {"))) - { - m_State = e_ParseEnum; - const QString name = a_line.left(a_line.length()-2).trimmed(); - m_ActElement = new LogViewXdrStruct(name, LogViewXdrElement::e_KindEnum, a_enumSize); - if (!addToElementMap(name, m_ActElement)) + else { - delete m_ActElement; - m_ActElement = nullptr; - return; + showErrorMessage(QObject::tr("Endet nicht mit {")); } - } - else - { - showErrorMessage(QObject::tr("Endet nicht mit {")); - } - break; + break; - case e_ParseEnum: + case e_ParseEnum: { // middle lines of struct containing the elements // i.e.: "MANIPULATIONSMELDUNG = 2," @@ -393,625 +427,643 @@ void LogViewXdrParser::parseEnum(const QString &a_line, const uint16_t a_enumSiz } } break; - } - } - else - { - // end of struct - m_State = e_ParseMain; - //INFO_LOG(m_logger) << "CheckEnum " << m_ActElement->getName().toStdString(); -// check(*m_ActElement); - } -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::parseStruct(const QString &a_line) -{ - fillWordList(a_line); - if (!m_DoReadUntilSemicolon) - { - // first line of struct: "struct gef_wirkfeld_flaechendeckendes_feuer_meldung_rt {" - // -------------------- - // keyword 'union' - if (isNextWord("struct")) - { - // union name - QString structName = getNextWord("Struktur-Name"); - if (structName.isEmpty()) return; - if (!isNextWord("{")) return; - // all ok => proceed parsing union - m_ActElement = new LogViewXdrStruct(structName, LogViewXdrElement::e_KindStruct); - if (!addToElementMap(structName, m_ActElement)) - { - delete m_ActElement; - m_ActElement = nullptr; - return; } - m_State = e_ParseStruct; - m_DoReadUntilSemicolon = true; - } - } - else - { - if (!isNextWord("}", false)) - { - // next lines of struct: "gef_header_rt:3..6 header;" - // -------------------- - // get type - bool ok; - QString type = getNextType(ok); - if (!ok) return; - // fixme: make boolean for structure wrong and gray out telegrams with wrong struct - if (m_UnionType != type) getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure - // get bitfield (if any) ":2..5" - int16_t firstBit = -1; - int16_t lastBit = -1; - bool isLast = true; - if (isNextWord(":", false)) - { - isNextWord(":"); - QString bitfield = getNextWord("Bitfield"); - isLast = parseBitfield(bitfield, firstBit, lastBit); - } - // get name - QString name = getNextWord("Name"); - if (name.isEmpty()) return; - if (!isNextWord(";")) return; - // all ok - uint16_t dynArrayOffset; - uint16_t arraySize = parseArray(name, dynArrayOffset); - if(firstBit >= 0) - DEBUG_LOG(m_logger) << "Add Element " << name - << " with type " << type - << " array size: " << arraySize - << " first:last " << firstBit << ":" << lastBit - << " isLast: " << isLast; - m_ActElement->addElement(name, type, arraySize, dynArrayOffset, LogViewXdrElement::e_KindStructElement, firstBit, lastBit, isLast); } else { - // end of struct "};" - if (!isNextWord("}")) return; - if (!isNextWord(";")) return; + // end of struct m_State = e_ParseMain; - m_DoReadUntilSemicolon = false; -// INFO_LOG(m_logger) << "CheckStruct \'" << m_ActElement->getName().toStdString() << "\'"; -// if (m_ActElement->getName() != "intern_tele") // fixme: remove this structure from element-map -// { -// check(*m_ActElement); -// } + //INFO_LOG(m_logger) << "CheckEnum " << m_ActElement->getName().toStdString(); + // check(*m_ActElement); } } -} -// --------------------------------------------------------------- -void LogViewXdrParser::parseUnion(const QString& a_line) -{ - // we can not really parse the union, we expect that only 1 union exists, and this - // union holds all the telegrams, which we insert into a telegram-list - static const LogViewXdrStruct* telegramIdType = nullptr; - - fillWordList(a_line); - if (!m_DoReadUntilSemicolon) + // --------------------------------------------------------------- + void LogViewXdrParser::parseStruct(const QString &a_line) { - // first line of union "union gef_tg_nd_ switch (gef_telegramm_id_et telegramm_id) {" - // ------------------- - // keyword 'union' - if (isNextWord("union")) + fillWordList(a_line); + if (!m_DoReadUntilSemicolon) { - // union name - m_UnionType = getNextWord("Union-Typ"); - if (m_UnionType.isEmpty()) return; - // keyword 'switch' - if (!isNextWord("switch")) return; - if (!isNextWord("(")) return; - // telegram-id-type - getNextEnum(telegramIdType); - if (telegramIdType == nullptr) return; - // telegram-id-name - QString name = getNextWord("Parameter-Name"); - if (name.isEmpty()) return; - if (!isNextWord(")")) return; - if (!isNextWord("{")) return; - // all ok => proceed parsing union - m_State = e_ParseUnion; - m_DoReadUntilSemicolon = true; - } - } - else - { - if (!isNextWord("}", false)) - { - QString keyword = getNextWord(); - if (keyword == QLatin1String("case")) + // first line of struct: "struct gef_wirkfeld_flaechendeckendes_feuer_meldung_rt {" + // -------------------- + // keyword 'union' + if (isNextWord("struct")) { - // next lines of union "case GEF_INIT: gef_init_meldung_rt init_meldung;" - // ------------------- - QStringList constExprList; - QString type; - do + // union name + QString structName = getNextWord("Struktur-Name"); + if (structName.isEmpty()) + return; + if (!isNextWord("{")) + return; + // all ok => proceed parsing union + m_ActElement = new LogViewXdrStruct(structName, LogViewXdrElement::e_KindStruct); + if (!addToElementMap(structName, m_ActElement)) { - // get constant-expression - QString constExpression = getNextWord("Konstanten-Ausdruck"); - if (constExpression.isEmpty()) return; - constExprList << constExpression; - // check double-point - if (!isNextWord(":")) return; - // get type or another case - type = getNextWord("Typ"); - if (type.isEmpty()) return; + delete m_ActElement; + m_ActElement = nullptr; + return; } - while (type == QLatin1String("case")); + m_State = e_ParseStruct; + m_DoReadUntilSemicolon = true; + } + } + else + { + if (!isNextWord("}", false)) + { + // next lines of struct: "gef_header_rt:3..6 header;" + // -------------------- + // get type + bool ok; + QString type = getNextType(ok); + if (!ok) + return; // fixme: make boolean for structure wrong and gray out telegrams with wrong struct - getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure + if (m_UnionType != type) + getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure + // get bitfield (if any) ":2..5" + int16_t firstBit = -1; + int16_t lastBit = -1; + bool isLast = true; + if (isNextWord(":", false)) + { + isNextWord(":"); + QString bitfield = getNextWord("Bitfield"); + isLast = parseBitfield(bitfield, firstBit, lastBit); + } // get name QString name = getNextWord("Name"); - if (name.isEmpty()) return; - // check semicolon - if (!isNextWord(";")) return; - - for (const QString &constExpr : std::as_const(constExprList)) + if (name.isEmpty()) + return; + if (!isNextWord(";")) + return; + // all ok + uint16_t dynArrayOffset; + uint16_t arraySize = parseArray(name, dynArrayOffset); + if (firstBit >= 0) + DEBUG_LOG(m_logger) << "Add Element " << name << " with type " << type << " array size: " << arraySize << " first:last " << firstBit << ":" << lastBit + << " isLast: " << isLast; + m_ActElement->addElement(name, type, arraySize, dynArrayOffset, LogViewXdrElement::e_KindStructElement, firstBit, lastBit, isLast); + } + else + { + // end of struct "};" + if (!isNextWord("}")) + return; + if (!isNextWord(";")) + return; + m_State = e_ParseMain; + m_DoReadUntilSemicolon = false; + // INFO_LOG(m_logger) << "CheckStruct \'" << m_ActElement->getName().toStdString() << "\'"; + // if (m_ActElement->getName() != "intern_tele") // fixme: remove this structure from element-map + // { + // check(*m_ActElement); + // } + } + } + } + + + // --------------------------------------------------------------- + void LogViewXdrParser::parseUnion(const QString &a_line) + { + // we can not really parse the union, we expect that only 1 union exists, and this + // union holds all the telegrams, which we insert into a telegram-list + static const LogViewXdrStruct *telegramIdType = nullptr; + + fillWordList(a_line); + if (!m_DoReadUntilSemicolon) + { + // first line of union "union gef_tg_nd_ switch (gef_telegramm_id_et telegramm_id) {" + // ------------------- + // keyword 'union' + if (isNextWord("union")) + { + // union name + m_UnionType = getNextWord("Union-Typ"); + if (m_UnionType.isEmpty()) + return; + // keyword 'switch' + if (!isNextWord("switch")) + return; + if (!isNextWord("(")) + return; + // telegram-id-type + getNextEnum(telegramIdType); + if (telegramIdType == nullptr) + return; + // telegram-id-name + QString name = getNextWord("Parameter-Name"); + if (name.isEmpty()) + return; + if (!isNextWord(")")) + return; + if (!isNextWord("{")) + return; + // all ok => proceed parsing union + m_State = e_ParseUnion; + m_DoReadUntilSemicolon = true; + } + } + else + { + if (!isNextWord("}", false)) + { + QString keyword = getNextWord(); + if (keyword == QLatin1String("case")) { - bool error; - int32_t telegramId = static_cast(telegramIdType->getChildValue(constExpr, &error)); - if (!error) + // next lines of union "case GEF_INIT: gef_init_meldung_rt init_meldung;" + // ------------------- + QStringList constExprList; + QString type; + do { - m_TelegramMap.insert(std::make_pair(telegramId, LogViewXdrType(constExpr, type, 1, 0, LogViewXdrElement::e_KindEnumElement))); // fixme: e_KindCaseElement und 1 entfernen - } - else + // get constant-expression + QString constExpression = getNextWord("Konstanten-Ausdruck"); + if (constExpression.isEmpty()) + return; + constExprList << constExpression; + // check double-point + if (!isNextWord(":")) + return; + // get type or another case + type = getNextWord("Typ"); + if (type.isEmpty()) + return; + } while (type == QLatin1String("case")); + // fixme: make boolean for structure wrong and gray out telegrams with wrong struct + getElement(type); // do not abort when type does not exist, otherwise we will never get an error, when we try to show a telegram with a wrong structure + // get name + QString name = getNextWord("Name"); + if (name.isEmpty()) + return; + // check semicolon + if (!isNextWord(";")) + return; + + for (const QString &constExpr : std::as_const(constExprList)) { - showErrorMessage(QObject::tr("\'%1\' ist nicht definiert in \'%2\'").arg(constExpr, telegramIdType->getName())); + bool error; + int32_t telegramId = static_cast(telegramIdType->getChildValue(constExpr, &error)); + if (!error) + { + m_TelegramMap.insert( + std::make_pair(telegramId, LogViewXdrType(constExpr, type, 1, 0, LogViewXdrElement::e_KindEnumElement))); // fixme: e_KindCaseElement und 1 entfernen + } + else + { + showErrorMessage(QObject::tr("\'%1\' ist nicht definiert in \'%2\'").arg(constExpr, telegramIdType->getName())); + } } } - } - else if (keyword == QLatin1String("default")) - { - // check double-point - if (isNextWord(":")) + else if (keyword == QLatin1String("default")) { - QString defaultDefinition = getNextWord(); - if (defaultDefinition == QLatin1String("void")) + // check double-point + if (isNextWord(":")) { - isNextWord(";"); - // all ok - } - else - { - showErrorMessage(QObject::tr("default: muss void; enthalten. Falls nicht, muss das richtige Verhalten implementiert werden...")); + QString defaultDefinition = getNextWord(); + if (defaultDefinition == QLatin1String("void")) + { + isNextWord(";"); + // all ok + } + else + { + showErrorMessage(QObject::tr("default: muss void; enthalten. Falls nicht, muss das richtige Verhalten implementiert werden...")); + } } } + else + { + showErrorMessage(QObject::tr("Erwarte Keyword case oder default statt \'%1\'").arg(keyword)); + } } else { - showErrorMessage(QObject::tr("Erwarte Keyword case oder default statt \'%1\'").arg(keyword)); + // end of union "};" + if (!isNextWord("}")) + return; + if (!isNextWord(";")) + return; + m_State = e_ParseMain; + m_DoReadUntilSemicolon = false; + //check(*m_ActElement); } } + } + + + // --------------------------------------------------------------- + bool LogViewXdrParser::parseEnumLine(const QString &a_line, QString &a_name, QString &a_value) const + { + QString line; + if (a_line.endsWith(QLatin1Char(','))) + { + line = a_line.left(a_line.length() - 1); + } else { - // end of union "};" - if (!isNextWord("}")) return; - if (!isNextWord(";")) return; - m_State = e_ParseMain; - m_DoReadUntilSemicolon = false; - //check(*m_ActElement); + line = a_line; } - } -} + line = line.trimmed(); - -// --------------------------------------------------------------- -bool LogViewXdrParser::parseEnumLine(const QString& a_line, QString& a_name, QString& a_value) const -{ - QString line; - if (a_line.endsWith(QLatin1Char(','))) - { - line = a_line.left(a_line.length()-1); - } - else - { - line = a_line; - } - line = line.trimmed(); - - int sepPos = line.lastIndexOf(QLatin1Char('=')); - if (-1 != sepPos) - { - a_name = line.left(sepPos).trimmed(); - a_value = line.mid(sepPos+1).trimmed(); - return true; - } - else - { - showErrorMessage(QObject::tr("konnte Trennzeichen \'=\' zwischen Name und Wert nicht finden!")); - } - return false; // failure happenend -} - - -// --------------------------------------------------------------- -// Shows an error-message containing the line-nbr, the line -// itself and an additional error-text -// --------------------------------------------------------------- -void LogViewXdrParser::showErrorMessage(const QString& a_errorText) const -{ - const auto tlws = QApplication::topLevelWidgets(); - QMessageBox::warning(tlws.size() ? tlws.first() : nullptr, - QObject::tr("Telegram Structure Parser"), - QStringLiteral("%4:%1:
%2


%3").arg(m_LineNbr).arg(m_Line, a_errorText, m_Filename)); -} - - -// --------------------------------------------------------------- -int64_t LogViewXdrParser::calcValue(const QString& a_calcText, bool& a_isOk) -{ - // ignore strings - a_isOk = false; - int64_t value = 0; - if (!a_calcText.startsWith(QLatin1Char('\"'))) - { - N_SST::IntegerCalculator::E_Error error; - std::string errorText; - value = calc(a_calcText.toStdString(), error, &errorText); - - // show error if one happend - if (error != N_SST::IntegerCalculator::e_Ok) + int sepPos = line.lastIndexOf(QLatin1Char('=')); + if (-1 != sepPos) { - switch (error) - { - case N_SST::IntegerCalculator::e_DivisionByZero: - showErrorMessage(QObject::tr("Division durch 0 nicht erlaubt!")); - break; - case N_SST::IntegerCalculator::e_InvalidOperand: - showErrorMessage(QObject::tr("Operand %1 ist fehlerhaft!").arg(QString::fromStdString(errorText))); - break; - case N_SST::IntegerCalculator::e_MissingLeftParanthesis: - showErrorMessage(QObject::tr("Es fehlen Klammer Öffnungen (!")); - break; - case N_SST::IntegerCalculator::e_MissingRightParanthesis: - showErrorMessage(QObject::tr("Es fehlen Klammer Schliessungen )!")); - break; - case N_SST::IntegerCalculator::e_NoOperandBetweenOperators: - showErrorMessage(QObject::tr("Zwei Operationen (%1) nacheinander sind nicht erlaubt!").arg(QString::fromStdString(errorText))); - break; - case N_SST::IntegerCalculator::e_UnknownOperationOrVariable: - showErrorMessage(QObject::tr("Operation oder Variable %1 unbekannt!").arg(QString::fromStdString(errorText))); - break; - case N_SST::IntegerCalculator::e_UnknownError: - showErrorMessage(QObject::tr("Unbekannter Fehler!")); - break; - default: - break; - } - ERROR_LOG(m_logger) << "Problem with converting '" << a_calcText << "' to integer"; + a_name = line.left(sepPos).trimmed(); + a_value = line.mid(sepPos + 1).trimmed(); + return true; } else { - a_isOk = true; + showErrorMessage(QObject::tr("konnte Trennzeichen \'=\' zwischen Name und Wert nicht finden!")); } + return false; // failure happenend } - return value; -} -// --------------------------------------------------------------- -bool LogViewXdrParser::getVariableValue(const std::string& a_variableName, int64_t& a_value) const -{ - return getDefine(QString::fromStdString(a_variableName), a_value); -} - -// --------------------------------------------------------------- -// This function delivers the name of the telegram and the -// name of its structure. The telegram will be defined with -// a_telegramId. -// The name will be delivered as return-parameter; the -// structure-name as out parameter a_structName. -// If the telegram was not found, error-texts instead names -// will be returned. -// --------------------------------------------------------------- -QString LogViewXdrParser::getTelegramName(int a_telegramId) const -{ - const auto iter = m_TelegramMap.find(a_telegramId); - if (m_TelegramMap.end() != iter) - return iter->second.getName(); - - return QObject::tr("").arg(a_telegramId); -} - -// --------------------------------------------------------------- -QString LogViewXdrParser::getStructName(int a_telegramId) const -{ - const auto iter = m_TelegramMap.find(a_telegramId); - if (m_TelegramMap.end() != iter) - return iter->second.getType(); - - return QObject::tr("").arg(a_telegramId); -} - -// --------------------------------------------------------------- -bool LogViewXdrParser::getDefine(const QString& a_name, int64_t& a_value) const -{ - const auto iter = m_DefinesMap.find(a_name); - if (iter != m_DefinesMap.end()) + // --------------------------------------------------------------- + // Shows an error-message containing the line-nbr, the line + // itself and an additional error-text + // --------------------------------------------------------------- + void LogViewXdrParser::showErrorMessage(const QString &a_errorText) const { - a_value = iter->second.getValue(); - return true; + const auto tlws = QApplication::topLevelWidgets(); + QMessageBox::warning(tlws.size() ? tlws.first() : nullptr, + QObject::tr("Telegram Structure Parser"), + QStringLiteral("%4:%1:
%2


%3").arg(m_LineNbr).arg(m_Line, a_errorText, m_Filename)); } - return false; -} -// --------------------------------------------------------------- -const LogViewXdrElement* LogViewXdrParser::getElement(const QString& a_name) const -{ - const auto iter = m_ElementMap.find(a_name); - if (iter != m_ElementMap.end()) - return iter->second; - - showErrorMessage(QObject::tr("Typ \'%1\' nicht definiert!").arg(a_name)); - return nullptr; -} - - -// --------------------------------------------------------------- -uint16_t LogViewXdrParser::parseArray(QString& a_name, uint16_t& a_dynArrayMsgOffset) const -{ - a_dynArrayMsgOffset = 0; - QString oldName = a_name; - - // is it a static array []? - // ------------------------ - int pos = a_name.indexOf(QLatin1Char('[')); - if (pos >= 0) + // --------------------------------------------------------------- + int64_t LogViewXdrParser::calcValue(const QString &a_calcText, bool &a_isOk) { - int endPos = a_name.indexOf(QLatin1Char(']')); - if (endPos > pos) + // ignore strings + a_isOk = false; + int64_t value = 0; + if (!a_calcText.startsWith(QLatin1Char('\"'))) { - // get the array-size - QString arraySizeText = a_name.mid(pos+1, endPos-pos-1); - // set new name - a_name = a_name.left(pos); -// INFO_LOG(m_logger) << "new a_name=" << a_name.toStdString() << " arraySizeText=" << arraySizeText.toStdString(); - int64_t arraySizeValue = 1; - // check whether it is a define - if (!getDefine(arraySizeText, arraySizeValue)) + N_SST::IntegerCalculator::E_Error error; + std::string errorText; + value = calc(a_calcText.toStdString(), error, &errorText); + + // show error if one happend + if (error != N_SST::IntegerCalculator::e_Ok) { - bool ok = false; - arraySizeValue = arraySizeText.toInt(&ok); - if (!ok) + switch (error) { - showErrorMessage(QObject::tr("%1: [%2] is not a number").arg(oldName, arraySizeText)); + case N_SST::IntegerCalculator::e_DivisionByZero: + showErrorMessage(QObject::tr("Division durch 0 nicht erlaubt!")); + break; + case N_SST::IntegerCalculator::e_InvalidOperand: + showErrorMessage(QObject::tr("Operand %1 ist fehlerhaft!").arg(QString::fromStdString(errorText))); + break; + case N_SST::IntegerCalculator::e_MissingLeftParanthesis: + showErrorMessage(QObject::tr("Es fehlen Klammer Öffnungen (!")); + break; + case N_SST::IntegerCalculator::e_MissingRightParanthesis: + showErrorMessage(QObject::tr("Es fehlen Klammer Schliessungen )!")); + break; + case N_SST::IntegerCalculator::e_NoOperandBetweenOperators: + showErrorMessage(QObject::tr("Zwei Operationen (%1) nacheinander sind nicht erlaubt!").arg(QString::fromStdString(errorText))); + break; + case N_SST::IntegerCalculator::e_UnknownOperationOrVariable: + showErrorMessage(QObject::tr("Operation oder Variable %1 unbekannt!").arg(QString::fromStdString(errorText))); + break; + case N_SST::IntegerCalculator::e_UnknownError: + showErrorMessage(QObject::tr("Unbekannter Fehler!")); + break; + default: + break; } + ERROR_LOG(m_logger) << "Problem with converting '" << a_calcText << "' to integer"; + } + else + { + a_isOk = true; } -// INFO_LOG(m_logger) << "ArraySize=" << arraySizeValue; - return arraySizeValue; - } - else - { - showErrorMessage(QObject::tr("%1: Did not found expected ']'").arg(oldName)); } + return value; } - else - { - // is it an dynamic array <>? - // -------------------------- - //INFO_LOG(m_logger) << "check for <"; - pos = a_name.indexOf(QLatin1Char('<')); + + // --------------------------------------------------------------- + bool LogViewXdrParser::getVariableValue(const std::string &a_variableName, int64_t &a_value) const + { + return getDefine(QString::fromStdString(a_variableName), a_value); + } + + // --------------------------------------------------------------- + // This function delivers the name of the telegram and the + // name of its structure. The telegram will be defined with + // a_telegramId. + // The name will be delivered as return-parameter; the + // structure-name as out parameter a_structName. + // If the telegram was not found, error-texts instead names + // will be returned. + // --------------------------------------------------------------- + QString LogViewXdrParser::getTelegramName(int a_telegramId) const + { + const auto iter = m_TelegramMap.find(a_telegramId); + if (m_TelegramMap.end() != iter) + return iter->second.getName(); + + return QObject::tr("").arg(a_telegramId); + } + + // --------------------------------------------------------------- + QString LogViewXdrParser::getStructName(int a_telegramId) const + { + const auto iter = m_TelegramMap.find(a_telegramId); + if (m_TelegramMap.end() != iter) + return iter->second.getType(); + + return QObject::tr("").arg(a_telegramId); + } + + // --------------------------------------------------------------- + bool LogViewXdrParser::getDefine(const QString &a_name, int64_t &a_value) const + { + const auto iter = m_DefinesMap.find(a_name); + if (iter != m_DefinesMap.end()) + { + a_value = iter->second.getValue(); + return true; + } + return false; + } + + + // --------------------------------------------------------------- + const LogViewXdrElement *LogViewXdrParser::getElement(const QString &a_name) const + { + const auto iter = m_ElementMap.find(a_name); + if (iter != m_ElementMap.end()) + return iter->second; + + showErrorMessage(QObject::tr("Typ \'%1\' nicht definiert!").arg(a_name)); + return nullptr; + } + + + // --------------------------------------------------------------- + uint16_t LogViewXdrParser::parseArray(QString &a_name, uint16_t &a_dynArrayMsgOffset) const + { + a_dynArrayMsgOffset = 0; + QString oldName = a_name; + + // is it a static array []? + // ------------------------ + int pos = a_name.indexOf(QLatin1Char('[')); if (pos >= 0) { - int endPos = a_name.indexOf(QLatin1Char('>')); + int endPos = a_name.indexOf(QLatin1Char(']')); if (endPos > pos) { // get the array-size - QString arraySizeText = a_name.mid(pos+1, endPos-pos-1); - //INFO_LOG(m_logger) << "pos=" << pos << " endPos=" << endPos << " => " << arraySizeText.toStdString(); + QString arraySizeText = a_name.mid(pos + 1, endPos - pos - 1); // set new name a_name = a_name.left(pos); -// INFO_LOG(m_logger) << "new a_name=" << a_name.toStdString() << " arraySizeText=" << arraySizeText.toStdString(); - // check whether it is a define + // INFO_LOG(m_logger) << "new a_name=" << a_name.toStdString() << " arraySizeText=" << arraySizeText.toStdString(); int64_t arraySizeValue = 1; + // check whether it is a define if (!getDefine(arraySizeText, arraySizeValue)) { bool ok = false; arraySizeValue = arraySizeText.toInt(&ok); if (!ok) { - showErrorMessage(QObject::tr("%1: \'%2\' is not a number").arg(a_name, arraySizeText)); - } - else - { -// INFO_LOG(m_logger) << "a_name=" << a_name.toStdString() << " a_dynArrayMsgOffset=" << a_dynArrayMsgOffset; + showErrorMessage(QObject::tr("%1: [%2] is not a number").arg(oldName, arraySizeText)); } } - a_dynArrayMsgOffset = arraySizeValue; -// INFO_LOG(m_logger) << a_name.toStdString() << " is a dynamic array with size=" << arraySizeValue; - return 0; + // INFO_LOG(m_logger) << "ArraySize=" << arraySizeValue; + return arraySizeValue; } else { - showErrorMessage(QObject::tr("%1: Did not found expected '>'").arg(a_name)); - } - } - } - return 1; -} - - -// --------------------------------------------------------------- -bool LogViewXdrParser::isNextWord(const char *a_word, const bool a_doIncrement) -{ - const QString word = QString::fromUtf8(a_word); - bool ok = (m_WordListIndex < m_WordList.size() && - m_WordList.at(m_WordListIndex) == word); - - // show error-message - if (!ok && a_doIncrement) - { - if (m_WordListIndex > 0) - showErrorMessage(QObject::tr("Erwarte %1 nach \'%2\'!").arg(word, m_WordList.at(m_WordListIndex-1))); - else - showErrorMessage(QObject::tr("Erwarte %1!").arg(word)); - } - - if (a_doIncrement) - m_WordListIndex++; - return ok; -} - - -// --------------------------------------------------------------- -void LogViewXdrParser::fillWordList(const QString& a_line) -{ - QString line = a_line; - line.replace(QLatin1Char('('), QLatin1String(" ( ")); - line.replace(QLatin1Char(')'), QLatin1String(" ) ")); - line.replace(QLatin1Char('{'), QLatin1String(" { ")); - line.replace(QLatin1Char('}'), QLatin1String(" } ")); - line.replace(QLatin1Char(':'), QLatin1String(" : ")); - line.replace(QLatin1Char(';'), QLatin1String(" ; ")); - m_WordList = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); - m_WordListIndex = 0; - // ---------------------- - // for debugging only -// foreach (const QString &str, qAsConst(m_WordList)) -// INFO_LOG(m_logger) << "word=" << str.toStdString(); - // ---------------------- -} - - -// --------------------------------------------------------------- -QString LogViewXdrParser::getNextWord(const char *a_errorText) -{ - QString word; - if (m_WordListIndex < m_WordList.size()) - word = m_WordList.at(m_WordListIndex); - - if (word.isEmpty() && a_errorText) - { - const QString errTxt(QString::fromUtf8(a_errorText)); - if (m_WordListIndex > 0) - showErrorMessage(QObject::tr("Erwarte %1 nach \'%2\'!").arg(errTxt, m_WordList.at(m_WordListIndex-1))); - else - showErrorMessage(QObject::tr("Erwarte %1!").arg(errTxt)); - } - m_WordListIndex++; - return word; -} - - -// --------------------------------------------------------------- -QString LogViewXdrParser::getNextType(bool& a_ok) -{ - a_ok = true; - QString type = getNextWord("Typ"); - if (type.isEmpty()) a_ok = false; - if (type == QLatin1String("unsigned") || - type == QLatin1String("signed")) - { - QString type2 = getNextWord("Typ"); - if (type2.isEmpty()) a_ok = false; - type = QStringLiteral("%1 %2").arg(type, type2); - } - return type; -} - - -// --------------------------------------------------------------- -QString LogViewXdrParser::getNextEnum(const LogViewXdrStruct*& a_enumStruct) -{ - QString type; - a_enumStruct = nullptr; - if (m_WordListIndex < m_WordList.size()) - { - type = m_WordList.at(m_WordListIndex); - a_enumStruct = static_cast(getElement(type)); - if (a_enumStruct) - { - if (LogViewXdrElement::e_KindEnum != a_enumStruct->getKind()) - { - showErrorMessage(QObject::tr("Typ \'%1\' muss ein Enum sein!").arg(type)); - a_enumStruct = nullptr; + showErrorMessage(QObject::tr("%1: Did not found expected ']'").arg(oldName)); } } else - showErrorMessage(QObject::tr("Enum \'%1\' nicht definiert!").arg(type)); - m_WordListIndex++; - } - return type; -} - - -// --------------------------------------------------------------- -bool LogViewXdrParser::parseBitfield(const QString& a_fieldText, int16_t& a_firstBit, int16_t& a_lastBit) const -{ -// INFO_LOG(m_logger) << "a_fieldText=" << a_fieldText.toStdString(); - // bitfield-definition: "0..2" - a_firstBit = -1; - a_lastBit = -1; - bool isLast = true; - // first bit - int doublePointPos = a_fieldText.indexOf(QLatin1String("..")); - if (doublePointPos != -1) - { - QString bitText = a_fieldText.left(doublePointPos); - bool ok; - a_firstBit = bitText.toInt(&ok); - if (ok) { - // last bit - bitText = a_fieldText.mid(doublePointPos+2); - // is it the last bitfield of this data-value (indicated by !) - if (bitText.endsWith(QLatin1Char('!'))) + + // is it an dynamic array <>? + // -------------------------- + //INFO_LOG(m_logger) << "check for <"; + pos = a_name.indexOf(QLatin1Char('<')); + if (pos >= 0) { - isLast = true; - bitText.chop(1); + int endPos = a_name.indexOf(QLatin1Char('>')); + if (endPos > pos) + { + // get the array-size + QString arraySizeText = a_name.mid(pos + 1, endPos - pos - 1); + //INFO_LOG(m_logger) << "pos=" << pos << " endPos=" << endPos << " => " << arraySizeText.toStdString(); + // set new name + a_name = a_name.left(pos); + // INFO_LOG(m_logger) << "new a_name=" << a_name.toStdString() << " arraySizeText=" << arraySizeText.toStdString(); + // check whether it is a define + int64_t arraySizeValue = 1; + if (!getDefine(arraySizeText, arraySizeValue)) + { + bool ok = false; + arraySizeValue = arraySizeText.toInt(&ok); + if (!ok) + { + showErrorMessage(QObject::tr("%1: \'%2\' is not a number").arg(a_name, arraySizeText)); + } + else + { + // INFO_LOG(m_logger) << "a_name=" << a_name.toStdString() << " a_dynArrayMsgOffset=" << a_dynArrayMsgOffset; + } + } + a_dynArrayMsgOffset = arraySizeValue; + // INFO_LOG(m_logger) << a_name.toStdString() << " is a dynamic array with size=" << arraySizeValue; + return 0; + } + else + { + showErrorMessage(QObject::tr("%1: Did not found expected '>'").arg(a_name)); + } + } + } + return 1; + } + + + // --------------------------------------------------------------- + bool LogViewXdrParser::isNextWord(const char *a_word, const bool a_doIncrement) + { + const QString word = QString::fromUtf8(a_word); + bool ok = (m_WordListIndex < m_WordList.size() && m_WordList.at(m_WordListIndex) == word); + + // show error-message + if (!ok && a_doIncrement) + { + if (m_WordListIndex > 0) + showErrorMessage(QObject::tr("Erwarte %1 nach \'%2\'!").arg(word, m_WordList.at(m_WordListIndex - 1))); + else + showErrorMessage(QObject::tr("Erwarte %1!").arg(word)); + } + + if (a_doIncrement) + m_WordListIndex++; + return ok; + } + + + // --------------------------------------------------------------- + void LogViewXdrParser::fillWordList(const QString &a_line) + { + QString line = a_line; + line.replace(QLatin1Char('('), QLatin1String(" ( ")); + line.replace(QLatin1Char(')'), QLatin1String(" ) ")); + line.replace(QLatin1Char('{'), QLatin1String(" { ")); + line.replace(QLatin1Char('}'), QLatin1String(" } ")); + line.replace(QLatin1Char(':'), QLatin1String(" : ")); + line.replace(QLatin1Char(';'), QLatin1String(" ; ")); + m_WordList = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); + m_WordListIndex = 0; + // ---------------------- + // for debugging only + // foreach (const QString &str, qAsConst(m_WordList)) + // INFO_LOG(m_logger) << "word=" << str.toStdString(); + // ---------------------- + } + + + // --------------------------------------------------------------- + QString LogViewXdrParser::getNextWord(const char *a_errorText) + { + QString word; + if (m_WordListIndex < m_WordList.size()) + word = m_WordList.at(m_WordListIndex); + + if (word.isEmpty() && a_errorText) + { + const QString errTxt(QString::fromUtf8(a_errorText)); + if (m_WordListIndex > 0) + showErrorMessage(QObject::tr("Erwarte %1 nach \'%2\'!").arg(errTxt, m_WordList.at(m_WordListIndex - 1))); + else + showErrorMessage(QObject::tr("Erwarte %1!").arg(errTxt)); + } + m_WordListIndex++; + return word; + } + + + // --------------------------------------------------------------- + QString LogViewXdrParser::getNextType(bool &a_ok) + { + a_ok = true; + QString type = getNextWord("Typ"); + if (type.isEmpty()) + a_ok = false; + if (type == QLatin1String("unsigned") || type == QLatin1String("signed")) + { + QString type2 = getNextWord("Typ"); + if (type2.isEmpty()) + a_ok = false; + type = QStringLiteral("%1 %2").arg(type, type2); + } + return type; + } + + + // --------------------------------------------------------------- + QString LogViewXdrParser::getNextEnum(const LogViewXdrStruct *&a_enumStruct) + { + QString type; + a_enumStruct = nullptr; + if (m_WordListIndex < m_WordList.size()) + { + type = m_WordList.at(m_WordListIndex); + a_enumStruct = static_cast(getElement(type)); + if (a_enumStruct) + { + if (LogViewXdrElement::e_KindEnum != a_enumStruct->getKind()) + { + showErrorMessage(QObject::tr("Typ \'%1\' muss ein Enum sein!").arg(type)); + a_enumStruct = nullptr; + } } else - { - isLast = false; - } - a_lastBit = bitText.toInt(&ok); + showErrorMessage(QObject::tr("Enum \'%1\' nicht definiert!").arg(type)); + m_WordListIndex++; + } + return type; + } + + + // --------------------------------------------------------------- + bool LogViewXdrParser::parseBitfield(const QString &a_fieldText, int16_t &a_firstBit, int16_t &a_lastBit) const + { + // INFO_LOG(m_logger) << "a_fieldText=" << a_fieldText.toStdString(); + // bitfield-definition: "0..2" + a_firstBit = -1; + a_lastBit = -1; + bool isLast = true; + // first bit + int doublePointPos = a_fieldText.indexOf(QLatin1String("..")); + if (doublePointPos != -1) + { + QString bitText = a_fieldText.left(doublePointPos); + bool ok; + a_firstBit = bitText.toInt(&ok); if (ok) { - // remove bitfield-stuff -// a_line = a_line.remove(bitfieldPos, endPos-bitfieldPos); + // last bit + bitText = a_fieldText.mid(doublePointPos + 2); + // is it the last bitfield of this data-value (indicated by !) + if (bitText.endsWith(QLatin1Char('!'))) + { + isLast = true; + bitText.chop(1); + } + else + { + isLast = false; + } + a_lastBit = bitText.toInt(&ok); + if (ok) + { + // remove bitfield-stuff + // a_line = a_line.remove(bitfieldPos, endPos-bitfieldPos); + } + else + { + showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Zweites Bit (%1) ist keine Zahl!").arg(bitText)); + } } else { - showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Zweites Bit (%1) ist keine Zahl!").arg(bitText)); + showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Erstes Bit (%1) ist keine Zahl!").arg(bitText)); } } else { - showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Erstes Bit (%1) ist keine Zahl!").arg(bitText)); + showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Habe .. nicht gefunden!")); } + return isLast; } - else - { - showErrorMessage(QObject::tr("Bitfeld-Defintion muss folgendes Format haben: :0..2. Habe .. nicht gefunden!")); - } - return isLast; -} -// --------------------------------------------------------------- -// adds an element to the element-map if it does not already -// exist within this map. -// If it exists, an error-message will be raised instead and -// false will be returned. -// --------------------------------------------------------------- -bool LogViewXdrParser::addToElementMap(const QString& a_name, LogViewXdrElement* a_element) -{ - if (m_ElementMap.find(a_name) == m_ElementMap.end()) + // --------------------------------------------------------------- + // adds an element to the element-map if it does not already + // exist within this map. + // If it exists, an error-message will be raised instead and + // false will be returned. + // --------------------------------------------------------------- + bool LogViewXdrParser::addToElementMap(const QString &a_name, LogViewXdrElement *a_element) { - m_ElementMap.insert(std::make_pair(a_name, a_element)); - return true; + if (m_ElementMap.find(a_name) == m_ElementMap.end()) + { + m_ElementMap.insert(std::make_pair(a_name, a_element)); + return true; + } + showErrorMessage(QObject::tr("Der Typ '%1' wurde bereits frueher definiert => Bitte ein einem Ort entfernen!").arg(a_name)); + return false; } - showErrorMessage(QObject::tr("Der Typ '%1' wurde bereits frueher definiert => Bitte ein einem Ort entfernen!").arg(a_name)); - return false; -} } // namespace N_LogView - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.hpp index 4d4460651..48dcc22a3 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrParser.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -37,7 +37,6 @@ namespace N_LogView class LogViewXdrParser : public N_SST::IntegerCalculator { public: - /** * Defines in which structure the parser is parsing now * @@ -62,7 +61,7 @@ namespace N_LogView * * @param a_fileName */ - void parseX_File(const QString& a_fileName); + void parseX_File(const QString &a_fileName); /** * This function delivers the name of the telegram. @@ -89,16 +88,15 @@ namespace N_LogView * @param a_name * @param a_value */ - bool getDefine(const QString& a_name, int64_t& a_value) const; + bool getDefine(const QString &a_name, int64_t &a_value) const; /** * * @param a_name */ - const LogViewXdrElement* getElement(const QString& a_name) const; + const LogViewXdrElement *getElement(const QString &a_name) const; protected: - QString m_MessageBoxTitle; bool m_WithinComment; QString m_Line; @@ -112,7 +110,7 @@ namespace N_LogView * telegram structure. */ QString m_UnionType; - std::map m_ElementMap; + std::map m_ElementMap; LogViewXdrStruct *m_ActElement; @@ -131,7 +129,7 @@ namespace N_LogView * @param a_dynArraySizeMethod * @param a_byteOrder */ - void addStandardType(const QString& a_name, + void addStandardType(const QString &a_name, const uint16_t a_dataSize, const uint16_t a_realSize, const LogViewXdrStandardType::E_ValueKind a_kind, @@ -142,7 +140,7 @@ namespace N_LogView * * @param a_line */ - QString removeComments(const QString& a_line); + QString removeComments(const QString &a_line); /** * @@ -173,7 +171,7 @@ namespace N_LogView * * @param a_line */ - void parseUnion(const QString& a_line); + void parseUnion(const QString &a_line); /** * @@ -181,7 +179,7 @@ namespace N_LogView * @param a_name * @param a_value */ - bool parseEnumLine(const QString& a_line, QString& a_name, QString& a_value) const; + bool parseEnumLine(const QString &a_line, QString &a_name, QString &a_value) const; /** * Shows an error-message containing the line-nbr, the line itself and an @@ -189,21 +187,21 @@ namespace N_LogView * * @param a_errorText */ - void showErrorMessage(const QString& a_errorText) const; + void showErrorMessage(const QString &a_errorText) const; /** * * @param a_calcText * @param a_isOk */ - int64_t calcValue(const QString& a_calcText, bool& a_isOk); + int64_t calcValue(const QString &a_calcText, bool &a_isOk); /** * * @param a_variableName * @param a_value */ - bool getVariableValue(const std::string& a_variableName, int64_t& a_value) const override; + bool getVariableValue(const std::string &a_variableName, int64_t &a_value) const override; /** * @@ -212,7 +210,7 @@ namespace N_LogView * e_DynArrayMsgLength. Here the value in will be subtracted from the message- * length to get the size of the dynamic array. */ - uint16_t parseArray(QString& a_name, uint16_t& a_dynArrayMsgOffset) const; + uint16_t parseArray(QString &a_name, uint16_t &a_dynArrayMsgOffset) const; /** * @@ -225,7 +223,7 @@ namespace N_LogView * * @param a_line */ - void fillWordList(const QString& a_line); + void fillWordList(const QString &a_line); /** * @@ -237,13 +235,13 @@ namespace N_LogView * * @param a_ok */ - QString getNextType(bool& a_ok); + QString getNextType(bool &a_ok); /** * * @param a_enumStruct */ - QString getNextEnum(const LogViewXdrStruct*& a_enumStruct); + QString getNextEnum(const LogViewXdrStruct *&a_enumStruct); /** * @@ -251,7 +249,7 @@ namespace N_LogView * @param a_firstBit * @param a_lastBit */ - bool parseBitfield(const QString& a_fieldText, int16_t& a_firstBit, int16_t& a_lastBit) const; + bool parseBitfield(const QString &a_fieldText, int16_t &a_firstBit, int16_t &a_lastBit) const; /** * adds an element to the element-map if it does not already exist within this map. @@ -262,7 +260,7 @@ namespace N_LogView * @param a_name * @param a_element */ - bool addToElementMap(const QString& a_name, LogViewXdrElement* a_element); + bool addToElementMap(const QString &a_name, LogViewXdrElement *a_element); private: LOGGER_T m_logger; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.cpp index 6cf6f2f26..79754c8e5 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.cpp @@ -1,84 +1,83 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "LogViewXdrStandardType.hpp" namespace N_LogView { -// --------------------------------------------------------------- -// (a_valueKind must be Unsigned, if a_dynArraySizeMethod is -// e_DynArray...) -// --------------------------------------------------------------- -LogViewXdrStandardType::LogViewXdrStandardType(const QString& a_name, const int a_valueSize, - const int a_editSize, const E_ValueKind a_valueKind, - const E_DynArraySizeMethod a_dynArraySizeMethod, E_ByteOrder a_byteOrder) - : LogViewXdrElement(a_name, e_KindStandardType, "LogViewXdrStandardType") - , m_ValueSize(a_valueSize) - , m_EditSize(a_editSize) - , m_ValueKind(a_valueKind) - , m_ByteOrder(a_byteOrder) - , m_DynArraySizeMethod(a_dynArraySizeMethod) -{} + // --------------------------------------------------------------- + // (a_valueKind must be Unsigned, if a_dynArraySizeMethod is + // e_DynArray...) + // --------------------------------------------------------------- + LogViewXdrStandardType::LogViewXdrStandardType(const QString &a_name, + const int a_valueSize, + const int a_editSize, + const E_ValueKind a_valueKind, + const E_DynArraySizeMethod a_dynArraySizeMethod, + E_ByteOrder a_byteOrder) + : LogViewXdrElement(a_name, e_KindStandardType, "LogViewXdrStandardType") + , m_ValueSize(a_valueSize) + , m_EditSize(a_editSize) + , m_ValueKind(a_valueKind) + , m_ByteOrder(a_byteOrder) + , m_DynArraySizeMethod(a_dynArraySizeMethod) + { + } -// --------------------------------------------------------------- -uint16_t LogViewXdrStandardType::getValueSize() const -{ - return m_ValueSize; -} + // --------------------------------------------------------------- + uint16_t LogViewXdrStandardType::getValueSize() const + { + return m_ValueSize; + } -// --------------------------------------------------------------- -LogViewXdrStandardType::E_ValueKind LogViewXdrStandardType::getValueKind() const -{ - return m_ValueKind; -} + // --------------------------------------------------------------- + LogViewXdrStandardType::E_ValueKind LogViewXdrStandardType::getValueKind() const + { + return m_ValueKind; + } -// --------------------------------------------------------------- -void LogViewXdrStandardType::dump() const -{ - INFO_LOG(m_logger) << "Element[" << getName() - << "]: kind=" << getKindName() - << " valueKind=" << getValueKind() - << " valueSize=" << getValueSize() - << " editSize=" << getEditSize() - << " dynArrSizeMethod=" << getDynArraySizeMethod() - << " byteOrder=" << getByteOrder(); -} + // --------------------------------------------------------------- + void LogViewXdrStandardType::dump() const + { + INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName() << " valueKind=" << getValueKind() << " valueSize=" << getValueSize() + << " editSize=" << getEditSize() << " dynArrSizeMethod=" << getDynArraySizeMethod() << " byteOrder=" << getByteOrder(); + } -// --------------------------------------------------------------- -LogViewXdrStandardType::E_DynArraySizeMethod LogViewXdrStandardType::getDynArraySizeMethod() const -{ - return m_DynArraySizeMethod; -} + // --------------------------------------------------------------- + LogViewXdrStandardType::E_DynArraySizeMethod LogViewXdrStandardType::getDynArraySizeMethod() const + { + return m_DynArraySizeMethod; + } -// --------------------------------------------------------------- -LogViewXdrStandardType::E_ByteOrder LogViewXdrStandardType::getByteOrder() const -{ - return m_ByteOrder; -} + // --------------------------------------------------------------- + LogViewXdrStandardType::E_ByteOrder LogViewXdrStandardType::getByteOrder() const + { + return m_ByteOrder; + } -// --------------------------------------------------------------- -// The 'real' size of the value, which will be allowd when -// editing this value -// --------------------------------------------------------------- -uint16_t LogViewXdrStandardType::getEditSize() const -{ - return m_EditSize; -} + // --------------------------------------------------------------- + // The 'real' size of the value, which will be allowd when + // editing this value + // --------------------------------------------------------------- + uint16_t LogViewXdrStandardType::getEditSize() const + { + return m_EditSize; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.hpp index 05e8480d8..a39a583d3 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStandardType.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewXdrElement.hpp" @@ -29,7 +29,6 @@ namespace N_LogView class LogViewXdrStandardType final : public LogViewXdrElement { public: - /** * @author alois.wismer * @version 1.0 @@ -130,7 +129,6 @@ namespace N_LogView uint16_t getEditSize() const; protected: - /** * The size of this value as stored data. It may be bigger as the real (edit) size. */ @@ -144,7 +142,6 @@ namespace N_LogView E_ByteOrder m_ByteOrder; E_DynArraySizeMethod m_DynArraySizeMethod; - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.cpp index d23a4121e..e4c442880 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewXdrStruct.hpp" #include "LogViewXdrValue.hpp" #include "LogViewXdrType.hpp" @@ -18,88 +18,94 @@ namespace N_LogView { -// --------------------------------------------------------------- -LogViewXdrStruct::LogViewXdrStruct(const QString& a_name, const LogViewXdrElement::E_ElementKind a_kind, uint16_t enumSize) - : LogViewXdrElement(a_name, a_kind, "LogViewXdrStruct") - , m_EnumSize(enumSize) -{ -} - -LogViewXdrStruct::~LogViewXdrStruct() -{ - for (auto ptr : m_ChildList) - delete ptr; -} - - -// --------------------------------------------------------------- -void LogViewXdrStruct::addElement(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind, const int16_t a_firstBit, const int16_t a_lastBit, const bool a_isLast) -{ - m_ChildList.push_back(new LogViewXdrType(a_name, a_type, a_arraySize, a_dynArrayOffset, a_kind, a_firstBit, a_lastBit, a_isLast)); -} - -// --------------------------------------------------------------- -void LogViewXdrStruct::addElement(const QString& a_name, const uint32_t a_value, const E_ElementKind a_kind) -{ - m_ChildList.push_back(new LogViewXdrValue(a_name, a_value, a_kind)); -} - - -// --------------------------------------------------------------- -LogViewXdrElement* LogViewXdrStruct::getChild(const uint32_t a_childIndex) const -{ - if (m_ChildList.size() > a_childIndex) - return m_ChildList[a_childIndex]; - - return nullptr; -} - - -// --------------------------------------------------------------- -LogViewXdrType* LogViewXdrStruct::getChildAsType(const uint32_t a_childIndex) const -{ - return static_cast(getChild(a_childIndex)); // fixme: check ob es wirklich ein XdrType ist -} - - -// --------------------------------------------------------------- -LogViewXdrValue* LogViewXdrStruct::getChildAsValue(const uint32_t a_childIndex) const -{ - return static_cast(getChild(a_childIndex)); // fixme: check ob es wirklich ein XdrValue ist -} - - -// --------------------------------------------------------------- -void LogViewXdrStruct::dump() const -{ - INFO_LOG(m_logger) << "Element[" << getName().toStdString() << "]: kind=" << getKindName().toStdString() << " enumSize=" << getEnumSize(); - INFO_LOG(m_logger) << "-------------- childs start -----------------"; - - std::vector::const_iterator iter = m_ChildList.begin(); - while (iter != m_ChildList.end()) + // --------------------------------------------------------------- + LogViewXdrStruct::LogViewXdrStruct(const QString &a_name, const LogViewXdrElement::E_ElementKind a_kind, uint16_t enumSize) + : LogViewXdrElement(a_name, a_kind, "LogViewXdrStruct") + , m_EnumSize(enumSize) { - (*iter)->dump(); - ++iter; } - INFO_LOG(m_logger) << "-------------- childs end -----------------"; -} -// --------------------------------------------------------------- -uint32_t LogViewXdrStruct::getChildValue(const QString& a_name, bool* a_error) const -{ - if (a_error) - *a_error = false; - std::vector::const_iterator iter = m_ChildList.begin(); - while (iter != m_ChildList.end()) + LogViewXdrStruct::~LogViewXdrStruct() { - if ((*iter)->getName() == a_name) - return static_cast(*iter)->getValue(); - ++iter; + for (auto ptr : m_ChildList) + delete ptr; + } + + + // --------------------------------------------------------------- + void LogViewXdrStruct::addElement(const QString &a_name, + const QString &a_type, + const uint16_t a_arraySize, + const uint16_t a_dynArrayOffset, + const E_ElementKind a_kind, + const int16_t a_firstBit, + const int16_t a_lastBit, + const bool a_isLast) + { + m_ChildList.push_back(new LogViewXdrType(a_name, a_type, a_arraySize, a_dynArrayOffset, a_kind, a_firstBit, a_lastBit, a_isLast)); + } + + // --------------------------------------------------------------- + void LogViewXdrStruct::addElement(const QString &a_name, const uint32_t a_value, const E_ElementKind a_kind) + { + m_ChildList.push_back(new LogViewXdrValue(a_name, a_value, a_kind)); + } + + + // --------------------------------------------------------------- + LogViewXdrElement *LogViewXdrStruct::getChild(const uint32_t a_childIndex) const + { + if (m_ChildList.size() > a_childIndex) + return m_ChildList[a_childIndex]; + + return nullptr; + } + + + // --------------------------------------------------------------- + LogViewXdrType *LogViewXdrStruct::getChildAsType(const uint32_t a_childIndex) const + { + return static_cast(getChild(a_childIndex)); // fixme: check ob es wirklich ein XdrType ist + } + + + // --------------------------------------------------------------- + LogViewXdrValue *LogViewXdrStruct::getChildAsValue(const uint32_t a_childIndex) const + { + return static_cast(getChild(a_childIndex)); // fixme: check ob es wirklich ein XdrValue ist + } + + + // --------------------------------------------------------------- + void LogViewXdrStruct::dump() const + { + INFO_LOG(m_logger) << "Element[" << getName().toStdString() << "]: kind=" << getKindName().toStdString() << " enumSize=" << getEnumSize(); + INFO_LOG(m_logger) << "-------------- childs start -----------------"; + + std::vector::const_iterator iter = m_ChildList.begin(); + while (iter != m_ChildList.end()) + { + (*iter)->dump(); + ++iter; + } + INFO_LOG(m_logger) << "-------------- childs end -----------------"; + } + + // --------------------------------------------------------------- + uint32_t LogViewXdrStruct::getChildValue(const QString &a_name, bool *a_error) const + { + if (a_error) + *a_error = false; + std::vector::const_iterator iter = m_ChildList.begin(); + while (iter != m_ChildList.end()) + { + if ((*iter)->getName() == a_name) + return static_cast(*iter)->getValue(); + ++iter; + } + if (a_error) + *a_error = true; + return 0; } - if (a_error) - *a_error = true; - return 0; -} } // namespace N_LogView - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.hpp index 47cdd3355..db34d102e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrStruct.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -39,27 +39,32 @@ namespace N_LogView class LogViewXdrStruct final : public LogViewXdrElement { public: - LogViewXdrStruct(const QString& a_name, const LogViewXdrElement::E_ElementKind a_kind, uint16_t enumSize = 0); + LogViewXdrStruct(const QString &a_name, const LogViewXdrElement::E_ElementKind a_kind, uint16_t enumSize = 0); ~LogViewXdrStruct(); - void addElement(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind, const int16_t a_firstBit = -1, const int16_t a_lastBit = -1, const bool a_isLast = true); - void addElement(const QString& a_name, const uint32_t a_value, const E_ElementKind a_kind); + void addElement(const QString &a_name, + const QString &a_type, + const uint16_t a_arraySize, + const uint16_t a_dynArrayOffset, + const E_ElementKind a_kind, + const int16_t a_firstBit = -1, + const int16_t a_lastBit = -1, + const bool a_isLast = true); + void addElement(const QString &a_name, const uint32_t a_value, const E_ElementKind a_kind); - LogViewXdrElement* getChild(const uint32_t a_childIndex) const; - LogViewXdrType* getChildAsType(const uint32_t a_childIndex) const; - LogViewXdrValue* getChildAsValue(const uint32_t a_childIndex) const; + LogViewXdrElement *getChild(const uint32_t a_childIndex) const; + LogViewXdrType *getChildAsType(const uint32_t a_childIndex) const; + LogViewXdrValue *getChildAsValue(const uint32_t a_childIndex) const; void dump() const override; - uint32_t getChildValue(const QString& a_name, bool* a_error = nullptr) const; + uint32_t getChildValue(const QString &a_name, bool *a_error = nullptr) const; uint16_t getEnumSize() const { return m_EnumSize; } protected: - uint16_t m_EnumSize; - std::vector m_ChildList; - + std::vector m_ChildList; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.cpp index 4c2825482..82ae39dfd 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.cpp @@ -1,106 +1,104 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewXdrType.hpp" namespace N_LogView { -// --------------------------------------------------------------- -LogViewXdrType::LogViewXdrType(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind) - : LogViewXdrElement(a_name, a_kind, "LogViewXdrElement") - , m_Type(a_type) - , m_ArraySize(a_arraySize) - , m_MaxArraySize(a_dynArrayOffset) - , m_FirstBit(-1) - , m_LastBit(-1) - , m_IsLast(true) -{ -} - - -// --------------------------------------------------------------- -LogViewXdrType::LogViewXdrType(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind, const int16_t a_firstBit, const int16_t a_lastBit, const bool a_isLast) - : LogViewXdrElement(a_name, a_kind, "LogViewXdrType") - , m_Type(a_type) - , m_ArraySize(a_arraySize) - , m_MaxArraySize(a_dynArrayOffset) - , m_FirstBit(a_firstBit) - , m_LastBit(a_lastBit) - , m_IsLast(a_isLast) -{ -} - - -// --------------------------------------------------------------- -void LogViewXdrType::dump() const -{ - INFO_LOG(m_logger) << "Element[" << getName() - << "]: kind=" << getKindName() - << " type=" << getType() - << " arraySize=" << getArraySize() - << " maxArraySize=" << getMaxArraySize() - << " firstBit=" << m_FirstBit - << " lastBit=" << m_LastBit - << " isLast=" << m_IsLast; -} - - -// --------------------------------------------------------------- -const QString& LogViewXdrType::getType() const -{ - return m_Type; -} - -// --------------------------------------------------------------- -// 0 => opaque -// 1 => normal (scalar) element -// >1 => array -// --------------------------------------------------------------- -uint16_t LogViewXdrType::getArraySize() const -{ - return m_ArraySize; -} - - -// --------------------------------------------------------------- -bool LogViewXdrType::maskValue(uint32_t& a_value, const uint16_t a_size, QString& a_tooltip) const -{ -// INFO_LOG(m_logger) << "firstBit=" << m_FirstBit << " lastBit=" << m_LastBit << " isLast=" << m_IsLast; - if (m_FirstBit != -1 && m_LastBit != -1) + // --------------------------------------------------------------- + LogViewXdrType::LogViewXdrType(const QString &a_name, const QString &a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind) + : LogViewXdrElement(a_name, a_kind, "LogViewXdrElement") + , m_Type(a_type) + , m_ArraySize(a_arraySize) + , m_MaxArraySize(a_dynArrayOffset) + , m_FirstBit(-1) + , m_LastBit(-1) + , m_IsLast(true) { - DEBUG_LOG(m_logger) << "MaskValue for Element " << m_Name - << " type: " << m_Type - << " size: " << m_ArraySize - << " first:last " << m_FirstBit << ":" << m_LastBit - << " isLast: " << m_IsLast; - uint16_t bitshift = (a_size*8)-m_LastBit-1; - uint32_t mask = (1<<(m_LastBit-m_FirstBit+1))-1; -// INFO_LOG(m_logger) << "value=" << a_value << " bitshift=" << bitshift << " mask=" << mask; - a_value = (a_value >> bitshift) & mask; - // make bold the corresponding bits in the bitfield - a_tooltip.insert(a_tooltip.length()-(a_size*8)+m_FirstBit, QLatin1String("")); - a_tooltip.insert(a_tooltip.length()-(a_size*8)+m_LastBit+1, QLatin1String("")); - return m_IsLast; } - return true; -} -// --------------------------------------------------------------- -uint16_t LogViewXdrType::getMaxArraySize() const -{ - return m_MaxArraySize; -} + // --------------------------------------------------------------- + LogViewXdrType::LogViewXdrType(const QString &a_name, + const QString &a_type, + const uint16_t a_arraySize, + const uint16_t a_dynArrayOffset, + const E_ElementKind a_kind, + const int16_t a_firstBit, + const int16_t a_lastBit, + const bool a_isLast) + : LogViewXdrElement(a_name, a_kind, "LogViewXdrType") + , m_Type(a_type) + , m_ArraySize(a_arraySize) + , m_MaxArraySize(a_dynArrayOffset) + , m_FirstBit(a_firstBit) + , m_LastBit(a_lastBit) + , m_IsLast(a_isLast) + { + } + + + // --------------------------------------------------------------- + void LogViewXdrType::dump() const + { + INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName() << " type=" << getType() << " arraySize=" << getArraySize() + << " maxArraySize=" << getMaxArraySize() << " firstBit=" << m_FirstBit << " lastBit=" << m_LastBit << " isLast=" << m_IsLast; + } + + + // --------------------------------------------------------------- + const QString &LogViewXdrType::getType() const + { + return m_Type; + } + + // --------------------------------------------------------------- + // 0 => opaque + // 1 => normal (scalar) element + // >1 => array + // --------------------------------------------------------------- + uint16_t LogViewXdrType::getArraySize() const + { + return m_ArraySize; + } + + + // --------------------------------------------------------------- + bool LogViewXdrType::maskValue(uint32_t &a_value, const uint16_t a_size, QString &a_tooltip) const + { + // INFO_LOG(m_logger) << "firstBit=" << m_FirstBit << " lastBit=" << m_LastBit << " isLast=" << m_IsLast; + if (m_FirstBit != -1 && m_LastBit != -1) + { + DEBUG_LOG(m_logger) << "MaskValue for Element " << m_Name << " type: " << m_Type << " size: " << m_ArraySize << " first:last " << m_FirstBit << ":" << m_LastBit + << " isLast: " << m_IsLast; + uint16_t bitshift = (a_size * 8) - m_LastBit - 1; + uint32_t mask = (1 << (m_LastBit - m_FirstBit + 1)) - 1; + // INFO_LOG(m_logger) << "value=" << a_value << " bitshift=" << bitshift << " mask=" << mask; + a_value = (a_value >> bitshift) & mask; + // make bold the corresponding bits in the bitfield + a_tooltip.insert(a_tooltip.length() - (a_size * 8) + m_FirstBit, QLatin1String("")); + a_tooltip.insert(a_tooltip.length() - (a_size * 8) + m_LastBit + 1, QLatin1String("")); + return m_IsLast; + } + return true; + } + + + // --------------------------------------------------------------- + uint16_t LogViewXdrType::getMaxArraySize() const + { + return m_MaxArraySize; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.hpp index cf13cad85..81fd83816 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrType.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewXdrElement.hpp" @@ -32,7 +32,6 @@ namespace N_LogView class LogViewXdrType final : public LogViewXdrElement { public: - /** * * @param a_name @@ -41,7 +40,7 @@ namespace N_LogView * @param a_dynArrayOffset * @param a_kind */ - LogViewXdrType(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind); + LogViewXdrType(const QString &a_name, const QString &a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind); /** * @@ -54,13 +53,20 @@ namespace N_LogView * @param a_lastBit * @param a_isLast */ - LogViewXdrType(const QString& a_name, const QString& a_type, const uint16_t a_arraySize, const uint16_t a_dynArrayOffset, const E_ElementKind a_kind, const int16_t a_firstBit, const int16_t a_lastBit, const bool a_isLast); + LogViewXdrType(const QString &a_name, + const QString &a_type, + const uint16_t a_arraySize, + const uint16_t a_dynArrayOffset, + const E_ElementKind a_kind, + const int16_t a_firstBit, + const int16_t a_lastBit, + const bool a_isLast); void dump() const override; - const QString& getType() const; + const QString &getType() const; /** * 0 => opaque @@ -75,13 +81,12 @@ namespace N_LogView * @param a_size * @param a_tooltip */ - bool maskValue(uint32_t& a_value, const uint16_t a_size, QString& a_tooltip) const; + bool maskValue(uint32_t &a_value, const uint16_t a_size, QString &a_tooltip) const; uint16_t getMaxArraySize() const; protected: - QString m_Type; /** * 0 => opaque @@ -108,4 +113,3 @@ namespace N_LogView }; } - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.cpp index cb8baa328..26d27d244 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.cpp @@ -1,40 +1,41 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + #include "LogViewXdrValue.hpp" namespace N_LogView { -// --------------------------------------------------------------- -LogViewXdrValue::LogViewXdrValue(const QString& a_name, const int64_t a_value, const LogViewXdrElement::E_ElementKind a_kind) - : LogViewXdrElement(a_name, a_kind, "LogViewXdrValue") - , m_Value(a_value) -{} + // --------------------------------------------------------------- + LogViewXdrValue::LogViewXdrValue(const QString &a_name, const int64_t a_value, const LogViewXdrElement::E_ElementKind a_kind) + : LogViewXdrElement(a_name, a_kind, "LogViewXdrValue") + , m_Value(a_value) + { + } -// --------------------------------------------------------------- -void LogViewXdrValue::dump() const -{ - INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName() << " value=" << getValue(); -} + // --------------------------------------------------------------- + void LogViewXdrValue::dump() const + { + INFO_LOG(m_logger) << "Element[" << getName() << "]: kind=" << getKindName() << " value=" << getValue(); + } -// --------------------------------------------------------------- -int64_t LogViewXdrValue::getValue() const -{ - return m_Value; -} + // --------------------------------------------------------------- + int64_t LogViewXdrValue::getValue() const + { + return m_Value; + } } // namespace N_LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.hpp index d711b4995..3610f9924 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/LogViewXdrValue.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "LogViewXdrElement.hpp" @@ -28,13 +28,12 @@ namespace N_LogView class LogViewXdrValue final : public LogViewXdrElement { public: - LogViewXdrValue(const QString& a_name, const int64_t a_value, const LogViewXdrElement::E_ElementKind a_kind); + LogViewXdrValue(const QString &a_name, const int64_t a_value, const LogViewXdrElement::E_ElementKind a_kind); void dump() const override; int64_t getValue() const; protected: - int64_t m_Value; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.cpp index ce2a64524..bbfbca317 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.cpp @@ -13,25 +13,24 @@ namespace N_LogView { -LOGGER_T getLogger(const char *name) -{ - static const char ns[] = "LogView."; - std::string loggerName; - const size_t len = strlen(name); - loggerName.reserve(sizeof(ns) + len); - loggerName.append(ns, sizeof(ns) - 1); - loggerName.append(name, len); + LOGGER_T getLogger(const char *name) + { + static const char ns[] = "LogView."; + std::string loggerName; + const size_t len = strlen(name); + loggerName.reserve(sizeof(ns) + len); + loggerName.append(ns, sizeof(ns) - 1); + loggerName.append(name, len); - try - { - return NGL::NGLLoggerBootstrap::getNGLRootLogger(). - getNGLLogger(loggerName); + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception &ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } - catch (const std::exception &ex) - { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); - } -} } // namespace LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.h b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.h index 2bb8a786e..c43a9c3db 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/LogView/logger.h @@ -12,11 +12,11 @@ namespace N_LogView { -typedef NGL::INGLLogger &LOGGER_T; + typedef NGL::INGLLogger &LOGGER_T; -LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) -{ - return getLogger(loggerName.toUtf8().constData()); -} + LOGGER_T getLogger(const char *name); + inline LOGGER_T getLogger(const QString &loggerName) + { + return getLogger(loggerName.toUtf8().constData()); + } } // namespace LogView diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.cpp index 9dc6e4c81..292e5eb96 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.cpp @@ -16,73 +16,72 @@ namespace N_AppComponent { -int32_t AppComponent::create(NGL::Settings *settings) -{ - for (IAppComponent *c : m_Childs) - c->create(settings); - return 0; -} - - -int32_t AppComponent::destroy() -{ - for (IAppComponent *c : m_Childs) - c->destroy(); - return 0; -} - - -int32_t AppComponent::init() -{ - for (IAppComponent *c : m_Childs) - c->init(); - return 0; -} - - -int32_t AppComponent::deinit() -{ - for (IAppComponent *c : m_Childs) - c->deinit(); - return 0; -} - - -int32_t AppComponent::start() -{ - for (IAppComponent *c : m_Childs) - c->start(); - return 0; -} - - -int32_t AppComponent::stop() -{ - for (IAppComponent *c : m_Childs) - c->stop(); - return 0; -} - - -void AppComponent::addChild(IAppComponent *a_child, const QString &a_name) -{ - if (a_child) + int32_t AppComponent::create(NGL::Settings *settings) { - a_child->setName(a_name); - m_Childs.push_back(a_child); + for (IAppComponent *c : m_Childs) + c->create(settings); + return 0; } -} -IAppComponent *AppComponent::getChild(const QString &a_name) -{ - for (IAppComponent *c : m_Childs) + int32_t AppComponent::destroy() { - if (a_name == c->getName()) - return c; + for (IAppComponent *c : m_Childs) + c->destroy(); + return 0; + } + + + int32_t AppComponent::init() + { + for (IAppComponent *c : m_Childs) + c->init(); + return 0; + } + + + int32_t AppComponent::deinit() + { + for (IAppComponent *c : m_Childs) + c->deinit(); + return 0; + } + + + int32_t AppComponent::start() + { + for (IAppComponent *c : m_Childs) + c->start(); + return 0; + } + + + int32_t AppComponent::stop() + { + for (IAppComponent *c : m_Childs) + c->stop(); + return 0; + } + + + void AppComponent::addChild(IAppComponent *a_child, const QString &a_name) + { + if (a_child) + { + a_child->setName(a_name); + m_Childs.push_back(a_child); + } + } + + + IAppComponent *AppComponent::getChild(const QString &a_name) + { + for (IAppComponent *c : m_Childs) + { + if (a_name == c->getName()) + return c; + } + return nullptr; } - return nullptr; -} } // namespace N_AppComponent - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.hpp index cafe1014c..bc17aa20f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/AppComponent.hpp @@ -1,12 +1,12 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ -// +// // Implementation of the Class AppComponent // ************************************************************************** @@ -16,30 +16,32 @@ #include "IAppComponent.hpp" #include "prtcnvlib_export.h" -namespace NGL { -class Settings; +namespace NGL +{ + class Settings; } namespace N_AppComponent { -class PRTCNVLIB_EXPORT AppComponent : public N_AppComponent::IAppComponent -{ -public: - AppComponent() = default; - ~AppComponent() = default; + class PRTCNVLIB_EXPORT AppComponent : public N_AppComponent::IAppComponent + { + public: + AppComponent() = default; + ~AppComponent() = default; - int32_t create(NGL::Settings *settings) override; - int32_t deinit() override; - int32_t destroy() override; - int32_t init() override; - int32_t start() override; - int32_t stop() override; + int32_t create(NGL::Settings *settings) override; + int32_t deinit() override; + int32_t destroy() override; + int32_t init() override; + int32_t start() override; + int32_t stop() override; -protected: - void addChild(IAppComponent* a_child, const QString& a_name = QString()); - IAppComponent* getChild(const QString& a_name); -private: - std::vector m_Childs; -}; + protected: + void addChild(IAppComponent *a_child, const QString &a_name = QString()); + IAppComponent *getChild(const QString &a_name); + + private: + std::vector m_Childs; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/IAppComponent.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/IAppComponent.hpp index 0b3be5bb9..cd2a231d7 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/IAppComponent.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/IAppComponent.hpp @@ -1,12 +1,12 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ -// +// // Implementation of the Class IAppComponent // ************************************************************************** @@ -14,7 +14,8 @@ #include -namespace NGL { +namespace NGL +{ class Settings; } @@ -44,14 +45,9 @@ namespace N_AppComponent virtual int32_t stop() = 0; - inline const QString& getName() const - { - return m_Name; - } - inline void setName(const QString& newVal) - { - m_Name = newVal; - } + inline const QString &getName() const { return m_Name; } + inline void setName(const QString &newVal) { m_Name = newVal; } + protected: QString m_Name; }; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/main.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/main.cpp index f9982346f..083b04924 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/main.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/main.cpp @@ -41,9 +41,7 @@ int main(int argc, char **argv) TetraIF::usage(); } const QString mode = args[3].toLower(); - if (mode != QLatin1String("listen") && - mode != QLatin1String("send_random") && - mode != QLatin1String("send_file")) + if (mode != QLatin1String("listen") && mode != QLatin1String("send_random") && mode != QLatin1String("send_file")) { ERROR_LOG(logger) << "Invalid mode " << args[3]; TetraIF::usage(); diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.cpp index 0afa42cf6..c15992a65 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.cpp @@ -35,9 +35,10 @@ TetraIF::TetraIF(const QHostAddress &addr, unsigned short port, unsigned short i , m_timer(nullptr) , m_SendCounter(0) ), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) { + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) +{ connect(m_socket, &QTcpSocket::connected, this, &TetraIF::onConnected); - connect(m_socket, &QTcpSocket::disconnected, this, &TetraIF::onDisconnected); + connect(m_socket, &QTcpSocket::disconnected, this, &TetraIF::onDisconnected); connect(m_socket, &QTcpSocket::readyRead, this, &TetraIF::onReadyRead); connect(m_socket, &QAbstractSocket::errorOccurred, this, &TetraIF::onError); @@ -60,8 +61,7 @@ void TetraIF::listenMode(const QStringList &args) m_outputDir = args[0]; if (!QDir().mkpath(m_outputDir)) { - ERROR_LOG(m_logger) << "Error creating directory " - << m_outputDir; + ERROR_LOG(m_logger) << "Error creating directory " << m_outputDir; usage(); } @@ -100,10 +100,8 @@ void TetraIF::randomMode(const QStringList &args) parseISSIs(args.mid(3)); - INFO_LOG(m_logger) << "Sending " << m_data.size() - << " bytes, " << m_telegramsPerSecond - << " telegrams/second for " << m_count - << " time(s) to issi(s) " << getIssisAsString(); + INFO_LOG(m_logger) << "Sending " << m_data.size() << " bytes, " << m_telegramsPerSecond << " telegrams/second for " << m_count << " time(s) to issi(s) " + << getIssisAsString(); setupTimer(); } @@ -136,19 +134,14 @@ void TetraIF::fileMode(const QStringList &args) } if (!f.open(QIODevice::ReadOnly)) { - ERROR_LOG(m_logger) << "Error opening file " - << f.fileName() - << " for reading - error: " - << f.errorString(); + ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for reading - error: " << f.errorString(); } m_data = f.readAll(); parseISSIs(args.mid(3)); - INFO_LOG(m_logger) << "Sending " << m_data.size() - << " bytes, " << m_telegramsPerSecond - << " telegrams/second for " << m_count - << " time(s) to issi(s) " << getIssisAsString(); + INFO_LOG(m_logger) << "Sending " << m_data.size() << " bytes, " << m_telegramsPerSecond << " telegrams/second for " << m_count << " time(s) to issi(s) " + << getIssisAsString(); setupTimer(); } @@ -189,16 +182,12 @@ void TetraIF::onReadyRead() m_socket->peek(reinterpret_cast(&header), sizeof(header)); if (N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER != header.m_MagicNumber) { - ERROR_LOG(m_logger) << "Incorrect magic number (0x" - << QString::number(header.m_MagicNumber, 16) - << " - aborting"; + ERROR_LOG(m_logger) << "Incorrect magic number (0x" << QString::number(header.m_MagicNumber, 16) << " - aborting"; exit(2); } if (!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(header.m_Length)) { - ERROR_LOG(m_logger) << "Radio-Telegram length to big: " - << header.m_Length - << ", but I proceed with this telegram."; + ERROR_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length << ", but I proceed with this telegram."; } const quint16 dataSize = header.m_Length + sizeof(header); @@ -211,17 +200,12 @@ void TetraIF::onReadyRead() m_socket->read(buf.data(), dataSize); handleReceivedTelegram(buf); - } - while (m_socket->bytesAvailable()); + } while (m_socket->bytesAvailable()); } void TetraIF::onError(QAbstractSocket::SocketError err) { - ERROR_LOG(m_logger) << "Socket error " - << err - << " (" - << m_socket->errorString() - << ") - aborting"; + ERROR_LOG(m_logger) << "Socket error " << err << " (" << m_socket->errorString() << ") - aborting"; exit(2); } @@ -238,28 +222,28 @@ void TetraIF::handleReceivedTelegram(const QByteArray &data) switch (type) { - // response to register indication - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: - handleRegisterRsp(data.at(5)); // registration status - break; + // response to register indication + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: + handleRegisterRsp(data.at(5)); // registration status + break; - // payload telegram - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: - handleDataIndReq(data); - break; + // payload telegram + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: + handleDataIndReq(data); + break; - // ack-telegram - not handled here - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: - // handleReportIndReq(data); - break; + // ack-telegram - not handled here + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: + // handleReportIndReq(data); + break; - // air-interface-load-telegram - not handled here - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: - // handleAirInterfaceLoadReq(data); - break; + // air-interface-load-telegram - not handled here + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: + // handleAirInterfaceLoadReq(data); + break; - default: - return; + default: + return; } INFO_LOG(m_logger) << "PDU Type: " << type; dumpData(data); @@ -270,29 +254,29 @@ void TetraIF::handleRegisterRsp(const uint8_t a_registrationStatus) QByteArray logText; switch (a_registrationStatus) { - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_IssiSuccessfulRegistered: - INFO_LOG(m_logger) << "Valid register response from Tetra "; - if (m_timer) - m_timer->start(); - return; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DuplicateISSI: - logText = "TETRA: Register-Response: Status=Duplicate ISSI"; - break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidISSI: - logText = "TETRA: Register-Response: Status=Invalid ISSI"; - break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidIpAddress: - logText = "TETRA: Register-Response: Status=Invalid IP address => Configure TETRA for accepting our IP-address ("; - { - const QList ipList = QNetworkInterface::allAddresses(); - for (const QHostAddress &addr : ipList) - logText += addr.toString().toUtf8() + ", "; - logText += ")..."; - } - break; - default: - logText = "Unknown registration status: " + QByteArray::number(a_registrationStatus); - break; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_IssiSuccessfulRegistered: + INFO_LOG(m_logger) << "Valid register response from Tetra "; + if (m_timer) + m_timer->start(); + return; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DuplicateISSI: + logText = "TETRA: Register-Response: Status=Duplicate ISSI"; + break; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidISSI: + logText = "TETRA: Register-Response: Status=Invalid ISSI"; + break; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidIpAddress: + logText = "TETRA: Register-Response: Status=Invalid IP address => Configure TETRA for accepting our IP-address ("; + { + const QList ipList = QNetworkInterface::allAddresses(); + for (const QHostAddress &addr : ipList) + logText += addr.toString().toUtf8() + ", "; + logText += ")..."; + } + break; + default: + logText = "Unknown registration status: " + QByteArray::number(a_registrationStatus); + break; } ERROR_LOG(m_logger) << logText; @@ -310,10 +294,7 @@ void TetraIF::dumpData(const QByteArray &data) QFile f(m_outputDir + timeStr + QLatin1String(".dat")); if (!f.open(QIODevice::WriteOnly)) { - ERROR_LOG(m_logger) << "Error opening file " - << f.fileName() - << " for writing - error: " - << f.errorString(); + ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for writing - error: " << f.errorString(); } f.write(data); f.close(); @@ -321,20 +302,12 @@ void TetraIF::dumpData(const QByteArray &data) if (data.size() > 27) { N_CoPrtCnv::CoPrtCnvRadioTelegram tele(data); - INFO_LOG(m_logger) << "Got telegram from " - << tele.getSrcISSI() - << " with size " - << data.size() - << " and payload size " - << tele.getPayloadSize(); + INFO_LOG(m_logger) << "Got telegram from " << tele.getSrcISSI() << " with size " << data.size() << " and payload size " << tele.getPayloadSize(); NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, tele.data()); QFile f(m_outputDir + QStringLiteral("payload-%1-%2.dat").arg(QString::number(tele.getSrcISSI()), timeStr)); if (!f.open(QIODevice::WriteOnly)) { - ERROR_LOG(m_logger) << "Error opening file " - << f.fileName() - << " for writing - error: " - << f.errorString(); + ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for writing - error: " << f.errorString(); } // 27 Bytes Header entfernen f.write(&data.data()[27], data.size() - 27); @@ -423,15 +396,15 @@ void TetraIF::handleDataIndReq(const QByteArray &data) switch (radioTelegram->getFragmentStatus()) { - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment: - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment: - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment: - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented: - handleLoginTelegram(radioTelegram); - break; - default: - ERROR_LOG(m_logger) << "Unknown payload-status!: " << radioTelegram->getFragmentStatus(); - break; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented: + handleLoginTelegram(radioTelegram); + break; + default: + ERROR_LOG(m_logger) << "Unknown payload-status!: " << radioTelegram->getFragmentStatus(); + break; } delete radioTelegram; // this deletes also a_data @@ -452,7 +425,6 @@ void TetraIF::handleLoginTelegram(N_CoPrtCnv::CoPrtCnvRadioTelegram *a_loginTele INFO_LOG(m_logger) << "Login: New TPU with Id=" << identity << " and ISSI=" << issi << " is NOT logged in"; } - } bool TetraIF::sendLoginResponse(const uint32_t a_ISSI) @@ -474,12 +446,12 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI) a_telegram->setPayloadData(0x01); a_telegram->setPayloadData(0x04); // Bitanzahl anpassen - a_telegram->getData()[22] = 0x0d; // Warum 13 (bzw. 21) ?? + a_telegram->getData()[22] = 0x0d; // Warum 13 (bzw. 21) ?? char *data = a_telegram->getData(); // Header - complete Payload in Bytes - data[02] = 0x18; // 24 Bytes + data[02] = 0x18; // 24 Bytes // Len in Bits data[22] = 0x0d; data[23] = 0x00; @@ -494,7 +466,6 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI) m_socket->write(data, 28); delete a_telegram; return m_socket->flush(); - } void TetraIF::setupTimer() diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.h b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.h index e080dad3a..60e7dc93f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTest/tetra_if.h @@ -32,8 +32,9 @@ protected Q_SLOTS: void onReadyRead(); void onError(QAbstractSocket::SocketError); void onSendData(); + protected: -NGL::INGLLogger &m_logger; + NGL::INGLLogger &m_logger; void doInitialLogin(); void handleReceivedTelegram(const QByteArray &data); void handleRegisterRsp(const uint8_t a_registrationStatus); diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.cpp index da80de76d..b7ce3000f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.cpp @@ -10,10 +10,9 @@ #include - -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow) +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) { ui->setupUi(this); init(); @@ -33,11 +32,11 @@ void MainWindow::changeEvent(QEvent *e) QMainWindow::changeEvent(e); switch (e->type()) { - case QEvent::LanguageChange: - ui->retranslateUi(this); - break; - default: - break; + case QEvent::LanguageChange: + ui->retranslateUi(this); + break; + default: + break; } } @@ -70,7 +69,6 @@ void MainWindow::slot_findFolder() QString name = QFileDialog::getExistingDirectory(this, tr("Choose folder"), QDir::homePath(), QFileDialog::DontResolveSymlinks); ui->lineEditOrdner->setText(name); ui->labelResult->setText(QString()); - } void MainWindow::slot_analysieren() @@ -170,7 +168,6 @@ void MainWindow::readFiles() writeToLogfile(issi, timeStart, getTimestamp(m_files[j]), m_files[j], nr); writeLogZeiten(timeStart, getTimestamp(m_files[j]), issi); - } } file.close(); @@ -181,7 +178,6 @@ void MainWindow::readFiles() ui->progressBar->setValue(int(val)); // ui->progressBar->repaint(); } - } void MainWindow::openLogfile(const QString &folder, int count) @@ -203,14 +199,9 @@ void MainWindow::openLogfile(const QString &folder, int count) file.write("ISSI;Sending Time ; Receiving Time\n"); file.close(); } - } -void MainWindow::writeToLogfile(const QString &issi, - const QDateTime ×tamp, - const QString &filename, - uint lfdNr, - const QString &bytes) +void MainWindow::writeToLogfile(const QString &issi, const QDateTime ×tamp, const QString &filename, uint lfdNr, const QString &bytes) { QString text = issi; text += QLatin1String(": "); @@ -235,11 +226,7 @@ void MainWindow::writeToLogfile(const QString &issi, m_logfileList.append(info); } -void MainWindow::writeToLogfile(const QString &issi, - const QDateTime &sendeZeit, - const QDateTime ×tamp, - const QString &filename, - uint lfdNr) +void MainWindow::writeToLogfile(const QString &issi, const QDateTime &sendeZeit, const QDateTime ×tamp, const QString &filename, uint lfdNr) { QString text = issi; text += QLatin1String(": "); @@ -269,7 +256,7 @@ QDateTime MainWindow::getTimestamp(const QString &filename) const const auto list1 = filename.split(QLatin1Char('-')); if (list1.size() < 2) return {}; - + const QString &fn = list1.at(1); const auto list2 = fn.split(QLatin1Char('.')); auto str = list2.at(0); @@ -284,7 +271,7 @@ QString MainWindow::getISSI(QByteArray ar) ar.remove(0, 5); ar.remove(4, 200); QByteArray issi = ar.toHex(); - + if (ar.size() == 4) { if (ar[2] == '\0' && ar[3] == '\0') @@ -299,7 +286,6 @@ QString MainWindow::getISSI(QByteArray ar) hex[i] = c - '0'; else if (c >= 'a' && c <= 'f') hex[i] = c - 'a' + 10; - } int sum = 0; sum += hex[1]; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.h b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.h index 1f65e1165..d49ac7744 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/LastTestAuswertung/mainwindow.h @@ -7,7 +7,7 @@ namespace Ui { -class MainWindow; + class MainWindow; } struct LogfileInfo @@ -41,17 +41,9 @@ private: QString m_logfile; QString m_logZeiten; void openLogfile(const QString &folder, int count); - void writeToLogfile(const QString &issi, - const QDateTime ×tamp, - const QString &filename, - uint lfdNr, - const QString &bytes); - void writeToLogfile(const QString &issi, - const QDateTime &sendeZeit, - const QDateTime ×tamp, - const QString &filename, - uint lfdNr); - QString getISSI(QByteArray ar);//Für alte TPUS + void writeToLogfile(const QString &issi, const QDateTime ×tamp, const QString &filename, uint lfdNr, const QString &bytes); + void writeToLogfile(const QString &issi, const QDateTime &sendeZeit, const QDateTime ×tamp, const QString &filename, uint lfdNr); + QString getISSI(QByteArray ar); //Für alte TPUS int auswerten(); QVector getFehlendeNums(const QVector &numsDurchgang); int fehlendeNumsEintragen(const QVector &numList, QFile &file); @@ -65,5 +57,4 @@ private slots: }; - #endif // MAINWINDOW_H diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.cpp index 057632af4..af5487327 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.cpp @@ -28,382 +28,362 @@ namespace PrtCnv { -static std::string threadIdToString(PrtCnvApplication::E_ThreadId id) -{ - switch (id) + static std::string threadIdToString(PrtCnvApplication::E_ThreadId id) { - case PrtCnvApplication::e_Central: - return "Central"; - case PrtCnvApplication::e_Radio: - return "Radio"; - case PrtCnvApplication::e_Db: - return "Db"; - case PrtCnvApplication::e_Log: - return "Log"; - case PrtCnvApplication::e_Injection: - return "Injection"; - case PrtCnvApplication::e_RadioTraffic: - return "RadioTraffic"; - case PrtCnvApplication::e_ThreadIdMax: - break; + switch (id) + { + case PrtCnvApplication::e_Central: + return "Central"; + case PrtCnvApplication::e_Radio: + return "Radio"; + case PrtCnvApplication::e_Db: + return "Db"; + case PrtCnvApplication::e_Log: + return "Log"; + case PrtCnvApplication::e_Injection: + return "Injection"; + case PrtCnvApplication::e_RadioTraffic: + return "RadioTraffic"; + case PrtCnvApplication::e_ThreadIdMax: + break; + } + return std::to_string(id); } - return std::to_string(id); -} -PrtCnvApplication::PrtCnvApplication() - : m_Config(nullptr) - , m_exerciseId(0) - , m_logger(getLogger("PrtCnvApplication")) -{} - - -PrtCnvApplication::~PrtCnvApplication() -{ - delete m_Config; - for (const auto &ti : m_threadInfo) - delete ti.thread; -} - - -// --------------------------------------------------------------- -// Synchronisation of threads before create(). -// --------------------------------------------------------------- -void PrtCnvApplication::waitForCreate(const E_ThreadId a_threadId) -{ - INFO_LOG(m_logger) << "Wait for others until we can create " << threadIdToString(a_threadId); - setConstructed(a_threadId); - switch (a_threadId) + PrtCnvApplication::PrtCnvApplication() + : m_Config(nullptr) + , m_exerciseId(0) + , m_logger(getLogger("PrtCnvApplication")) { - case e_Central: - while (!(isConstructed(e_Db) && - isConstructed(e_Radio) && - isConstructed(e_Log) && - isConstructed(e_Injection))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - - case e_Radio: - while (!(isConstructed(e_Db) && - isConstructed(e_Central) && - isConstructed(e_Log) && - isConstructed(e_Injection))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - - case e_Db: - while (!(isConstructed(e_Radio) && - isConstructed(e_Central))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - default: - break; } - INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId); -} -// --------------------------------------------------------------- -// Synchronisation of threads before init(). -// --------------------------------------------------------------- -void PrtCnvApplication::waitForInit(E_ThreadId a_threadId) -{ - INFO_LOG(m_logger) << "Wait for others until we can initialize " << threadIdToString(a_threadId); - setCreated(a_threadId); - switch (a_threadId) + PrtCnvApplication::~PrtCnvApplication() { - case e_Central: - while (!(isCreated(e_Db) && - isCreated(e_Radio))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - - case e_Radio: - while (!(isCreated(e_Db) && - isCreated(e_Central))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - - case e_Db: - while (!(isCreated(e_Radio) && - isCreated(e_Central))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - default: - break; + delete m_Config; + for (const auto &ti : m_threadInfo) + delete ti.thread; } - INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId); -} -// --------------------------------------------------------------- -// Synchronisation of threads before start(). -// --------------------------------------------------------------- -void PrtCnvApplication::waitForStart(E_ThreadId a_threadId) -{ - INFO_LOG(m_logger) << "Wait for others until we can start " << threadIdToString(a_threadId); - setInitialized(a_threadId); - switch (a_threadId) + + // --------------------------------------------------------------- + // Synchronisation of threads before create(). + // --------------------------------------------------------------- + void PrtCnvApplication::waitForCreate(const E_ThreadId a_threadId) { - case e_Central: - while (!(isStarted(e_Db) && - isInitialized(e_Radio) && - isStarted(e_Log) && - isStarted(e_Injection))) + INFO_LOG(m_logger) << "Wait for others until we can create " << threadIdToString(a_threadId); + setConstructed(a_threadId); + switch (a_threadId) { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; + case e_Central: + while (!(isConstructed(e_Db) && isConstructed(e_Radio) && isConstructed(e_Log) && isConstructed(e_Injection))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; - case e_Radio: - while (!(isStarted(e_Db) && - isInitialized(e_Central) && - isStarted(e_Log) && - isStarted(e_Injection) && - isInitialized(e_RadioTraffic))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; + case e_Radio: + while (!(isConstructed(e_Db) && isConstructed(e_Central) && isConstructed(e_Log) && isConstructed(e_Injection))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; - case e_Db: - while (!(isInitialized(e_Radio) && - isInitialized(e_Central) && - isStarted(e_Log))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); + case e_Db: + while (!(isConstructed(e_Radio) && isConstructed(e_Central))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + default: + break; } - break; - - case e_RadioTraffic: - while (!(isInitialized(e_Radio) && - isStarted(e_Log))) - { - DEBUG_LOG(m_logger) << "wait..."; - QThread::sleep(1); - } - break; - default: - break; + INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId); } - INFO_LOG(m_logger) << "Now we can start " << threadIdToString(a_threadId); -} -// --------------------------------------------------------------- -// Synchronisation of threads before execution of thread. -// --------------------------------------------------------------- -void PrtCnvApplication::waitForExec(E_ThreadId a_threadId) -{ - setStarted(a_threadId); -} - -// --------------------------------------------------------------- -// Starts the main-application -// --------------------------------------------------------------- -void PrtCnvApplication::startApp() -{ - createApplication(); - init(); - start(); -} - -void PrtCnvApplication::shutdownApp() -{ - stop(); - deinit(); - destroy(); - for (const auto &ti : m_threadInfo) - ti.thread->quit(); - for (const auto &ti : m_threadInfo) - ti.thread->wait(); - for (auto &ti : m_threadInfo) + // --------------------------------------------------------------- + // Synchronisation of threads before init(). + // --------------------------------------------------------------- + void PrtCnvApplication::waitForInit(E_ThreadId a_threadId) { - delete ti.thread; - ti.thread = nullptr; + INFO_LOG(m_logger) << "Wait for others until we can initialize " << threadIdToString(a_threadId); + setCreated(a_threadId); + switch (a_threadId) + { + case e_Central: + while (!(isCreated(e_Db) && isCreated(e_Radio))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + + case e_Radio: + while (!(isCreated(e_Db) && isCreated(e_Central))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + + case e_Db: + while (!(isCreated(e_Radio) && isCreated(e_Central))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + default: + break; + } + INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId); } -} -void PrtCnvApplication::setCleanDb(bool bCleanDb) -{ - PrtCnvThread::m_DoCleanDb = bCleanDb; -} - -void PrtCnvApplication::setExerciseId(int exerciseId) -{ - m_exerciseId = exerciseId; -} - -void PrtCnvApplication::setConfigFile(const QString &configFile) -{ - m_ConfigFileName = configFile; -} - -// --------------------------------------------------------------- -// Creates the childs -// --------------------------------------------------------------- -int32_t PrtCnvApplication::createApplication() -{ - setName(QStringLiteral("Common")); - if (m_ConfigFileName.isEmpty()) + // --------------------------------------------------------------- + // Synchronisation of threads before start(). + // --------------------------------------------------------------- + void PrtCnvApplication::waitForStart(E_ThreadId a_threadId) { - m_ConfigFileName = QCoreApplication::applicationDirPath(); - if (m_exerciseId > 0) - m_ConfigFileName += QStringLiteral("/PrtCnv_ex_") + QString::number(m_exerciseId) + QStringLiteral(".dat"); - else - m_ConfigFileName += QStringLiteral("/PrtCnv.dat"); + INFO_LOG(m_logger) << "Wait for others until we can start " << threadIdToString(a_threadId); + setInitialized(a_threadId); + switch (a_threadId) + { + case e_Central: + while (!(isStarted(e_Db) && isInitialized(e_Radio) && isStarted(e_Log) && isStarted(e_Injection))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + + case e_Radio: + while (!(isStarted(e_Db) && isInitialized(e_Central) && isStarted(e_Log) && isStarted(e_Injection) && isInitialized(e_RadioTraffic))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + + case e_Db: + while (!(isInitialized(e_Radio) && isInitialized(e_Central) && isStarted(e_Log))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + + case e_RadioTraffic: + while (!(isInitialized(e_Radio) && isStarted(e_Log))) + { + DEBUG_LOG(m_logger) << "wait..."; + QThread::sleep(1); + } + break; + default: + break; + } + INFO_LOG(m_logger) << "Now we can start " << threadIdToString(a_threadId); } - m_Config = new NGL::Settings(m_ConfigFileName); - std::cout << "Use config-file: " << qPrintable(m_ConfigFileName) << std::endl; - - for (int i = 0; i < e_ThreadIdMax; i++) - m_threadInfo[i].thread = new PrtCnvThreadStarter((E_ThreadId)i, m_ConfigFileName, this); - - N_AppComponent::AppComponent::create(m_Config); - - return 0; -} - -// --------------------------------------------------------------- -// Starts the childs and then the main application -// --------------------------------------------------------------- -int32_t PrtCnvApplication::start() -{ - // start and create threads - for (const auto &ti : m_threadInfo) - ti.thread->start(); - - N_AppComponent::AppComponent::start(); - - return 0; -} -// --------------------------------------------------------------- -// Returns the desired thread-starter -// --------------------------------------------------------------- -PrtCnv::PrtCnvThreadStarter *PrtCnvApplication::getThreadStarter(const E_ThreadId a_threadId) -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return nullptr; + // --------------------------------------------------------------- + // Synchronisation of threads before execution of thread. + // --------------------------------------------------------------- + void PrtCnvApplication::waitForExec(E_ThreadId a_threadId) + { + setStarted(a_threadId); + } - QMutexLocker l(&m_accessMutex); - return m_threadInfo[a_threadId].thread; -} + // --------------------------------------------------------------- + // Starts the main-application + // --------------------------------------------------------------- + void PrtCnvApplication::startApp() + { + createApplication(); + init(); + start(); + } -void PrtCnvApplication::setDatabaseConnectionParams(const QString &driver, - const QString &hostName, - const QString &database, - const QString &schemaName, - const QString &userName, - const QString &password) -{ - m_dbDriver = driver; - m_dbHostName = hostName; - m_dbDatabaseName = database; - m_dbSchemaName = schemaName; - m_dbUserName = userName; - m_dbPassword = password; -} + void PrtCnvApplication::shutdownApp() + { + stop(); + deinit(); + destroy(); + for (const auto &ti : m_threadInfo) + ti.thread->quit(); + for (const auto &ti : m_threadInfo) + ti.thread->wait(); + for (auto &ti : m_threadInfo) + { + delete ti.thread; + ti.thread = nullptr; + } + } -void PrtCnvApplication::logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, - bool bIsSend) -{ - const auto threadHandler = m_threadInfo[e_Log].thread; - PrtCnvTelegramLogThread *t = static_cast(threadHandler ? threadHandler->getThread() : nullptr); - if (t) - t->writeWlsTelegramLog(tele, bIsSend, 0); -} + void PrtCnvApplication::setCleanDb(bool bCleanDb) + { + PrtCnvThread::m_DoCleanDb = bCleanDb; + } -// --------------------------------------------------------------- -bool PrtCnvApplication::isConstructed(const E_ThreadId a_threadId) const -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return false; - QMutexLocker l(&m_accessMutex); - return m_threadInfo[a_threadId].isConstructed; -} + void PrtCnvApplication::setExerciseId(int exerciseId) + { + m_exerciseId = exerciseId; + } -// --------------------------------------------------------------- -void PrtCnvApplication::setConstructed(const E_ThreadId a_threadId) -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return; - QMutexLocker l(&m_accessMutex); - m_threadInfo[a_threadId].isConstructed = true; -} + void PrtCnvApplication::setConfigFile(const QString &configFile) + { + m_ConfigFileName = configFile; + } -// --------------------------------------------------------------- -bool PrtCnvApplication::isInitialized(const E_ThreadId a_threadId) const -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return false; - QMutexLocker l(&m_accessMutex); - return m_threadInfo[a_threadId].isInitialized; -} + // --------------------------------------------------------------- + // Creates the childs + // --------------------------------------------------------------- + int32_t PrtCnvApplication::createApplication() + { + setName(QStringLiteral("Common")); + if (m_ConfigFileName.isEmpty()) + { + m_ConfigFileName = QCoreApplication::applicationDirPath(); + if (m_exerciseId > 0) + m_ConfigFileName += QStringLiteral("/PrtCnv_ex_") + QString::number(m_exerciseId) + QStringLiteral(".dat"); + else + m_ConfigFileName += QStringLiteral("/PrtCnv.dat"); + } + m_Config = new NGL::Settings(m_ConfigFileName); + std::cout << "Use config-file: " << qPrintable(m_ConfigFileName) << std::endl; -// --------------------------------------------------------------- -void PrtCnvApplication::setInitialized(const E_ThreadId a_threadId) -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return; - QMutexLocker l(&m_accessMutex); - m_threadInfo[a_threadId].isInitialized = true; -} + for (int i = 0; i < e_ThreadIdMax; i++) + m_threadInfo[i].thread = new PrtCnvThreadStarter((E_ThreadId)i, m_ConfigFileName, this); -// --------------------------------------------------------------- -bool PrtCnvApplication::isCreated(const E_ThreadId a_threadId) const -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return false; - QMutexLocker l(&m_accessMutex); - return m_threadInfo[a_threadId].isCreated; -} + N_AppComponent::AppComponent::create(m_Config); -// --------------------------------------------------------------- -void PrtCnvApplication::setCreated(const E_ThreadId a_threadId) -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return; - QMutexLocker l(&m_accessMutex); - m_threadInfo[a_threadId].isCreated = true; -} + return 0; + } -// --------------------------------------------------------------- -bool PrtCnvApplication::isStarted(const E_ThreadId a_threadId) const -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return false; - QMutexLocker l(&m_accessMutex); - return m_threadInfo[a_threadId].isStarted; -} + // --------------------------------------------------------------- + // Starts the childs and then the main application + // --------------------------------------------------------------- + int32_t PrtCnvApplication::start() + { + // start and create threads + for (const auto &ti : m_threadInfo) + ti.thread->start(); -// --------------------------------------------------------------- -void PrtCnvApplication::setStarted(const E_ThreadId a_threadId) -{ - if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) - return; - QMutexLocker l(&m_accessMutex); - m_threadInfo[a_threadId].isStarted = true; -} + N_AppComponent::AppComponent::start(); + + return 0; + } + + + // --------------------------------------------------------------- + // Returns the desired thread-starter + // --------------------------------------------------------------- + PrtCnv::PrtCnvThreadStarter *PrtCnvApplication::getThreadStarter(const E_ThreadId a_threadId) + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return nullptr; + + QMutexLocker l(&m_accessMutex); + return m_threadInfo[a_threadId].thread; + } + + void PrtCnvApplication::setDatabaseConnectionParams(const QString &driver, + const QString &hostName, + const QString &database, + const QString &schemaName, + const QString &userName, + const QString &password) + { + m_dbDriver = driver; + m_dbHostName = hostName; + m_dbDatabaseName = database; + m_dbSchemaName = schemaName; + m_dbUserName = userName; + m_dbPassword = password; + } + + void PrtCnvApplication::logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool bIsSend) + { + const auto threadHandler = m_threadInfo[e_Log].thread; + PrtCnvTelegramLogThread *t = static_cast(threadHandler ? threadHandler->getThread() : nullptr); + if (t) + t->writeWlsTelegramLog(tele, bIsSend, 0); + } + + // --------------------------------------------------------------- + bool PrtCnvApplication::isConstructed(const E_ThreadId a_threadId) const + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return false; + QMutexLocker l(&m_accessMutex); + return m_threadInfo[a_threadId].isConstructed; + } + + // --------------------------------------------------------------- + void PrtCnvApplication::setConstructed(const E_ThreadId a_threadId) + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return; + QMutexLocker l(&m_accessMutex); + m_threadInfo[a_threadId].isConstructed = true; + } + + // --------------------------------------------------------------- + bool PrtCnvApplication::isInitialized(const E_ThreadId a_threadId) const + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return false; + QMutexLocker l(&m_accessMutex); + return m_threadInfo[a_threadId].isInitialized; + } + + // --------------------------------------------------------------- + void PrtCnvApplication::setInitialized(const E_ThreadId a_threadId) + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return; + QMutexLocker l(&m_accessMutex); + m_threadInfo[a_threadId].isInitialized = true; + } + + // --------------------------------------------------------------- + bool PrtCnvApplication::isCreated(const E_ThreadId a_threadId) const + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return false; + QMutexLocker l(&m_accessMutex); + return m_threadInfo[a_threadId].isCreated; + } + + // --------------------------------------------------------------- + void PrtCnvApplication::setCreated(const E_ThreadId a_threadId) + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return; + QMutexLocker l(&m_accessMutex); + m_threadInfo[a_threadId].isCreated = true; + } + + // --------------------------------------------------------------- + bool PrtCnvApplication::isStarted(const E_ThreadId a_threadId) const + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return false; + QMutexLocker l(&m_accessMutex); + return m_threadInfo[a_threadId].isStarted; + } + + // --------------------------------------------------------------- + void PrtCnvApplication::setStarted(const E_ThreadId a_threadId) + { + if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax) + return; + QMutexLocker l(&m_accessMutex); + m_threadInfo[a_threadId].isStarted = true; + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.hpp index bdafaa32d..15c6d6177 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvApplication.hpp @@ -37,11 +37,12 @@ namespace PrtCnv * @version 1.0 * @created 23-Jun-2009 17:48:47 */ - class PRTCNVLIB_EXPORT PrtCnvApplication : public QObject, public N_AppComponent::AppComponent + class PRTCNVLIB_EXPORT PrtCnvApplication + : public QObject + , public N_AppComponent::AppComponent { Q_OBJECT public: - /** * This enum will be used to unique identify the threads * @@ -112,7 +113,7 @@ namespace PrtCnv * @param a_threadId Id of the desired thread-started (corresponding thread has * the same id) */ - PrtCnvThreadStarter* getThreadStarter(const E_ThreadId a_threadId); + PrtCnvThreadStarter *getThreadStarter(const E_ThreadId a_threadId); /** * @brief Set the database connection parameter when used as library @@ -130,15 +131,16 @@ namespace PrtCnv QString databaseUserName() const { return m_dbUserName; } QString databasePassword() const { return m_dbPassword; } -public slots: + public slots: void logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool bIsSend); -signals: + signals: void textMessageFromPrtCnvToCentral(const QByteArray &ba); void textMessageFromCentralToPrtCnv(const QByteArray &ba); void outgoingBroadcastTelegramsRequest(int equipmentNumber, int broadcastIndex, int resetCounter); void warehouseMessageFromPtrCnv(const QByteArray &jsonData); -protected: + + protected: /** * Creates the childs */ @@ -188,7 +190,7 @@ protected: */ void setStarted(const E_ThreadId a_threadId); -protected: + protected: /** * Used to get configuration-parameter */ @@ -211,7 +213,6 @@ protected: */ int m_exerciseId; - mutable QRecursiveMutex m_accessMutex; @@ -223,6 +224,6 @@ protected: QString m_dbPassword; NGL::INGLLogger &m_logger; -}; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.cpp index 5371a6c6a..dca61ba3e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.cpp @@ -23,1688 +23,1637 @@ namespace PrtCnv { -PrtCnvBroadcastMgr::PrtCnvBroadcastMgr() : m_ClaimWindow(0) - , m_HighLoadFactor(0) - , m_BroadcastLimit(0) - , m_Config(nullptr) - , m_ActClaimWindow(0) - , m_State(e_ST_UNDEFINED) - , m_TickCounter(0) - , m_DbThread(nullptr) - , m_BroadcastIndex(0) - , m_IsFullLoad(false) - , m_FinishedBroadcastIndex(0) - , m_FirstBroadcastIndexOfBc1(0) - , m_logger(getLogger("PrtCnvBroadcastMgr")) - , m_loggerBcRequest(getLogger("PrtCnvBroadcastMgr.BcRequest")) -{ -} - -// --------------------------------------------------------------- -// Creates all subcomponents -// --------------------------------------------------------------- -int32_t PrtCnvBroadcastMgr::create(NGL::Settings *settings) -{ - m_Config = settings; - return 0; -} - -// --------------------------------------------------------------- -// Initializes the variables. -// --------------------------------------------------------------- -int32_t PrtCnvBroadcastMgr::init() -{ - const QString broadcastGroup(QStringLiteral("Broadcast")); - N_CoPrtCnv::CoPrtCnvRadioTelegram::setBroadcastDelayTimes( - m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastDelay2"), 60), - m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastDelay3"), 60)); - N_CoPrtCnv::CoPrtCnvRadioTelegram::setMaxBroadcastSendCnt(m_Config->getInteger(broadcastGroup, QStringLiteral("MaxBroadcastSendCount"), 1)); - // the time [ms] to wait between sending broadcasts - const int sendGap = m_Config->getInteger(broadcastGroup, QStringLiteral("SendGap"), 500); - m_ClaimWindow = (m_Config->getInteger(broadcastGroup, QStringLiteral("ClaimWindow"), 30) * 1000) / sendGap; - m_HighLoadFactor = m_Config->getInteger(broadcastGroup, QStringLiteral("HighLoadFactor"), 3); // fixme: in spec steht 90sec normal und 3min für high - m_BroadcastLimit = m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastLimit"), 10); - - cleanAndInit(true); - - INFO_LOG(m_loggerBcRequest) << "m_ActClaimWindow=" << m_ActClaimWindow << " m_State=" << m_State; - - return 0; -} - - -// --------------------------------------------------------------- -// sets the DbThread used for get the stored broadcast- -// telegrams -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::setDbThread(PrtCnvDbThread *a_dbThread) -{ - m_DbThread = a_dbThread; -} - - -// --------------------------------------------------------------- -// Initializes the broadcast-manager. If a_deleteTelegrams is -// true, all stored telegrams and maps will be deleted. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::cleanAndInit(const bool a_deleteTelegrams) -{ - if (a_deleteTelegrams) + PrtCnvBroadcastMgr::PrtCnvBroadcastMgr() + : m_ClaimWindow(0) + , m_HighLoadFactor(0) + , m_BroadcastLimit(0) + , m_Config(nullptr) + , m_ActClaimWindow(0) + , m_State(e_ST_UNDEFINED) + , m_TickCounter(0) + , m_DbThread(nullptr) + , m_BroadcastIndex(0) + , m_IsFullLoad(false) + , m_FinishedBroadcastIndex(0) + , m_FirstBroadcastIndexOfBc1(0) + , m_logger(getLogger("PrtCnvBroadcastMgr")) + , m_loggerBcRequest(getLogger("PrtCnvBroadcastMgr.BcRequest")) { - m_deactivatedAesArea2bcIndex.clear(); - m_deactivatedBcIndex2AesArea.clear(); - - m_deactivatedDusMine2bcIndex.clear(); - m_deactivatedBcIndex2DusMine.clear(); - - m_deactivatedFuncArea2bcIndex.clear(); - m_deactivatedBcIndex2FuncArea.clear(); - - m_BroadcastMap.clear(); - - m_LastTelegramMap.clear(); // the telegrams itself were already deleted while looping through broadcastmap - m_FunktionsraumTelegramMap.clear(); // the telegrams itself were already deleted while looping through broadcastmap - m_WirkfeldTelegramMapByKennung.clear(); // the telegrams itself were already deleted while looping through broadcastmap - m_WirkfeldTelegramMapByTime.clear(); // the telegrams itself were already deleted while looping through broadcastmap - - m_BroadcastIndex = 0; } - m_claimerArray.clear(); - - m_ActClaimWindow = m_ClaimWindow; - m_IsFullLoad = false; - m_TickCounter = 0; - m_State = e_ST_COLLECT; - - m_FinishedBroadcastIndex = 0; - m_FirstBroadcastIndexOfBc1 = 0; -} - -// --------------------------------------------------------------- -// returns true when the telegram should be sent to central -// --------------------------------------------------------------- -bool PrtCnvBroadcastMgr::handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) -{ - switch (a_radioTelegram.getTelID()) + // --------------------------------------------------------------- + // Creates all subcomponents + // --------------------------------------------------------------- + int32_t PrtCnvBroadcastMgr::create(NGL::Settings *settings) { - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: - handleNachforderungBroadcastTelegram(a_radioTelegram.getIdentity(), - a_radioTelegram.getPayloadDataUInt32(8, 2) + 1, - a_radioTelegram.getPayloadDataUInt8(7)); - return false; - default: - // nothing - break; + m_Config = settings; + return 0; } - return true; // => send the telegram to central -} -// --------------------------------------------------------------- -// Adds the TNE to the nachforderungs-list -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter) -{ - INFO_LOG(m_loggerBcRequest) << "Got NachforderungBroadcast from TNE with id=" << identity - << " resetCounter=" << resetCounter - << " broadcastIndex=" << broadcastIndex - 1 - << " m_TickCounter=" << m_TickCounter << " m_State=" << m_State; - if (resetCounter == m_DbThread->getResetCounter()) + // --------------------------------------------------------------- + // Initializes the variables. + // --------------------------------------------------------------- + int32_t PrtCnvBroadcastMgr::init() { - m_DbThread->incClaimCount(identity); - // already in there? - for (auto &ebi : m_claimerArray) - { - if (ebi.equipNo == identity) - { - ebi.bcIndex = broadcastIndex; - return; - } - } - m_claimerArray.emplace_back(identity, broadcastIndex); - return; + const QString broadcastGroup(QStringLiteral("Broadcast")); + N_CoPrtCnv::CoPrtCnvRadioTelegram::setBroadcastDelayTimes(m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastDelay2"), 60), + m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastDelay3"), 60)); + N_CoPrtCnv::CoPrtCnvRadioTelegram::setMaxBroadcastSendCnt(m_Config->getInteger(broadcastGroup, QStringLiteral("MaxBroadcastSendCount"), 1)); + // the time [ms] to wait between sending broadcasts + const int sendGap = m_Config->getInteger(broadcastGroup, QStringLiteral("SendGap"), 500); + m_ClaimWindow = (m_Config->getInteger(broadcastGroup, QStringLiteral("ClaimWindow"), 30) * 1000) / sendGap; + m_HighLoadFactor = m_Config->getInteger(broadcastGroup, QStringLiteral("HighLoadFactor"), 3); // fixme: in spec steht 90sec normal und 3min für high + m_BroadcastLimit = m_Config->getInteger(broadcastGroup, QStringLiteral("BroadcastLimit"), 10); + + cleanAndInit(true); + + INFO_LOG(m_loggerBcRequest) << "m_ActClaimWindow=" << m_ActClaimWindow << " m_State=" << m_State; + + return 0; } - WARNING_LOG(m_logger) << "NachforderungBroadcast from TNE with id=" << identity - << ": resetCounter different we have: " << int(m_DbThread->getResetCounter()) - << "; TNE has: " << resetCounter << " => discarded"; -} -// --------------------------------------------------------------- -// returns the next normal broadcast to send. -// Use the same a_currentTime in one tick-loop. -// --------------------------------------------------------------- -std::shared_ptr PrtCnvBroadcastMgr::getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex, - const time_t a_currentTime) -{ - - // iterate the braodcast-list and get the next broadcast to send - // but check whether it is not a sammeltelegram or has an attached - // broadcast-only-telegram - DEBUG_LOG(m_logger) << "getNextBroadcastTelegramToSend, startIdx: " << a_beginSearchWithBroadcastIndex; - auto iter = m_BroadcastMap.upper_bound(0 == a_beginSearchWithBroadcastIndex ? m_FinishedBroadcastIndex : a_beginSearchWithBroadcastIndex); - while (iter != m_BroadcastMap.end()) + // --------------------------------------------------------------- + // sets the DbThread used for get the stored broadcast- + // telegrams + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::setDbThread(PrtCnvDbThread *a_dbThread) { - auto broadcastTelegram = iter->second; - gef_telegramm_id_et telId = broadcastTelegram->getTelID(); - // the following telegrams will never be sent as normal broadcast - if (GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM == telId - || GEF_WF_SAMMELDEAKTIVIERUNG == telId - || GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN == telId) + m_DbThread = a_dbThread; + } + + + // --------------------------------------------------------------- + // Initializes the broadcast-manager. If a_deleteTelegrams is + // true, all stored telegrams and maps will be deleted. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::cleanAndInit(const bool a_deleteTelegrams) + { + if (a_deleteTelegrams) { - // respect an attached broadcast-only-telegram, otherwise step to next telegram - if (!broadcastTelegram->getBroadcastonlyTelegram()) - { - ++iter; - continue; - } + m_deactivatedAesArea2bcIndex.clear(); + m_deactivatedBcIndex2AesArea.clear(); + + m_deactivatedDusMine2bcIndex.clear(); + m_deactivatedBcIndex2DusMine.clear(); + + m_deactivatedFuncArea2bcIndex.clear(); + m_deactivatedBcIndex2FuncArea.clear(); + + m_BroadcastMap.clear(); + + m_LastTelegramMap.clear(); // the telegrams itself were already deleted while looping through broadcastmap + m_FunktionsraumTelegramMap.clear(); // the telegrams itself were already deleted while looping through broadcastmap + m_WirkfeldTelegramMapByKennung.clear(); // the telegrams itself were already deleted while looping through broadcastmap + m_WirkfeldTelegramMapByTime.clear(); // the telegrams itself were already deleted while looping through broadcastmap + + m_BroadcastIndex = 0; } - // use the attached broadcast-only-telegram if there is one - bool isBcOnly = false; - if (broadcastTelegram->getBroadcastonlyTelegram()) + + m_claimerArray.clear(); + + m_ActClaimWindow = m_ClaimWindow; + m_IsFullLoad = false; + m_TickCounter = 0; + m_State = e_ST_COLLECT; + + m_FinishedBroadcastIndex = 0; + m_FirstBroadcastIndexOfBc1 = 0; + } + + // --------------------------------------------------------------- + // returns true when the telegram should be sent to central + // --------------------------------------------------------------- + bool PrtCnvBroadcastMgr::handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) + { + switch (a_radioTelegram.getTelID()) { - broadcastTelegram = broadcastTelegram->getBroadcastonlyTelegram(); - isBcOnly = true; + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: + handleNachforderungBroadcastTelegram(a_radioTelegram.getIdentity(), a_radioTelegram.getPayloadDataUInt32(8, 2) + 1, a_radioTelegram.getPayloadDataUInt8(7)); + return false; + default: + // nothing + break; } - // check whether it is time to send this broadcast-telegram the 2nd or 3rd time - bool wasLast = false; - if (broadcastTelegram->mustBeSentAsBroadcast(a_currentTime, wasLast)) + return true; // => send the telegram to central + } + + // --------------------------------------------------------------- + // Adds the TNE to the nachforderungs-list + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter) + { + INFO_LOG(m_loggerBcRequest) << "Got NachforderungBroadcast from TNE with id=" << identity << " resetCounter=" << resetCounter + << " broadcastIndex=" << broadcastIndex - 1 << " m_TickCounter=" << m_TickCounter << " m_State=" << m_State; + if (resetCounter == m_DbThread->getResetCounter()) { - // remove a 3rd-time-sent broadcast-only from all maps - if (wasLast) + m_DbThread->incClaimCount(identity); + // already in there? + for (auto &ebi : m_claimerArray) { - if (isBcOnly || broadcastTelegram->isBroadcastOnly()) + if (ebi.equipNo == identity) { - removeFromAllMaps(broadcastTelegram); // this will destroy our iterator, but we don't need it anymore... - } - else - { - // time-optimizing: 3rd-time sent broadcast-telegrams must no longer be examined - m_FinishedBroadcastIndex = broadcastTelegram->getBroadcastIndex(); + ebi.bcIndex = broadcastIndex; + return; } } - // the identity could be dirty, because it could be sent as directed nachforderung in past - broadcastTelegram->setIdentity(0); - return broadcastTelegram; + m_claimerArray.emplace_back(identity, broadcastIndex); + return; } - else + WARNING_LOG(m_logger) << "NachforderungBroadcast from TNE with id=" << identity << ": resetCounter different we have: " << int(m_DbThread->getResetCounter()) + << "; TNE has: " << resetCounter << " => discarded"; + } + + + // --------------------------------------------------------------- + // returns the next normal broadcast to send. + // Use the same a_currentTime in one tick-loop. + // --------------------------------------------------------------- + std::shared_ptr PrtCnvBroadcastMgr::getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex, + const time_t a_currentTime) + { + + // iterate the braodcast-list and get the next broadcast to send + // but check whether it is not a sammeltelegram or has an attached + // broadcast-only-telegram + DEBUG_LOG(m_logger) << "getNextBroadcastTelegramToSend, startIdx: " << a_beginSearchWithBroadcastIndex; + auto iter = m_BroadcastMap.upper_bound(0 == a_beginSearchWithBroadcastIndex ? m_FinishedBroadcastIndex : a_beginSearchWithBroadcastIndex); + while (iter != m_BroadcastMap.end()) { - // this broadcast-telegram must not yet be sent - // ------------------------------------------------------------------------------------ - // optimize by time: - // Beside the fact that the m_BroadcastMap is ordered by BC-index there is also another - // implicit order: first come all 3rd time sent telegramms, then all 2nd time sent - // telegrams and finally all 1st time sent telegrams. Furthermore, the 3rd time sent - // telegrams are ordered ascending by nextsendtime. The same order exists also for 2nd - // and 1st time sent telegrams. This allows us some optimizings. - // Example: - // BC-index broadcast-counter next-send-time - // 1 3 0 - // 2 3 0 - // 3 2 1000 - // 4 2 1000 - // 5 2 1001 - // 6 2 1005 - // 7 1 1000 - // 8 1 1001 - // 9 1 1001 - // ------------------------------------------------------------------------------------- - uint16_t bcCounter = broadcastTelegram->getBroadcastCounter(); - if (2 == bcCounter) + auto broadcastTelegram = iter->second; + gef_telegramm_id_et telId = broadcastTelegram->getTelID(); + // the following telegrams will never be sent as normal broadcast + if (GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM == telId || GEF_WF_SAMMELDEAKTIVIERUNG == telId || GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN == telId) { - // step to first telegram with bc-counter == 1, because all other telegrams will have same - // or higher nextsendtime - if (m_FirstBroadcastIndexOfBc1 > iter->first) + // respect an attached broadcast-only-telegram, otherwise step to next telegram + if (!broadcastTelegram->getBroadcastonlyTelegram()) { - iter = m_BroadcastMap.lower_bound(m_FirstBroadcastIndexOfBc1); + ++iter; continue; } } - else if (1 == bcCounter) + // use the attached broadcast-only-telegram if there is one + bool isBcOnly = false; + if (broadcastTelegram->getBroadcastonlyTelegram()) { - m_FirstBroadcastIndexOfBc1 = broadcastTelegram->getBroadcastIndex(); - return nullptr; // break, because all further telegrams will have same or higher nextsendtime + broadcastTelegram = broadcastTelegram->getBroadcastonlyTelegram(); + isBcOnly = true; } - } - ++iter; - } - return nullptr; -} - - -// --------------------------------------------------------------- -// returns the next broadcast to send for nachforderungen -// --------------------------------------------------------------- -std::shared_ptr PrtCnvBroadcastMgr::getNextNachforderungTelegramToSend() -{ - removeExpiredTelegrams(); - switch (m_State) - { - case e_ST_COLLECT: - // is the claim-window elapsed (usually 30 sec)? - if (m_TickCounter >= m_ActClaimWindow && !m_IsFullLoad) - { - // yes, the window has elapsed - prepareForSendNachforderungen(); - } - else - { - // the claim-window has not elapsed - getAllFinishedBroadcastsFromDb(); - } - break; - - - case e_ST_SEND_NACHFORDERUNG: - return evaluateNextNachforderungToSend(); - default: - break; - } - return {}; -} - - -// --------------------------------------------------------------- -// Takes expired wirkfeld-telegrams out of maps. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeExpiredTelegrams() -{ - const time_t now = time(nullptr); - auto iter = m_WirkfeldTelegramMapByTime.begin(); - while (iter != m_WirkfeldTelegramMapByTime.end()) - { - // 5 Sekunden warten wir noch da sonst ggf. Wirkfelder mit Wirkzeiten < 5 Sekunden - // schon rausfallen bevor sie ins Gefechtsfeld gesendet wurden. - if (iter->first + 5 > now) - return; - - auto radioTelegram = iter->second; - INFO_LOG(m_logger) << "Remove expired telegram with telId=" << radioTelegram->getTelID() - << " and BC=" << radioTelegram->getBroadcastIndex() << " from BC-list"; - uint16_t wirkfeldKennung = radioTelegram->getPayloadDataUInt32(5, 2); - removeWirkfeldTelegrams(wirkfeldKennung); - iter = m_WirkfeldTelegramMapByTime.begin(); - } -} - - -// --------------------------------------------------------------- -// Prepares values for start sending nachforderungen -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::prepareForSendNachforderungen() -{ - // are there any broadcast nachforderungen? - m_TickCounter = 0; - if (!m_claimerArray.empty()) - { - dump(); - - // yes, there are any nachforderungen - // do we have to send them directed or broadcasted? - m_State = e_ST_SEND_NACHFORDERUNG; - - // fill the receiver-map - std::swap(m_claimerArray, m_claimerArray); - std::sort(m_claimerArray.begin(), m_claimerArray.end(), - [] (const EquipNoBcIndex &a, const EquipNoBcIndex &b) - { - if (a.bcIndex != b.bcIndex) - return a.bcIndex < b.bcIndex; - return a.equipNo < b.equipNo; - }); - - // evaluate if we begin with sending directed or broadcasted - INFO_LOG(m_loggerBcRequest) << "BroadcastLimit: " << m_BroadcastLimit; - if (m_claimerArray.size() > m_BroadcastLimit) - { - m_claimerArray.clear(); - m_claimerArray.emplace_back(0, m_claimerArray.begin()->bcIndex); - } - - // now build up the telegrams - for (const EquipNoBcIndex &enbi : m_claimerArray) - { - int curBcIndex = enbi.bcIndex; - int nextBcIndex = -1; - - while (true) + // check whether it is time to send this broadcast-telegram the 2nd or 3rd time + bool wasLast = false; + if (broadcastTelegram->mustBeSentAsBroadcast(a_currentTime, wasLast)) { - auto tel = getNachforderungsTelegram(curBcIndex, enbi.bcIndex, nextBcIndex); - curBcIndex = nextBcIndex; - if (tel) + // remove a 3rd-time-sent broadcast-only from all maps + if (wasLast) { - auto copy(std::make_shared(*tel)); - copy->setIdentity(enbi.equipNo); // issi is set during sending - m_broadcastTelegamsToSend.push_back(copy); + if (isBcOnly || broadcastTelegram->isBroadcastOnly()) + { + removeFromAllMaps(broadcastTelegram); // this will destroy our iterator, but we don't need it anymore... + } + else + { + // time-optimizing: 3rd-time sent broadcast-telegrams must no longer be examined + m_FinishedBroadcastIndex = broadcastTelegram->getBroadcastIndex(); + } + } + // the identity could be dirty, because it could be sent as directed nachforderung in past + broadcastTelegram->setIdentity(0); + return broadcastTelegram; + } + else + { + // this broadcast-telegram must not yet be sent + // ------------------------------------------------------------------------------------ + // optimize by time: + // Beside the fact that the m_BroadcastMap is ordered by BC-index there is also another + // implicit order: first come all 3rd time sent telegramms, then all 2nd time sent + // telegrams and finally all 1st time sent telegrams. Furthermore, the 3rd time sent + // telegrams are ordered ascending by nextsendtime. The same order exists also for 2nd + // and 1st time sent telegrams. This allows us some optimizings. + // Example: + // BC-index broadcast-counter next-send-time + // 1 3 0 + // 2 3 0 + // 3 2 1000 + // 4 2 1000 + // 5 2 1001 + // 6 2 1005 + // 7 1 1000 + // 8 1 1001 + // 9 1 1001 + // ------------------------------------------------------------------------------------- + uint16_t bcCounter = broadcastTelegram->getBroadcastCounter(); + if (2 == bcCounter) + { + // step to first telegram with bc-counter == 1, because all other telegrams will have same + // or higher nextsendtime + if (m_FirstBroadcastIndexOfBc1 > iter->first) + { + iter = m_BroadcastMap.lower_bound(m_FirstBroadcastIndexOfBc1); + continue; + } + } + else if (1 == bcCounter) + { + m_FirstBroadcastIndexOfBc1 = broadcastTelegram->getBroadcastIndex(); + return nullptr; // break, because all further telegrams will have same or higher nextsendtime + } + } + ++iter; + } + return nullptr; + } + + + // --------------------------------------------------------------- + // returns the next broadcast to send for nachforderungen + // --------------------------------------------------------------- + std::shared_ptr PrtCnvBroadcastMgr::getNextNachforderungTelegramToSend() + { + removeExpiredTelegrams(); + switch (m_State) + { + case e_ST_COLLECT: + // is the claim-window elapsed (usually 30 sec)? + if (m_TickCounter >= m_ActClaimWindow && !m_IsFullLoad) + { + // yes, the window has elapsed + prepareForSendNachforderungen(); } else - break; - }; + { + // the claim-window has not elapsed + getAllFinishedBroadcastsFromDb(); + } + break; - std::sort(m_broadcastTelegamsToSend.begin(), m_broadcastTelegamsToSend.end(), - [] (const std::shared_ptr &a, const std::shared_ptr &b) - { - const int bcIndexA = a->getTelID() == GEF_NOP ? a->getPayloadDataUInt32(3, 2) : a->getBroadcastIndex(); - const int bcIndexB = b->getTelID() == GEF_NOP ? b->getPayloadDataUInt32(3, 2) : b->getBroadcastIndex(); - if (bcIndexA != bcIndexB) - return bcIndexA > bcIndexB; // reverse, we use back()/pop_back() - return a->getIdentity() < b->getIdentity(); - }); - if (m_loggerBcRequest.isDebugEnabled()) + case e_ST_SEND_NACHFORDERUNG: + return evaluateNextNachforderungToSend(); + default: + break; + } + return {}; + } + + + // --------------------------------------------------------------- + // Takes expired wirkfeld-telegrams out of maps. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeExpiredTelegrams() + { + const time_t now = time(nullptr); + auto iter = m_WirkfeldTelegramMapByTime.begin(); + while (iter != m_WirkfeldTelegramMapByTime.end()) + { + // 5 Sekunden warten wir noch da sonst ggf. Wirkfelder mit Wirkzeiten < 5 Sekunden + // schon rausfallen bevor sie ins Gefechtsfeld gesendet wurden. + if (iter->first + 5 > now) + return; + + auto radioTelegram = iter->second; + INFO_LOG(m_logger) << "Remove expired telegram with telId=" << radioTelegram->getTelID() << " and BC=" << radioTelegram->getBroadcastIndex() << " from BC-list"; + uint16_t wirkfeldKennung = radioTelegram->getPayloadDataUInt32(5, 2); + removeWirkfeldTelegrams(wirkfeldKennung); + iter = m_WirkfeldTelegramMapByTime.begin(); + } + } + + + // --------------------------------------------------------------- + // Prepares values for start sending nachforderungen + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::prepareForSendNachforderungen() + { + // are there any broadcast nachforderungen? + m_TickCounter = 0; + if (!m_claimerArray.empty()) + { + dump(); + + // yes, there are any nachforderungen + // do we have to send them directed or broadcasted? + m_State = e_ST_SEND_NACHFORDERUNG; + + // fill the receiver-map + std::swap(m_claimerArray, m_claimerArray); + std::sort(m_claimerArray.begin(), + m_claimerArray.end(), + [](const EquipNoBcIndex &a, const EquipNoBcIndex &b) + { + if (a.bcIndex != b.bcIndex) + return a.bcIndex < b.bcIndex; + return a.equipNo < b.equipNo; + }); + + // evaluate if we begin with sending directed or broadcasted + INFO_LOG(m_loggerBcRequest) << "BroadcastLimit: " << m_BroadcastLimit; + if (m_claimerArray.size() > m_BroadcastLimit) { - DEBUG_LOG(m_loggerBcRequest) << "Created broadcast list:"; - for (const auto &tele : m_broadcastTelegamsToSend) - DEBUG_LOG(m_loggerBcRequest) << "Identity: " << tele->getIdentity() - << ", bc: " << tele->getBroadcastIndex() - << ", type: " << tele->getTelID(); + m_claimerArray.clear(); + m_claimerArray.emplace_back(0, m_claimerArray.begin()->bcIndex); } + + // now build up the telegrams + for (const EquipNoBcIndex &enbi : m_claimerArray) + { + int curBcIndex = enbi.bcIndex; + int nextBcIndex = -1; + + while (true) + { + auto tel = getNachforderungsTelegram(curBcIndex, enbi.bcIndex, nextBcIndex); + curBcIndex = nextBcIndex; + if (tel) + { + auto copy(std::make_shared(*tel)); + copy->setIdentity(enbi.equipNo); // issi is set during sending + m_broadcastTelegamsToSend.push_back(copy); + } + else + break; + }; + + std::sort(m_broadcastTelegamsToSend.begin(), + m_broadcastTelegamsToSend.end(), + [](const std::shared_ptr &a, const std::shared_ptr &b) + { + const int bcIndexA = a->getTelID() == GEF_NOP ? a->getPayloadDataUInt32(3, 2) : a->getBroadcastIndex(); + const int bcIndexB = b->getTelID() == GEF_NOP ? b->getPayloadDataUInt32(3, 2) : b->getBroadcastIndex(); + if (bcIndexA != bcIndexB) + return bcIndexA > bcIndexB; // reverse, we use back()/pop_back() + return a->getIdentity() < b->getIdentity(); + }); + + if (m_loggerBcRequest.isDebugEnabled()) + { + DEBUG_LOG(m_loggerBcRequest) << "Created broadcast list:"; + for (const auto &tele : m_broadcastTelegamsToSend) + DEBUG_LOG(m_loggerBcRequest) << "Identity: " << tele->getIdentity() << ", bc: " << tele->getBroadcastIndex() << ", type: " << tele->getTelID(); + } + } + m_claimerArray.clear(); } - m_claimerArray.clear(); - } -} - - -// --------------------------------------------------------------- -// returns the next nachforderung to send -// --------------------------------------------------------------- -std::shared_ptr PrtCnvBroadcastMgr::evaluateNextNachforderungToSend() -{ - if (m_broadcastTelegamsToSend.empty()) - { - m_State = e_ST_COLLECT; - return nullptr; - } - auto tel = m_broadcastTelegamsToSend.back(); - m_broadcastTelegamsToSend.pop_back(); - return tel; -} - -std::shared_ptr PrtCnvBroadcastMgr::createAccumulationTelegram(int curBcIndex, - int startBcIndex, - gef_telegramm_id_et telId, - const QMap &bcIndex2Type, - int maxIdsPerTelegram, - int sizeOfSumField) const -{ - if (bcIndex2Type.isEmpty()) - return nullptr; - - auto itLastBcTele = m_BroadcastMap.end(); - --itLastBcTele; - const int endBcIndex = itLastBcTele->second->getBroadcastIndex(); - - DEBUG_LOG(m_loggerBcRequest) << "createAccumulationTelegram for telId " << telId - << ", begin: " << startBcIndex - << ", cur: " << curBcIndex << ", end: " << endBcIndex - << ", #elements in container: " << bcIndex2Type.size(); - DEBUG_LOG(m_loggerBcRequest) << "Given broadcast list for " << telegramId2String(telId); - for (auto it = bcIndex2Type.begin(); it != bcIndex2Type.end(); ++it) - DEBUG_LOG(m_loggerBcRequest) << " bcIndex: " << it.key() - << ", id: " << it.value(); - - // the asserts are only sanity checks - should never happen - auto itStart = bcIndex2Type.lowerBound(startBcIndex); - if (itStart == bcIndex2Type.end()) - { - Q_ASSERT(false); - return nullptr; - } - auto itEnd = bcIndex2Type.lowerBound(endBcIndex); - if (itEnd == bcIndex2Type.end()) - --itEnd; - - const int completeTelegrams = std::distance(itStart, itEnd) + 1; - if (completeTelegrams <= 0) - { - Q_ASSERT(false); - return nullptr; - } - const auto itCur = bcIndex2Type.find(curBcIndex); - if (itCur == bcIndex2Type.end()) - { - Q_ASSERT(false); - return nullptr; - } - const int telegramsStillSendable = std::distance(itCur, itEnd) + 1; - if (telegramsStillSendable <= 0) - { - Q_ASSERT(false); - return nullptr; } - const int telegramsToSend = (completeTelegrams / maxIdsPerTelegram) + 1; - if (telegramsStillSendable > telegramsToSend) + + // --------------------------------------------------------------- + // returns the next nachforderung to send + // --------------------------------------------------------------- + std::shared_ptr PrtCnvBroadcastMgr::evaluateNextNachforderungToSend() { - INFO_LOG(m_loggerBcRequest) << telId << ": sending nop since accuTelegram is sent later (" << telegramsStillSendable - << ", need only " << telegramsToSend << ")"; - return nullptr; - } - - const int curIdStart = (telegramsToSend - telegramsStillSendable) * maxIdsPerTelegram; - const int idsToSendNow = (curIdStart + maxIdsPerTelegram <= completeTelegrams ? maxIdsPerTelegram : completeTelegrams % maxIdsPerTelegram); - INFO_LOG(m_loggerBcRequest) << telId << ": creating accuTelegram from index " << curIdStart << ", count: " << idsToSendNow; - - std::advance(itStart, curIdStart); - - // hdr (3 bytes) + bc idx + sum field - auto tele(std::make_shared(telId, 3 + 2 + sizeOfSumField + sizeof(uint16_t) * idsToSendNow, 0)); - tele->setPayload2Byte(curBcIndex); - if (sizeOfSumField == 1) - tele->setPayload1Byte(idsToSendNow); // #Ids - else if (sizeOfSumField == 2) - tele->setPayload2Byte(idsToSendNow); // #Ids - else - { - Q_ASSERT(false); - return nullptr; - } - for (int i = 0; i < idsToSendNow; ++i) - { - tele->setPayload2Byte(itStart.value()); - ++itStart; - } - return tele; -} - -std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedAesAreas(int curBcIndex, - int startBcIndex) const -{ - return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG, - m_deactivatedBcIndex2AesArea, 100, 1); -} - -std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedFuncAreas(int curBcIndex, - int startBcIndex) const -{ - return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM, - m_deactivatedBcIndex2FuncArea, 100, 1); -} - -std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedDusMines(int curBcIndex, - int startBcIndex) const -{ - return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN, - m_deactivatedBcIndex2DusMine, 500, 2); -} - -std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleActivatedDusMines(int curBcIndex) -{ - if (m_activatedDusMines.isEmpty()) - return {}; - // we currently only can have exactly *one* telegram of this type (with max. 500 entries) - const int idsToSendNow = m_activatedDusMines.size(); - if (idsToSendNow > 500) - { - WARNING_LOG(m_logger) << "More than 500 activated DUS mines in system - this is not allowed!"; - Q_ASSERT(false); - return {}; - } - auto tele(std::make_shared(GEF_REAKTIVIERUNG_DUS_MINE, 5 + 2 + sizeof(uint16_t) * idsToSendNow, 0)); - tele->setPayload2Byte(curBcIndex); - tele->setPayload2Byte(idsToSendNow); - for (int dusMineId : std::as_const(m_activatedDusMines)) - tele->setPayload2Byte(dusMineId); - - return tele; -} - - -// --------------------------------------------------------------- -// returns the Nachforderungs-telegram with this broadcast- -// index from the broadcast-map with sammeltelegrams. If the -// telegram with a_broadcastIndex does not exist, a NOP- -// telegram will be returned, which must be consumed -// immediately and must never be deleted. -// The parameter a_broadcastIndex will be updated to the value -// of found telegram. -// ATTENTION: the returned a_broadcastIndex could be different -// from the value returned by getBroadcastIndex(), for example -// in NOP-telegrams getBroadcastIndex() returns the Anfang, -// but a_broadcastIndex will be the Ende. -// --------------------------------------------------------------- -std::shared_ptrPrtCnvBroadcastMgr::getNachforderungsTelegram(int curBcIndex, - int startBcIndex, - int &nextBcIndex) -{ - DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - curBcIndex: " << curBcIndex - << ", startBcIndex: " << startBcIndex; - if (curBcIndex == 0) curBcIndex++; - DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - curBcIndex after Ssnity: " << curBcIndex - << ", startBcIndex: " << startBcIndex; - - nextBcIndex = curBcIndex; - bool doSendNop = false; - - while (true) - { - auto iter = m_BroadcastMap.lower_bound(nextBcIndex); - if (iter == m_BroadcastMap.end()) - break; - - auto radioTelegram = iter->second; - DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - cur tel id is " << radioTelegram->getTelID() - << ", bcIndex: " << radioTelegram->getBroadcastIndex() - << ", send nop: " << doSendNop; - - if (nextBcIndex < iter->first) + if (m_broadcastTelegamsToSend.empty()) { - // do we have gaps or is it a broadcast-only telegram => send NOP-telegram - // but iterate for summarize all broadcast-only and gaps - doSendNop = true; - nextBcIndex = iter->first; + m_State = e_ST_COLLECT; + return nullptr; } - else if (radioTelegram->isBroadcastOnly()) + auto tel = m_broadcastTelegamsToSend.back(); + m_broadcastTelegamsToSend.pop_back(); + return tel; + } + + std::shared_ptr PrtCnvBroadcastMgr::createAccumulationTelegram(int curBcIndex, + int startBcIndex, + gef_telegramm_id_et telId, + const QMap &bcIndex2Type, + int maxIdsPerTelegram, + int sizeOfSumField) const + { + if (bcIndex2Type.isEmpty()) + return nullptr; + + auto itLastBcTele = m_BroadcastMap.end(); + --itLastBcTele; + const int endBcIndex = itLastBcTele->second->getBroadcastIndex(); + + DEBUG_LOG(m_loggerBcRequest) << "createAccumulationTelegram for telId " << telId << ", begin: " << startBcIndex << ", cur: " << curBcIndex << ", end: " << endBcIndex + << ", #elements in container: " << bcIndex2Type.size(); + DEBUG_LOG(m_loggerBcRequest) << "Given broadcast list for " << telegramId2String(telId); + for (auto it = bcIndex2Type.begin(); it != bcIndex2Type.end(); ++it) + DEBUG_LOG(m_loggerBcRequest) << " bcIndex: " << it.key() << ", id: " << it.value(); + + // the asserts are only sanity checks - should never happen + auto itStart = bcIndex2Type.lowerBound(startBcIndex); + if (itStart == bcIndex2Type.end()) { - doSendNop = true; - nextBcIndex = iter->first + 1; + Q_ASSERT(false); + return nullptr; } + auto itEnd = bcIndex2Type.lowerBound(endBcIndex); + if (itEnd == bcIndex2Type.end()) + --itEnd; + + const int completeTelegrams = std::distance(itStart, itEnd) + 1; + if (completeTelegrams <= 0) + { + Q_ASSERT(false); + return nullptr; + } + const auto itCur = bcIndex2Type.find(curBcIndex); + if (itCur == bcIndex2Type.end()) + { + Q_ASSERT(false); + return nullptr; + } + const int telegramsStillSendable = std::distance(itCur, itEnd) + 1; + if (telegramsStillSendable <= 0) + { + Q_ASSERT(false); + return nullptr; + } + + const int telegramsToSend = (completeTelegrams / maxIdsPerTelegram) + 1; + if (telegramsStillSendable > telegramsToSend) + { + INFO_LOG(m_loggerBcRequest) << telId << ": sending nop since accuTelegram is sent later (" << telegramsStillSendable << ", need only " << telegramsToSend << ")"; + return nullptr; + } + + const int curIdStart = (telegramsToSend - telegramsStillSendable) * maxIdsPerTelegram; + const int idsToSendNow = (curIdStart + maxIdsPerTelegram <= completeTelegrams ? maxIdsPerTelegram : completeTelegrams % maxIdsPerTelegram); + INFO_LOG(m_loggerBcRequest) << telId << ": creating accuTelegram from index " << curIdStart << ", count: " << idsToSendNow; + + std::advance(itStart, curIdStart); + + // hdr (3 bytes) + bc idx + sum field + auto tele(std::make_shared(telId, 3 + 2 + sizeOfSumField + sizeof(uint16_t) * idsToSendNow, 0)); + tele->setPayload2Byte(curBcIndex); + if (sizeOfSumField == 1) + tele->setPayload1Byte(idsToSendNow); // #Ids + else if (sizeOfSumField == 2) + tele->setPayload2Byte(idsToSendNow); // #Ids else { - std::shared_ptr retTele; - switch (radioTelegram->getTelID()) - { - case GEF_DEAKTIVIERUNG_WIRKFELD: - retTele = createAccuTeleDeactivatedAesAreas(radioTelegram->getBroadcastIndex(), startBcIndex); - break; - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - retTele = createAccuTeleDeactivatedFuncAreas(radioTelegram->getBroadcastIndex(), startBcIndex); - break; - case GEF_DEAKTIVIERUNG_EINZELMINE: - retTele = createAccuTeleDeactivatedDusMines(radioTelegram->getBroadcastIndex(), startBcIndex); - break; - case GEF_REAKTIVIERUNG_DUS_MINE: - retTele = createAccuTeleActivatedDusMines(radioTelegram->getBroadcastIndex()); - break; - default: - retTele = radioTelegram; - break; - } + Q_ASSERT(false); + return nullptr; + } + for (int i = 0; i < idsToSendNow; ++i) + { + tele->setPayload2Byte(itStart.value()); + ++itStart; + } + return tele; + } - // when we got a tele but have to send a nop first, wait for the next iteration and return nop now - if (retTele && doSendNop) + std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedAesAreas(int curBcIndex, int startBcIndex) const + { + return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG, m_deactivatedBcIndex2AesArea, 100, 1); + } + + std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedFuncAreas(int curBcIndex, int startBcIndex) const + { + return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM, m_deactivatedBcIndex2FuncArea, 100, 1); + } + + std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleDeactivatedDusMines(int curBcIndex, int startBcIndex) const + { + return createAccumulationTelegram(curBcIndex, startBcIndex, GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN, m_deactivatedBcIndex2DusMine, 500, 2); + } + + std::shared_ptr PrtCnvBroadcastMgr::createAccuTeleActivatedDusMines(int curBcIndex) + { + if (m_activatedDusMines.isEmpty()) + return {}; + // we currently only can have exactly *one* telegram of this type (with max. 500 entries) + const int idsToSendNow = m_activatedDusMines.size(); + if (idsToSendNow > 500) + { + WARNING_LOG(m_logger) << "More than 500 activated DUS mines in system - this is not allowed!"; + Q_ASSERT(false); + return {}; + } + auto tele(std::make_shared(GEF_REAKTIVIERUNG_DUS_MINE, 5 + 2 + sizeof(uint16_t) * idsToSendNow, 0)); + tele->setPayload2Byte(curBcIndex); + tele->setPayload2Byte(idsToSendNow); + for (int dusMineId : std::as_const(m_activatedDusMines)) + tele->setPayload2Byte(dusMineId); + + return tele; + } + + + // --------------------------------------------------------------- + // returns the Nachforderungs-telegram with this broadcast- + // index from the broadcast-map with sammeltelegrams. If the + // telegram with a_broadcastIndex does not exist, a NOP- + // telegram will be returned, which must be consumed + // immediately and must never be deleted. + // The parameter a_broadcastIndex will be updated to the value + // of found telegram. + // ATTENTION: the returned a_broadcastIndex could be different + // from the value returned by getBroadcastIndex(), for example + // in NOP-telegrams getBroadcastIndex() returns the Anfang, + // but a_broadcastIndex will be the Ende. + // --------------------------------------------------------------- + std::shared_ptr PrtCnvBroadcastMgr::getNachforderungsTelegram(int curBcIndex, int startBcIndex, int &nextBcIndex) + { + DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - curBcIndex: " << curBcIndex << ", startBcIndex: " << startBcIndex; + if (curBcIndex == 0) + curBcIndex++; + DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - curBcIndex after Ssnity: " << curBcIndex << ", startBcIndex: " << startBcIndex; + + nextBcIndex = curBcIndex; + bool doSendNop = false; + + while (true) + { + auto iter = m_BroadcastMap.lower_bound(nextBcIndex); + if (iter == m_BroadcastMap.end()) + break; + + auto radioTelegram = iter->second; + DEBUG_LOG(m_loggerBcRequest) << "getNachforderungsTelegram - cur tel id is " << radioTelegram->getTelID() << ", bcIndex: " << radioTelegram->getBroadcastIndex() + << ", send nop: " << doSendNop; + + if (nextBcIndex < iter->first) + { + // do we have gaps or is it a broadcast-only telegram => send NOP-telegram + // but iterate for summarize all broadcast-only and gaps + doSendNop = true; + nextBcIndex = iter->first; + } + else if (radioTelegram->isBroadcastOnly()) + { + doSendNop = true; + nextBcIndex = iter->first + 1; + } + else + { + std::shared_ptr retTele; + switch (radioTelegram->getTelID()) + { + case GEF_DEAKTIVIERUNG_WIRKFELD: + retTele = createAccuTeleDeactivatedAesAreas(radioTelegram->getBroadcastIndex(), startBcIndex); + break; + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + retTele = createAccuTeleDeactivatedFuncAreas(radioTelegram->getBroadcastIndex(), startBcIndex); + break; + case GEF_DEAKTIVIERUNG_EINZELMINE: + retTele = createAccuTeleDeactivatedDusMines(radioTelegram->getBroadcastIndex(), startBcIndex); + break; + case GEF_REAKTIVIERUNG_DUS_MINE: + retTele = createAccuTeleActivatedDusMines(radioTelegram->getBroadcastIndex()); + break; + default: + retTele = radioTelegram; + break; + } + + // when we got a tele but have to send a nop first, wait for the next iteration and return nop now + if (retTele && doSendNop) break; - ++nextBcIndex; - if (retTele) - return retTele; + ++nextBcIndex; + if (retTele) + return retTele; + doSendNop = true; + } + } + + // due to some asyncs during startup it *may* happen that the last entry(ies) of + // the broadcast map are empty - make sure that we send a nop for them + if (!doSendNop && nextBcIndex <= m_BroadcastIndex) + { + nextBcIndex = m_BroadcastIndex + 1; doSendNop = true; } - } - // due to some asyncs during startup it *may* happen that the last entry(ies) of - // the broadcast map are empty - make sure that we send a nop for them - if (!doSendNop && nextBcIndex <= m_BroadcastIndex) - { - nextBcIndex = m_BroadcastIndex + 1; - doSendNop = true; - } - - if (doSendNop) - { - // return a NOP-telegram since next tele is a 'normal' telegram to send - INFO_LOG(m_loggerBcRequest) << "Returning NOP: " << curBcIndex << " to " << nextBcIndex - 1; - return getNopTelegram(curBcIndex, nextBcIndex - 1); - } - - return nullptr; -} - - -// --------------------------------------------------------------- -// Gets the braodcast-telegrams from Db, which were sent 1st -// time and adds them to the maps. Expired telegrams will be -// removed. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::getAllFinishedBroadcastsFromDb(const bool a_doRestore) -{ - // => get all broadcasts which are sent first time; replace some telegrams with - // sammeltelegrams or NOP-telegrams - - // Attention: this must only be done, when we are not sending broadcast-nachforderungen, - // because otherwise we could change sammeltelegrams which are already sent. - - uint16_t broadcastIndex = 0; - while (true) - { - auto radioTelegram = m_DbThread->getNextBroadcastTelegram(); - if (!radioTelegram) - break; - broadcastIndex = radioTelegram->getBroadcastIndex(); - INFO_LOG(m_logger) << "Move Broadcast-telegram from DbThread>BroadcastMgr with telId=" - << radioTelegram->getTelID() << " BC=" << broadcastIndex; - dumpTelegram(m_logger, broadcastIndex, radioTelegram.get()); - // abgelaufene Telegramme hier *nicht* loeschen da sonst z.B. WF_FL_FEUER_STOP/FORTSETZEN - // spaeter nicht beachtet werden und WF_FL_FEUER nicht aus der Broadcastliste - // entfernt wird. außerdem hätten wir so eine andere Ausgangsbasis als wenn der PrtCnv - // nicht neu gestartet wurde was u.U. auch woanders noch zu Problemen führt. - //if (radioTelegram->hasExpired()) - //{ - // INFO_LOG(m_logger) << "Telegram with BC " << broadcastIndex - // << " is expired - throwing away"; - // delete radioTelegram; - //} - //else + if (doSendNop) { - addToBroadcastMap(radioTelegram); + // return a NOP-telegram since next tele is a 'normal' telegram to send + INFO_LOG(m_loggerBcRequest) << "Returning NOP: " << curBcIndex << " to " << nextBcIndex - 1; + return getNopTelegram(curBcIndex, nextBcIndex - 1); } - // remake overrun when restoring - if (a_doRestore && MAX_BROADCAST_INDEX == broadcastIndex) - handleOverrunOfBroadcastCounter(a_doRestore); + + return nullptr; } - if (m_logger.isDebugEnabled()) + + // --------------------------------------------------------------- + // Gets the braodcast-telegrams from Db, which were sent 1st + // time and adds them to the maps. Expired telegrams will be + // removed. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::getAllFinishedBroadcastsFromDb(const bool a_doRestore) { - static int iBroadcastDumpCounter = 0; - if ((iBroadcastDumpCounter++ % 30) == 0) + // => get all broadcasts which are sent first time; replace some telegrams with + // sammeltelegrams or NOP-telegrams + + // Attention: this must only be done, when we are not sending broadcast-nachforderungen, + // because otherwise we could change sammeltelegrams which are already sent. + + uint16_t broadcastIndex = 0; + while (true) { - DEBUG_LOG(m_logger) << "Dumping broadcast map:"; - for (const auto &it : m_BroadcastMap) - dumpTelegram(m_logger, it.first, it.second.get()); - } - } - - // set the actual BC-index - if (a_doRestore) - { - m_BroadcastIndex = broadcastIndex; - m_FinishedBroadcastIndex = m_BroadcastIndex; - } -} - - -// --------------------------------------------------------------- -// adds the radio-telegram to the broadcast-map, or generates -// the sammeltelegramme -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::addToBroadcastMap(const std::shared_ptr &a_radioTelegram) -{ - INFO_LOG(m_logger) << "Move from radioList to bcList: BC=" << a_radioTelegram->getBroadcastIndex() - << " telID=" << a_radioTelegram->getTelID(); - switch (a_radioTelegram->getTelID()) - { - // following telegrams should never be broadcasts - case GEF_INIT: - case GEF_UMGEBUNGS_MELDUNG2: - ERROR_LOG(m_logger) << "Internal error: telegram with telId=" << a_radioTelegram->getTelID() << " should never be a normal broadcast"; - break; - // the following telegrams should only be sent as normal broadcast (not as Nachforderung) - case GEF_DATENVERKEHR_TDS_SRT: - case GEF_DATENVERKEHR_TDS_DMF: - case GEF_TREFFER_AUSLOESUNG: - case GEF_ALLGEMEINE_NACHRICHT: - addBroadcastOnlyTelegramToMap(a_radioTelegram); - break; - - // the following telegrams must exist only once in BC-list - case GEF_SPRACHAUSWAHL: - case GEF_KONFIGURATION_WIRKMODELL: - case GEF_TEILNEHMERMODE_SETZEN: - case GEF_TEILNEHMER_KONFIG_SETZEN: - replaceLastTelegramAndAddAtEnd(a_radioTelegram); - break; - - case GEF_WIRKFELD_EINZELGESCHOSS: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_C_KAMPFMITTEL: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_EINZELMINENSIMULATOR: - { - // take wirkfeld to be (re)activated out of sammeltelegram of deactivated wirkfelder - const uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - INFO_LOG(m_logger) << "Adding to braodcast map, Telegram Id: " << a_radioTelegram->getTelID() - << ", kennung: " << wirkfeldKennung; - if (isEffectSimulationIdDeactivated(wirkfeldKennung)) - { - INFO_LOG(m_logger) << "Got tele with tel id " << telegramId2String(a_radioTelegram->getTelID()) - << ", wirkfeldkennung: " << wirkfeldKennung << ", bcIndex: " << a_radioTelegram->getBroadcastIndex() - << " but this effect simulation is already deactivated... ignoring"; - dumpTelegram(m_logger, a_radioTelegram->getBroadcastIndex(), a_radioTelegram.get()); - emit areaEffectSimulationActivated(wirkfeldKennung); - } - else if (0 != wirkfeldKennung && wirkfeldKennung <= std::numeric_limits::max()) - { - switch (a_radioTelegram->getTelID()) + auto radioTelegram = m_DbThread->getNextBroadcastTelegram(); + if (!radioTelegram) + break; + broadcastIndex = radioTelegram->getBroadcastIndex(); + INFO_LOG(m_logger) << "Move Broadcast-telegram from DbThread>BroadcastMgr with telId=" << radioTelegram->getTelID() << " BC=" << broadcastIndex; + dumpTelegram(m_logger, broadcastIndex, radioTelegram.get()); + // abgelaufene Telegramme hier *nicht* loeschen da sonst z.B. WF_FL_FEUER_STOP/FORTSETZEN + // spaeter nicht beachtet werden und WF_FL_FEUER nicht aus der Broadcastliste + // entfernt wird. außerdem hätten wir so eine andere Ausgangsbasis als wenn der PrtCnv + // nicht neu gestartet wurde was u.U. auch woanders noch zu Problemen führt. + //if (radioTelegram->hasExpired()) + //{ + // INFO_LOG(m_logger) << "Telegram with BC " << broadcastIndex + // << " is expired - throwing away"; + // delete radioTelegram; + //} + //else { + addToBroadcastMap(radioTelegram); + } + // remake overrun when restoring + if (a_doRestore && MAX_BROADCAST_INDEX == broadcastIndex) + handleOverrunOfBroadcastCounter(a_doRestore); + } + + if (m_logger.isDebugEnabled()) + { + static int iBroadcastDumpCounter = 0; + if ((iBroadcastDumpCounter++ % 30) == 0) + { + DEBUG_LOG(m_logger) << "Dumping broadcast map:"; + for (const auto &it : m_BroadcastMap) + dumpTelegram(m_logger, it.first, it.second.get()); + } + } + + // set the actual BC-index + if (a_doRestore) + { + m_BroadcastIndex = broadcastIndex; + m_FinishedBroadcastIndex = m_BroadcastIndex; + } + } + + + // --------------------------------------------------------------- + // adds the radio-telegram to the broadcast-map, or generates + // the sammeltelegramme + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::addToBroadcastMap(const std::shared_ptr &a_radioTelegram) + { + INFO_LOG(m_logger) << "Move from radioList to bcList: BC=" << a_radioTelegram->getBroadcastIndex() << " telID=" << a_radioTelegram->getTelID(); + switch (a_radioTelegram->getTelID()) + { + // following telegrams should never be broadcasts + case GEF_INIT: + case GEF_UMGEBUNGS_MELDUNG2: + ERROR_LOG(m_logger) << "Internal error: telegram with telId=" << a_radioTelegram->getTelID() << " should never be a normal broadcast"; + break; + // the following telegrams should only be sent as normal broadcast (not as Nachforderung) + case GEF_DATENVERKEHR_TDS_SRT: + case GEF_DATENVERKEHR_TDS_DMF: + case GEF_TREFFER_AUSLOESUNG: + case GEF_ALLGEMEINE_NACHRICHT: + addBroadcastOnlyTelegramToMap(a_radioTelegram); + break; + + // the following telegrams must exist only once in BC-list + case GEF_SPRACHAUSWAHL: + case GEF_KONFIGURATION_WIRKMODELL: + case GEF_TEILNEHMERMODE_SETZEN: + case GEF_TEILNEHMER_KONFIG_SETZEN: + replaceLastTelegramAndAddAtEnd(a_radioTelegram); + break; + + case GEF_WIRKFELD_EINZELGESCHOSS: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_C_KAMPFMITTEL: case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - // remove the corresponding FeuerFortsetzen telegram - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN); - break; case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - // remove the corresponding FeuerStop telegram - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP); - break; - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); - break; case GEF_WIRKFELD_STATUS_MINENSPERRE: - // remove the corresponding deactivierung_einzelmine telegrams - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_DEAKTIVIERUNG_EINZELMINE); - break; - default: - removeWirkfeldTelegrams(wirkfeldKennung); - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); - removeFromDeactivatedAesArea(wirkfeldKennung); - emit areaEffectSimulationActivated(wirkfeldKennung); + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + { + // take wirkfeld to be (re)activated out of sammeltelegram of deactivated wirkfelder + const uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + INFO_LOG(m_logger) << "Adding to braodcast map, Telegram Id: " << a_radioTelegram->getTelID() << ", kennung: " << wirkfeldKennung; + if (isEffectSimulationIdDeactivated(wirkfeldKennung)) + { + INFO_LOG(m_logger) << "Got tele with tel id " << telegramId2String(a_radioTelegram->getTelID()) << ", wirkfeldkennung: " << wirkfeldKennung + << ", bcIndex: " << a_radioTelegram->getBroadcastIndex() << " but this effect simulation is already deactivated... ignoring"; + dumpTelegram(m_logger, a_radioTelegram->getBroadcastIndex(), a_radioTelegram.get()); + emit areaEffectSimulationActivated(wirkfeldKennung); + } + else if (0 != wirkfeldKennung && wirkfeldKennung <= std::numeric_limits::max()) + { + switch (a_radioTelegram->getTelID()) + { + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + // remove the corresponding FeuerFortsetzen telegram + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN); + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + // remove the corresponding FeuerStop telegram + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP); + break; + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); + break; + case GEF_WIRKFELD_STATUS_MINENSPERRE: + // remove the corresponding deactivierung_einzelmine telegrams + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung, GEF_DEAKTIVIERUNG_EINZELMINE); + break; + default: + removeWirkfeldTelegrams(wirkfeldKennung); + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); + removeFromDeactivatedAesArea(wirkfeldKennung); + emit areaEffectSimulationActivated(wirkfeldKennung); + break; + } + // the original telegram will be added to broadcast-list + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + } + else + { + // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out + ERROR_LOG(m_logger) << "Internal error: Got invalid kennung: " << wirkfeldKennung; + } break; } - // the original telegram will be added to broadcast-list + + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + { + auto wirkfeldTyp = static_cast(a_radioTelegram->getPayloadDataUInt32(5, 1)); + uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); + INFO_LOG(m_logger) << "addToBroadcastMap - Wirkfeld Aenderung Bezeichner for type " << wirkfeldTyp2Str(wirkfeldTyp) << " - kennung: " << wirkfeldKennung; + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); + break; + } + case GEF_DEAKTIVIERUNG_WIRKFELD: + { + auto wirkfeldTyp = static_cast(a_radioTelegram->getPayloadDataUInt32(5, 1)); + uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); + INFO_LOG(m_logger) << "Deaktivierung Wirkfeld for type " << wirkfeldTyp2Str(wirkfeldTyp) << " - kennung: " << wirkfeldKennung + << ", bc: " << a_radioTelegram->getBroadcastIndex(); + switch (wirkfeldTyp) + { + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::MineArea: // Minensperre + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionArea: // Steilfeuer Fläche + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionSingle: // Steilfeuer Einzel + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::NContamination: // A-Waffe + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::CContamination: // C-Waffe + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DusSingleMineSimulator: // DUS-Einzelminensimulator + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DangerZoneExplosion: + if (0 != wirkfeldKennung && wirkfeldKennung <= 32767) + { + emit areaEffectSimulationDeactivated(wirkfeldKennung); + + removeWirkfeldTelegrams(wirkfeldKennung); + if (addToDeactivatedAesArea(wirkfeldKennung, a_radioTelegram->getBroadcastIndex())) + addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); + } + else + { + // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out + ERROR_LOG(m_logger) << "Internal error: Got invalid kennung: " << wirkfeldKennung; + } + break; + case TrainingAreaBase::TetraIcd::AreaEffectSimulationType:: + FunctionalArea: // Telegram DeaktivierenFunktionsraum should be used, instead DeaktivierungWirkfeld with wirkfeldTyp 6 + default: + // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out + ERROR_LOG(m_logger) << "Internal error: WirkfeldTyp " << wirkfeldTyp2Str(wirkfeldTyp) << " in GEF_DEAKTIVIERUNG_WIRKFELD not implemented"; + } + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + break; + } + + case GEF_DEAKTIVIERUNG_EINZELMINE: + { + deactivateSingleMine(a_radioTelegram); + break; + } + + case GEF_REAKTIVIERUNG_DUS_MINE: + { + reactivateDusMine(a_radioTelegram); + break; + } + + case GEF_TECHNIK_FUNKTIONSRAUM: + { + // take funktionsraum to be (re)activated out of sammeltelegram of deactivated funktionsräume + uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + // remove an old already existing funktionsraum-telegram with this kennung + removeFromTechnikFunktionsAndBroadcastMaps(funktionsraumkennung); + + // insert the funktionsraum-telegram + m_TechnikFunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); + + // the original telegram will be added to broadcast-list + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + break; + } + + case GEF_FUNKTIONSRAUM: + { + // take funktionsraum to be (re)activated out of sammeltelegram of deactivated funktionsräume + uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + // remove an old already existing funktionsraum-telegram with this kennung + removeFromFunktionsAndBroadcastMaps(funktionsraumkennung); + removeFromDeactivatedFuncArea(funktionsraumkennung); + + // insert the funktionsraum-telegram + m_FunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); + + // the original telegram will be added to broadcast-list + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + break; + } + + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + { + uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); + emit areaEffectSimulationDeactivated(funktionsraumkennung); + + removeFromFunktionsAndBroadcastMaps(funktionsraumkennung); + if (addToDeactivatedFuncArea(funktionsraumkennung, a_radioTelegram->getBroadcastIndex())) + m_FunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + break; + } + + default: + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + } + // dump(); + } + + + template bool removeFromContainers(T &id2bcIndex, S &BcIndex2id, int aesAreaId) + { + auto it = id2bcIndex.find(aesAreaId); + if (it == id2bcIndex.end()) + return false; + BcIndex2id.remove(it.value()); + id2bcIndex.erase(it); + return true; + } + + template bool addToContainers(T &id2bcIndex, S &BcIndex2id, int aesAreaId, int bcIndex) + { + auto it = id2bcIndex.find(aesAreaId); + if (it != id2bcIndex.end()) + { + if (it.value() == bcIndex) + return false; + BcIndex2id.remove(it.value()); + } + id2bcIndex[aesAreaId] = bcIndex; + BcIndex2id[bcIndex] = aesAreaId; + return true; + } + + bool PrtCnvBroadcastMgr::removeFromDeactivatedAesArea(int aesAreaId) + { + return removeFromContainers(m_deactivatedAesArea2bcIndex, m_deactivatedBcIndex2AesArea, aesAreaId); + } + + // returns true when added + bool PrtCnvBroadcastMgr::addToDeactivatedAesArea(int aesAreaId, int bcIndex) + { + return addToContainers(m_deactivatedAesArea2bcIndex, m_deactivatedBcIndex2AesArea, aesAreaId, bcIndex); + } + + bool PrtCnvBroadcastMgr::removeFromDeactivatedFuncArea(int aesAreaId) + { + return removeFromContainers(m_deactivatedFuncArea2bcIndex, m_deactivatedBcIndex2FuncArea, aesAreaId); + } + + bool PrtCnvBroadcastMgr::addToDeactivatedFuncArea(int aesAreaId, int bcIndex) + { + return addToContainers(m_deactivatedFuncArea2bcIndex, m_deactivatedBcIndex2FuncArea, aesAreaId, bcIndex); + } + + bool PrtCnvBroadcastMgr::removeFromDeactivatedDusMine(int dusMineId) + { + return removeFromContainers(m_deactivatedDusMine2bcIndex, m_deactivatedBcIndex2DusMine, dusMineId); + } + + bool PrtCnvBroadcastMgr::addToDeactivatedDusMine(int dusMineId, int bcIndex) + { + return addToContainers(m_deactivatedDusMine2bcIndex, m_deactivatedBcIndex2DusMine, dusMineId, bcIndex); + } + + bool PrtCnvBroadcastMgr::removeFromActivatedDusMine(int dusMineId) + { + return (m_activatedDusMines.remove(dusMineId)); + } + + void PrtCnvBroadcastMgr::addToActivatedDusMine(int dusMineId) + { + m_activatedDusMines.insert(dusMineId); + } + + // --------------------------------------------------------------- + // searches the kennung within sammeltelegram. + // returns -1 when kennung not found + // --------------------------------------------------------------- + int PrtCnvBroadcastMgr::getSammeltelegramIndex(const std::shared_ptr &a_sammelTelegram, const uint16_t a_kennung) const + { + // decide the length of anzahl + uint16_t nbrLength = 0; + switch (a_sammelTelegram->getTelID()) + { + case GEF_WF_SAMMELDEAKTIVIERUNG: + case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: + nbrLength = 1; + break; + case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: + case GEF_REAKTIVIERUNG_DUS_MINE: + nbrLength = 2; + break; + default: + ERROR_LOG(m_logger) << "Unknown Sammeltelegram with telId=" << a_sammelTelegram->getTelID(); + return -1; + } + // search the kennung in sammeltelegram + const int cntAesIds = a_sammelTelegram->getPayloadDataUInt32(5, nbrLength); + for (int i = 0; i < cntAesIds; i++) + { + if (a_kennung == a_sammelTelegram->getPayloadDataUInt32(5 + nbrLength + i * 2, 2)) + return i; + } + return -1; + } + + + // --------------------------------------------------------------- + // Handles the DEAKTIVIERUNG_EINZELMINE-telegram for normal- + // broadcasts and nachforderungen. This includes deactivation + // of mines from minen-sperre and DUS-mines. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::deactivateSingleMine(const std::shared_ptr &a_radioTelegram) + { + uint32_t wirkfeldkennung = a_radioTelegram->getPayloadDataUInt32(9, 2); + uint32_t minenkennung = a_radioTelegram->getPayloadDataUInt32(11, 2); + // DUS or normal mine? + if (0 == wirkfeldkennung) + { + removeFromActivatedDusMine(minenkennung); + addToDeactivatedDusMine(minenkennung, a_radioTelegram->getBroadcastIndex()); + DEBUG_LOG(m_logger) << "Deactivating DUS-Mine: " << minenkennung << ", #deactivated mines: " << m_deactivatedBcIndex2DusMine.size(); + removeDusMineDeactivationFromBroadcastMap(minenkennung); // remove old if there is already a telegram m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); } else { - // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out - ERROR_LOG(m_logger) << "Internal error: Got invalid kennung: " << wirkfeldKennung; - } - break; - } - - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - { - auto wirkfeldTyp = static_cast(a_radioTelegram->getPayloadDataUInt32(5, 1)); - uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); - INFO_LOG(m_logger) << "addToBroadcastMap - Wirkfeld Aenderung Bezeichner for type " - << wirkfeldTyp2Str(wirkfeldTyp) << " - kennung: " - << wirkfeldKennung; - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); - break; - } - case GEF_DEAKTIVIERUNG_WIRKFELD: - { - auto wirkfeldTyp = static_cast(a_radioTelegram->getPayloadDataUInt32(5, 1)); - uint16_t wirkfeldKennung = a_radioTelegram->getPayloadDataUInt32(6, 2); - INFO_LOG(m_logger) << "Deaktivierung Wirkfeld for type " - << wirkfeldTyp2Str(wirkfeldTyp) << " - kennung: " - << wirkfeldKennung << ", bc: " << a_radioTelegram->getBroadcastIndex(); - switch (wirkfeldTyp) - { - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::MineArea: // Minensperre - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionArea: // Steilfeuer Fläche - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::ExplosionSingle: // Steilfeuer Einzel - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::NContamination: // A-Waffe - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::CContamination: // C-Waffe - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DusSingleMineSimulator: // DUS-Einzelminensimulator - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::DangerZoneExplosion: - if (0 != wirkfeldKennung && wirkfeldKennung <= 32767) + // normal mine => change mine in "wirkfeldStatusMinensperre" + bool sentAsNormalBroadcastFinished = deactivateEinzelmineFromMinensperre(wirkfeldkennung, minenkennung, a_radioTelegram->getBroadcastIndex()); + if (sentAsNormalBroadcastFinished) { - emit areaEffectSimulationDeactivated(wirkfeldKennung); - - removeWirkfeldTelegrams(wirkfeldKennung); - if (addToDeactivatedAesArea(wirkfeldKennung, a_radioTelegram->getBroadcastIndex())) - addWirkfeldTelegram(a_radioTelegram, wirkfeldKennung); + // add the deactivierungEinzelmine-telegram as broadcast-only-telegram + addWirkfeldTelegram(a_radioTelegram, wirkfeldkennung, GEF_BESTAETIGUNG, minenkennung); + addBroadcastOnlyTelegramToMap(a_radioTelegram); } else { - // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out - ERROR_LOG(m_logger) << "Internal error: Got invalid kennung: " << wirkfeldKennung; + // the wirkfeldstatusMinensperre-telegram has changed while sending it as normal broadcast is not yet + // finished => we not add the deactiveEinzelmine-telegram as broadcast-only, so the updated wirkfeld- + // statusMinensperre-telegram will be sent as normal broadcast-telegram. The deactivateEinzelmine- + // telegram must be deleted + // delete a_radioTelegram; // no longer needed, shared_ptr } - break; - case TrainingAreaBase::TetraIcd::AreaEffectSimulationType::FunctionalArea: // Telegram DeaktivierenFunktionsraum should be used, instead DeaktivierungWirkfeld with wirkfeldTyp 6 - default: - // this should never happen, because CoPrtCnvRadioTelegram::isContentValid() filters this out - ERROR_LOG(m_logger) << "Internal error: WirkfeldTyp " << wirkfeldTyp2Str(wirkfeldTyp) << " in GEF_DEAKTIVIERUNG_WIRKFELD not implemented"; - } - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - break; - } - - case GEF_DEAKTIVIERUNG_EINZELMINE: - { - deactivateSingleMine(a_radioTelegram); - break; - } - - case GEF_REAKTIVIERUNG_DUS_MINE: - { - reactivateDusMine(a_radioTelegram); - break; - } - - case GEF_TECHNIK_FUNKTIONSRAUM: - { - // take funktionsraum to be (re)activated out of sammeltelegram of deactivated funktionsräume - uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - // remove an old already existing funktionsraum-telegram with this kennung - removeFromTechnikFunktionsAndBroadcastMaps(funktionsraumkennung); - - // insert the funktionsraum-telegram - m_TechnikFunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); - - // the original telegram will be added to broadcast-list - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - break; - } - - case GEF_FUNKTIONSRAUM: - { - // take funktionsraum to be (re)activated out of sammeltelegram of deactivated funktionsräume - uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - // remove an old already existing funktionsraum-telegram with this kennung - removeFromFunktionsAndBroadcastMaps(funktionsraumkennung); - removeFromDeactivatedFuncArea(funktionsraumkennung); - - // insert the funktionsraum-telegram - m_FunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); - - // the original telegram will be added to broadcast-list - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - break; - } - - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - { - uint16_t funktionsraumkennung = a_radioTelegram->getPayloadDataUInt32(5, 2); - emit areaEffectSimulationDeactivated(funktionsraumkennung); - - removeFromFunktionsAndBroadcastMaps(funktionsraumkennung); - if (addToDeactivatedFuncArea(funktionsraumkennung, a_radioTelegram->getBroadcastIndex())) - m_FunktionsraumTelegramMap.insert(std::make_pair(funktionsraumkennung, a_radioTelegram)); - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - break; - } - - default: - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - } -// dump(); -} - - -template -bool removeFromContainers(T &id2bcIndex, S &BcIndex2id, int aesAreaId) -{ - auto it = id2bcIndex.find(aesAreaId); - if (it == id2bcIndex.end()) - return false; - BcIndex2id.remove(it.value()); - id2bcIndex.erase(it); - return true; -} - -template -bool addToContainers(T &id2bcIndex, S &BcIndex2id, int aesAreaId, int bcIndex) -{ - auto it = id2bcIndex.find(aesAreaId); - if (it != id2bcIndex.end()) - { - if (it.value() == bcIndex) - return false; - BcIndex2id.remove(it.value()); - } - id2bcIndex[aesAreaId] = bcIndex; - BcIndex2id[bcIndex] = aesAreaId; - return true; -} - -bool PrtCnvBroadcastMgr::removeFromDeactivatedAesArea(int aesAreaId) -{ - return removeFromContainers(m_deactivatedAesArea2bcIndex, m_deactivatedBcIndex2AesArea, aesAreaId); -} - -// returns true when added -bool PrtCnvBroadcastMgr::addToDeactivatedAesArea(int aesAreaId, int bcIndex) -{ - return addToContainers(m_deactivatedAesArea2bcIndex, m_deactivatedBcIndex2AesArea, aesAreaId, bcIndex); -} - -bool PrtCnvBroadcastMgr::removeFromDeactivatedFuncArea(int aesAreaId) -{ - return removeFromContainers(m_deactivatedFuncArea2bcIndex, m_deactivatedBcIndex2FuncArea, aesAreaId); -} - -bool PrtCnvBroadcastMgr::addToDeactivatedFuncArea(int aesAreaId, int bcIndex) -{ - return addToContainers(m_deactivatedFuncArea2bcIndex, m_deactivatedBcIndex2FuncArea, aesAreaId, bcIndex); -} - -bool PrtCnvBroadcastMgr::removeFromDeactivatedDusMine(int dusMineId) -{ - return removeFromContainers(m_deactivatedDusMine2bcIndex, m_deactivatedBcIndex2DusMine, dusMineId); -} - -bool PrtCnvBroadcastMgr::addToDeactivatedDusMine(int dusMineId, int bcIndex) -{ - return addToContainers(m_deactivatedDusMine2bcIndex, m_deactivatedBcIndex2DusMine, dusMineId, bcIndex); -} - -bool PrtCnvBroadcastMgr::removeFromActivatedDusMine(int dusMineId) -{ - return (m_activatedDusMines.remove(dusMineId)); -} - -void PrtCnvBroadcastMgr::addToActivatedDusMine(int dusMineId) -{ - m_activatedDusMines.insert(dusMineId); -} - -// --------------------------------------------------------------- -// searches the kennung within sammeltelegram. -// returns -1 when kennung not found -// --------------------------------------------------------------- -int PrtCnvBroadcastMgr::getSammeltelegramIndex(const std::shared_ptr &a_sammelTelegram, - const uint16_t a_kennung) const -{ - // decide the length of anzahl - uint16_t nbrLength = 0; - switch (a_sammelTelegram->getTelID()) - { - case GEF_WF_SAMMELDEAKTIVIERUNG: - case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: - nbrLength = 1; - break; - case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: - case GEF_REAKTIVIERUNG_DUS_MINE: - nbrLength = 2; - break; - default: - ERROR_LOG(m_logger) << "Unknown Sammeltelegram with telId=" << a_sammelTelegram->getTelID(); - return -1; - } - // search the kennung in sammeltelegram - const int cntAesIds = a_sammelTelegram->getPayloadDataUInt32(5, nbrLength); - for (int i = 0; i < cntAesIds; i++) - { - if (a_kennung == a_sammelTelegram->getPayloadDataUInt32(5 + nbrLength + i * 2, 2)) - return i; - } - return -1; -} - - -// --------------------------------------------------------------- -// Handles the DEAKTIVIERUNG_EINZELMINE-telegram for normal- -// broadcasts and nachforderungen. This includes deactivation -// of mines from minen-sperre and DUS-mines. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::deactivateSingleMine(const std::shared_ptr &a_radioTelegram) -{ - uint32_t wirkfeldkennung = a_radioTelegram->getPayloadDataUInt32(9, 2); - uint32_t minenkennung = a_radioTelegram->getPayloadDataUInt32(11, 2); - // DUS or normal mine? - if (0 == wirkfeldkennung) - { - removeFromActivatedDusMine(minenkennung); - addToDeactivatedDusMine(minenkennung, a_radioTelegram->getBroadcastIndex()); - DEBUG_LOG(m_logger) << "Deactivating DUS-Mine: " << minenkennung << ", #deactivated mines: " << m_deactivatedBcIndex2DusMine.size(); - removeDusMineDeactivationFromBroadcastMap(minenkennung); // remove old if there is already a telegram - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); - } - else - { - // normal mine => change mine in "wirkfeldStatusMinensperre" - bool sentAsNormalBroadcastFinished = deactivateEinzelmineFromMinensperre(wirkfeldkennung, minenkennung, a_radioTelegram->getBroadcastIndex()); - if (sentAsNormalBroadcastFinished) - { - // add the deactivierungEinzelmine-telegram as broadcast-only-telegram - addWirkfeldTelegram(a_radioTelegram, wirkfeldkennung, GEF_BESTAETIGUNG, minenkennung); - addBroadcastOnlyTelegramToMap(a_radioTelegram); - } - else - { - // the wirkfeldstatusMinensperre-telegram has changed while sending it as normal broadcast is not yet - // finished => we not add the deactiveEinzelmine-telegram as broadcast-only, so the updated wirkfeld- - // statusMinensperre-telegram will be sent as normal broadcast-telegram. The deactivateEinzelmine- - // telegram must be deleted - // delete a_radioTelegram; // no longer needed, shared_ptr } } -} -// --------------------------------------------------------------- -// Deactivates the mine in the corresponding -// "WirkfeldstatusMinensperre"-telegram and moves the -// "WirkfeldstatusMinensperre"-telegram to the position of -// "DeactiviereEinzelmine"-telegram. -// Returns true if the "WirkfeldstatusMinensperre"-telegram -// was already sent 3 times as normal broadcast. -// --------------------------------------------------------------- -bool PrtCnvBroadcastMgr::deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, - const uint16_t a_minenKennung, - const uint16_t a_broadcastIndex) -{ - // search the corresponding "WirkfeldstatusMinensperre"-telegram in the broadcast-map - auto iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); - while (iter != m_WirkfeldTelegramMapByKennung.end()) + // --------------------------------------------------------------- + // Deactivates the mine in the corresponding + // "WirkfeldstatusMinensperre"-telegram and moves the + // "WirkfeldstatusMinensperre"-telegram to the position of + // "DeactiviereEinzelmine"-telegram. + // Returns true if the "WirkfeldstatusMinensperre"-telegram + // was already sent 3 times as normal broadcast. + // --------------------------------------------------------------- + bool PrtCnvBroadcastMgr::deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex) { - if (iter->first != a_wirkfeldKennung) break; - - auto radioTelegram = iter->second; - if (radioTelegram->getTelID() == GEF_WIRKFELD_STATUS_MINENSPERRE && a_wirkfeldKennung == radioTelegram->getPayloadDataUInt32(5, 2)) + // search the corresponding "WirkfeldstatusMinensperre"-telegram in the broadcast-map + auto iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); + while (iter != m_WirkfeldTelegramMapByKennung.end()) { - // check whether the minekennung is valid - uint16_t nbrOfMines = radioTelegram->getPayloadDataUInt32(7, 2); - if (nbrOfMines >= a_minenKennung && a_minenKennung != 0) + if (iter->first != a_wirkfeldKennung) + break; + + auto radioTelegram = iter->second; + if (radioTelegram->getTelID() == GEF_WIRKFELD_STATUS_MINENSPERRE && a_wirkfeldKennung == radioTelegram->getPayloadDataUInt32(5, 2)) { - // calc the position of mine - // definition: The first mine is mine 1; MSB is bit 0 => mine 1 is bit 7; mine 2 is bit 6; ... mine 8 is bit 0; Mine 9 is bit 7 (of next byte)... - uint16_t bytePos = 9 + (a_minenKennung - 1) / 8; - if (bytePos < radioTelegram->getPayloadSize()) + // check whether the minekennung is valid + uint16_t nbrOfMines = radioTelegram->getPayloadDataUInt32(7, 2); + if (nbrOfMines >= a_minenKennung && a_minenKennung != 0) { - uint8_t mask = 0x80 >> ((a_minenKennung - 1) % 8); -// INFO_LOG(m_logger) << "pos=" << (pos-9) << " mask=" << (int)mask; - // clear the bit for the mine - radioTelegram->setPayloadDataWithIndex(bytePos, (uint8_t)(radioTelegram->getPayloadDataUInt8(bytePos) & (~mask)), 1); - moveTelegramInBroadcastMap(radioTelegram, a_broadcastIndex); - - // if we have a corresponding wirkstatus-minensperre which was not sent 3 times as normal broadcast, - // we have to take it out and to send the new wirkfeldstatus-minensperre-telegram instead. Also all - // the deactivate einzelmine-telegrams must not be stored within the broadcast-list as broadcast-only - // telegram, therefore we return false - bool dummy; - if (radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), dummy, false)) + // calc the position of mine + // definition: The first mine is mine 1; MSB is bit 0 => mine 1 is bit 7; mine 2 is bit 6; ... mine 8 is bit 0; Mine 9 is bit 7 (of next byte)... + uint16_t bytePos = 9 + (a_minenKennung - 1) / 8; + if (bytePos < radioTelegram->getPayloadSize()) { - INFO_LOG(m_logger) << "A normal broadcast-telegram WirkfeldStatusMinensperre still exists"; - return false; + uint8_t mask = 0x80 >> ((a_minenKennung - 1) % 8); + // INFO_LOG(m_logger) << "pos=" << (pos-9) << " mask=" << (int)mask; + // clear the bit for the mine + radioTelegram->setPayloadDataWithIndex(bytePos, (uint8_t)(radioTelegram->getPayloadDataUInt8(bytePos) & (~mask)), 1); + moveTelegramInBroadcastMap(radioTelegram, a_broadcastIndex); + + // if we have a corresponding wirkstatus-minensperre which was not sent 3 times as normal broadcast, + // we have to take it out and to send the new wirkfeldstatus-minensperre-telegram instead. Also all + // the deactivate einzelmine-telegrams must not be stored within the broadcast-list as broadcast-only + // telegram, therefore we return false + bool dummy; + if (radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), dummy, false)) + { + INFO_LOG(m_logger) << "A normal broadcast-telegram WirkfeldStatusMinensperre still exists"; + return false; + } + return true; } - return true; + else + ERROR_LOG(m_logger) << "Got corrupt telegram WirkfeldstatusMinensperre with nbrOfMines=" << nbrOfMines + << " and payloadSize=" << radioTelegram->getPayloadSize(); } else - ERROR_LOG(m_logger) << "Got corrupt telegram WirkfeldstatusMinensperre with nbrOfMines=" << nbrOfMines << " and payloadSize=" << radioTelegram->getPayloadSize(); - } - else - { - // minenkennung is too big to fit into statusMinensperre => Errormessage, do not update in status, but send as normal broadcast - ERROR_LOG(m_logger) << "Mine with kennung=" << a_minenKennung << " does not fit into status (nbrOfMines=" << nbrOfMines << ")"; - } - return true; - } - ++iter; - } - ERROR_LOG(m_logger) << "Did not find the WirkfeldStatusMinensperre with kennung=" << a_wirkfeldKennung - << ", therefore deactivated mine with kennung=" << a_minenKennung << " could not be updated."; - return true; -} - - -// --------------------------------------------------------------- -// Handles the REAKTIVIERUNG_DUS_MINE-telegram for normal- -// broadcasts and nachforderungen. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::reactivateDusMine(const std::shared_ptr &a_radioTelegram) -{ - // take all DUS-mines to be reactivated out of sammeltelegram of deactivated DUS-mines - const uint32_t nbrOfMines = a_radioTelegram->getPayloadDataUInt32(5, 2); // #mines is 2 bytes - - DEBUG_LOG(m_logger) << "Reactivating DUS-Mines, #mines: " << nbrOfMines; - if (0 == nbrOfMines) - { - - for (int dusMineId : std::as_const(m_deactivatedBcIndex2DusMine)) - { - removeDusMineDeactivationFromBroadcastMap(dusMineId); - addToActivatedDusMine(dusMineId); - } - m_deactivatedDusMine2bcIndex.clear(); - m_deactivatedBcIndex2DusMine.clear(); - } - else - { - // normal-case: reactivate some DUS-mines - for (uint32_t i = 0; i < nbrOfMines; i++) - { - const int dusMineId = a_radioTelegram->getPayloadDataUInt32(7 + 2 * i, 2); - DEBUG_LOG(m_logger) << "Reactivating DUS-Mines, mindId: " << dusMineId; - removeDusMineDeactivationFromBroadcastMap(dusMineId); - removeFromDeactivatedDusMine(dusMineId); - addToActivatedDusMine(dusMineId); - } - } - - auto pred = [](const std::shared_ptr &tele) -> bool - { - return (tele->getTelID() == GEF_REAKTIVIERUNG_DUS_MINE); - }; - removeFromBroadcastMapFunc(pred); - m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); -} - - -// --------------------------------------------------------------- -// adds the wirkfeld-telegram to the by time and by kennung -// maps -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::addWirkfeldTelegram(const std::shared_ptr &a_radioTelegram, - const uint16_t a_wirkfeldKennung, - const gef_telegramm_id_et a_telId, - const uint16_t a_minenKennung) -{ - // remove an old already existing wirkfeld-telegram with this kennung - auto iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); - while (iter != m_WirkfeldTelegramMapByKennung.end()) - { - if (iter->first != a_wirkfeldKennung) - break; - auto radioTelegram = iter->second; - // same mineindex (only for "Deaktivierung_Einzelmine")? - bool isSameMine = true; - if (0 != a_minenKennung) - { - if (GEF_DEAKTIVIERUNG_EINZELMINE == a_radioTelegram->getTelID()) - { - if (GEF_DEAKTIVIERUNG_EINZELMINE == radioTelegram->getTelID()) { - uint16_t mineIndex = radioTelegram->getPayloadDataUInt32(11, 2); - isSameMine = mineIndex == a_minenKennung; - INFO_LOG(m_logger) << "Mine with kennung=" << a_minenKennung << " found: " << isSameMine; + // minenkennung is too big to fit into statusMinensperre => Errormessage, do not update in status, but send as normal broadcast + ERROR_LOG(m_logger) << "Mine with kennung=" << a_minenKennung << " does not fit into status (nbrOfMines=" << nbrOfMines << ")"; } + return true; } - else - ERROR_LOG(m_logger) << "Internal error: Only telegrams 'Deaktivierung_Einzelmine' must be called with a_mineKennung. I proceed without respecting mine-kennung..."; + ++iter; } - // same telegram-id, or opposite telegram (used for stop- and fortsetzen dauerfeuer and deaktivierung einzelmine)? - if ((radioTelegram->getTelID() == a_radioTelegram->getTelID() || radioTelegram->getTelID() == a_telId) && isSameMine) + ERROR_LOG(m_logger) << "Did not find the WirkfeldStatusMinensperre with kennung=" << a_wirkfeldKennung + << ", therefore deactivated mine with kennung=" << a_minenKennung << " could not be updated."; + return true; + } + + + // --------------------------------------------------------------- + // Handles the REAKTIVIERUNG_DUS_MINE-telegram for normal- + // broadcasts and nachforderungen. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::reactivateDusMine(const std::shared_ptr &a_radioTelegram) + { + // take all DUS-mines to be reactivated out of sammeltelegram of deactivated DUS-mines + const uint32_t nbrOfMines = a_radioTelegram->getPayloadDataUInt32(5, 2); // #mines is 2 bytes + + DEBUG_LOG(m_logger) << "Reactivating DUS-Mines, #mines: " << nbrOfMines; + if (0 == nbrOfMines) { - // remove the old telegram from wirkfeld- and broadcast-map - removeFromWirkfeldAndBroadcastMaps(iter); // iterator is corrupt after calling this function ... - iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); + + for (int dusMineId : std::as_const(m_deactivatedBcIndex2DusMine)) + { + removeDusMineDeactivationFromBroadcastMap(dusMineId); + addToActivatedDusMine(dusMineId); + } + m_deactivatedDusMine2bcIndex.clear(); + m_deactivatedBcIndex2DusMine.clear(); } else - ++iter; - } - - // now add the new wirkfeld-telegram - INFO_LOG(m_logger) << "Add kennung: " << a_wirkfeldKennung - << " telId=" << a_radioTelegram->getTelID() - << " BC=" << a_radioTelegram->getBroadcastIndex(); - m_WirkfeldTelegramMapByKennung.insert(std::make_pair(a_wirkfeldKennung, a_radioTelegram)); - time_t expireTime = a_radioTelegram->getExpireTime(); - if (expireTime > 0) - m_WirkfeldTelegramMapByTime.insert(std::make_pair(expireTime, a_radioTelegram)); -} - - -// --------------------------------------------------------------- -// Removes the wirkfeld-telegrams with this kennung from the -// by time and by kennung maps. -// Replace this telegrams with Nop in BC-list. -// Finally the telegram will be deleted. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeWirkfeldTelegrams(const uint16_t a_kennung) -{ - INFO_LOG(m_logger) << "Removing all Wirkfeld-Telegrams with kennung=" << a_kennung; - // search all wirkfeld-telegrams with this kennung - auto iter = m_WirkfeldTelegramMapByKennung.find(a_kennung); - while (iter != m_WirkfeldTelegramMapByKennung.end()) - { - if (iter->first != a_kennung) - break; - - removeFromWirkfeldAndBroadcastMaps(iter); - - iter = m_WirkfeldTelegramMapByKennung.find(a_kennung); - } -} - - -// --------------------------------------------------------------- -// Removes the telegram with a_funktionsraumKennung from -// funktionsraum-map and from the broadcast-map. -// If the telegram is a attached BC-only-telegram, it will be -// detached. -// The telegram itself will be deleted. -// ATTENTION: iterators to m_FunktionsraumTelegramMap could be -// invalid after calling this function -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung) -{ - auto iter = m_FunktionsraumTelegramMap.find(a_funktionsraumKennung); - if (iter != m_FunktionsraumTelegramMap.end()) - { - auto radioTelegram = iter->second; - // get the BC-Index for removing of broadcast-map - // remove the telegram from funktionsraum-map - INFO_LOG(m_logger) << "Removing Funktionsraum-telegram with kennung=" << a_funktionsraumKennung - << " and BC=" << radioTelegram->getBroadcastIndex(); - m_FunktionsraumTelegramMap.erase(iter); - - removeFromBroadcastMap(radioTelegram); - } -} - - -// --------------------------------------------------------------- -// Removes the telegram with a_funktionsraumKennung from -// funktionsraum-map and from the broadcast-map. -// If the telegram is a attached BC-only-telegram, it will be -// detached. -// The telegram itself will be deleted. -// ATTENTION: iterators to m_FunktionsraumTelegramMap could be -// invalid after calling this function -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung) -{ - auto iter = m_TechnikFunktionsraumTelegramMap.find(a_funktionsraumKennung); - if (iter != m_TechnikFunktionsraumTelegramMap.end()) - { - auto radioTelegram = iter->second; - // get the BC-Index for removing of broadcast-map - // remove the telegram from funktionsraum-map - INFO_LOG(m_logger) << "Removing Funktionsraum-telegram with kennung=" << a_funktionsraumKennung - << " and BC=" << radioTelegram->getBroadcastIndex(); - m_TechnikFunktionsraumTelegramMap.erase(iter); - - removeFromBroadcastMap(radioTelegram); - } -} - - -// --------------------------------------------------------------- -// Removes the telegram where -// wirkfeldTelegramMapByKennungIterator points to from -// wirkfeld-maps and from the broadcast-map. -// If the telegram is a attached BC-only-telegram, it will be -// detached. -// The telegram itself will be deleted. -// ATTENTION: iterators to m_WirkfeldTelegramMapByKennung and -// m_WirkfeldTelegramMapByTime could be invalid after calling -// this function -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeFromWirkfeldAndBroadcastMaps(const std::multimap>::iterator &a_wirkfeldTelegramMapByKennungIterator) -{ - auto radioTelegram = a_wirkfeldTelegramMapByKennungIterator->second; - - INFO_LOG(m_logger) << "Removing wirkfeld-telegram with telId=" << radioTelegram->getTelID() - << ", kennung=" << a_wirkfeldTelegramMapByKennungIterator->first - << " and BC=" << radioTelegram->getBroadcastIndex() - << " from byWirkfeldKennung-map"; - - // remove the telegram from by kennung map - m_WirkfeldTelegramMapByKennung.erase(a_wirkfeldTelegramMapByKennungIterator); - - // remove the telegram from by time map - time_t expireTime = radioTelegram->getExpireTime(); - if (0 != expireTime) - { - auto iter = m_WirkfeldTelegramMapByTime.find(expireTime); - while (iter != m_WirkfeldTelegramMapByTime.end()) { - if (iter->second == radioTelegram) + // normal-case: reactivate some DUS-mines + for (uint32_t i = 0; i < nbrOfMines; i++) { - INFO_LOG(m_logger) << "Removing wirkfeld-telegram with telId=" << radioTelegram->getTelID() - << " also from byTime-map"; - m_WirkfeldTelegramMapByTime.erase(iter); + const int dusMineId = a_radioTelegram->getPayloadDataUInt32(7 + 2 * i, 2); + DEBUG_LOG(m_logger) << "Reactivating DUS-Mines, mindId: " << dusMineId; + removeDusMineDeactivationFromBroadcastMap(dusMineId); + removeFromDeactivatedDusMine(dusMineId); + addToActivatedDusMine(dusMineId); + } + } + + auto pred = [](const std::shared_ptr &tele) -> bool { return (tele->getTelID() == GEF_REAKTIVIERUNG_DUS_MINE); }; + removeFromBroadcastMapFunc(pred); + m_BroadcastMap.insert(std::make_pair(a_radioTelegram->getBroadcastIndex(), a_radioTelegram)); + } + + + // --------------------------------------------------------------- + // adds the wirkfeld-telegram to the by time and by kennung + // maps + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::addWirkfeldTelegram(const std::shared_ptr &a_radioTelegram, + const uint16_t a_wirkfeldKennung, + const gef_telegramm_id_et a_telId, + const uint16_t a_minenKennung) + { + // remove an old already existing wirkfeld-telegram with this kennung + auto iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); + while (iter != m_WirkfeldTelegramMapByKennung.end()) + { + if (iter->first != a_wirkfeldKennung) break; - } - ++iter; - } - } - - removeFromBroadcastMap(radioTelegram); -} - - -// --------------------------------------------------------------- -// Removes the telegram a_radioTelegram from the broadcast-map. -// If the a_radioTelegram has an attached telegram, the -// attached telegram will be detached and added to broadcast- -// map as broadcast-only telegram. -// If the telegram is an attached BC-only-telegram, it will be -// detached. -// ATTENTION: iterators to m_BroadcastMap could be invalid -// after calling this function -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeFromBroadcastMap(const std::shared_ptr &a_radioTelegram) -{ - // remove from broadcast-map - if (!a_radioTelegram) - return; - - auto iter = m_BroadcastMap.find(a_radioTelegram->getBroadcastIndex()); - if (iter != m_BroadcastMap.end()) - { - if (iter->second == a_radioTelegram) - { - m_BroadcastMap.erase(iter); - detachTelegram(a_radioTelegram); - } - else if (iter->second->getBroadcastonlyTelegram() == a_radioTelegram) - iter->second->setBroadcastonlyTelegram(nullptr); - } -} - -void PrtCnvBroadcastMgr::removeFromBroadcastMapFunc(const std::function &)> &pred) -{ - auto it = m_BroadcastMap.begin(); - while (it != m_BroadcastMap.end()) - { - const auto &p = *it; - if (pred(p.second)) - it = m_BroadcastMap.erase(it); - else - ++it; - } -} - -void PrtCnvBroadcastMgr::removeDusMineDeactivationFromBroadcastMap(int dusMineId) -{ - auto pred = [dusMineId](const std::shared_ptr &tele) -> bool - { - return (tele->getTelID() == GEF_DEAKTIVIERUNG_EINZELMINE && - 0 == tele->getPayloadDataUInt32(9, 2) && - uint32_t(dusMineId) == tele->getPayloadDataUInt32(11, 2)); - }; - removeFromBroadcastMapFunc(pred); -} - -template -void removeFromMap(T &cont, const std::shared_ptr &a_radioTelegram) -{ - auto iter = cont.begin(); - while (iter != cont.end()) - { - if (iter->second == a_radioTelegram) - iter = cont.erase(iter); - else - ++iter; - } -} - -// --------------------------------------------------------------- -// Removes the telegram a_radioTelegram from all maps -// (broadcast-, wirkfeld-, funktionsraum- and lastTelegram- -// map). -// If the telegram is a attached BC-only-telegram, it will be -// detached. -// ATTENTION: iterators to all maps could be invalid after -// calling this function -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::removeFromAllMaps(const std::shared_ptr &a_radioTelegram) -{ - INFO_LOG(m_logger) << "Remove telegram with telId=" << a_radioTelegram->getTelID() << " BC=" << a_radioTelegram->getBroadcastIndex(); - - removeFromBroadcastMap(a_radioTelegram); - - // remove from byWirkfeldKennung-map - removeFromMap(m_WirkfeldTelegramMapByKennung, a_radioTelegram); - - // remove from byWirkfeldTime-map - removeFromMap(m_WirkfeldTelegramMapByTime, a_radioTelegram); - - // remove from funktionsraum-map - removeFromMap(m_FunktionsraumTelegramMap, a_radioTelegram); - - // remove from last-telegram-map - removeFromMap(m_LastTelegramMap, a_radioTelegram); -} - - -// --------------------------------------------------------------- -// used for telegrams that must only exists once in BC-list -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::replaceLastTelegramAndAddAtEnd(const std::shared_ptr &a_newRadioTelegram) -{ - // do we have a last telegram? - auto iter = m_LastTelegramMap.find(a_newRadioTelegram->getTelID()); - if (iter != m_LastTelegramMap.end()) - { - auto lastRadioTelegram = iter->second; - // yes => replace the last telegram with NOP - INFO_LOG(m_logger) << "remove last telegram with telId=" << lastRadioTelegram->getTelID() - << " and BC=" << lastRadioTelegram->getBroadcastIndex(); - removeFromBroadcastMap(lastRadioTelegram); - m_LastTelegramMap.erase(iter); - } - // insert the new telegram into BC-list - m_BroadcastMap.insert(std::make_pair(a_newRadioTelegram->getBroadcastIndex(), a_newRadioTelegram)); - // and insert into last-telegram-list - m_LastTelegramMap.insert(std::make_pair(a_newRadioTelegram->getTelID(), a_newRadioTelegram)); - INFO_LOG(m_logger) << "New last telegram with with telId=" << a_newRadioTelegram->getTelID() - << " and BC=" << a_newRadioTelegram->getBroadcastIndex(); -} - - -// --------------------------------------------------------------- -// Moves a_radioTelegram to a_newBroadcastIndex in broadcast- -// map. -// If a_radioTelegram has an attached broadcast-only-telegram, -// the broadcastOnly-telegram will be detached and kept on the -// old broadcast-index position. -// If a_attachTelegram in not NULL, this telegram will be -// attached to a_radioTelegram. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::moveTelegramInBroadcastMap(const std::shared_ptr &a_radioTelegram, - const uint16_t a_newBroadcastIndex, - const std::shared_ptr &a_attachTelegram) -{ - // remove the old telegram from map (and detach) - INFO_LOG(m_logger) << "Move telId=" << a_radioTelegram->getTelID() - << " from BC=" << a_radioTelegram->getBroadcastIndex() - << " to BC=" << a_newBroadcastIndex; - removeFromBroadcastMap(a_radioTelegram); - // insert telegram a end - a_radioTelegram->setBroadcastIndex(a_newBroadcastIndex); - m_BroadcastMap.insert(std::make_pair(a_newBroadcastIndex, a_radioTelegram)); - // attach a_attachTelegram - if (a_attachTelegram && (a_attachTelegram->getTelID() != GEF_REAKTIVIERUNG_DUS_MINE)) - { - INFO_LOG(m_logger) << "Attach telID=" << a_attachTelegram->getTelID() - << " to telID=" << a_radioTelegram->getTelID() - << " BC=" << a_newBroadcastIndex; - a_radioTelegram->setBroadcastonlyTelegram(a_attachTelegram); - a_attachTelegram->setBroadcastIndex(a_newBroadcastIndex); - } -} - - -// --------------------------------------------------------------- -// Returns the actual broadcast-index for normal broadcasts. -// --------------------------------------------------------------- -uint16_t PrtCnvBroadcastMgr::getBroadcastIndex() const -{ - return m_BroadcastIndex; -} - - -// --------------------------------------------------------------- -// Returns the broadcastindex for the next broadcast -// --------------------------------------------------------------- -uint16_t PrtCnvBroadcastMgr::getNextBroadcastIndex() -{ - return ++m_BroadcastIndex; -} - - -// --------------------------------------------------------------- -// Returns a NOP-telegramm filled with the desired values. -// --------------------------------------------------------------- -std::shared_ptr PrtCnvBroadcastMgr::getNopTelegram(const uint16_t a_from, const uint16_t a_to) -{ - auto nopTelegram(std::make_shared(GEF_NOP, 7, 0)); - nopTelegram->setPayloadDataWithIndex(3, a_from, 2); // Feld Anfang - nopTelegram->setPayloadDataWithIndex(5, a_to, 2); // Feld Ende - return nopTelegram; -} - - -// --------------------------------------------------------------- -// Adds the telegram a_broadcastOnlyTelegram (which must have -// set already the broadcast-index) to the broadcast-map. The -// telegram will be attached to an already existing broadcast- -// telegram with same broadcast-index in the map, otherwise it -// will be marked as broadcast-only. -// If the there is already an broadcast-only-telegram attached, -// nothing will be done. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::addBroadcastOnlyTelegramToMap(const std::shared_ptr &a_broadcastOnlyTelegram) -{ - uint16_t broadcastIndex = a_broadcastOnlyTelegram->getBroadcastIndex(); - auto iter = m_BroadcastMap.find(broadcastIndex); - if (m_BroadcastMap.end() == iter) - { - // insert as braodcast-only marked telegram - INFO_LOG(m_logger) << "Insert telId=" << a_broadcastOnlyTelegram->getTelID() - << " as broadcastonly telegram with BC=" << broadcastIndex; - a_broadcastOnlyTelegram->setBroadcastOnly(); - m_BroadcastMap.insert(std::make_pair(broadcastIndex, a_broadcastOnlyTelegram)); - } - else - { - // attach to an already existing broadcast-telegram - INFO_LOG(m_logger) << "Add telId=" << a_broadcastOnlyTelegram->getTelID() - << " as broadcastonly telegram to telegramm with BC=" << iter->second->getBroadcastIndex(); - iter->second->setBroadcastonlyTelegram(a_broadcastOnlyTelegram); - } -} - - -// --------------------------------------------------------------- -// Detaches an existing radio-telegram and adds it to the -// broadcast-map -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::detachTelegram(const std::shared_ptr &a_radioTelegram) -{ - auto broadcastOnlyTelegram = a_radioTelegram->getBroadcastonlyTelegram(); - if (broadcastOnlyTelegram) - { - uint16_t broadcastIndex = a_radioTelegram->getBroadcastIndex(); - // do some checks - INFO_LOG(m_logger) << "detach bconly-telegram : telId=" << a_radioTelegram->getTelID() << " BC=" << broadcastIndex; - if (broadcastOnlyTelegram->getBroadcastIndex() != broadcastIndex) - ERROR_LOG(m_logger) << "Internal error: BC=" << broadcastOnlyTelegram->getBroadcastIndex() << " of attached telegram is not equal BC=" << broadcastIndex; - auto iter = m_BroadcastMap.find(broadcastIndex); - if (iter != m_BroadcastMap.end()) - ERROR_LOG(m_logger) << "Internal error: m_BroadcastMap-entry with BC=" << broadcastIndex << " must not exists"; - else - { - INFO_LOG(m_logger) << "Insert broadcast-only BC=" << broadcastOnlyTelegram->getBroadcastIndex(); - broadcastOnlyTelegram->setBroadcastOnly(); - m_BroadcastMap.insert(std::make_pair(broadcastIndex, broadcastOnlyTelegram)); - } - a_radioTelegram->setBroadcastonlyTelegram(nullptr); - } -} - - -// --------------------------------------------------------------- -// Removes all Nop out of broadcast-list and numerates the -// broadcast-index of kept broadcast-telegrams new. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::handleOverrunOfBroadcastCounter(const bool a_doRestore) -{ - WARNING_LOG(m_logger) << "Broadcast-counter reaches maximum => reduce broadcast-list and increment reset-counter"; - - // first we must wait until all data are stored in DB, otherwise we will loose - // the broadcast-telegrams, which were sent the 1st time, but not yet stored permanent - if (!a_doRestore) - { - m_DbThread->waitUntilDbWritten(); - getAllFinishedBroadcastsFromDb(); - } - - // reduce the broadcast-list - uint16_t newBroadcastCounter = 0; - std::map> newBroadcastMap; - auto iter = m_BroadcastMap.begin(); - while (iter != m_BroadcastMap.end()) - { - auto radioTelegram = iter->second; - if (radioTelegram->isBroadcastOnly()) - { - // delete all broadcast-only telegrams - ++iter; // removeFromAllMaps() will destroy the iterator => we increment it before removing - removeFromAllMaps(radioTelegram); - } - else - { - radioTelegram->setBroadcastIndex(++newBroadcastCounter); - auto broadcastOnlyTelegram = radioTelegram->getBroadcastonlyTelegram(); - if (broadcastOnlyTelegram) + auto radioTelegram = iter->second; + // same mineindex (only for "Deaktivierung_Einzelmine")? + bool isSameMine = true; + if (0 != a_minenKennung) { - radioTelegram->setBroadcastonlyTelegram(nullptr); - ++iter; // removeFromAllMaps() will destroy the iterator => we increment it before removing - removeFromAllMaps(broadcastOnlyTelegram); + if (GEF_DEAKTIVIERUNG_EINZELMINE == a_radioTelegram->getTelID()) + { + if (GEF_DEAKTIVIERUNG_EINZELMINE == radioTelegram->getTelID()) + { + uint16_t mineIndex = radioTelegram->getPayloadDataUInt32(11, 2); + isSameMine = mineIndex == a_minenKennung; + INFO_LOG(m_logger) << "Mine with kennung=" << a_minenKennung << " found: " << isSameMine; + } + } + else + ERROR_LOG(m_logger) + << "Internal error: Only telegrams 'Deaktivierung_Einzelmine' must be called with a_mineKennung. I proceed without respecting mine-kennung..."; + } + // same telegram-id, or opposite telegram (used for stop- and fortsetzen dauerfeuer and deaktivierung einzelmine)? + if ((radioTelegram->getTelID() == a_radioTelegram->getTelID() || radioTelegram->getTelID() == a_telId) && isSameMine) + { + // remove the old telegram from wirkfeld- and broadcast-map + removeFromWirkfeldAndBroadcastMaps(iter); // iterator is corrupt after calling this function ... + iter = m_WirkfeldTelegramMapByKennung.find(a_wirkfeldKennung); } else + ++iter; + } + + // now add the new wirkfeld-telegram + INFO_LOG(m_logger) << "Add kennung: " << a_wirkfeldKennung << " telId=" << a_radioTelegram->getTelID() << " BC=" << a_radioTelegram->getBroadcastIndex(); + m_WirkfeldTelegramMapByKennung.insert(std::make_pair(a_wirkfeldKennung, a_radioTelegram)); + time_t expireTime = a_radioTelegram->getExpireTime(); + if (expireTime > 0) + m_WirkfeldTelegramMapByTime.insert(std::make_pair(expireTime, a_radioTelegram)); + } + + + // --------------------------------------------------------------- + // Removes the wirkfeld-telegrams with this kennung from the + // by time and by kennung maps. + // Replace this telegrams with Nop in BC-list. + // Finally the telegram will be deleted. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeWirkfeldTelegrams(const uint16_t a_kennung) + { + INFO_LOG(m_logger) << "Removing all Wirkfeld-Telegrams with kennung=" << a_kennung; + // search all wirkfeld-telegrams with this kennung + auto iter = m_WirkfeldTelegramMapByKennung.find(a_kennung); + while (iter != m_WirkfeldTelegramMapByKennung.end()) + { + if (iter->first != a_kennung) + break; + + removeFromWirkfeldAndBroadcastMaps(iter); + + iter = m_WirkfeldTelegramMapByKennung.find(a_kennung); + } + } + + + // --------------------------------------------------------------- + // Removes the telegram with a_funktionsraumKennung from + // funktionsraum-map and from the broadcast-map. + // If the telegram is a attached BC-only-telegram, it will be + // detached. + // The telegram itself will be deleted. + // ATTENTION: iterators to m_FunktionsraumTelegramMap could be + // invalid after calling this function + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung) + { + auto iter = m_FunktionsraumTelegramMap.find(a_funktionsraumKennung); + if (iter != m_FunktionsraumTelegramMap.end()) + { + auto radioTelegram = iter->second; + // get the BC-Index for removing of broadcast-map + // remove the telegram from funktionsraum-map + INFO_LOG(m_logger) << "Removing Funktionsraum-telegram with kennung=" << a_funktionsraumKennung << " and BC=" << radioTelegram->getBroadcastIndex(); + m_FunktionsraumTelegramMap.erase(iter); + + removeFromBroadcastMap(radioTelegram); + } + } + + + // --------------------------------------------------------------- + // Removes the telegram with a_funktionsraumKennung from + // funktionsraum-map and from the broadcast-map. + // If the telegram is a attached BC-only-telegram, it will be + // detached. + // The telegram itself will be deleted. + // ATTENTION: iterators to m_FunktionsraumTelegramMap could be + // invalid after calling this function + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung) + { + auto iter = m_TechnikFunktionsraumTelegramMap.find(a_funktionsraumKennung); + if (iter != m_TechnikFunktionsraumTelegramMap.end()) + { + auto radioTelegram = iter->second; + // get the BC-Index for removing of broadcast-map + // remove the telegram from funktionsraum-map + INFO_LOG(m_logger) << "Removing Funktionsraum-telegram with kennung=" << a_funktionsraumKennung << " and BC=" << radioTelegram->getBroadcastIndex(); + m_TechnikFunktionsraumTelegramMap.erase(iter); + + removeFromBroadcastMap(radioTelegram); + } + } + + + // --------------------------------------------------------------- + // Removes the telegram where + // wirkfeldTelegramMapByKennungIterator points to from + // wirkfeld-maps and from the broadcast-map. + // If the telegram is a attached BC-only-telegram, it will be + // detached. + // The telegram itself will be deleted. + // ATTENTION: iterators to m_WirkfeldTelegramMapByKennung and + // m_WirkfeldTelegramMapByTime could be invalid after calling + // this function + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeFromWirkfeldAndBroadcastMaps( + const std::multimap>::iterator &a_wirkfeldTelegramMapByKennungIterator) + { + auto radioTelegram = a_wirkfeldTelegramMapByKennungIterator->second; + + INFO_LOG(m_logger) << "Removing wirkfeld-telegram with telId=" << radioTelegram->getTelID() << ", kennung=" << a_wirkfeldTelegramMapByKennungIterator->first + << " and BC=" << radioTelegram->getBroadcastIndex() << " from byWirkfeldKennung-map"; + + // remove the telegram from by kennung map + m_WirkfeldTelegramMapByKennung.erase(a_wirkfeldTelegramMapByKennungIterator); + + // remove the telegram from by time map + time_t expireTime = radioTelegram->getExpireTime(); + if (0 != expireTime) + { + auto iter = m_WirkfeldTelegramMapByTime.find(expireTime); + while (iter != m_WirkfeldTelegramMapByTime.end()) { - // all pending normal broadcast should no longer be sent as normal broadcasts, because all TNEs - // will anyway ask for nachforderung - bool wasLast; - if (radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), wasLast, false)) + if (iter->second == radioTelegram) { - do - { - radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), wasLast, true); - } - while (!wasLast); + INFO_LOG(m_logger) << "Removing wirkfeld-telegram with telId=" << radioTelegram->getTelID() << " also from byTime-map"; + m_WirkfeldTelegramMapByTime.erase(iter); + break; } ++iter; } - INFO_LOG(m_logger) << "New BC-index for broadcast-telegram with telId=" << radioTelegram->getTelID() << " BC=" << newBroadcastCounter; - newBroadcastMap.insert(std::make_pair(newBroadcastCounter, radioTelegram)); + } + + removeFromBroadcastMap(radioTelegram); + } + + + // --------------------------------------------------------------- + // Removes the telegram a_radioTelegram from the broadcast-map. + // If the a_radioTelegram has an attached telegram, the + // attached telegram will be detached and added to broadcast- + // map as broadcast-only telegram. + // If the telegram is an attached BC-only-telegram, it will be + // detached. + // ATTENTION: iterators to m_BroadcastMap could be invalid + // after calling this function + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeFromBroadcastMap(const std::shared_ptr &a_radioTelegram) + { + // remove from broadcast-map + if (!a_radioTelegram) + return; + + auto iter = m_BroadcastMap.find(a_radioTelegram->getBroadcastIndex()); + if (iter != m_BroadcastMap.end()) + { + if (iter->second == a_radioTelegram) + { + m_BroadcastMap.erase(iter); + detachTelegram(a_radioTelegram); + } + else if (iter->second->getBroadcastonlyTelegram() == a_radioTelegram) + iter->second->setBroadcastonlyTelegram(nullptr); } } - m_BroadcastMap.clear(); - m_BroadcastMap = newBroadcastMap; - // stop actual nachforderungen and increment reset-counter - cleanAndInit(false); - if (!a_doRestore) m_DbThread->setResetCounter(m_DbThread->getResetCounter() + 1); + void PrtCnvBroadcastMgr::removeFromBroadcastMapFunc(const std::function &)> &pred) + { + auto it = m_BroadcastMap.begin(); + while (it != m_BroadcastMap.end()) + { + const auto &p = *it; + if (pred(p.second)) + it = m_BroadcastMap.erase(it); + else + ++it; + } + } - WARNING_LOG(m_logger) << "New broadcast-counter=" << newBroadcastCounter << " new reset-counter=" << (int)m_DbThread->getResetCounter(); - m_BroadcastIndex = newBroadcastCounter; -} + void PrtCnvBroadcastMgr::removeDusMineDeactivationFromBroadcastMap(int dusMineId) + { + auto pred = [dusMineId](const std::shared_ptr &tele) -> bool + { return (tele->getTelID() == GEF_DEAKTIVIERUNG_EINZELMINE && 0 == tele->getPayloadDataUInt32(9, 2) && uint32_t(dusMineId) == tele->getPayloadDataUInt32(11, 2)); }; + removeFromBroadcastMapFunc(pred); + } + + template void removeFromMap(T &cont, const std::shared_ptr &a_radioTelegram) + { + auto iter = cont.begin(); + while (iter != cont.end()) + { + if (iter->second == a_radioTelegram) + iter = cont.erase(iter); + else + ++iter; + } + } + + // --------------------------------------------------------------- + // Removes the telegram a_radioTelegram from all maps + // (broadcast-, wirkfeld-, funktionsraum- and lastTelegram- + // map). + // If the telegram is a attached BC-only-telegram, it will be + // detached. + // ATTENTION: iterators to all maps could be invalid after + // calling this function + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::removeFromAllMaps(const std::shared_ptr &a_radioTelegram) + { + INFO_LOG(m_logger) << "Remove telegram with telId=" << a_radioTelegram->getTelID() << " BC=" << a_radioTelegram->getBroadcastIndex(); + + removeFromBroadcastMap(a_radioTelegram); + + // remove from byWirkfeldKennung-map + removeFromMap(m_WirkfeldTelegramMapByKennung, a_radioTelegram); + + // remove from byWirkfeldTime-map + removeFromMap(m_WirkfeldTelegramMapByTime, a_radioTelegram); + + // remove from funktionsraum-map + removeFromMap(m_FunktionsraumTelegramMap, a_radioTelegram); + + // remove from last-telegram-map + removeFromMap(m_LastTelegramMap, a_radioTelegram); + } -// --------------------------------------------------------------- -// Restores data after crash for seamless proceeding of work. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::restoreAfterCrash() -{ - getAllFinishedBroadcastsFromDb(true); -} + // --------------------------------------------------------------- + // used for telegrams that must only exists once in BC-list + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::replaceLastTelegramAndAddAtEnd(const std::shared_ptr &a_newRadioTelegram) + { + // do we have a last telegram? + auto iter = m_LastTelegramMap.find(a_newRadioTelegram->getTelID()); + if (iter != m_LastTelegramMap.end()) + { + auto lastRadioTelegram = iter->second; + // yes => replace the last telegram with NOP + INFO_LOG(m_logger) << "remove last telegram with telId=" << lastRadioTelegram->getTelID() << " and BC=" << lastRadioTelegram->getBroadcastIndex(); + removeFromBroadcastMap(lastRadioTelegram); + m_LastTelegramMap.erase(iter); + } + // insert the new telegram into BC-list + m_BroadcastMap.insert(std::make_pair(a_newRadioTelegram->getBroadcastIndex(), a_newRadioTelegram)); + // and insert into last-telegram-list + m_LastTelegramMap.insert(std::make_pair(a_newRadioTelegram->getTelID(), a_newRadioTelegram)); + INFO_LOG(m_logger) << "New last telegram with with telId=" << a_newRadioTelegram->getTelID() << " and BC=" << a_newRadioTelegram->getBroadcastIndex(); + } -// --------------------------------------------------------------- -// dumps important values, only for debugging -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::dump() -{ - // dump the broadcast-list - for (const auto &it : m_BroadcastMap) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_BroadcastMap, "); - - for (const auto &it : m_WirkfeldTelegramMapByKennung) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_WirkfeldTelegramMapByKennung, "); - - for (const auto &it : m_WirkfeldTelegramMapByTime) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_WirkfeldTelegramMapByTime, "); - - for (const auto &it : m_FunktionsraumTelegramMap) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_FunktionsraumTelegramMap, "); - - for (const auto &it : m_TechnikFunktionsraumTelegramMap) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_TechnikFunktionsraumTelegramMap, "); - - for (const auto &it : m_LastTelegramMap) - dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_LastTelegramMap, "); -} + // --------------------------------------------------------------- + // Moves a_radioTelegram to a_newBroadcastIndex in broadcast- + // map. + // If a_radioTelegram has an attached broadcast-only-telegram, + // the broadcastOnly-telegram will be detached and kept on the + // old broadcast-index position. + // If a_attachTelegram in not NULL, this telegram will be + // attached to a_radioTelegram. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::moveTelegramInBroadcastMap(const std::shared_ptr &a_radioTelegram, + const uint16_t a_newBroadcastIndex, + const std::shared_ptr &a_attachTelegram) + { + // remove the old telegram from map (and detach) + INFO_LOG(m_logger) << "Move telId=" << a_radioTelegram->getTelID() << " from BC=" << a_radioTelegram->getBroadcastIndex() << " to BC=" << a_newBroadcastIndex; + removeFromBroadcastMap(a_radioTelegram); + // insert telegram a end + a_radioTelegram->setBroadcastIndex(a_newBroadcastIndex); + m_BroadcastMap.insert(std::make_pair(a_newBroadcastIndex, a_radioTelegram)); + // attach a_attachTelegram + if (a_attachTelegram && (a_attachTelegram->getTelID() != GEF_REAKTIVIERUNG_DUS_MINE)) + { + INFO_LOG(m_logger) << "Attach telID=" << a_attachTelegram->getTelID() << " to telID=" << a_radioTelegram->getTelID() << " BC=" << a_newBroadcastIndex; + a_radioTelegram->setBroadcastonlyTelegram(a_attachTelegram); + a_attachTelegram->setBroadcastIndex(a_newBroadcastIndex); + } + } -// --------------------------------------------------------------- -// Increments the tick-counter of broadcast-manager and -// informs the broadcast-manager about the traffic-load. -// --------------------------------------------------------------- -void PrtCnvBroadcastMgr::incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad) -{ - if (e_ST_COLLECT == m_State) - ++m_TickCounter; - m_IsFullLoad = a_isFullLoad; - if (a_isHighLoad) - m_ActClaimWindow = m_HighLoadFactor * m_ClaimWindow; - else - m_ActClaimWindow = m_ClaimWindow; -} + // --------------------------------------------------------------- + // Returns the actual broadcast-index for normal broadcasts. + // --------------------------------------------------------------- + uint16_t PrtCnvBroadcastMgr::getBroadcastIndex() const + { + return m_BroadcastIndex; + } -// --------------------------------------------------------------- -// Checks if the given id is in m_deactivatedAesArea2bcIndex -// --------------------------------------------------------------- -bool PrtCnvBroadcastMgr::isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const -{ - INFO_LOG(m_logger) << "Checking deactivation for Id " << effectsimulationId; - return m_deactivatedAesArea2bcIndex.contains(effectsimulationId); -} + + // --------------------------------------------------------------- + // Returns the broadcastindex for the next broadcast + // --------------------------------------------------------------- + uint16_t PrtCnvBroadcastMgr::getNextBroadcastIndex() + { + return ++m_BroadcastIndex; + } + + + // --------------------------------------------------------------- + // Returns a NOP-telegramm filled with the desired values. + // --------------------------------------------------------------- + std::shared_ptr PrtCnvBroadcastMgr::getNopTelegram(const uint16_t a_from, const uint16_t a_to) + { + auto nopTelegram(std::make_shared(GEF_NOP, 7, 0)); + nopTelegram->setPayloadDataWithIndex(3, a_from, 2); // Feld Anfang + nopTelegram->setPayloadDataWithIndex(5, a_to, 2); // Feld Ende + return nopTelegram; + } + + + // --------------------------------------------------------------- + // Adds the telegram a_broadcastOnlyTelegram (which must have + // set already the broadcast-index) to the broadcast-map. The + // telegram will be attached to an already existing broadcast- + // telegram with same broadcast-index in the map, otherwise it + // will be marked as broadcast-only. + // If the there is already an broadcast-only-telegram attached, + // nothing will be done. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::addBroadcastOnlyTelegramToMap(const std::shared_ptr &a_broadcastOnlyTelegram) + { + uint16_t broadcastIndex = a_broadcastOnlyTelegram->getBroadcastIndex(); + auto iter = m_BroadcastMap.find(broadcastIndex); + if (m_BroadcastMap.end() == iter) + { + // insert as braodcast-only marked telegram + INFO_LOG(m_logger) << "Insert telId=" << a_broadcastOnlyTelegram->getTelID() << " as broadcastonly telegram with BC=" << broadcastIndex; + a_broadcastOnlyTelegram->setBroadcastOnly(); + m_BroadcastMap.insert(std::make_pair(broadcastIndex, a_broadcastOnlyTelegram)); + } + else + { + // attach to an already existing broadcast-telegram + INFO_LOG(m_logger) << "Add telId=" << a_broadcastOnlyTelegram->getTelID() + << " as broadcastonly telegram to telegramm with BC=" << iter->second->getBroadcastIndex(); + iter->second->setBroadcastonlyTelegram(a_broadcastOnlyTelegram); + } + } + + + // --------------------------------------------------------------- + // Detaches an existing radio-telegram and adds it to the + // broadcast-map + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::detachTelegram(const std::shared_ptr &a_radioTelegram) + { + auto broadcastOnlyTelegram = a_radioTelegram->getBroadcastonlyTelegram(); + if (broadcastOnlyTelegram) + { + uint16_t broadcastIndex = a_radioTelegram->getBroadcastIndex(); + // do some checks + INFO_LOG(m_logger) << "detach bconly-telegram : telId=" << a_radioTelegram->getTelID() << " BC=" << broadcastIndex; + if (broadcastOnlyTelegram->getBroadcastIndex() != broadcastIndex) + ERROR_LOG(m_logger) << "Internal error: BC=" << broadcastOnlyTelegram->getBroadcastIndex() << " of attached telegram is not equal BC=" << broadcastIndex; + auto iter = m_BroadcastMap.find(broadcastIndex); + if (iter != m_BroadcastMap.end()) + ERROR_LOG(m_logger) << "Internal error: m_BroadcastMap-entry with BC=" << broadcastIndex << " must not exists"; + else + { + INFO_LOG(m_logger) << "Insert broadcast-only BC=" << broadcastOnlyTelegram->getBroadcastIndex(); + broadcastOnlyTelegram->setBroadcastOnly(); + m_BroadcastMap.insert(std::make_pair(broadcastIndex, broadcastOnlyTelegram)); + } + a_radioTelegram->setBroadcastonlyTelegram(nullptr); + } + } + + + // --------------------------------------------------------------- + // Removes all Nop out of broadcast-list and numerates the + // broadcast-index of kept broadcast-telegrams new. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::handleOverrunOfBroadcastCounter(const bool a_doRestore) + { + WARNING_LOG(m_logger) << "Broadcast-counter reaches maximum => reduce broadcast-list and increment reset-counter"; + + // first we must wait until all data are stored in DB, otherwise we will loose + // the broadcast-telegrams, which were sent the 1st time, but not yet stored permanent + if (!a_doRestore) + { + m_DbThread->waitUntilDbWritten(); + getAllFinishedBroadcastsFromDb(); + } + + // reduce the broadcast-list + uint16_t newBroadcastCounter = 0; + std::map> newBroadcastMap; + auto iter = m_BroadcastMap.begin(); + while (iter != m_BroadcastMap.end()) + { + auto radioTelegram = iter->second; + if (radioTelegram->isBroadcastOnly()) + { + // delete all broadcast-only telegrams + ++iter; // removeFromAllMaps() will destroy the iterator => we increment it before removing + removeFromAllMaps(radioTelegram); + } + else + { + radioTelegram->setBroadcastIndex(++newBroadcastCounter); + auto broadcastOnlyTelegram = radioTelegram->getBroadcastonlyTelegram(); + if (broadcastOnlyTelegram) + { + radioTelegram->setBroadcastonlyTelegram(nullptr); + ++iter; // removeFromAllMaps() will destroy the iterator => we increment it before removing + removeFromAllMaps(broadcastOnlyTelegram); + } + else + { + // all pending normal broadcast should no longer be sent as normal broadcasts, because all TNEs + // will anyway ask for nachforderung + bool wasLast; + if (radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), wasLast, false)) + { + do + { + radioTelegram->mustBeSentAsBroadcast(std::numeric_limits::max(), wasLast, true); + } while (!wasLast); + } + ++iter; + } + INFO_LOG(m_logger) << "New BC-index for broadcast-telegram with telId=" << radioTelegram->getTelID() << " BC=" << newBroadcastCounter; + newBroadcastMap.insert(std::make_pair(newBroadcastCounter, radioTelegram)); + } + } + m_BroadcastMap.clear(); + m_BroadcastMap = newBroadcastMap; + + // stop actual nachforderungen and increment reset-counter + cleanAndInit(false); + if (!a_doRestore) + m_DbThread->setResetCounter(m_DbThread->getResetCounter() + 1); + + WARNING_LOG(m_logger) << "New broadcast-counter=" << newBroadcastCounter << " new reset-counter=" << (int)m_DbThread->getResetCounter(); + m_BroadcastIndex = newBroadcastCounter; + } + + + // --------------------------------------------------------------- + // Restores data after crash for seamless proceeding of work. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::restoreAfterCrash() + { + getAllFinishedBroadcastsFromDb(true); + } + + + // --------------------------------------------------------------- + // dumps important values, only for debugging + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::dump() + { + // dump the broadcast-list + for (const auto &it : m_BroadcastMap) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_BroadcastMap, "); + + for (const auto &it : m_WirkfeldTelegramMapByKennung) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_WirkfeldTelegramMapByKennung, "); + + for (const auto &it : m_WirkfeldTelegramMapByTime) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_WirkfeldTelegramMapByTime, "); + + for (const auto &it : m_FunktionsraumTelegramMap) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_FunktionsraumTelegramMap, "); + + for (const auto &it : m_TechnikFunktionsraumTelegramMap) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_TechnikFunktionsraumTelegramMap, "); + + for (const auto &it : m_LastTelegramMap) + dumpTelegram(m_loggerBcRequest, it.first, it.second.get(), "m_LastTelegramMap, "); + } + + + // --------------------------------------------------------------- + // Increments the tick-counter of broadcast-manager and + // informs the broadcast-manager about the traffic-load. + // --------------------------------------------------------------- + void PrtCnvBroadcastMgr::incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad) + { + if (e_ST_COLLECT == m_State) + ++m_TickCounter; + m_IsFullLoad = a_isFullLoad; + if (a_isHighLoad) + m_ActClaimWindow = m_HighLoadFactor * m_ClaimWindow; + else + m_ActClaimWindow = m_ClaimWindow; + } + + // --------------------------------------------------------------- + // Checks if the given id is in m_deactivatedAesArea2bcIndex + // --------------------------------------------------------------- + bool PrtCnvBroadcastMgr::isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const + { + INFO_LOG(m_logger) << "Checking deactivation for Id " << effectsimulationId; + return m_deactivatedAesArea2bcIndex.contains(effectsimulationId); + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.hpp index bf97f357b..d8f7503b5 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvBroadcastMgr.hpp @@ -29,7 +29,7 @@ namespace N_CoPrtCnv { -class CoPrtCnvRadioTelegram; + class CoPrtCnvRadioTelegram; } #define MAX_BROADCAST_INDEX 65535 @@ -37,9 +37,9 @@ class CoPrtCnvRadioTelegram; namespace PrtCnv { -class PrtCnvDbThread; + class PrtCnvDbThread; -/** + /** * This class is responsible for handling all the broadcast stuff. This includes: * - sending the broadcast 3 times * - sending Broadcast-Nachforderungen to TNE @@ -49,45 +49,44 @@ class PrtCnvDbThread; * @version 1.0 * @updated 30-Apr-2010 11:21:05 */ -class PrtCnvBroadcastMgr final : public QObject -{ - Q_OBJECT -public: - - /** + class PrtCnvBroadcastMgr final : public QObject + { + Q_OBJECT + public: + /** * The different states the broadcast-manager can be. * @author wia * @version 1.0 * @updated 30-Apr-2010 11:21:05 */ - enum E_State - { - e_ST_UNDEFINED, - e_ST_COLLECT, - e_ST_SEND_NACHFORDERUNG - }; + enum E_State + { + e_ST_UNDEFINED, + e_ST_COLLECT, + e_ST_SEND_NACHFORDERUNG + }; - PrtCnvBroadcastMgr(); + PrtCnvBroadcastMgr(); - /** + /** * returns true when the telegram should be sent to central * * @param a_radioTelegram */ - bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram); + bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram); - /** + /** * Creates all subcomponents */ - int32_t create(NGL::Settings *settings); + int32_t create(NGL::Settings *settings); - /** + /** * Initializes the variables. */ - int32_t init(); + int32_t init(); - /** + /** * returns the next normal broadcast to send. * a_doDelete is true, when the caller has to delete the telegram when no longer * using it. @@ -97,62 +96,61 @@ public: * @param a_actualTime * @param a_doDelete true if telegram must be deleted after using it */ - std::shared_ptr getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex, - const time_t a_currentTime); + std::shared_ptr getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex, const time_t a_currentTime); - /** + /** * sets the DbThread used for get the stored broadcast-telegrams * * @param a_dbThread */ - void setDbThread(PrtCnvDbThread *a_dbThread); + void setDbThread(PrtCnvDbThread *a_dbThread); - /** + /** * Initializes the broadcast-manager. If a_deleteTelegrams is true, all stored * telegrams and maps will be deleted. * * @param a_deleteTelegrams */ - void cleanAndInit(const bool a_deleteTelegrams); + void cleanAndInit(const bool a_deleteTelegrams); - /** + /** * Removes all Nop out of broadcast-list and numerates the broadcast-index of kept * broadcast-telegrams new. * * @param a_doRestore */ - void handleOverrunOfBroadcastCounter(const bool a_doRestore = false); + void handleOverrunOfBroadcastCounter(const bool a_doRestore = false); - /** + /** * returns the next broadcast to send for nachforderungen */ - std::shared_ptr getNextNachforderungTelegramToSend(); + std::shared_ptr getNextNachforderungTelegramToSend(); - /** + /** * dumps important values, only for debugging */ - void dump(); + void dump(); - /** + /** * Restores data after crash for seamless proceeding of work. */ - void restoreAfterCrash(); + void restoreAfterCrash(); - /** + /** * Returns the actual broadcast-index for normal broadcasts. */ - uint16_t getBroadcastIndex() const; + uint16_t getBroadcastIndex() const; - /** + /** * Returns the broadcastindex for the next broadcast */ - uint16_t getNextBroadcastIndex(); + uint16_t getNextBroadcastIndex(); - /** + /** * Adds the telegram a_broadcastOnlyTelegram (which must have set already the * broadcast-index) to the broadcast-map. The telegram will be attached to an * already existing broadcast-telegram with same broadcast-index in the map, @@ -162,152 +160,156 @@ public: * * @param a_broadcastOnlyTelegram */ - void addBroadcastOnlyTelegramToMap(const std::shared_ptr &a_broadcastOnlyTelegram); + void addBroadcastOnlyTelegramToMap(const std::shared_ptr &a_broadcastOnlyTelegram); - /** + /** * Increments the tick-counter of broadcast-manager and informs the broadcast- * manager about the traffic-load. * * @param a_isHighLoad * @param a_isFullLoad */ - void incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad); + void incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad); - /** + /** * Checks if the given id is in m_deactivatedAesMine2bcIndex/m_deactivatedDusMine2bcIndex/m_deactivatedFuncAreaMine2bcIndex * * @brief isEffectSimulationIdDeactivated * @param effectsimulationId * @return */ - bool isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const; + bool isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const; - /** + /** * Adds the TNE to the nachforderungs-list * * @param a_radioTelegram */ - void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter); + void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter); -protected: - struct EquipNoBcIndex - { - int equipNo = 0; - int bcIndex = 0; + protected: + struct EquipNoBcIndex + { + int equipNo = 0; + int bcIndex = 0; - EquipNoBcIndex() = default; - EquipNoBcIndex(int e, int b) : equipNo(e), bcIndex(b) {} - }; - /** + EquipNoBcIndex() = default; + EquipNoBcIndex(int e, int b) + : equipNo(e) + , bcIndex(b) + { + } + }; + /** * Map of TNE, that sent a NachforderungBroadcast-Telegram. * Key: identity of TNE; Value: broadcast-counter */ - std::vector m_claimerArray; - /** + std::vector m_claimerArray; + /** * Time (in SendGap-ticks) spent for collection NachforderungeBroadcast, before * sending broadcasts begins * This value will be used for normal load. */ - uint16_t m_ClaimWindow; - /** + uint16_t m_ClaimWindow; + /** * the factor for widening claim-window before sending broadcasts when we have * high load traffic */ - uint16_t m_HighLoadFactor; - /** + uint16_t m_HighLoadFactor; + /** * the number of TPUs needed for sending the broadcasts as broadcast instead * directed */ - uint16_t m_BroadcastLimit; - /** + uint16_t m_BroadcastLimit; + /** * Used to get configuration-parameter. */ - NGL::Settings *m_Config; - /** + NGL::Settings *m_Config; + /** * Actual time (in SendGap-ticks) spent for collection NachforderungeBroadcast, * before sending broadcasts begins. This value changes depending on downlink-load. */ - uint16_t m_ActClaimWindow; - /** + uint16_t m_ActClaimWindow; + /** * The state of broadcast-manager. */ - PrtCnvBroadcastMgr::E_State m_State; - uint16_t m_TickCounter; - /** + PrtCnvBroadcastMgr::E_State m_State; + uint16_t m_TickCounter; + /** * The actual broadcast-index for sending nachforderungen */ - PrtCnvDbThread *m_DbThread; + PrtCnvDbThread *m_DbThread; - /** + /** * sorted by broadcast-index */ - std::map> m_BroadcastMap; + std::map> m_BroadcastMap; - std::vector> m_broadcastTelegamsToSend; + std::vector> m_broadcastTelegamsToSend; - /** + /** * Contains all telegrams which must only be stored once for nachforderungen */ - std::map> m_LastTelegramMap; + std::map> m_LastTelegramMap; - /** + /** * Contains all wirkfeld-telegrams which must be stored for nachforderungen * ordered by wirkfeldkennung. */ - std::multimap> m_WirkfeldTelegramMapByKennung; + std::multimap> m_WirkfeldTelegramMapByKennung; - /** + /** * Contains all wirkfeld-telegrams which must be stored for nachforderungen * ordered by expiration-time. */ - std::multimap> m_WirkfeldTelegramMapByTime; + std::multimap> m_WirkfeldTelegramMapByTime; - /** + /** * Contains all funktionsraum-telegrams which must be stored for nachforderungen * ordered by funktionsraumkennung. */ - std::map> m_FunktionsraumTelegramMap; + std::map> m_FunktionsraumTelegramMap; - /** + /** * Contains all technik-funktionsraum-telegrams which must be stored for nachforderungen * ordered by funktionsraumkennung. */ - std::map> m_TechnikFunktionsraumTelegramMap; + std::map> m_TechnikFunktionsraumTelegramMap; - /** + /** * The actual broadcast-index for normal broadcast */ - uint16_t m_BroadcastIndex; + uint16_t m_BroadcastIndex; - /** + /** * True if send-traffic is on full-load => no nachforderungen will be sent */ - bool m_IsFullLoad; - /** + bool m_IsFullLoad; + /** * The highest broadcast-index of 3rd time sent broadcast-telegram (for optimize * by time) */ - uint16_t m_FinishedBroadcastIndex; - /** + uint16_t m_FinishedBroadcastIndex; + /** * The broadcast-index of the 1st broadcast-telegram which has been sent 1 time * only (for optimize by time) */ - uint16_t m_FirstBroadcastIndexOfBc1; + uint16_t m_FirstBroadcastIndexOfBc1; - /** + /** * adds the radio-telegram to the broadcast-map, or generates the sammeltelegramme * * @param a_radioTelegram */ - void addToBroadcastMap(const std::shared_ptr &a_radioTelegram); + void addToBroadcastMap(const std::shared_ptr &a_radioTelegram); - /** + /** * returns the Nachforderungs-telegram with this broadcast-index from the * broadcast-map with sammeltelegrams. If the telegram with a_broadcastIndex does * not exist, a NOP-telegram will be returned, which must be consumed immediately @@ -319,19 +321,18 @@ protected: * * @param a_broadcastIndex */ - std::shared_ptr getNachforderungsTelegram(int curBcIndex, int startBcIndex, int &nextBcIndex); + std::shared_ptr getNachforderungsTelegram(int curBcIndex, int startBcIndex, int &nextBcIndex); - /** + /** * searches the kennung within sammeltelegram. * returns -1 when kennung not found * * @param a_sammelTelegram * @param a_kennung */ - int getSammeltelegramIndex(const std::shared_ptr &a_sammelTelegram, - const uint16_t a_kennung) const; + int getSammeltelegramIndex(const std::shared_ptr &a_sammelTelegram, const uint16_t a_kennung) const; - /** + /** * Moves a_radioTelegram to a_newBroadcastIndex in broadcast-map. * If a_radioTelegram has an attached broadcast-only-telegram, the broadcastOnly- * telegram will be detached and kept on the old broadcast-index position. @@ -342,11 +343,11 @@ protected: * @param a_newBroadcastIndex The new broadcast-index * @param a_attachTelegram The telegram to be attached */ - void moveTelegramInBroadcastMap(const std::shared_ptr &a_radioTelegram, - const uint16_t a_newBroadcastIndex, - const std::shared_ptr &a_attachTelegram = {}); + void moveTelegramInBroadcastMap(const std::shared_ptr &a_radioTelegram, + const uint16_t a_newBroadcastIndex, + const std::shared_ptr &a_attachTelegram = {}); - /** + /** * Removes the telegram a_radioTelegram from the broadcast-map. If the * a_radioTelegram has an attached telegram, the attached telegram will be * detached and added to broadcast-map as broadcast-only telegram. @@ -358,47 +359,47 @@ protected: * @param a_radioTelegram * @param a_doDeleteTelegram */ - void removeFromBroadcastMap(const std::shared_ptr &a_radioTelegram); - void removeFromBroadcastMapFunc(const std::function &)> &pred); - void removeDusMineDeactivationFromBroadcastMap(int dusMineId); + void removeFromBroadcastMap(const std::shared_ptr &a_radioTelegram); + void removeFromBroadcastMapFunc(const std::function &)> &pred); + void removeDusMineDeactivationFromBroadcastMap(int dusMineId); - std::shared_ptr createAccumulationTelegram(int curBcIndex, - int startBcIndex, - gef_telegramm_id_et telId, - const QMap &bcIndex2Type, - int maxIdsPerTelegram, - int sizeOfSumField) const; + std::shared_ptr createAccumulationTelegram(int curBcIndex, + int startBcIndex, + gef_telegramm_id_et telId, + const QMap &bcIndex2Type, + int maxIdsPerTelegram, + int sizeOfSumField) const; - bool removeFromDeactivatedAesArea(int aesAreaId); - bool addToDeactivatedAesArea(int aesAreaId, int bcIndex); - // QHash - QHash m_deactivatedAesArea2bcIndex; - // QMap, keep sorted! - QMap m_deactivatedBcIndex2AesArea; - std::shared_ptrcreateAccuTeleDeactivatedAesAreas(int curBcIndex, int startBcIndex) const; + bool removeFromDeactivatedAesArea(int aesAreaId); + bool addToDeactivatedAesArea(int aesAreaId, int bcIndex); + // QHash + QHash m_deactivatedAesArea2bcIndex; + // QMap, keep sorted! + QMap m_deactivatedBcIndex2AesArea; + std::shared_ptr createAccuTeleDeactivatedAesAreas(int curBcIndex, int startBcIndex) const; - bool removeFromDeactivatedFuncArea(int aesAreaId); - bool addToDeactivatedFuncArea(int aesAreaId, int bcIndex); - // QHash - QHash m_deactivatedFuncArea2bcIndex; - // QHash, keep sorted! - QMap m_deactivatedBcIndex2FuncArea; - std::shared_ptrcreateAccuTeleDeactivatedFuncAreas(int curBcIndex, int startBcIndex) const; + bool removeFromDeactivatedFuncArea(int aesAreaId); + bool addToDeactivatedFuncArea(int aesAreaId, int bcIndex); + // QHash + QHash m_deactivatedFuncArea2bcIndex; + // QHash, keep sorted! + QMap m_deactivatedBcIndex2FuncArea; + std::shared_ptr createAccuTeleDeactivatedFuncAreas(int curBcIndex, int startBcIndex) const; - bool removeFromDeactivatedDusMine(int dusMineId); - bool addToDeactivatedDusMine(int dusMineId, int bcIndex); - // QHash - QHash m_deactivatedDusMine2bcIndex; - // QHash, keep sorted! - QMap m_deactivatedBcIndex2DusMine; - std::shared_ptr createAccuTeleDeactivatedDusMines(int curBcIndex, int startBcIndex) const; + bool removeFromDeactivatedDusMine(int dusMineId); + bool addToDeactivatedDusMine(int dusMineId, int bcIndex); + // QHash + QHash m_deactivatedDusMine2bcIndex; + // QHash, keep sorted! + QMap m_deactivatedBcIndex2DusMine; + std::shared_ptr createAccuTeleDeactivatedDusMines(int curBcIndex, int startBcIndex) const; - bool removeFromActivatedDusMine(int dusMineId); - void addToActivatedDusMine(int dusMineId); - QSet m_activatedDusMines; - std::shared_ptr createAccuTeleActivatedDusMines(int curBcIndex); + bool removeFromActivatedDusMine(int dusMineId); + void addToActivatedDusMine(int dusMineId); + QSet m_activatedDusMines; + std::shared_ptr createAccuTeleActivatedDusMines(int curBcIndex); - /** + /** * Removes the kennung from the sammeltelegram. * If the sammeltelegram is empty after remove of kennung, it will be taken out of * broadcast-map (but not deleted) and a_sammelTelRemoved will be true. A attached @@ -412,40 +413,40 @@ protected: * @param a_anzahlSize * @param a_sammelTelRemoved */ - bool removeFromSammeltelegram(const std::shared_ptr &a_sammelTelegram, - const uint16_t a_kennung, - const uint16_t a_anzahlPos, - const uint8_t a_anzahlSize, - bool &a_sammelTelRemoved); + bool removeFromSammeltelegram(const std::shared_ptr &a_sammelTelegram, + const uint16_t a_kennung, + const uint16_t a_anzahlPos, + const uint8_t a_anzahlSize, + bool &a_sammelTelRemoved); - /** + /** * used for telegrams that must only exists once in BC-list * * @param a_newRadioTelegram */ - void replaceLastTelegramAndAddAtEnd(const std::shared_ptr &a_newRadioTelegram); + void replaceLastTelegramAndAddAtEnd(const std::shared_ptr &a_newRadioTelegram); - /** + /** * Small helper to dump all wf-ids from a sammeltelegramm */ - std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram *sammelTelegram); + std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram *sammelTelegram); - /** + /** * Gets the braodcast-telegrams from Db, which were sent 1st time and adds them to * the maps. Expired telegrams will be removed. * * @param a_doRestore */ - void getAllFinishedBroadcastsFromDb(const bool a_doRestore = false); + void getAllFinishedBroadcastsFromDb(const bool a_doRestore = false); - /** + /** * Takes expired wirkfeld-telegrams out of maps. */ - void removeExpiredTelegrams(); + void removeExpiredTelegrams(); - /** + /** * Removes the wirkfeld-telegrams with this kennung from the by time and by * kennung maps. * Replace this telegrams with Nop in BC-list. @@ -453,9 +454,9 @@ protected: * * @param a_kennung */ - void removeWirkfeldTelegrams(const uint16_t a_kennung); + void removeWirkfeldTelegrams(const uint16_t a_kennung); - /** + /** * adds the wirkfeld-telegram to the by time and by kennung maps * * @param a_radioTelegram @@ -463,11 +464,12 @@ protected: * @param a_telId * @param a_minenKennung */ - void addWirkfeldTelegram(const std::shared_ptr &a_radioTelegram, - const uint16_t a_wirkfeldKennung, const gef_telegramm_id_et a_telId = GEF_BESTAETIGUNG, - const uint16_t a_minenKennung = 0); + void addWirkfeldTelegram(const std::shared_ptr &a_radioTelegram, + const uint16_t a_wirkfeldKennung, + const gef_telegramm_id_et a_telId = GEF_BESTAETIGUNG, + const uint16_t a_minenKennung = 0); - /** + /** * Deactivates the mine in the corresponding "WirkfeldstatusMinensperre"-telegram * and moves the "WirkfeldstatusMinensperre"-telegram to the position of * "DeactiviereEinzelmine"-telegram. @@ -478,16 +480,16 @@ protected: * @param a_minenKennung * @param a_broadcastIndex */ - bool deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex); + bool deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex); - /** + /** * Returns a NOP-telegramm filled with the desired values. * * @param a_from * @param a_to */ - std::shared_ptr getNopTelegram(const uint16_t a_from, const uint16_t a_to); - /** + std::shared_ptr getNopTelegram(const uint16_t a_from, const uint16_t a_to); + /** * Removes the telegram a_radioTelegram from all maps (broadcast-, wirkfeld-, * funktionsraum- and lastTelegram-map). * If the telegram is a attached BC-only-telegram, it will be detached. @@ -497,16 +499,16 @@ protected: * @param a_radioTelegram * @param a_doDeleteTelegram */ - void removeFromAllMaps(const std::shared_ptr &a_radioTelegram); + void removeFromAllMaps(const std::shared_ptr &a_radioTelegram); - /** + /** * Detaches an existing radio-telegram and adds it to the broadcast-map * * @param a_radioTelegram The telegram which could contain an attached telegram */ - void detachTelegram(const std::shared_ptr &a_radioTelegram); + void detachTelegram(const std::shared_ptr &a_radioTelegram); - /** + /** * Removes the telegram with a_funktionsraumKennung from funktionsraum-map and * from the broadcast-map. * If the telegram is a attached BC-only-telegram, it will be detached. @@ -516,10 +518,10 @@ protected: * * @param a_funktionsraumKennung */ - void removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung); - void removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung); + void removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung); + void removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung); - /** + /** * Removes the telegram where wirkfeldTelegramMapByKennungIterator points to from * wirkfeld-maps and from the broadcast-map. * If the telegram is a attached BC-only-telegram, it will be detached. @@ -529,43 +531,44 @@ protected: * * @param a_wirkfeldTelegramMapByKennungIterator */ - void removeFromWirkfeldAndBroadcastMaps(const std::multimap>::iterator &a_wirkfeldTelegramMapByKennungIterator); + void removeFromWirkfeldAndBroadcastMaps( + const std::multimap>::iterator &a_wirkfeldTelegramMapByKennungIterator); - /** + /** * Handles the REAKTIVIERUNG_DUS_MINE-telegram for normal-broadcasts and * nachforderungen. * * @param a_radioTelegram The GEF_REAKTIVIERUNG_DUS_MINE-telegram */ - void reactivateDusMine(const std::shared_ptr &a_radioTelegram); + void reactivateDusMine(const std::shared_ptr &a_radioTelegram); - /** + /** * Handles the DEAKTIVIERUNG_EINZELMINE-telegram for normal-broadcasts and * nachforderungen. This includes deactivation of mines from minen-sperre and DUS- * mines. * * @param a_radioTelegram The GEF_REAKTIVIERUNG_DUS_MINE-telegram */ - void deactivateSingleMine(const std::shared_ptr &a_radioTelegram); + void deactivateSingleMine(const std::shared_ptr &a_radioTelegram); - /** + /** * Prepares values for start sending nachforderungen */ - void prepareForSendNachforderungen(); + void prepareForSendNachforderungen(); - /** + /** * returns the next nachforderung to send and prepares collecting window if no * more nachforderungen are to be sent */ - std::shared_ptr evaluateNextNachforderungToSend(); + std::shared_ptr evaluateNextNachforderungToSend(); -Q_SIGNALS: - void areaEffectSimulationActivated(int wirkfeldKennung); - void areaEffectSimulationDeactivated(int wirkfeldKennung); + Q_SIGNALS: + void areaEffectSimulationActivated(int wirkfeldKennung); + void areaEffectSimulationDeactivated(int wirkfeldKennung); -private: - NGL::INGLLogger &m_logger; - NGL::INGLLogger &m_loggerBcRequest; -}; + private: + NGL::INGLLogger &m_logger; + NGL::INGLLogger &m_loggerBcRequest; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.cpp index df356fc87..73c1caddb 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.cpp @@ -35,465 +35,460 @@ namespace PrtCnv { -// --------------------------------------------------------------- -PrtCnvCentralThread::PrtCnvCentralThread(PrtCnv::PrtCnvThreadStarter* a_parent) - : PrtCnvThread(a_parent, "PrtCnvCentralThread") - , m_webSocket(nullptr) - , m_SendCounter(0) - , m_RadioThread(nullptr) - , m_RadioStopped(false) - , m_CentralStopped(false) - , m_LastSendCounter(0) - , m_VirtualTeilnehmerId(0) - , m_maxEqID(50000) - , m_aliveTimer(nullptr) - , m_sendAckTimer(nullptr) - , m_reconnectTimer(nullptr) - , m_DbThread(nullptr) - , m_LogThread(nullptr) - , m_InjectionThread(nullptr) - , m_ReceiveCounter(0) - , m_ReceiveAckCounter(0) - , m_State(PrtCnvSocketThread::e_INITIAL) - , m_bDirectConnection(false) - , m_bRadioThreadInitDone(false) -{ - m_Name = QStringLiteral("Central"); -} - -PrtCnvCentralThread::~PrtCnvCentralThread() -{ - destroy(); -} - -// --------------------------------------------------------------- -// Creates all subcomponents and connects signals to slots -// --------------------------------------------------------------- -int32_t PrtCnvCentralThread::create(NGL::Settings *settings) -{ - PrtCnvThread::create(settings); - - INFO_LOG(m_logger) << "Create"; - - m_RadioThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Radio)); - m_DbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); - m_LogThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Log)); - m_InjectionThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Injection)); - connect(m_DbThread, &PrtCnvDbThread::playerLicencedChanged, - this, &PrtCnvCentralThread::onPlayerLicencedChanged, Qt::QueuedConnection); - connect(this, &PrtCnvCentralThread::checkSendToCentral, this, &PrtCnvCentralThread::checkSend, Qt::QueuedConnection); - connect(this, &PrtCnvCentralThread::checkSendToRadio, m_RadioThread, &PrtCnvRadioThread::checkSend, Qt::QueuedConnection); - connect(this, &PrtCnvCentralThread::stopRadio, m_RadioThread, &PrtCnvRadioThread::doStop, Qt::QueuedConnection); - connect(this, &PrtCnvCentralThread::cleanRadio, m_RadioThread, &PrtCnvRadioThread::doClean, Qt::QueuedConnection); - connect(this, &PrtCnvCentralThread::startRadio, m_RadioThread, &PrtCnvRadioThread::doStart, Qt::QueuedConnection); - connect(m_RadioThread, &PrtCnvRadioThread::initDone, - this, &PrtCnvCentralThread::onRadioThreadInitDone); - connect(m_RadioThread, &PrtCnvRadioThread::areaEffectSimulationActivated, - this, &PrtCnvCentralThread::onAreaEffectSimulationActivated, Qt::QueuedConnection); - connect(m_RadioThread, &PrtCnvRadioThread::areaEffectSimulationDeactivated, - this, &PrtCnvCentralThread::onAreaEffectSimulationDeactivated, Qt::QueuedConnection); - - auto mainApp = m_Parent->getMainApp(); - connect(this, &PrtCnvCentralThread::directTextMessage, - mainApp, &PrtCnvApplication::textMessageFromPrtCnvToCentral); - connect(mainApp, &PrtCnvApplication::textMessageFromCentralToPrtCnv, - this, &PrtCnvCentralThread::onDirectTextMessageReceived); - - m_aliveTimer = new QTimer(this); - connect(m_aliveTimer, &QTimer::timeout, this, &PrtCnvCentralThread::timeoutAliveAndConnection); - - m_sendAckTimer = new QTimer(this); - connect(m_sendAckTimer, &QTimer::timeout, this, &PrtCnvCentralThread::timeoutTick); - - const int disconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000); - m_reconnectTimer = new QTimer(this); - m_reconnectTimer->setInterval(disconnectTimeout); - m_reconnectTimer->setSingleShot(true); - connect(m_reconnectTimer, &QTimer::timeout, this, &PrtCnvCentralThread::connectSocket); - - return 0; -} - - -// --------------------------------------------------------------- -// Deallocates subcomponents. -// --------------------------------------------------------------- -int32_t PrtCnvCentralThread::destroy() -{ - INFO_LOG(m_logger) << "Destroy"; - PrtCnvThread::destroy(); - delete m_webSocket; m_webSocket = nullptr; - delete m_aliveTimer; m_aliveTimer = nullptr; - delete m_sendAckTimer; m_sendAckTimer = nullptr; - delete m_reconnectTimer; m_reconnectTimer = nullptr; - return 0; -} - -// --------------------------------------------------------------- -// Initializes the variables. -// --------------------------------------------------------------- -int32_t PrtCnvCentralThread::init() -{ - INFO_LOG(m_logger) << "Init"; - PrtCnvThread::init(); - m_CentralStopped = false; - m_RadioStopped = false; - - m_aliveTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000)); - m_sendAckTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("AckTimeout"), 900)); - - m_VirtualTeilnehmerId = m_Config->getInteger(QStringLiteral("Common"), QStringLiteral("VirtualIdPrtCnv"), 90); - m_maxEqID = m_Config->getInteger(QStringLiteral("Common"), QStringLiteral("MaxEqID"), 50000); //or max unsigned short 65535 - - return 0; -} - -int32_t PrtCnvCentralThread::deinit() -{ - INFO_LOG(m_logger) << "Deinit"; - PrtCnvThread::deinit(); - return 0; -} - -// --------------------------------------------------------------- -// Starts the thread and connects to TCP-server -// --------------------------------------------------------------- -int32_t PrtCnvCentralThread::start() -{ - INFO_LOG(m_logger) << "Start"; - PrtCnvThread::start(); - if (m_DbThread->mustProceedCleanup()) + // --------------------------------------------------------------- + PrtCnvCentralThread::PrtCnvCentralThread(PrtCnv::PrtCnvThreadStarter *a_parent) + : PrtCnvThread(a_parent, "PrtCnvCentralThread") + , m_webSocket(nullptr) + , m_SendCounter(0) + , m_RadioThread(nullptr) + , m_RadioStopped(false) + , m_CentralStopped(false) + , m_LastSendCounter(0) + , m_VirtualTeilnehmerId(0) + , m_maxEqID(50000) + , m_aliveTimer(nullptr) + , m_sendAckTimer(nullptr) + , m_reconnectTimer(nullptr) + , m_DbThread(nullptr) + , m_LogThread(nullptr) + , m_InjectionThread(nullptr) + , m_ReceiveCounter(0) + , m_ReceiveAckCounter(0) + , m_State(PrtCnvSocketThread::e_INITIAL) + , m_bDirectConnection(false) + , m_bRadioThreadInitDone(false) { - INFO_LOG(m_logger) << "Proceed cleanup DB after crash..."; - m_CentralStopped = true; - emit stopRadio(); - } - else - { - connectSocket(); + m_Name = QStringLiteral("Central"); } - return 0; -} - -// --------------------------------------------------------------- -// Stops the thread -// --------------------------------------------------------------- -int32_t PrtCnvCentralThread::stop() -{ - INFO_LOG(m_logger) << "Stop"; - PrtCnvThread::stop(); - - return 0; -} - - -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvCentralThread::connected() -{ - INFO_LOG(m_logger) << "Central-Socket connected m_Socket=" << m_webSocket; - m_SendCounter = 0; // we reset this counter after every connect to 0 => next telegram to send has counter 1 (preincrement) - m_LastSendCounter = 0; - m_ReceiveCounter = 0; // send 0 until we get a telegram, we reset this counter after every connect to 0 => the next telegram from central must be 1 - m_ReceiveAckCounter = 0; - m_aliveTimer->start(); - if (m_bRadioThreadInitDone) - m_sendAckTimer->start(); - m_State = PrtCnvSocketThread::e_WORKING; - emit checkSendToCentral(); // start sending telegrams for central still in list (reconnection) -} - -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvCentralThread::disconnected() -{ - INFO_LOG(m_logger) << "disconnected m_Socket=" << m_webSocket; - // for the case central is disconnecting, we have to disconnect also, otherwise - // we could send rubish (still resisting in buffers) after a reconnection - if (PrtCnvSocketThread::e_WORKING == m_State && m_webSocket) - m_webSocket->close(); - - m_State = PrtCnvSocketThread::e_DISCONNECTING; - if (m_DoCleanup) + PrtCnvCentralThread::~PrtCnvCentralThread() { - INFO_LOG(m_logger) << "cleanup while disconnection"; - m_sendAckTimer->stop(); - m_CentralStopped = true; - if (m_RadioStopped) - cleanAndReinit(); + destroy(); } - else + + // --------------------------------------------------------------- + // Creates all subcomponents and connects signals to slots + // --------------------------------------------------------------- + int32_t PrtCnvCentralThread::create(NGL::Settings *settings) { - m_DbThread->prepareCentralTelegramsForReconnection(); - connectSocket(); + PrtCnvThread::create(settings); + + INFO_LOG(m_logger) << "Create"; + + m_RadioThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Radio)); + m_DbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); + m_LogThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Log)); + m_InjectionThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Injection)); + connect(m_DbThread, &PrtCnvDbThread::playerLicencedChanged, this, &PrtCnvCentralThread::onPlayerLicencedChanged, Qt::QueuedConnection); + connect(this, &PrtCnvCentralThread::checkSendToCentral, this, &PrtCnvCentralThread::checkSend, Qt::QueuedConnection); + connect(this, &PrtCnvCentralThread::checkSendToRadio, m_RadioThread, &PrtCnvRadioThread::checkSend, Qt::QueuedConnection); + connect(this, &PrtCnvCentralThread::stopRadio, m_RadioThread, &PrtCnvRadioThread::doStop, Qt::QueuedConnection); + connect(this, &PrtCnvCentralThread::cleanRadio, m_RadioThread, &PrtCnvRadioThread::doClean, Qt::QueuedConnection); + connect(this, &PrtCnvCentralThread::startRadio, m_RadioThread, &PrtCnvRadioThread::doStart, Qt::QueuedConnection); + connect(m_RadioThread, &PrtCnvRadioThread::initDone, this, &PrtCnvCentralThread::onRadioThreadInitDone); + connect(m_RadioThread, &PrtCnvRadioThread::areaEffectSimulationActivated, this, &PrtCnvCentralThread::onAreaEffectSimulationActivated, Qt::QueuedConnection); + connect(m_RadioThread, &PrtCnvRadioThread::areaEffectSimulationDeactivated, this, &PrtCnvCentralThread::onAreaEffectSimulationDeactivated, Qt::QueuedConnection); + + auto mainApp = m_Parent->getMainApp(); + connect(this, &PrtCnvCentralThread::directTextMessage, mainApp, &PrtCnvApplication::textMessageFromPrtCnvToCentral); + connect(mainApp, &PrtCnvApplication::textMessageFromCentralToPrtCnv, this, &PrtCnvCentralThread::onDirectTextMessageReceived); + + m_aliveTimer = new QTimer(this); + connect(m_aliveTimer, &QTimer::timeout, this, &PrtCnvCentralThread::timeoutAliveAndConnection); + + m_sendAckTimer = new QTimer(this); + connect(m_sendAckTimer, &QTimer::timeout, this, &PrtCnvCentralThread::timeoutTick); + + const int disconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000); + m_reconnectTimer = new QTimer(this); + m_reconnectTimer->setInterval(disconnectTimeout); + m_reconnectTimer->setSingleShot(true); + connect(m_reconnectTimer, &QTimer::timeout, this, &PrtCnvCentralThread::connectSocket); + + return 0; } -} -// --------------------------------------------------------------- -// Stores that radio-thread has stopped. Cleans the Db and -// reinitializes when central-thread has also stopped. -// --------------------------------------------------------------- -void PrtCnvCentralThread::radioStopped() -{ - m_RadioStopped = true; - if (m_CentralStopped) - cleanAndReinit(); -} - - -// --------------------------------------------------------------- -// Calls clean of radio-thread and Db-thread and initializes -// the variables for rework. -// --------------------------------------------------------------- -void PrtCnvCentralThread::cleanAndReinit() -{ - INFO_LOG(m_logger) << "cleanAndReinit"; - emit cleanRadio(); - // reinit mit sicherung und löschung der datenbestände - m_ReceiveAckCounter = 0; - m_DbThread->cleanAndInit(); - m_DoCleanup = false; -} - - -// --------------------------------------------------------------- -// Starts radio-thread and itself for proceeding work after -// cleaning the Db. -// --------------------------------------------------------------- -void PrtCnvCentralThread::radioCleant() -{ - if (!m_DoCleanup) + // --------------------------------------------------------------- + // Deallocates subcomponents. + // --------------------------------------------------------------- + int32_t PrtCnvCentralThread::destroy() { - m_DbThread->setMachineState(0); - m_RadioStopped = false; + INFO_LOG(m_logger) << "Destroy"; + PrtCnvThread::destroy(); + delete m_webSocket; + m_webSocket = nullptr; + delete m_aliveTimer; + m_aliveTimer = nullptr; + delete m_sendAckTimer; + m_sendAckTimer = nullptr; + delete m_reconnectTimer; + m_reconnectTimer = nullptr; + return 0; + } + + // --------------------------------------------------------------- + // Initializes the variables. + // --------------------------------------------------------------- + int32_t PrtCnvCentralThread::init() + { + INFO_LOG(m_logger) << "Init"; + PrtCnvThread::init(); m_CentralStopped = false; - emit startRadio(); - connectSocket(); + m_RadioStopped = false; + + m_aliveTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000)); + m_sendAckTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("AckTimeout"), 900)); + + m_VirtualTeilnehmerId = m_Config->getInteger(QStringLiteral("Common"), QStringLiteral("VirtualIdPrtCnv"), 90); + m_maxEqID = m_Config->getInteger(QStringLiteral("Common"), QStringLiteral("MaxEqID"), 50000); //or max unsigned short 65535 + + return 0; } - else + + int32_t PrtCnvCentralThread::deinit() { - ERROR_LOG(m_logger) << "Internal error: radioCleant, but central still cleaning up."; + INFO_LOG(m_logger) << "Deinit"; + PrtCnvThread::deinit(); + return 0; } -} -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvCentralThread::onTextMessageReceived(const QString &msg) -{ - // eat all pending readyReadyRead - if (m_DoCleanup) - return; - if (PrtCnvSocketThread::e_WORKING != m_State) - return; // do nothing when we are not in working state - onDirectTextMessageReceived(msg.toUtf8()); -} - -void PrtCnvCentralThread::onDirectTextMessageReceived(const QByteArray &baJson) -{ - try + // --------------------------------------------------------------- + // Starts the thread and connects to TCP-server + // --------------------------------------------------------------- + int32_t PrtCnvCentralThread::start() { - if (baJson.isEmpty()) - throw std::exception(); // FIXME: use own exception - const QJsonObject obj = QJsonDocument::fromJson(baJson).object(); - - const QJsonValue typeId = obj.value(QStringLiteral("typeId")); - if (!typeId.isDouble()) - throw TrainingAreaBase::TetraIcd::JsonException(obj, QStringLiteral("typeId")); - - N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(baJson, obj, static_cast(typeId.toInt())); - - m_LogThread->writeCentralTelegramLog(&telegram, false, 1); - - m_aliveTimer->start(); - - // which kind of telegram is it? - if (telegram.telegramId() == TrainingAreaBase::TetraIcd::BESTAETIGUNG) + INFO_LOG(m_logger) << "Start"; + PrtCnvThread::start(); + if (m_DbThread->mustProceedCleanup()) { - // it is an ack-telegram - handleAck(&telegram); + INFO_LOG(m_logger) << "Proceed cleanup DB after crash..."; + m_CentralStopped = true; + emit stopRadio(); } else { - DEBUG_LOG(m_logger) << "Received telegram '" << baJson << "'"; - // a payload-telegram - handleTelegram(&telegram); + connectSocket(); + } + + return 0; + } + + // --------------------------------------------------------------- + // Stops the thread + // --------------------------------------------------------------- + int32_t PrtCnvCentralThread::stop() + { + INFO_LOG(m_logger) << "Stop"; + PrtCnvThread::stop(); + + return 0; + } + + + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvCentralThread::connected() + { + INFO_LOG(m_logger) << "Central-Socket connected m_Socket=" << m_webSocket; + m_SendCounter = 0; // we reset this counter after every connect to 0 => next telegram to send has counter 1 (preincrement) + m_LastSendCounter = 0; + m_ReceiveCounter = 0; // send 0 until we get a telegram, we reset this counter after every connect to 0 => the next telegram from central must be 1 + m_ReceiveAckCounter = 0; + m_aliveTimer->start(); + if (m_bRadioThreadInitDone) + m_sendAckTimer->start(); + m_State = PrtCnvSocketThread::e_WORKING; + emit checkSendToCentral(); // start sending telegrams for central still in list (reconnection) + } + + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvCentralThread::disconnected() + { + INFO_LOG(m_logger) << "disconnected m_Socket=" << m_webSocket; + // for the case central is disconnecting, we have to disconnect also, otherwise + // we could send rubish (still resisting in buffers) after a reconnection + if (PrtCnvSocketThread::e_WORKING == m_State && m_webSocket) + m_webSocket->close(); + + m_State = PrtCnvSocketThread::e_DISCONNECTING; + if (m_DoCleanup) + { + INFO_LOG(m_logger) << "cleanup while disconnection"; + m_sendAckTimer->stop(); + m_CentralStopped = true; + if (m_RadioStopped) + cleanAndReinit(); + } + else + { + m_DbThread->prepareCentralTelegramsForReconnection(); + connectSocket(); } } - catch (const std::exception &e) + + + // --------------------------------------------------------------- + // Stores that radio-thread has stopped. Cleans the Db and + // reinitializes when central-thread has also stopped. + // --------------------------------------------------------------- + void PrtCnvCentralThread::radioStopped() { - ERROR_LOG(m_logger) << "JSon conversion error happenend. Error:" - << e.what() << ", msg: " << baJson; - // inform central about the failure - TrainingAreaBase::TetraIcd::CtaDataError tele; - tele.header.equipmentNumber = m_VirtualTeilnehmerId; - tele.header.timeStamp = time(nullptr) * 1000LL; - tele.reason = TrainingAreaBase::TetraIcd::CtaDataError::Reason::JsonDecodeFailure; - tele.originTelegramId = 0; - N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(tele); - sendTelegram(&telegram); + m_RadioStopped = true; + if (m_CentralStopped) + cleanAndReinit(); } -} -// --------------------------------------------------------------- -void PrtCnvCentralThread::stateChanged(QAbstractSocket::SocketState newState) -{ - INFO_LOG(m_logger) << "Websocket changed to state " << newState; -} -// --------------------------------------------------------------- -// Stores a telegram to be sent to radio in volatile radio- -// list and permanent in DB. -// --------------------------------------------------------------- -void PrtCnvCentralThread::handleTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - // => check with receive-counter if we lost a telegram or we get a telegram twice. - // => in this cases neither store the telegram nor send an ack (just ignore and read the next telegram) - // => the receive-counter will be hold on the last correct received telegram - DEBUG_LOG(m_logger) << "Receive Central-Telegram with telId=" << a_telegram->telegramId() - << "; rcounter=" << a_telegram->counter(); - if (checkAndUpdateReceiveCounter(a_telegram->counter())) + // --------------------------------------------------------------- + // Calls clean of radio-thread and Db-thread and initializes + // the variables for rework. + // --------------------------------------------------------------- + void PrtCnvCentralThread::cleanAndReinit() { - if (handleSpecialTelegram(a_telegram)) - { - using namespace TrainingAreaBase::TetraIcd; - if (a_telegram->telegramId() == TelegramId::DEAKTIVIERUNG_WIRKFELD) - { - const DeactivateEffectSimulation des(DeactivateEffectSimulation::fromJson(a_telegram->jsonData())); - switch (des.aesType) - { - case AreaEffectSimulationType::MineArea: - case AreaEffectSimulationType::ExplosionArea: - case AreaEffectSimulationType::ExplosionSingle: - case AreaEffectSimulationType::NContamination: - case AreaEffectSimulationType::CContamination: - case AreaEffectSimulationType::FunctionalArea: - case AreaEffectSimulationType::DusSingleMineSimulator: - if (m_deactivatedAreaEffectSimulations.contains(des.aesDdsId)) - { - INFO_LOG(m_logger) << "AES with id " << des.aesDdsId << " already deactivated - ignoring new deactivation telegram"; - return; - } - break; - case AreaEffectSimulationType::TechnicalArea: - case AreaEffectSimulationType::GasPipeDetonation: - case AreaEffectSimulationType::SpecialArea: - case AreaEffectSimulationType::Unknown: - Q_ASSERT(false); // should not happen but who knows - break; - case AreaEffectSimulationType::BeStillWarning: - case AreaEffectSimulationType::DangerZoneExplosion: - case AreaEffectSimulationType::AirSupport: - break; - } - } - else if (a_telegram->telegramId() == TelegramId::WIRKFELD_STATUS_MINENSPERRE) - { - const MineAreaSingleMineState msms(MineAreaSingleMineState::fromJson(a_telegram->jsonData())); - QSet &oldTriggeredMines = m_alreadyTriggeredMines[msms.aesDdsId]; - QSet newTriggeredMines; - newTriggeredMines.reserve(oldTriggeredMines.size() + 5); - bool bSomethingChanged = false; - for (int i = 0; i < msms.mineCount; ++i) - { - if (!LtsUtils::BitArray::testBit(msms.mineState, i)) // 0 = triggered - { - INFO_LOG(m_logger) << "Testing bit " << i << " ... not set = triggered"; - if (!oldTriggeredMines.contains(i)) - { - INFO_LOG(m_logger) << "not in old one"; - bSomethingChanged = true; - } - newTriggeredMines.insert(i); - } - } - if (!bSomethingChanged) - bSomethingChanged = newTriggeredMines.size() != oldTriggeredMines.size(); - if (!bSomethingChanged) - { - INFO_LOG(m_logger) << "MineState telegram contains no new informations - skipping " << msms.aesDdsId; - return; - } - INFO_LOG(m_logger) << "MineState telegram contains new informations... " << msms.aesDdsId; - oldTriggeredMines = newTriggeredMines; // update in m_alreadyTriggeredMines[] - } + INFO_LOG(m_logger) << "cleanAndReinit"; + emit cleanRadio(); + // reinit mit sicherung und löschung der datenbestände + m_ReceiveAckCounter = 0; + m_DbThread->cleanAndInit(); + m_DoCleanup = false; + } - std::shared_ptr - radioTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(a_telegram)); - if (radioTelegram) + + // --------------------------------------------------------------- + // Starts radio-thread and itself for proceeding work after + // cleaning the Db. + // --------------------------------------------------------------- + void PrtCnvCentralThread::radioCleant() + { + if (!m_DoCleanup) + { + m_DbThread->setMachineState(0); + m_RadioStopped = false; + m_CentralStopped = false; + emit startRadio(); + connectSocket(); + } + else + { + ERROR_LOG(m_logger) << "Internal error: radioCleant, but central still cleaning up."; + } + } + + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvCentralThread::onTextMessageReceived(const QString &msg) + { + // eat all pending readyReadyRead + if (m_DoCleanup) + return; + if (PrtCnvSocketThread::e_WORKING != m_State) + return; // do nothing when we are not in working state + onDirectTextMessageReceived(msg.toUtf8()); + } + + void PrtCnvCentralThread::onDirectTextMessageReceived(const QByteArray &baJson) + { + try + { + if (baJson.isEmpty()) + throw std::exception(); // FIXME: use own exception + const QJsonObject obj = QJsonDocument::fromJson(baJson).object(); + + const QJsonValue typeId = obj.value(QStringLiteral("typeId")); + if (!typeId.isDouble()) + throw TrainingAreaBase::TetraIcd::JsonException(obj, QStringLiteral("typeId")); + + N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(baJson, obj, static_cast(typeId.toInt())); + + m_LogThread->writeCentralTelegramLog(&telegram, false, 1); + + m_aliveTimer->start(); + + // which kind of telegram is it? + if (telegram.telegramId() == TrainingAreaBase::TetraIcd::BESTAETIGUNG) { - if (radioTelegram->getIdentity() <= m_maxEqID) { - // save data in persistent database - m_DbThread->storeRadioTelegram(radioTelegram, a_telegram->counter()); - } else { - WARNING_LOG(m_logger) << "Central telegram with telId=" << a_telegram->telegramId() - << " has invalid identity:" << radioTelegram->getIdentity(); - } + // it is an ack-telegram + handleAck(&telegram); } else { - m_DbThread->centralCounterReadyForAck(a_telegram->counter()); - WARNING_LOG(m_logger) << "Central telegram with telId=" << a_telegram->telegramId() - << " could not be converted"; + DEBUG_LOG(m_logger) << "Received telegram '" << baJson << "'"; + // a payload-telegram + handleTelegram(&telegram); } } + catch (const std::exception &e) + { + ERROR_LOG(m_logger) << "JSon conversion error happenend. Error:" << e.what() << ", msg: " << baJson; + // inform central about the failure + TrainingAreaBase::TetraIcd::CtaDataError tele; + tele.header.equipmentNumber = m_VirtualTeilnehmerId; + tele.header.timeStamp = time(nullptr) * 1000LL; + tele.reason = TrainingAreaBase::TetraIcd::CtaDataError::Reason::JsonDecodeFailure; + tele.originTelegramId = 0; + N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(tele); + sendTelegram(&telegram); + } } - emit checkSendToRadio(); -} -// --------------------------------------------------------------- -// The counter will be set to a_startCounter if a_maxCounter -// is reached -// returns true if receive-counter is ok -// returns false if a telegram is repeated or lost -// --------------------------------------------------------------- -bool PrtCnvCentralThread::checkAndUpdateReceiveCounter(const int32_t a_counter) -{ - TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter; - // check for wrap - if (std::numeric_limits::max() == ++m_ReceiveCounter) - m_ReceiveCounter = 0; - - // has the counter the expected value? - if (m_ReceiveCounter != a_counter) + // --------------------------------------------------------------- + void PrtCnvCentralThread::stateChanged(QAbstractSocket::SocketState newState) { - if (m_ReceiveCounter > a_counter) + INFO_LOG(m_logger) << "Websocket changed to state " << newState; + } + + // --------------------------------------------------------------- + // Stores a telegram to be sent to radio in volatile radio- + // list and permanent in DB. + // --------------------------------------------------------------- + void PrtCnvCentralThread::handleTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) + { + // => check with receive-counter if we lost a telegram or we get a telegram twice. + // => in this cases neither store the telegram nor send an ack (just ignore and read the next telegram) + // => the receive-counter will be hold on the last correct received telegram + DEBUG_LOG(m_logger) << "Receive Central-Telegram with telId=" << a_telegram->telegramId() << "; rcounter=" << a_telegram->counter(); + if (checkAndUpdateReceiveCounter(a_telegram->counter())) { - ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from " - << getName() << "! Expected: " << m_ReceiveCounter; + if (handleSpecialTelegram(a_telegram)) + { + using namespace TrainingAreaBase::TetraIcd; + if (a_telegram->telegramId() == TelegramId::DEAKTIVIERUNG_WIRKFELD) + { + const DeactivateEffectSimulation des(DeactivateEffectSimulation::fromJson(a_telegram->jsonData())); + switch (des.aesType) + { + case AreaEffectSimulationType::MineArea: + case AreaEffectSimulationType::ExplosionArea: + case AreaEffectSimulationType::ExplosionSingle: + case AreaEffectSimulationType::NContamination: + case AreaEffectSimulationType::CContamination: + case AreaEffectSimulationType::FunctionalArea: + case AreaEffectSimulationType::DusSingleMineSimulator: + if (m_deactivatedAreaEffectSimulations.contains(des.aesDdsId)) + { + INFO_LOG(m_logger) << "AES with id " << des.aesDdsId << " already deactivated - ignoring new deactivation telegram"; + return; + } + break; + case AreaEffectSimulationType::TechnicalArea: + case AreaEffectSimulationType::GasPipeDetonation: + case AreaEffectSimulationType::SpecialArea: + case AreaEffectSimulationType::Unknown: + Q_ASSERT(false); // should not happen but who knows + break; + case AreaEffectSimulationType::BeStillWarning: + case AreaEffectSimulationType::DangerZoneExplosion: + case AreaEffectSimulationType::AirSupport: + break; + } + } + else if (a_telegram->telegramId() == TelegramId::WIRKFELD_STATUS_MINENSPERRE) + { + const MineAreaSingleMineState msms(MineAreaSingleMineState::fromJson(a_telegram->jsonData())); + QSet &oldTriggeredMines = m_alreadyTriggeredMines[msms.aesDdsId]; + QSet newTriggeredMines; + newTriggeredMines.reserve(oldTriggeredMines.size() + 5); + bool bSomethingChanged = false; + for (int i = 0; i < msms.mineCount; ++i) + { + if (!LtsUtils::BitArray::testBit(msms.mineState, i)) // 0 = triggered + { + INFO_LOG(m_logger) << "Testing bit " << i << " ... not set = triggered"; + if (!oldTriggeredMines.contains(i)) + { + INFO_LOG(m_logger) << "not in old one"; + bSomethingChanged = true; + } + newTriggeredMines.insert(i); + } + } + if (!bSomethingChanged) + bSomethingChanged = newTriggeredMines.size() != oldTriggeredMines.size(); + if (!bSomethingChanged) + { + INFO_LOG(m_logger) << "MineState telegram contains no new informations - skipping " << msms.aesDdsId; + return; + } + INFO_LOG(m_logger) << "MineState telegram contains new informations... " << msms.aesDdsId; + oldTriggeredMines = newTriggeredMines; // update in m_alreadyTriggeredMines[] + } + + std::shared_ptr radioTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(a_telegram)); + if (radioTelegram) + { + if (radioTelegram->getIdentity() <= m_maxEqID) + { + // save data in persistent database + m_DbThread->storeRadioTelegram(radioTelegram, a_telegram->counter()); + } + else + { + WARNING_LOG(m_logger) << "Central telegram with telId=" << a_telegram->telegramId() << " has invalid identity:" << radioTelegram->getIdentity(); + } + } + else + { + m_DbThread->centralCounterReadyForAck(a_telegram->counter()); + WARNING_LOG(m_logger) << "Central telegram with telId=" << a_telegram->telegramId() << " could not be converted"; + } + } } - else + emit checkSendToRadio(); + } + + // --------------------------------------------------------------- + // The counter will be set to a_startCounter if a_maxCounter + // is reached + // returns true if receive-counter is ok + // returns false if a telegram is repeated or lost + // --------------------------------------------------------------- + bool PrtCnvCentralThread::checkAndUpdateReceiveCounter(const int32_t a_counter) + { + TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter; + // check for wrap + if (std::numeric_limits::max() == ++m_ReceiveCounter) + m_ReceiveCounter = 0; + + // has the counter the expected value? + if (m_ReceiveCounter != a_counter) { - ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName() - << ": receive-counter of received telegram: " << a_counter << "; Expected: " << m_ReceiveCounter; - } + if (m_ReceiveCounter > a_counter) + { + ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from " << getName() << "! Expected: " << m_ReceiveCounter; + } + else + { + ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName() << ": receive-counter of received telegram: " << a_counter + << "; Expected: " << m_ReceiveCounter; + } #if 0 m_ReceiveCounter--; return false; // failure #else - m_ReceiveCounter = a_counter; - return true; + m_ReceiveCounter = a_counter; + return true; #endif + } + return true; // all ok } - return true; // all ok -} -// --------------------------------------------------------------- -// used to send periodically an ack to central -// --------------------------------------------------------------- -void PrtCnvCentralThread::timeoutTick() -{ - //NOTICE_LOG(m_logger) << "timeoutTick, " << m_DoCleanup << ", " << m_State; - if (m_DoCleanup) - return; // eat all pending timeouts - if (PrtCnvSocketThread::e_WORKING != m_State) - return; // do nothing when we are not in working state + // --------------------------------------------------------------- + // used to send periodically an ack to central + // --------------------------------------------------------------- + void PrtCnvCentralThread::timeoutTick() + { + //NOTICE_LOG(m_logger) << "timeoutTick, " << m_DoCleanup << ", " << m_State; + if (m_DoCleanup) + return; // eat all pending timeouts + if (PrtCnvSocketThread::e_WORKING != m_State) + return; // do nothing when we are not in working state -/* + /* // Das bringt nur noch mehr Traffic wenn zskskp die gesendeten Daten // nicht schnell genug abarbeiten kann - deshalb ersteinmal auskommentiert @@ -509,349 +504,345 @@ void PrtCnvCentralThread::timeoutTick() } */ - // do we have to inject a central-telegram? - try - { - N_CoPrtCnv::CoPrtCnvCentralTelegram *centralInjectTelegram; - while ((centralInjectTelegram = m_InjectionThread->getNextCentralInjectionTelegram())) + // do we have to inject a central-telegram? + try { - sendTelegram(centralInjectTelegram); - delete centralInjectTelegram; - } - } - catch (std::exception& e) - { - ERROR_LOG(m_logger) << "Catched an unexpected exception: " << e.what() - << " => could not inject radio-telegram, but we proceed..."; - } - - // send the periodically ack-telegram to central - sendAck(); -} - -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvCentralThread::timeoutAliveAndConnection() -{ - INFO_LOG(m_logger) << "timeoutAliveAndConnection socketState=" - << int(m_webSocket ? m_webSocket->state() : -1) - << " m_State=" << m_State << " m_Socket=" << m_webSocket; - switch (m_State) - { - case PrtCnvSocketThread::e_CONNECTING: - connectSocket(); - break; - case PrtCnvSocketThread::e_WORKING: - if (!m_bDirectConnection) + N_CoPrtCnv::CoPrtCnvCentralTelegram *centralInjectTelegram; + while ((centralInjectTelegram = m_InjectionThread->getNextCentralInjectionTelegram())) { - disconnectSocket(); - m_reconnectTimer->start(); + sendTelegram(centralInjectTelegram); + delete centralInjectTelegram; } - break; - case PrtCnvSocketThread::e_DISCONNECTING: - break; - default: - ERROR_LOG(m_logger) << "timeoutAlive for m_State=" << m_State << " not implemented"; - } -} + } + catch (std::exception &e) + { + ERROR_LOG(m_logger) << "Catched an unexpected exception: " << e.what() << " => could not inject radio-telegram, but we proceed..."; + } -// --------------------------------------------------------------- -// Sends a ack-telegram to central. -// --------------------------------------------------------------- -void PrtCnvCentralThread::sendAck() -{ - TrainingAreaBase::TetraIcd::Acknowledge ack; - ack.timeStamp = time(nullptr) * 1000; - ack.ackCounter = m_ReceiveAckCounter; - N_CoPrtCnv::CoPrtCnvCentralTelegram tele(ack); - // send to socket - if (m_webSocket) - m_webSocket->sendTextMessage(QString::fromUtf8(tele.data())); - else - emit directTextMessage(tele.data()); - - TRACE_LOG(m_logger) << "Wrote ack: " << tele.data(); -} - - -// --------------------------------------------------------------- -// Sends a central-telegram to socket or file, depending on -// configuration. Before sending, the send-counter will be set. -// --------------------------------------------------------------- -void PrtCnvCentralThread::sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - PrtCnvStoredCentralTelegram *handle = nullptr; - sendTelegram(a_telegram, handle); -} - - -// --------------------------------------------------------------- -// Sends a central-telegram to socket or file, depending on -// configuration. Before sending, the send-counter will be set. -// After sending the Db will be updated. -// --------------------------------------------------------------- -void PrtCnvCentralThread::sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram, - PrtCnvStoredCentralTelegram *a_handle) -{ - using namespace TrainingAreaBase::TetraIcd; - if (a_telegram->telegramId() == TelegramId::DEAKTIVIERUNG_EINZELMINE) - { - const MineTriggered tele(MineTriggered::fromJson(a_telegram->jsonData())); - m_alreadyTriggeredMines[tele.mineAreaId].insert(tele.mineIndex - 1); // starts at 1 ... - INFO_LOG(m_logger) << "Adding triggered mine with id " << tele.mineIndex << " to area id " << tele.mineAreaId; - } - - // set the counter, but keep old counter if we resend the telegram - const int writeCounter = a_handle ? a_handle->writeCounter() : 0; - if (writeCounter != 0) - a_telegram->setCounter(writeCounter); - else - a_telegram->setCounter(++m_SendCounter); - - // send telegram to central - DEBUG_LOG(m_logger) << "Send telegram to central: telId=" << a_telegram->telegramId() - << " wcounter=" << a_telegram->counter(); - // send to socket - if (m_webSocket) - m_webSocket->sendTextMessage(QString::fromUtf8(a_telegram->data())); - else - emit directTextMessage(a_telegram->data()); - - // mark in Db telegram as sent - if (a_handle) - m_DbThread->centralTelegramSent(a_telegram->counter(), a_handle); - m_LogThread->writeCentralTelegramLog(a_telegram, true, 1); -} - -// --------------------------------------------------------------- -// Processes the telegram -// AnforderungStatistikBroadcastNachforderugen. The function -// fills the answer telegram StatistikBroadNachforderungen -// with the actual statistic. -// --------------------------------------------------------------- -void PrtCnvCentralThread::handleAnforderungStatistikBroadcastNachforderungen() -{ - const auto nachforderungsStat = m_DbThread->getClaimStatistics(); - - // inform central about the failure - TrainingAreaBase::TetraIcd::BroadcastStatistics tele; - tele.header.equipmentNumber = m_VirtualTeilnehmerId; - tele.header.timeStamp = time(nullptr) * 1000LL; - tele.information.reserve(nachforderungsStat.size()); - for (const auto &it : nachforderungsStat) - { - TrainingAreaBase::TetraIcd::BroadcastInformation bi; - bi.equipmentNumber = it.first; - bi.broadcastRequests = it.second; - tele.information.push_back(std::move(bi)); - } - - N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(tele); - sendTelegram(&telegram); -} - -// --------------------------------------------------------------- -// Checks whether a telegram must be sent and sends it. -// --------------------------------------------------------------- -void PrtCnvCentralThread::checkSend() -{ - // eat all pending checkSend-signals, if we have to cleanup - if (m_DoCleanup) return; - if (PrtCnvSocketThread::e_WORKING != m_State) return; // do nothing when we are not in working state - PrtCnvStoredCentralTelegram *handle = nullptr; - auto *centralTelegram = m_DbThread->getNextCentralTelegram(handle); - if (centralTelegram) - { - sendTelegram(centralTelegram, handle); - delete centralTelegram; - emit checkSendToCentral(); - } -} - -// --------------------------------------------------------------- -// Removes telegrams from ToCentral-table, if the central -// acknowledges their reception -// --------------------------------------------------------------- -void PrtCnvCentralThread::handleAck(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - TrainingAreaBase::TetraIcd::Acknowledge ack(TrainingAreaBase::TetraIcd::Acknowledge::fromJson(a_telegram->jsonData())); -// INFO_LOG(m_logger) << "Got Central-Ack with wcounter=" << a_ackTelegram.zaehler(); - m_DbThread->ackCentralTelegrams(ack.ackCounter); -} - -// --------------------------------------------------------------- -// Will be called from Db-thread when telegrams were stored -// permanent. This function will then send the ack to central -// (socket-based) or delete the telegramfiles (file-based) -// --------------------------------------------------------------- -void PrtCnvCentralThread::permanentStored(int32_t a_centralCounter) -{ - if (m_DoCleanup) return; // eat all pending permanentStored - if (PrtCnvSocketThread::e_WORKING != m_State) return; // do nothing when we are not in working state - DEBUG_LOG(m_logger) << "got permanentStored a_centralCounter=" << a_centralCounter; - if (0 != a_centralCounter && a_centralCounter > m_ReceiveAckCounter) - { - m_ReceiveAckCounter = a_centralCounter; + // send the periodically ack-telegram to central sendAck(); } -} -void PrtCnvCentralThread::onTetraConnectionState(bool bConnected) -{ - TrainingAreaBase::TetraIcd::ProxyConnectionState connState; - connState.connectedToSystem = bConnected; - N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(connState); - sendTelegram(&telegram); -} - -void PrtCnvCentralThread::onPlayerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind) -{ - TrainingAreaBase::TetraIcd::ParticipantLicenseChange lc; - lc.equipmentNumber = equipNo; - lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unknown; - switch (kind) + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvCentralThread::timeoutAliveAndConnection() { - case N_CoPrtCnv::E_LicensingKind::Success: - lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Licensed; - break; - case N_CoPrtCnv::E_LicensingKind::Rejected: - lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Rejected; - break; - case N_CoPrtCnv::E_LicensingKind::Unlicense: - lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unlicense; - break; - } - Q_ASSERT(lc.licenseState != TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unknown); - N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(lc); - sendTelegram(&telegram); -} - -void PrtCnvCentralThread::onAreaEffectSimulationDeactivated(int wirkfeldKennung) -{ - m_deactivatedAreaEffectSimulations.insert(wirkfeldKennung); - m_alreadyTriggeredMines.remove(wirkfeldKennung); -} - -void PrtCnvCentralThread::onAreaEffectSimulationActivated(int wirkfeldKennung) -{ - m_deactivatedAreaEffectSimulations.remove(wirkfeldKennung); -} - -void PrtCnvCentralThread::onRadioThreadInitDone() -{ - m_bRadioThreadInitDone = true; - if (!m_sendAckTimer->isActive()) - m_sendAckTimer->start(); -} - -// --------------------------------------------------------------- -// returns true if telegram should be converted, stored and -// sent to radio -// --------------------------------------------------------------- -bool PrtCnvCentralThread::handleSpecialTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - using namespace TrainingAreaBase::TetraIcd; - - switch (a_telegram->telegramId()) - { - case Constraints::id(): - { - ExerciseStateData tele(ExerciseStateData::fromJson(a_telegram->jsonData())); - switch(tele.exerciseState) + INFO_LOG(m_logger) << "timeoutAliveAndConnection socketState=" << int(m_webSocket ? m_webSocket->state() : -1) << " m_State=" << m_State + << " m_Socket=" << m_webSocket; + switch (m_State) { - case ExerciseStateData::ExerciseState::Terminated: + case PrtCnvSocketThread::e_CONNECTING: + connectSocket(); + break; + case PrtCnvSocketThread::e_WORKING: + if (!m_bDirectConnection) + { + disconnectSocket(); + m_reconnectTimer->start(); + } + break; + case PrtCnvSocketThread::e_DISCONNECTING: + break; + default: + ERROR_LOG(m_logger) << "timeoutAlive for m_State=" << m_State << " not implemented"; + } + } + + // --------------------------------------------------------------- + // Sends a ack-telegram to central. + // --------------------------------------------------------------- + void PrtCnvCentralThread::sendAck() + { + TrainingAreaBase::TetraIcd::Acknowledge ack; + ack.timeStamp = time(nullptr) * 1000; + ack.ackCounter = m_ReceiveAckCounter; + N_CoPrtCnv::CoPrtCnvCentralTelegram tele(ack); + // send to socket + if (m_webSocket) + m_webSocket->sendTextMessage(QString::fromUtf8(tele.data())); + else + emit directTextMessage(tele.data()); + + TRACE_LOG(m_logger) << "Wrote ack: " << tele.data(); + } + + + // --------------------------------------------------------------- + // Sends a central-telegram to socket or file, depending on + // configuration. Before sending, the send-counter will be set. + // --------------------------------------------------------------- + void PrtCnvCentralThread::sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) + { + PrtCnvStoredCentralTelegram *handle = nullptr; + sendTelegram(a_telegram, handle); + } + + + // --------------------------------------------------------------- + // Sends a central-telegram to socket or file, depending on + // configuration. Before sending, the send-counter will be set. + // After sending the Db will be updated. + // --------------------------------------------------------------- + void PrtCnvCentralThread::sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram, PrtCnvStoredCentralTelegram *a_handle) + { + using namespace TrainingAreaBase::TetraIcd; + if (a_telegram->telegramId() == TelegramId::DEAKTIVIERUNG_EINZELMINE) { - INFO_LOG(m_logger) << "Got Betriebszustandsmeldung Uebung_Aufraeumen => disconnect, cleanup and reconnect"; - m_DbThread->setMachineState(1); // store permanent that we cleanup now, so we will proceed cleanup, after a crash - // send ack before disconnecting - permanentStored(a_telegram->counter()); - m_DoCleanup = true; - m_CentralStopped = false; - m_RadioStopped = false; - // INFO_LOG(m_logger) << "stop timer"; - m_sendAckTimer->stop(); - m_DbThread->waitUntilDbWritten(); - disconnectSocket(); - m_RadioThread->prepareCleanUp(); // this makes empty the message-queue of radio-thread faster - emit stopRadio(); - m_reconnectTimer->start(); - break; + const MineTriggered tele(MineTriggered::fromJson(a_telegram->jsonData())); + m_alreadyTriggeredMines[tele.mineAreaId].insert(tele.mineIndex - 1); // starts at 1 ... + INFO_LOG(m_logger) << "Adding triggered mine with id " << tele.mineIndex << " to area id " << tele.mineAreaId; } - case ExerciseStateData::ExerciseState::Started: - m_DbThread->setPause(false); - m_RadioThread->sendEnvironmentTelegramTimerNow(); - break; - case ExerciseStateData::ExerciseState::Paused: - m_DbThread->setPause(true); - m_RadioThread->sendEnvironmentTelegramTimerNow(); - break; - default: - break; + + // set the counter, but keep old counter if we resend the telegram + const int writeCounter = a_handle ? a_handle->writeCounter() : 0; + if (writeCounter != 0) + a_telegram->setCounter(writeCounter); + else + a_telegram->setCounter(++m_SendCounter); + + // send telegram to central + DEBUG_LOG(m_logger) << "Send telegram to central: telId=" << a_telegram->telegramId() << " wcounter=" << a_telegram->counter(); + // send to socket + if (m_webSocket) + m_webSocket->sendTextMessage(QString::fromUtf8(a_telegram->data())); + else + emit directTextMessage(a_telegram->data()); + + // mark in Db telegram as sent + if (a_handle) + m_DbThread->centralTelegramSent(a_telegram->counter(), a_handle); + m_LogThread->writeCentralTelegramLog(a_telegram, true, 1); + } + + // --------------------------------------------------------------- + // Processes the telegram + // AnforderungStatistikBroadcastNachforderugen. The function + // fills the answer telegram StatistikBroadNachforderungen + // with the actual statistic. + // --------------------------------------------------------------- + void PrtCnvCentralThread::handleAnforderungStatistikBroadcastNachforderungen() + { + const auto nachforderungsStat = m_DbThread->getClaimStatistics(); + + // inform central about the failure + TrainingAreaBase::TetraIcd::BroadcastStatistics tele; + tele.header.equipmentNumber = m_VirtualTeilnehmerId; + tele.header.timeStamp = time(nullptr) * 1000LL; + tele.information.reserve(nachforderungsStat.size()); + for (const auto &it : nachforderungsStat) + { + TrainingAreaBase::TetraIcd::BroadcastInformation bi; + bi.equipmentNumber = it.first; + bi.broadcastRequests = it.second; + tele.information.push_back(std::move(bi)); } - return false; - } - case Constraints::id(): - // here we must not use sendAck(), because it could be that we ack central-telegrams which are not yet stored permanent - m_DbThread->centralCounterReadyForAck(a_telegram->counter()); - handleAnforderungStatistikBroadcastNachforderungen(); - return false; - case Constraints::id(): + N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(tele); + sendTelegram(&telegram); + } + + // --------------------------------------------------------------- + // Checks whether a telegram must be sent and sends it. + // --------------------------------------------------------------- + void PrtCnvCentralThread::checkSend() { - const ExerciseEquipmentAssignmentComplete tele(ExerciseEquipmentAssignmentComplete::fromJson(a_telegram->jsonData())); - m_RadioThread->exerciseEquipmentChanged(tele); - return false; + // eat all pending checkSend-signals, if we have to cleanup + if (m_DoCleanup) + return; + if (PrtCnvSocketThread::e_WORKING != m_State) + return; // do nothing when we are not in working state + PrtCnvStoredCentralTelegram *handle = nullptr; + auto *centralTelegram = m_DbThread->getNextCentralTelegram(handle); + if (centralTelegram) + { + sendTelegram(centralTelegram, handle); + delete centralTelegram; + emit checkSendToCentral(); + } } - default: - break; - } - return true; -} -// --------------------------------------------------------------- -void PrtCnvCentralThread::connectSocket() -{ - const QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("EXCTDS01")); - if (host == QLatin1String("directConnection")) + // --------------------------------------------------------------- + // Removes telegrams from ToCentral-table, if the central + // acknowledges their reception + // --------------------------------------------------------------- + void PrtCnvCentralThread::handleAck(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) { - m_bDirectConnection = true; - connected(); - return; + TrainingAreaBase::TetraIcd::Acknowledge ack(TrainingAreaBase::TetraIcd::Acknowledge::fromJson(a_telegram->jsonData())); + // INFO_LOG(m_logger) << "Got Central-Ack with wcounter=" << a_ackTelegram.zaehler(); + m_DbThread->ackCentralTelegrams(ack.ackCounter); } - m_bDirectConnection = false; - disconnectSocket(); - m_webSocket = new QWebSocket; + // --------------------------------------------------------------- + // Will be called from Db-thread when telegrams were stored + // permanent. This function will then send the ack to central + // (socket-based) or delete the telegramfiles (file-based) + // --------------------------------------------------------------- + void PrtCnvCentralThread::permanentStored(int32_t a_centralCounter) + { + if (m_DoCleanup) + return; // eat all pending permanentStored + if (PrtCnvSocketThread::e_WORKING != m_State) + return; // do nothing when we are not in working state + DEBUG_LOG(m_logger) << "got permanentStored a_centralCounter=" << a_centralCounter; + if (0 != a_centralCounter && a_centralCounter > m_ReceiveAckCounter) + { + m_ReceiveAckCounter = a_centralCounter; + sendAck(); + } + } - connect(m_webSocket, &QWebSocket::stateChanged, - this, &PrtCnvCentralThread::stateChanged); - connect(m_webSocket, &QWebSocket::textMessageReceived, - this, &PrtCnvCentralThread::onTextMessageReceived); - connect(m_webSocket, &QWebSocket::connected, - this, &PrtCnvCentralThread::connected); - connect(m_webSocket, &QWebSocket::disconnected, - this, &PrtCnvCentralThread::disconnected); + void PrtCnvCentralThread::onTetraConnectionState(bool bConnected) + { + TrainingAreaBase::TetraIcd::ProxyConnectionState connState; + connState.connectedToSystem = bConnected; + N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(connState); + sendTelegram(&telegram); + } - const uint16_t port = static_cast(m_Config->getInteger(getName(), QStringLiteral("Port"), 4934)); - const QUrl scmUrl(QStringLiteral("ws://%1:%2").arg(host).arg(port)); + void PrtCnvCentralThread::onPlayerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind) + { + TrainingAreaBase::TetraIcd::ParticipantLicenseChange lc; + lc.equipmentNumber = equipNo; + lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unknown; + switch (kind) + { + case N_CoPrtCnv::E_LicensingKind::Success: + lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Licensed; + break; + case N_CoPrtCnv::E_LicensingKind::Rejected: + lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Rejected; + break; + case N_CoPrtCnv::E_LicensingKind::Unlicense: + lc.licenseState = TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unlicense; + break; + } + Q_ASSERT(lc.licenseState != TrainingAreaBase::TetraIcd::ParticipantLicenseState::Unknown); + N_CoPrtCnv::CoPrtCnvCentralTelegram telegram(lc); + sendTelegram(&telegram); + } - m_webSocket->open(scmUrl); - m_State = PrtCnvSocketThread::e_CONNECTING; -} + void PrtCnvCentralThread::onAreaEffectSimulationDeactivated(int wirkfeldKennung) + { + m_deactivatedAreaEffectSimulations.insert(wirkfeldKennung); + m_alreadyTriggeredMines.remove(wirkfeldKennung); + } -// --------------------------------------------------------------- -void PrtCnvCentralThread::disconnectSocket() -{ - m_State = PrtCnvSocketThread::e_INITIAL; - if (!m_webSocket) - return; + void PrtCnvCentralThread::onAreaEffectSimulationActivated(int wirkfeldKennung) + { + m_deactivatedAreaEffectSimulations.remove(wirkfeldKennung); + } - m_State = PrtCnvSocketThread::e_DISCONNECTING; - m_webSocket->disconnect(this); - m_webSocket->close(); - m_webSocket->deleteLater(); - m_webSocket = nullptr; -} + void PrtCnvCentralThread::onRadioThreadInitDone() + { + m_bRadioThreadInitDone = true; + if (!m_sendAckTimer->isActive()) + m_sendAckTimer->start(); + } + + // --------------------------------------------------------------- + // returns true if telegram should be converted, stored and + // sent to radio + // --------------------------------------------------------------- + bool PrtCnvCentralThread::handleSpecialTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) + { + using namespace TrainingAreaBase::TetraIcd; + + switch (a_telegram->telegramId()) + { + case Constraints::id(): + { + ExerciseStateData tele(ExerciseStateData::fromJson(a_telegram->jsonData())); + switch (tele.exerciseState) + { + case ExerciseStateData::ExerciseState::Terminated: + { + INFO_LOG(m_logger) << "Got Betriebszustandsmeldung Uebung_Aufraeumen => disconnect, cleanup and reconnect"; + m_DbThread->setMachineState(1); // store permanent that we cleanup now, so we will proceed cleanup, after a crash + // send ack before disconnecting + permanentStored(a_telegram->counter()); + m_DoCleanup = true; + m_CentralStopped = false; + m_RadioStopped = false; + // INFO_LOG(m_logger) << "stop timer"; + m_sendAckTimer->stop(); + m_DbThread->waitUntilDbWritten(); + disconnectSocket(); + m_RadioThread->prepareCleanUp(); // this makes empty the message-queue of radio-thread faster + emit stopRadio(); + m_reconnectTimer->start(); + break; + } + case ExerciseStateData::ExerciseState::Started: + m_DbThread->setPause(false); + m_RadioThread->sendEnvironmentTelegramTimerNow(); + break; + case ExerciseStateData::ExerciseState::Paused: + m_DbThread->setPause(true); + m_RadioThread->sendEnvironmentTelegramTimerNow(); + break; + default: + break; + } + return false; + } + case Constraints::id(): + // here we must not use sendAck(), because it could be that we ack central-telegrams which are not yet stored permanent + m_DbThread->centralCounterReadyForAck(a_telegram->counter()); + handleAnforderungStatistikBroadcastNachforderungen(); + return false; + + case Constraints::id(): + { + const ExerciseEquipmentAssignmentComplete tele(ExerciseEquipmentAssignmentComplete::fromJson(a_telegram->jsonData())); + m_RadioThread->exerciseEquipmentChanged(tele); + return false; + } + default: + break; + } + return true; + } + + // --------------------------------------------------------------- + void PrtCnvCentralThread::connectSocket() + { + const QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("EXCTDS01")); + if (host == QLatin1String("directConnection")) + { + m_bDirectConnection = true; + connected(); + return; + } + m_bDirectConnection = false; + + disconnectSocket(); + m_webSocket = new QWebSocket; + + connect(m_webSocket, &QWebSocket::stateChanged, this, &PrtCnvCentralThread::stateChanged); + connect(m_webSocket, &QWebSocket::textMessageReceived, this, &PrtCnvCentralThread::onTextMessageReceived); + connect(m_webSocket, &QWebSocket::connected, this, &PrtCnvCentralThread::connected); + connect(m_webSocket, &QWebSocket::disconnected, this, &PrtCnvCentralThread::disconnected); + + const uint16_t port = static_cast(m_Config->getInteger(getName(), QStringLiteral("Port"), 4934)); + const QUrl scmUrl(QStringLiteral("ws://%1:%2").arg(host).arg(port)); + + m_webSocket->open(scmUrl); + m_State = PrtCnvSocketThread::e_CONNECTING; + } + + // --------------------------------------------------------------- + void PrtCnvCentralThread::disconnectSocket() + { + m_State = PrtCnvSocketThread::e_INITIAL; + if (!m_webSocket) + return; + + m_State = PrtCnvSocketThread::e_DISCONNECTING; + m_webSocket->disconnect(this); + m_webSocket->close(); + m_webSocket->deleteLater(); + m_webSocket = nullptr; + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.hpp index 4365f5bff..ef48b3893 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvCentralThread.hpp @@ -40,9 +40,7 @@ namespace PrtCnv { Q_OBJECT -private: - - + private: public: /** * @author wia @@ -54,7 +52,7 @@ private: /** * @param a_parent The pointer to the starter-thread */ - explicit PrtCnvCentralThread(PrtCnvThreadStarter* a_parent); + explicit PrtCnvCentralThread(PrtCnvThreadStarter *a_parent); /** * Creates all subcomponents and connects signals to slots */ @@ -192,8 +190,7 @@ private: * @param a_telegram The central-telegram to be sent. * @param a_handle The handle assigned to telegram to be sent, we got from Db. */ - void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram, - PrtCnvStoredCentralTelegram *a_handle); + void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram, PrtCnvStoredCentralTelegram *a_handle); /** * Processes the telegram AnforderungStatistikBroadcastNachforderugen. The * function fills the answer telegram StatistikBroadNachforderungen with the diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.cpp index f23899324..317009f27 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.cpp @@ -32,791 +32,781 @@ namespace PrtCnv { -// --------------------------------------------------------------- -// Constructor with thread-starter as argument -// --------------------------------------------------------------- -PrtCnvDbThread::PrtCnvDbThread(const QString &dbDriver, - const QString &dbHostName, - const QString &dbDatabaseName, - const QString &schemaName, - const QString &dbUserName, - const QString &dbPassword, - PrtCnv::PrtCnvThreadStarter *a_parent) - : PrtCnvThread(a_parent, "PrtCnvDbThread") - , m_BattleFieldOpStateMutex() - , m_MemberListByIdMutex() - , m_CentralListMutex() - , m_OldCentralAckCounter(0) - , m_RadioListMutex() - , m_SqlCmdListMutex() - , m_BroadcastMapMutex() - , m_DoClean(false) - , m_DoWaitUntilSqlWritten(false) - , m_DoStorePermanent(false) - , m_ResetCounter(0) - , m_BattleFieldOperatingState(0) - , m_EnvironmentTelegram(nullptr) - , m_DoProceedCleanup(false) - , m_OldCentralCounter(0) - , m_StorePermanentPending(0) - , m_NbrOfAttempts(5) - , m_dbDriver(dbDriver.isEmpty() ? QStringLiteral("QSQLITE") : dbDriver) - , m_dbHostName(dbHostName) - , m_dbDatabaseName(dbDatabaseName) - , m_dbSchemaName(schemaName) - , m_dbUserName(dbUserName) - , m_dbPassword(dbPassword) -{ - m_Name = QStringLiteral("Db"); -} - - -PrtCnvDbThread::~PrtCnvDbThread() -{ - closeDb(); - qDeleteAll(m_BroadcastList); - qDeleteAll(m_RadioList); - qDeleteAll(m_CentralList); - for (const auto &p : m_MemberListById) - delete p.second; -} - - -// --------------------------------------------------------------- -// reinit database -// --------------------------------------------------------------- -static const int s_iCurrentDatabaseSchemeVersion = 1; -void PrtCnvDbThread::reinitDatabase() -{ - DBTransaction trans(m_db); - NSqlQuery q(m_db); - if (m_db.driverName() == QStringLiteral("QSQLITE")) + // --------------------------------------------------------------- + // Constructor with thread-starter as argument + // --------------------------------------------------------------- + PrtCnvDbThread::PrtCnvDbThread(const QString &dbDriver, + const QString &dbHostName, + const QString &dbDatabaseName, + const QString &schemaName, + const QString &dbUserName, + const QString &dbPassword, + PrtCnv::PrtCnvThreadStarter *a_parent) + : PrtCnvThread(a_parent, "PrtCnvDbThread") + , m_BattleFieldOpStateMutex() + , m_MemberListByIdMutex() + , m_CentralListMutex() + , m_OldCentralAckCounter(0) + , m_RadioListMutex() + , m_SqlCmdListMutex() + , m_BroadcastMapMutex() + , m_DoClean(false) + , m_DoWaitUntilSqlWritten(false) + , m_DoStorePermanent(false) + , m_ResetCounter(0) + , m_BattleFieldOperatingState(0) + , m_EnvironmentTelegram(nullptr) + , m_DoProceedCleanup(false) + , m_OldCentralCounter(0) + , m_StorePermanentPending(0) + , m_NbrOfAttempts(5) + , m_dbDriver(dbDriver.isEmpty() ? QStringLiteral("QSQLITE") : dbDriver) + , m_dbHostName(dbHostName) + , m_dbDatabaseName(dbDatabaseName) + , m_dbSchemaName(schemaName) + , m_dbUserName(dbUserName) + , m_dbPassword(dbPassword) { - q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(versionTableName())); - q.exec(QStringLiteral("CREATE TABLE %1 (" - "version integer," - "date text," - "product text," - "change text)").arg(versionTableName())); - q.exec(QStringLiteral("INSERT INTO %1 (version, date, product, change) VALUES " - "(1, '2012-11-20', 'TetraInterface', 'Initial version table');").arg(versionTableName())); - - q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(toCentralTableName())); - q.exec(QStringLiteral("CREATE TABLE %1 (" - "id INTEGER PRIMARY KEY AUTOINCREMENT," - "tel_id INTEGER," - "counter INTEGER DEFAULT 0," - "data BLOB);").arg(toCentralTableName())); - q.exec(QStringLiteral("CREATE INDEX counterIndex ON %1(counter);").arg(toCentralTableName())); - - q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(toRadioTableName())); - q.exec(QStringLiteral("CREATE TABLE %1 (" - "id INTEGER PRIMARY KEY AUTOINCREMENT," - "tel_id INTEGER," - "counter INTEGER DEFAULT 0," - "broadcast_index INTEGER DEFAULT 0," - "reset_counter INTEGER DEFAULT 0," - "data BLOB);").arg(toRadioTableName())); - q.exec(QStringLiteral("CREATE INDEX bcindex ON %1(reset_counter, broadcast_index);").arg(toRadioTableName())); - - q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(memberTableName())); - q.exec(QStringLiteral("CREATE TABLE %1 (" - "id INTEGER PRIMARY KEY," - "issi INTEGER," - "licensed INTEGER DEFAULT 0," - "claims INTEGER DEFAULT 0," - "exercise_id INTEGER" - ");").arg(memberTableName())); - - q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(statusTableName())); - q.exec(QStringLiteral("CREATE TABLE %1 (" - "id INTEGER PRIMARY KEY," - "reset_counter INTEGER," - "ctas_operating_state INTEGER," - "machine_state INTEGER" /* 0=>normal; 1=>DB-cleanup*/ - ");").arg(statusTableName())); - } - - q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 1;").arg(statusTableName())); - q.exec(QStringLiteral("INSERT INTO %1 " - "(id, reset_counter, ctas_operating_state, machine_state) " - "VALUES (1, %2, %3, 0);") - .arg(statusTableName()).arg(int(m_ResetCounter)).arg(int(m_BattleFieldOperatingState))); - - q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 0;").arg(memberTableName())); - - trans.commit(); -} - -// --------------------------------------------------------------- -// creates or restores the permanent database -// --------------------------------------------------------------- -bool PrtCnvDbThread::createDatabase() -{ - closeDb(); - - m_db = QSqlDatabase::addDatabase(m_dbDriver, QStringLiteral("PrtCnv")); - if (m_dbDriver == QLatin1String("QSQLITE")) - { - QString path = m_Config->getString(getName(), QStringLiteral("DatabaseFileName"), QStringLiteral("telegrams.db")); - if (!QDir::isAbsolutePath(path)) - { - path = QCoreApplication::applicationDirPath() + QLatin1String("/../") + path; - QFileInfo fi(path); - QDir().mkpath(fi.absolutePath()); - } - m_db.setDatabaseName(path); - INFO_LOG(m_logger) << "Use db-file: " << path; - std::cout << "Use db-file: " << qPrintable(path) << std::endl; - } - else - { - m_db.setDatabaseName(m_dbDatabaseName); - m_db.setHostName(m_dbHostName); - m_db.setUserName(m_dbUserName); - m_db.setPassword(m_dbPassword); + m_Name = QStringLiteral("Db"); } - DEBUG_LOG(m_logger) << "Connection name: " << m_db.connectionName(); - - if (!m_db.open()) + PrtCnvDbThread::~PrtCnvDbThread() { - FATAL_LOG(m_logger) << "Error while opening database: " << m_db.lastError().text(); - return false; + closeDb(); + qDeleteAll(m_BroadcastList); + qDeleteAll(m_RadioList); + qDeleteAll(m_CentralList); + for (const auto &p : m_MemberListById) + delete p.second; } - if (m_DoCleanDb) + + // --------------------------------------------------------------- + // reinit database + // --------------------------------------------------------------- + static const int s_iCurrentDatabaseSchemeVersion = 1; + void PrtCnvDbThread::reinitDatabase() { - NOTICE_LOG(m_logger) << "Permanent data will be erased..."; - reinitDatabase(); - } - else - { - NOTICE_LOG(m_logger) << "Check database..."; + DBTransaction trans(m_db); NSqlQuery q(m_db); if (m_db.driverName() == QStringLiteral("QSQLITE")) { - if (!q.execAndFetch(QStringLiteral("SELECT MAX(version) FROM %1;").arg(versionTableName()))) - { - ERROR_LOG(m_logger) << "Could not read version table - reinitialize database"; - reinitDatabase(); - } - else - { - // check for correct version see version table in reinitDatabase()! - int iVersion = q.value(0).toInt(); - if (iVersion != s_iCurrentDatabaseSchemeVersion) - { - ERROR_LOG(m_logger) << "Database version does not match (is: " - << iVersion << " expected: " << s_iCurrentDatabaseSchemeVersion - << " - reinitialize database"; - reinitDatabase(); - } - } + q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(versionTableName())); + q.exec(QStringLiteral("CREATE TABLE %1 (" + "version integer," + "date text," + "product text," + "change text)") + .arg(versionTableName())); + q.exec(QStringLiteral("INSERT INTO %1 (version, date, product, change) VALUES " + "(1, '2012-11-20', 'TetraInterface', 'Initial version table');") + .arg(versionTableName())); + + q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(toCentralTableName())); + q.exec(QStringLiteral("CREATE TABLE %1 (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "tel_id INTEGER," + "counter INTEGER DEFAULT 0," + "data BLOB);") + .arg(toCentralTableName())); + q.exec(QStringLiteral("CREATE INDEX counterIndex ON %1(counter);").arg(toCentralTableName())); + + q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(toRadioTableName())); + q.exec(QStringLiteral("CREATE TABLE %1 (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "tel_id INTEGER," + "counter INTEGER DEFAULT 0," + "broadcast_index INTEGER DEFAULT 0," + "reset_counter INTEGER DEFAULT 0," + "data BLOB);") + .arg(toRadioTableName())); + q.exec(QStringLiteral("CREATE INDEX bcindex ON %1(reset_counter, broadcast_index);").arg(toRadioTableName())); + + q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(memberTableName())); + q.exec(QStringLiteral("CREATE TABLE %1 (" + "id INTEGER PRIMARY KEY," + "issi INTEGER," + "licensed INTEGER DEFAULT 0," + "claims INTEGER DEFAULT 0," + "exercise_id INTEGER" + ");") + .arg(memberTableName())); + + q.exec(QStringLiteral("DROP TABLE IF EXISTS %1;").arg(statusTableName())); + q.exec(QStringLiteral("CREATE TABLE %1 (" + "id INTEGER PRIMARY KEY," + "reset_counter INTEGER," + "ctas_operating_state INTEGER," + "machine_state INTEGER" /* 0=>normal; 1=>DB-cleanup*/ + ");") + .arg(statusTableName())); } - if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(statusTableName()))) - { - ERROR_LOG(m_logger) << "Failure while checking DB-table Status"; - std::cout << "Failure while checking DB-table Status. Start PrtCnv with --cleandb" << std::endl; - return false; - } - if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(toCentralTableName()))) - { - ERROR_LOG(m_logger) << "Failure while checking DB-table ToCentral"; - std::cout << "Failure while checking DB-table ToCentral. Start PrtCnv with --cleandb" << std::endl; - return false; - } - if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(toRadioTableName()))) - { - ERROR_LOG(m_logger) << "Failure while checking DB-table ToRadio"; - std::cout << "Failure while checking DB-table ToRadio. Start PrtCnv with --cleandb" << std::endl; - return false; - } - // check whether the broadcast-member is ok - if (!q.exec(QStringLiteral("SELECT issi FROM %1 WHERE id=0;").arg(memberTableName()))) - { - ERROR_LOG(m_logger) << "Failure while checking DB-table Member"; - std::cout << "Failure while checking DB-table Member. Start PrtCnv with --cleandb" << std::endl; - return false; - } + q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 1;").arg(statusTableName())); + q.exec(QStringLiteral("INSERT INTO %1 " + "(id, reset_counter, ctas_operating_state, machine_state) " + "VALUES (1, %2, %3, 0);") + .arg(statusTableName()) + .arg(int(m_ResetCounter)) + .arg(int(m_BattleFieldOperatingState))); - const int broadcastIssi = m_Config->getInteger(QStringLiteral("Radio"), QStringLiteral("BroadcastISSI"), 5000); - if (q.next()) + q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 0;").arg(memberTableName())); + + trans.commit(); + } + + // --------------------------------------------------------------- + // creates or restores the permanent database + // --------------------------------------------------------------- + bool PrtCnvDbThread::createDatabase() + { + closeDb(); + + m_db = QSqlDatabase::addDatabase(m_dbDriver, QStringLiteral("PrtCnv")); + if (m_dbDriver == QLatin1String("QSQLITE")) { - const int dbBroadcastIssi = q.value(0).toInt(); - if (broadcastIssi != dbBroadcastIssi) + QString path = m_Config->getString(getName(), QStringLiteral("DatabaseFileName"), QStringLiteral("telegrams.db")); + if (!QDir::isAbsolutePath(path)) { - WARNING_LOG(m_logger) << "Broadcast-ISSI mismatch (DB: " << dbBroadcastIssi << "; Configfile: " << broadcastIssi << ")"; - q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 0;").arg(memberTableName())); - licenseMember(addMember(0, broadcastIssi)); + path = QCoreApplication::applicationDirPath() + QLatin1String("/../") + path; + QFileInfo fi(path); + QDir().mkpath(fi.absolutePath()); } + m_db.setDatabaseName(path); + INFO_LOG(m_logger) << "Use db-file: " << path; + std::cout << "Use db-file: " << qPrintable(path) << std::endl; } else { - licenseMember(addMember(0, broadcastIssi)); + m_db.setDatabaseName(m_dbDatabaseName); + m_db.setHostName(m_dbHostName); + m_db.setUserName(m_dbUserName); + m_db.setPassword(m_dbPassword); } - INFO_LOG(m_logger) << "Restore permanent data (after crash)..."; - m_DoStorePermanent = false; - INFO_LOG(m_logger) << "restoreStatus"; - // restore important varibles - if (!q.execAndFetch(QStringLiteral("SELECT reset_counter, ctas_operating_state, machine_state FROM %1;").arg(statusTableName()))) - { - ERROR_LOG(m_logger) << "Error reading Status from DB"; - std::cout << "Error reading Status from DB. Start PrtCnv with --cleandb" << std::endl; - return false; - } - m_ResetCounter = q.value(0).toInt(); - INFO_LOG(m_logger) << "Restore resetCounter=" << (int)m_ResetCounter; - // check whether the crash happend just while cleaning up DB - if (1 == q.value(2).toInt()) - { - INFO_LOG(m_logger) << "Crash happenend while cleaning-DB"; - // crash while cleaning DB => clean-DB and restart - m_DoStorePermanent = true; - m_DoProceedCleanup = true; - return true; - } - m_BattleFieldOperatingState = q.value(1).toInt(); - INFO_LOG(m_logger) << "Restore battleFieldOperatingState=" << (int)m_BattleFieldOperatingState; + DEBUG_LOG(m_logger) << "Connection name: " << m_db.connectionName(); - // restore the members - if (!q.exec(QStringLiteral("SELECT id, issi, licensed, claims, exercise_id FROM %1;").arg(memberTableName()))) + if (!m_db.open()) { - ERROR_LOG(m_logger) << "Error reading Member from DB"; - std::cout << "Error reading Member from DB. Start PrtCnv with --cleandb" << std::endl; + FATAL_LOG(m_logger) << "Error while opening database: " << m_db.lastError().text(); return false; } - while (q.next()) + if (m_DoCleanDb) { - int id = q.value(0).toInt(); - int issi = q.value(1).toInt(); - bool licensed = q.value(2).toBool(); - int claims = q.value(3).toInt(); - int exerciseId = q.value(4).toInt(); - INFO_LOG(m_logger) << "Restore member: id=" << id << " issi=" << issi << " licensed=" << licensed - << " claims=" << claims << " exerciseId " << exerciseId; - PrtCnvMember *member = addMember(id, issi); - if (member) + NOTICE_LOG(m_logger) << "Permanent data will be erased..."; + reinitDatabase(); + } + else + { + NOTICE_LOG(m_logger) << "Check database..."; + NSqlQuery q(m_db); + if (m_db.driverName() == QStringLiteral("QSQLITE")) { - member->m_ClaimCount = claims; - member->m_loggedInExerciseId = exerciseId; - if (licensed) + if (!q.execAndFetch(QStringLiteral("SELECT MAX(version) FROM %1;").arg(versionTableName()))) { - bool ok = licenseMember(member); - if (ok) - { - //emit signal - emit playerLicencedChanged(member->m_Id, N_CoPrtCnv::E_LicensingKind::Success); - } - } - } - } - - // restore radio-telegrams - // Sortierung nach resetCounter + broadcastindex weil die Daten dann in - // getAllFinishedBroadcastsFromDb() der Reihenfolge nach abholt werden - // also müssen wir sie hier richtig herum in m_RadioList eintragen - if (!q.exec(QStringLiteral("SELECT id, counter, broadcast_index, data " - "FROM %1 ORDER BY reset_counter, broadcast_index, id;").arg(toRadioTableName()))) - { - ERROR_LOG(m_logger) << "Error reading from ToRadio table"; - std::cout << "Error reading from ToRadio table. Start PrtCnv with --cleandb" << std::endl; - return false; - } - while (q.next()) - { - const qint64 id = q.value(0).toLongLong(); - const int counter = q.value(1).toInt(); - const int bcIndex = q.value(2).toInt(); - const QByteArray telData(q.value(3).toByteArray()); - - auto radioTelegram(std::make_shared(telData)); - PrtCnvStoredRadioTelegram *storedTelegram = - new PrtCnvStoredRadioTelegram(radioTelegram); - storedTelegram->m_Id = id; - // -------------------------- - // ---------------------------- - if (0 == counter) - { - // telegram not yet sent to radio - m_RadioList.push_back(storedTelegram); - INFO_LOG(m_logger) << "Restore unsent radiotelegram: id=" << storedTelegram->m_Id - << " telId=" << storedTelegram->m_RadioTelegram->getTelID() - << " BC=" << storedTelegram->m_RadioTelegram->getBroadcastIndex() - << " counter=" << counter; - } - else - { - // telegram sent to radio - if (bcIndex == 0) - { - if (radioTelegram->getTelID() == GEF_UMGEBUNGS_MELDUNG2) - m_RadioList.push_back(storedTelegram); - else - delete storedTelegram; // normally not possible to get here, but just in case + ERROR_LOG(m_logger) << "Could not read version table - reinitialize database"; + reinitDatabase(); } else { - // => broadcast-telegram - radioTelegram->setBroadcastIndex(bcIndex); - bool dummy; - radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); - radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); - radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); - m_BroadcastList.push_back(storedTelegram); - INFO_LOG(m_logger) << "Restore broadcast-radiotelegram: id=" - << storedTelegram->m_Id << " telId=" << storedTelegram->m_RadioTelegram->getTelID() - << " BC=" << storedTelegram->m_RadioTelegram->getBroadcastIndex() - << " counter=" << counter; + // check for correct version see version table in reinitDatabase()! + int iVersion = q.value(0).toInt(); + if (iVersion != s_iCurrentDatabaseSchemeVersion) + { + ERROR_LOG(m_logger) << "Database version does not match (is: " << iVersion << " expected: " << s_iCurrentDatabaseSchemeVersion << " - reinitialize database"; + reinitDatabase(); + } } } - } - // restore central-telegrams - q.exec(QStringLiteral("UPDATE %1 SET counter=0;").arg(toCentralTableName())); // => resend all not acked telegrams - if (!q.exec(QStringLiteral("SELECT id, data FROM %1 ORDER BY id;").arg(toCentralTableName()))) - { - ERROR_LOG(m_logger) << "Error reading from ToCentral table"; - std::cout << "Error reading from ToCentral table. Start PrtCnv with --cleandb" << std::endl; - return false; - } - while (q.next()) - { - const qint64 id = q.value(0).toLongLong(); - const QByteArray telData(q.value(1).toByteArray()); - - N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(telData); - std::shared_ptr - centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); - if (centralTelegram) + if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(statusTableName()))) { - PrtCnvStoredCentralTelegram *storedTelegram = new PrtCnvStoredCentralTelegram(centralTelegram, nullptr); - storedTelegram->m_Id = id; - m_CentralList.push_back(storedTelegram); - INFO_LOG(m_logger) << "Restore unsent or unacked centraltelegram: id=" << storedTelegram->m_Id - << " telId=" << storedTelegram->m_CentralTelegram->telegramId() - << " counter=" << storedTelegram->m_WriteCounter - << " size=" << telData.size(); - //NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, telData, blobSize); + ERROR_LOG(m_logger) << "Failure while checking DB-table Status"; + std::cout << "Failure while checking DB-table Status. Start PrtCnv with --cleandb" << std::endl; + return false; + } + if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(toCentralTableName()))) + { + ERROR_LOG(m_logger) << "Failure while checking DB-table ToCentral"; + std::cout << "Failure while checking DB-table ToCentral. Start PrtCnv with --cleandb" << std::endl; + return false; + } + if (!q.exec(QStringLiteral("SELECT * from %1 LIMIT 1;").arg(toRadioTableName()))) + { + ERROR_LOG(m_logger) << "Failure while checking DB-table ToRadio"; + std::cout << "Failure while checking DB-table ToRadio. Start PrtCnv with --cleandb" << std::endl; + return false; + } + // check whether the broadcast-member is ok + if (!q.exec(QStringLiteral("SELECT issi FROM %1 WHERE id=0;").arg(memberTableName()))) + { + ERROR_LOG(m_logger) << "Failure while checking DB-table Member"; + std::cout << "Failure while checking DB-table Member. Start PrtCnv with --cleandb" << std::endl; + return false; + } + + const int broadcastIssi = m_Config->getInteger(QStringLiteral("Radio"), QStringLiteral("BroadcastISSI"), 5000); + if (q.next()) + { + const int dbBroadcastIssi = q.value(0).toInt(); + if (broadcastIssi != dbBroadcastIssi) + { + WARNING_LOG(m_logger) << "Broadcast-ISSI mismatch (DB: " << dbBroadcastIssi << "; Configfile: " << broadcastIssi << ")"; + q.exec(QStringLiteral("DELETE FROM %1 WHERE id = 0;").arg(memberTableName())); + licenseMember(addMember(0, broadcastIssi)); + } } else - ERROR_LOG(m_logger) << "Internal error: conversion of telegram with telId=" << radioTelegram.getTelID() << " from radio to central failed"; - } - - if (m_db.driverName() == QLatin1String("QSQLITE")) - { - q.exec(QStringLiteral("VACUUM;")); - q.exec(QStringLiteral("PRAGMA journal_mode=WAL;")); - // Sync mode to NORMAL instead FULL - small speedup at the cost - // of a little higher risk for data loss on power failure - q.exec(QStringLiteral("PRAGMA synchronous=NORMAL;")); - } - } - m_DoStorePermanent = true; - - return true; -} - -// --------------------------------------------------------------- -// creates this thread and its childs -// --------------------------------------------------------------- -int32_t PrtCnvDbThread::create(NGL::Settings *settings) -{ - INFO_LOG(m_logger) << "create"; - PrtCnvThread::create(settings); - m_NbrOfAttempts = m_Config->getInteger(QStringLiteral("Central"), QStringLiteral("NbrOfAttempts"), 5); - if (!createDatabase()) - { - ERROR_LOG(m_logger) << "Trying to create clean database after error"; - m_DoCleanDb = true; - if (!createDatabase()) - exit(-2); - } - - connect(this, &PrtCnvDbThread::doStorePermanent, this, &PrtCnvDbThread::storePermanent, Qt::QueuedConnection); - connect(this, &PrtCnvDbThread::doClean, this, &PrtCnvDbThread::clean, Qt::QueuedConnection); - - PrtCnvCentralThread *centralThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Central)); - connect(this, &PrtCnvDbThread::permanentStored, centralThread, &PrtCnvCentralThread::permanentStored, Qt::QueuedConnection); - - return 0; -} - - -// --------------------------------------------------------------- -// initializes this thread and its childs -// --------------------------------------------------------------- -int32_t PrtCnvDbThread::init() -{ - INFO_LOG(m_logger) << "init"; - PrtCnvThread::init(); - m_CentralAckCounter = 0; - m_OldCentralAckCounter = 0; - m_OldCentralCounter = 0; - m_DoClean = false; - m_DoWaitUntilSqlWritten = false; - - return 0; -} - - -// --------------------------------------------------------------- -// starts this thread and its childs -// --------------------------------------------------------------- -int32_t PrtCnvDbThread::start() -{ - INFO_LOG(m_logger) << "start"; - PrtCnvThread::start(); - - return 0; -} - - -// --------------------------------------------------------------- -// stops this thread and its childs -// --------------------------------------------------------------- -int32_t PrtCnvDbThread::stop() -{ - PrtCnvThread::stop(); - m_db.close(); - m_db = QSqlDatabase(); - - return 0; -} - - -// --------------------------------------------------------------- -// stores the telegram to be sent to central in working-list -// and also in Db. Because storing data in XDR_Wrapper_it- -// format is complicated (has pointer to data), we store them -// in the radio-telegram-format). -// Attention: Be aware that centralTelegram and radioTelegram -// contain the same data. -// The DbThread takes control over centralTelegram and -// radioTelegram and deletes them when no longer needed. -// --------------------------------------------------------------- -void PrtCnvDbThread::storeCentralTelegram(const std::shared_ptr &a_centralTelegram, - const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) -{ - PrtCnvStoredCentralTelegram *storedTelegram = - new PrtCnvStoredCentralTelegram(a_centralTelegram, - std::make_shared(a_radioTelegram)); - QMutexLocker l(&m_CentralListMutex); - m_CentralList.push_back(storedTelegram); -// INFO_LOG(m_logger) << "Store Central-Telegram with telId=" << a_telegram->getTelID() << " and rc=" << a_telegram->zaehler(); - - sendStorePermanentSignal(); -} - - -// --------------------------------------------------------------- -// returns the next telegram to send to central. -// returns NULL if no telegram found. -// ATTENTION: The caller is responsible to deallocate the -// returned centralTelegram! -// --------------------------------------------------------------- -N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvDbThread::getNextCentralTelegram(PrtCnvStoredCentralTelegram *&a_handle) -{ - // get next telegram to send to central from DB - QMutexLocker l(&m_CentralListMutex); - std::vector::const_iterator iter = m_CentralList.begin(); - std::vector::const_iterator end = m_CentralList.end(); - for (; iter != end; ++iter) - { - PrtCnvStoredCentralTelegram *storedTelegram = *iter; - if (!storedTelegram || !storedTelegram->m_CentralTelegram) - continue; - if (0 == storedTelegram->m_WriteCounter || storedTelegram->m_DoResend) - { - const auto &telegram = storedTelegram->m_CentralTelegram; - storedTelegram->m_DoResend = false; - a_handle = storedTelegram; - DEBUG_LOG(m_logger) << "Next telegram to send to central: id=" << storedTelegram->m_Id - << " a_telId=" << telegram->telegramId(); - // allocate a central-telegram - return new N_CoPrtCnv::CoPrtCnvCentralTelegram(*telegram); - } - } - return nullptr; -} - - -// --------------------------------------------------------------- -// Marks the central-telegram as to be sent -// --------------------------------------------------------------- -void PrtCnvDbThread::centralTelegramSent(const int32_t a_counter, PrtCnvStoredCentralTelegram *a_handle) -{ - // update sendcounter - QMutexLocker l(&m_CentralListMutex); - a_handle->m_WriteCounter = a_counter; - a_handle->m_WriteCounterChanged = true; - - sendStorePermanentSignal(); -} - - -// --------------------------------------------------------------- -// Indicates the Db, which telegrams were successful received -// by central. This will delete this telegrams from Db. -// --------------------------------------------------------------- -void PrtCnvDbThread::ackCentralTelegrams(int32_t a_counter) -{ - //DEBUG_LOG(m_logger) << "Got Ack from Central with wc=" << a_counter; - m_CentralAckCounter = a_counter; - - sendStorePermanentSignal(); -} - - -// --------------------------------------------------------------- -// Updates the counter for unsuccessful sending the telegram. -// If a maximal value of this counter is reached, the central- -// telegram will be deleted. -// a_handle could be deleted after calling this function! -// This function could block some milliseconds, because it -// must wait until all changes are written to DB. -// --------------------------------------------------------------- -void PrtCnvDbThread::centralTelegramCouldNotBeSent(PrtCnvStoredCentralTelegram *a_handle) -{ - if (a_handle) - { - // delete the telegram if much enough unsuccessfully sent - QMutexLocker l(&m_CentralListMutex); - if (++(a_handle->m_Attempts) >= 5) - { - WARNING_LOG(m_logger) << "Delete unsendable Central-Telegram with id=" << a_handle->m_Id - << " telId=" << a_handle->m_CentralTelegram->telegramId() - << " rc=" << a_handle->m_CentralTelegram->counter() << " wc=" << a_handle->m_WriteCounter; - a_handle->m_DoDelete = true; - // mark in Db telegram as sent - } - l.unlock(); - - waitUntilDbWritten(); - } -} - - -// --------------------------------------------------------------- -// Stores the telegram to be sent to radio in working-list and -// also in Db. -// The DbThread takes control over a_telegram and deletes it -// when no longer needed. -// --------------------------------------------------------------- -void PrtCnvDbThread::storeRadioTelegram(const std::shared_ptr &a_telegram, - const int32_t a_readCounter) -{ - PrtCnvStoredRadioTelegram *storedTelegram = new PrtCnvStoredRadioTelegram(a_telegram); - storedTelegram->m_ReadCounter = a_readCounter; - { - QMutexLocker l(&m_RadioListMutex); - m_RadioList.push_back(storedTelegram); - } - if (a_telegram) - DEBUG_LOG(m_logger) << "Store Radio-Telegram with telId=" << a_telegram->getTelID() - << " rc=" << a_readCounter - << " wc=" << int(storedTelegram->m_WriteCounter); - - if (m_DoStorePermanent) - sendStorePermanentSignal(); -} - - -// --------------------------------------------------------------- -// This function causes acking a central-telegram, which must -// not be stored permanent in Db, because it will be handled -// immediately (i.e. -// AnforderungStatistikBroadcastNachforderungen). -// --------------------------------------------------------------- -void PrtCnvDbThread::centralCounterReadyForAck(const int32_t a_centralCounter) -{ - storeRadioTelegram(nullptr, a_centralCounter); - DEBUG_LOG(m_logger) << "No Radio-Telegram to store, but rc=" << a_centralCounter << " must be acked"; -} - - -// --------------------------------------------------------------- -// returns the next broadcast-telegram from list. -// Deletes the telegram from this list. -// returns NULL if list empty. -// --------------------------------------------------------------- -std::shared_ptr PrtCnvDbThread::getNextBroadcastTelegram() -{ - QMutexLocker l(&m_BroadcastMapMutex); - if (m_BroadcastList.empty()) - return nullptr; - - PrtCnvStoredRadioTelegram *storedRadioTelegram = m_BroadcastList.front(); - std::shared_ptr radioTelegram; - // check whether the telegram is already stored permanent in DB - if (storedRadioTelegram->m_Id != 0 && !storedRadioTelegram->m_WriteCounterChanged) - { - radioTelegram = storedRadioTelegram->m_RadioTelegram; - m_BroadcastList.pop_front(); - delete storedRadioTelegram; - } - - return radioTelegram; -} - - -// --------------------------------------------------------------- -// returns the next telegram to send to radio, respecting the -// priority. -// returns NULL if no radio-telegram found. -// --------------------------------------------------------------- -std::shared_ptr PrtCnvDbThread::getNextRadioTelegram(PrtCnvStoredRadioTelegram *&a_handle) -{ - // get next telegram respecting the priority to send to radio from DB - std::shared_ptr telegram; - uint8_t priority = 255; - - QMutexLocker l(&m_RadioListMutex); - for (PrtCnvStoredRadioTelegram *storedTelegram: m_RadioList) - { - const auto &radioTelegram = storedTelegram->m_RadioTelegram; - if (radioTelegram) - { - if (!storedTelegram->m_IsSent) { - // search the telegram with the lowest priority - uint8_t newPriority = radioTelegram->getPriority(); - if (newPriority < priority) + licenseMember(addMember(0, broadcastIssi)); + } + + INFO_LOG(m_logger) << "Restore permanent data (after crash)..."; + m_DoStorePermanent = false; + + INFO_LOG(m_logger) << "restoreStatus"; + // restore important varibles + if (!q.execAndFetch(QStringLiteral("SELECT reset_counter, ctas_operating_state, machine_state FROM %1;").arg(statusTableName()))) + { + ERROR_LOG(m_logger) << "Error reading Status from DB"; + std::cout << "Error reading Status from DB. Start PrtCnv with --cleandb" << std::endl; + return false; + } + m_ResetCounter = q.value(0).toInt(); + INFO_LOG(m_logger) << "Restore resetCounter=" << (int)m_ResetCounter; + // check whether the crash happend just while cleaning up DB + if (1 == q.value(2).toInt()) + { + INFO_LOG(m_logger) << "Crash happenend while cleaning-DB"; + // crash while cleaning DB => clean-DB and restart + m_DoStorePermanent = true; + m_DoProceedCleanup = true; + return true; + } + m_BattleFieldOperatingState = q.value(1).toInt(); + INFO_LOG(m_logger) << "Restore battleFieldOperatingState=" << (int)m_BattleFieldOperatingState; + + // restore the members + if (!q.exec(QStringLiteral("SELECT id, issi, licensed, claims, exercise_id FROM %1;").arg(memberTableName()))) + { + ERROR_LOG(m_logger) << "Error reading Member from DB"; + std::cout << "Error reading Member from DB. Start PrtCnv with --cleandb" << std::endl; + return false; + } + + while (q.next()) + { + int id = q.value(0).toInt(); + int issi = q.value(1).toInt(); + bool licensed = q.value(2).toBool(); + int claims = q.value(3).toInt(); + int exerciseId = q.value(4).toInt(); + INFO_LOG(m_logger) << "Restore member: id=" << id << " issi=" << issi << " licensed=" << licensed << " claims=" << claims << " exerciseId " << exerciseId; + PrtCnvMember *member = addMember(id, issi); + if (member) { - priority = newPriority; - telegram = radioTelegram; - a_handle = storedTelegram; + member->m_ClaimCount = claims; + member->m_loggedInExerciseId = exerciseId; + if (licensed) + { + bool ok = licenseMember(member); + if (ok) + { + //emit signal + emit playerLicencedChanged(member->m_Id, N_CoPrtCnv::E_LicensingKind::Success); + } + } + } + } + + // restore radio-telegrams + // Sortierung nach resetCounter + broadcastindex weil die Daten dann in + // getAllFinishedBroadcastsFromDb() der Reihenfolge nach abholt werden + // also müssen wir sie hier richtig herum in m_RadioList eintragen + if (!q.exec(QStringLiteral("SELECT id, counter, broadcast_index, data " + "FROM %1 ORDER BY reset_counter, broadcast_index, id;") + .arg(toRadioTableName()))) + { + ERROR_LOG(m_logger) << "Error reading from ToRadio table"; + std::cout << "Error reading from ToRadio table. Start PrtCnv with --cleandb" << std::endl; + return false; + } + while (q.next()) + { + const qint64 id = q.value(0).toLongLong(); + const int counter = q.value(1).toInt(); + const int bcIndex = q.value(2).toInt(); + const QByteArray telData(q.value(3).toByteArray()); + + auto radioTelegram(std::make_shared(telData)); + PrtCnvStoredRadioTelegram *storedTelegram = new PrtCnvStoredRadioTelegram(radioTelegram); + storedTelegram->m_Id = id; + // -------------------------- + // ---------------------------- + if (0 == counter) + { + // telegram not yet sent to radio + m_RadioList.push_back(storedTelegram); + INFO_LOG(m_logger) << "Restore unsent radiotelegram: id=" << storedTelegram->m_Id << " telId=" << storedTelegram->m_RadioTelegram->getTelID() + << " BC=" << storedTelegram->m_RadioTelegram->getBroadcastIndex() << " counter=" << counter; + } + else + { + // telegram sent to radio + if (bcIndex == 0) + { + if (radioTelegram->getTelID() == GEF_UMGEBUNGS_MELDUNG2) + m_RadioList.push_back(storedTelegram); + else + delete storedTelegram; // normally not possible to get here, but just in case + } + else + { + // => broadcast-telegram + radioTelegram->setBroadcastIndex(bcIndex); + bool dummy; + radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); + radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); + radioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); + m_BroadcastList.push_back(storedTelegram); + INFO_LOG(m_logger) << "Restore broadcast-radiotelegram: id=" << storedTelegram->m_Id << " telId=" << storedTelegram->m_RadioTelegram->getTelID() + << " BC=" << storedTelegram->m_RadioTelegram->getBroadcastIndex() << " counter=" << counter; + } + } + } + + // restore central-telegrams + q.exec(QStringLiteral("UPDATE %1 SET counter=0;").arg(toCentralTableName())); // => resend all not acked telegrams + if (!q.exec(QStringLiteral("SELECT id, data FROM %1 ORDER BY id;").arg(toCentralTableName()))) + { + ERROR_LOG(m_logger) << "Error reading from ToCentral table"; + std::cout << "Error reading from ToCentral table. Start PrtCnv with --cleandb" << std::endl; + return false; + } + while (q.next()) + { + const qint64 id = q.value(0).toLongLong(); + const QByteArray telData(q.value(1).toByteArray()); + + N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(telData); + std::shared_ptr centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); + if (centralTelegram) + { + PrtCnvStoredCentralTelegram *storedTelegram = new PrtCnvStoredCentralTelegram(centralTelegram, nullptr); + storedTelegram->m_Id = id; + m_CentralList.push_back(storedTelegram); + INFO_LOG(m_logger) << "Restore unsent or unacked centraltelegram: id=" << storedTelegram->m_Id << " telId=" << storedTelegram->m_CentralTelegram->telegramId() + << " counter=" << storedTelegram->m_WriteCounter << " size=" << telData.size(); + //NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, telData, blobSize); + } + else + ERROR_LOG(m_logger) << "Internal error: conversion of telegram with telId=" << radioTelegram.getTelID() << " from radio to central failed"; + } + + if (m_db.driverName() == QLatin1String("QSQLITE")) + { + q.exec(QStringLiteral("VACUUM;")); + q.exec(QStringLiteral("PRAGMA journal_mode=WAL;")); + // Sync mode to NORMAL instead FULL - small speedup at the cost + // of a little higher risk for data loss on power failure + q.exec(QStringLiteral("PRAGMA synchronous=NORMAL;")); + } + } + m_DoStorePermanent = true; + + return true; + } + + // --------------------------------------------------------------- + // creates this thread and its childs + // --------------------------------------------------------------- + int32_t PrtCnvDbThread::create(NGL::Settings *settings) + { + INFO_LOG(m_logger) << "create"; + PrtCnvThread::create(settings); + m_NbrOfAttempts = m_Config->getInteger(QStringLiteral("Central"), QStringLiteral("NbrOfAttempts"), 5); + if (!createDatabase()) + { + ERROR_LOG(m_logger) << "Trying to create clean database after error"; + m_DoCleanDb = true; + if (!createDatabase()) + exit(-2); + } + + connect(this, &PrtCnvDbThread::doStorePermanent, this, &PrtCnvDbThread::storePermanent, Qt::QueuedConnection); + connect(this, &PrtCnvDbThread::doClean, this, &PrtCnvDbThread::clean, Qt::QueuedConnection); + + PrtCnvCentralThread *centralThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Central)); + connect(this, &PrtCnvDbThread::permanentStored, centralThread, &PrtCnvCentralThread::permanentStored, Qt::QueuedConnection); + + return 0; + } + + + // --------------------------------------------------------------- + // initializes this thread and its childs + // --------------------------------------------------------------- + int32_t PrtCnvDbThread::init() + { + INFO_LOG(m_logger) << "init"; + PrtCnvThread::init(); + m_CentralAckCounter = 0; + m_OldCentralAckCounter = 0; + m_OldCentralCounter = 0; + m_DoClean = false; + m_DoWaitUntilSqlWritten = false; + + return 0; + } + + + // --------------------------------------------------------------- + // starts this thread and its childs + // --------------------------------------------------------------- + int32_t PrtCnvDbThread::start() + { + INFO_LOG(m_logger) << "start"; + PrtCnvThread::start(); + + return 0; + } + + + // --------------------------------------------------------------- + // stops this thread and its childs + // --------------------------------------------------------------- + int32_t PrtCnvDbThread::stop() + { + PrtCnvThread::stop(); + m_db.close(); + m_db = QSqlDatabase(); + + return 0; + } + + + // --------------------------------------------------------------- + // stores the telegram to be sent to central in working-list + // and also in Db. Because storing data in XDR_Wrapper_it- + // format is complicated (has pointer to data), we store them + // in the radio-telegram-format). + // Attention: Be aware that centralTelegram and radioTelegram + // contain the same data. + // The DbThread takes control over centralTelegram and + // radioTelegram and deletes them when no longer needed. + // --------------------------------------------------------------- + void PrtCnvDbThread::storeCentralTelegram(const std::shared_ptr &a_centralTelegram, + const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) + { + PrtCnvStoredCentralTelegram *storedTelegram = + new PrtCnvStoredCentralTelegram(a_centralTelegram, std::make_shared(a_radioTelegram)); + QMutexLocker l(&m_CentralListMutex); + m_CentralList.push_back(storedTelegram); + // INFO_LOG(m_logger) << "Store Central-Telegram with telId=" << a_telegram->getTelID() << " and rc=" << a_telegram->zaehler(); + + sendStorePermanentSignal(); + } + + + // --------------------------------------------------------------- + // returns the next telegram to send to central. + // returns NULL if no telegram found. + // ATTENTION: The caller is responsible to deallocate the + // returned centralTelegram! + // --------------------------------------------------------------- + N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvDbThread::getNextCentralTelegram(PrtCnvStoredCentralTelegram *&a_handle) + { + // get next telegram to send to central from DB + QMutexLocker l(&m_CentralListMutex); + std::vector::const_iterator iter = m_CentralList.begin(); + std::vector::const_iterator end = m_CentralList.end(); + for (; iter != end; ++iter) + { + PrtCnvStoredCentralTelegram *storedTelegram = *iter; + if (!storedTelegram || !storedTelegram->m_CentralTelegram) + continue; + if (0 == storedTelegram->m_WriteCounter || storedTelegram->m_DoResend) + { + const auto &telegram = storedTelegram->m_CentralTelegram; + storedTelegram->m_DoResend = false; + a_handle = storedTelegram; + DEBUG_LOG(m_logger) << "Next telegram to send to central: id=" << storedTelegram->m_Id << " a_telId=" << telegram->telegramId(); + // allocate a central-telegram + return new N_CoPrtCnv::CoPrtCnvCentralTelegram(*telegram); + } + } + return nullptr; + } + + + // --------------------------------------------------------------- + // Marks the central-telegram as to be sent + // --------------------------------------------------------------- + void PrtCnvDbThread::centralTelegramSent(const int32_t a_counter, PrtCnvStoredCentralTelegram *a_handle) + { + // update sendcounter + QMutexLocker l(&m_CentralListMutex); + a_handle->m_WriteCounter = a_counter; + a_handle->m_WriteCounterChanged = true; + + sendStorePermanentSignal(); + } + + + // --------------------------------------------------------------- + // Indicates the Db, which telegrams were successful received + // by central. This will delete this telegrams from Db. + // --------------------------------------------------------------- + void PrtCnvDbThread::ackCentralTelegrams(int32_t a_counter) + { + //DEBUG_LOG(m_logger) << "Got Ack from Central with wc=" << a_counter; + m_CentralAckCounter = a_counter; + + sendStorePermanentSignal(); + } + + + // --------------------------------------------------------------- + // Updates the counter for unsuccessful sending the telegram. + // If a maximal value of this counter is reached, the central- + // telegram will be deleted. + // a_handle could be deleted after calling this function! + // This function could block some milliseconds, because it + // must wait until all changes are written to DB. + // --------------------------------------------------------------- + void PrtCnvDbThread::centralTelegramCouldNotBeSent(PrtCnvStoredCentralTelegram *a_handle) + { + if (a_handle) + { + // delete the telegram if much enough unsuccessfully sent + QMutexLocker l(&m_CentralListMutex); + if (++(a_handle->m_Attempts) >= 5) + { + WARNING_LOG(m_logger) << "Delete unsendable Central-Telegram with id=" << a_handle->m_Id << " telId=" << a_handle->m_CentralTelegram->telegramId() + << " rc=" << a_handle->m_CentralTelegram->counter() << " wc=" << a_handle->m_WriteCounter; + a_handle->m_DoDelete = true; + // mark in Db telegram as sent + } + l.unlock(); + + waitUntilDbWritten(); + } + } + + + // --------------------------------------------------------------- + // Stores the telegram to be sent to radio in working-list and + // also in Db. + // The DbThread takes control over a_telegram and deletes it + // when no longer needed. + // --------------------------------------------------------------- + void PrtCnvDbThread::storeRadioTelegram(const std::shared_ptr &a_telegram, const int32_t a_readCounter) + { + PrtCnvStoredRadioTelegram *storedTelegram = new PrtCnvStoredRadioTelegram(a_telegram); + storedTelegram->m_ReadCounter = a_readCounter; + { + QMutexLocker l(&m_RadioListMutex); + m_RadioList.push_back(storedTelegram); + } + if (a_telegram) + DEBUG_LOG(m_logger) << "Store Radio-Telegram with telId=" << a_telegram->getTelID() << " rc=" << a_readCounter << " wc=" << int(storedTelegram->m_WriteCounter); + + if (m_DoStorePermanent) + sendStorePermanentSignal(); + } + + + // --------------------------------------------------------------- + // This function causes acking a central-telegram, which must + // not be stored permanent in Db, because it will be handled + // immediately (i.e. + // AnforderungStatistikBroadcastNachforderungen). + // --------------------------------------------------------------- + void PrtCnvDbThread::centralCounterReadyForAck(const int32_t a_centralCounter) + { + storeRadioTelegram(nullptr, a_centralCounter); + DEBUG_LOG(m_logger) << "No Radio-Telegram to store, but rc=" << a_centralCounter << " must be acked"; + } + + + // --------------------------------------------------------------- + // returns the next broadcast-telegram from list. + // Deletes the telegram from this list. + // returns NULL if list empty. + // --------------------------------------------------------------- + std::shared_ptr PrtCnvDbThread::getNextBroadcastTelegram() + { + QMutexLocker l(&m_BroadcastMapMutex); + if (m_BroadcastList.empty()) + return nullptr; + + PrtCnvStoredRadioTelegram *storedRadioTelegram = m_BroadcastList.front(); + std::shared_ptr radioTelegram; + // check whether the telegram is already stored permanent in DB + if (storedRadioTelegram->m_Id != 0 && !storedRadioTelegram->m_WriteCounterChanged) + { + radioTelegram = storedRadioTelegram->m_RadioTelegram; + m_BroadcastList.pop_front(); + delete storedRadioTelegram; + } + + return radioTelegram; + } + + + // --------------------------------------------------------------- + // returns the next telegram to send to radio, respecting the + // priority. + // returns NULL if no radio-telegram found. + // --------------------------------------------------------------- + std::shared_ptr PrtCnvDbThread::getNextRadioTelegram(PrtCnvStoredRadioTelegram *&a_handle) + { + // get next telegram respecting the priority to send to radio from DB + std::shared_ptr telegram; + uint8_t priority = 255; + + QMutexLocker l(&m_RadioListMutex); + for (PrtCnvStoredRadioTelegram *storedTelegram : m_RadioList) + { + const auto &radioTelegram = storedTelegram->m_RadioTelegram; + if (radioTelegram) + { + if (!storedTelegram->m_IsSent) + { + // search the telegram with the lowest priority + uint8_t newPriority = radioTelegram->getPriority(); + if (newPriority < priority) + { + priority = newPriority; + telegram = radioTelegram; + a_handle = storedTelegram; + } } } } - } - return telegram; -} - -// --------------------------------------------------------------- -// Marks the radio-telegram as to be sent -// --------------------------------------------------------------- -void PrtCnvDbThread::radioTelegramSent(const uint32_t a_sendCounter, PrtCnvStoredRadioTelegram *a_handle, const uint32_t a_broadcastIndex) -{ - QMutexLocker l(&m_RadioListMutex); - - if (a_broadcastIndex) - { - DEBUG_LOG(m_logger) << "request update radio telegramm in db - sc: " << a_sendCounter - << " telId: " << a_handle->m_RadioTelegram->getTelID() - << " BC: " << a_broadcastIndex; + return telegram; } - // update sendcounter in telegram - a_handle->m_WriteCounter = a_sendCounter; - a_handle->m_WriteCounterChanged = true; - a_handle->m_IsSent = true; - if (a_broadcastIndex != 0) - a_handle->m_BroadcastIndex = a_broadcastIndex; + // --------------------------------------------------------------- + // Marks the radio-telegram as to be sent + // --------------------------------------------------------------- + void PrtCnvDbThread::radioTelegramSent(const uint32_t a_sendCounter, PrtCnvStoredRadioTelegram *a_handle, const uint32_t a_broadcastIndex) + { + QMutexLocker l(&m_RadioListMutex); - if (a_handle->m_BroadcastIndex != 0) - { - // set the time for the 2nd broadcast - bool dummy; - a_handle->m_RadioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); - DEBUG_LOG(m_logger) << "Move Radio-Telegram with telId=" << a_handle->m_RadioTelegram->getTelID() - << " and BC=" << a_handle->m_RadioTelegram->getBroadcastIndex() - << " to BC-List of DB"; -// if (a_handle->m_Id != 0) -// { -// M_DEBUG("Remove from radio-list") -// m_RadioList.remove(a_handle); -// } - QMutexLocker l2(&m_BroadcastMapMutex); - m_BroadcastList.push_back(a_handle); - } - else - { - // do not delete umgebungsmeldung, because we need it for restore after crash - if (a_handle->m_RadioTelegram->isNormalTelegram() && (a_handle->m_RadioTelegram->getTelID() == GEF_UMGEBUNGS_MELDUNG2)) + if (a_broadcastIndex) { - // store only the last Umgebungsmeldung - if (m_EnvironmentTelegram) - m_EnvironmentTelegram->m_DoDelete = true; - m_EnvironmentTelegram = a_handle; + DEBUG_LOG(m_logger) << "request update radio telegramm in db - sc: " << a_sendCounter << " telId: " << a_handle->m_RadioTelegram->getTelID() + << " BC: " << a_broadcastIndex; + } + + // update sendcounter in telegram + a_handle->m_WriteCounter = a_sendCounter; + a_handle->m_WriteCounterChanged = true; + a_handle->m_IsSent = true; + if (a_broadcastIndex != 0) + a_handle->m_BroadcastIndex = a_broadcastIndex; + + if (a_handle->m_BroadcastIndex != 0) + { + // set the time for the 2nd broadcast + bool dummy; + a_handle->m_RadioTelegram->mustBeSentAsBroadcast(0xFFFFFFFF, dummy); + DEBUG_LOG(m_logger) << "Move Radio-Telegram with telId=" << a_handle->m_RadioTelegram->getTelID() << " and BC=" << a_handle->m_RadioTelegram->getBroadcastIndex() + << " to BC-List of DB"; + // if (a_handle->m_Id != 0) + // { + // M_DEBUG("Remove from radio-list") + // m_RadioList.remove(a_handle); + // } + QMutexLocker l2(&m_BroadcastMapMutex); + m_BroadcastList.push_back(a_handle); } else - a_handle->m_DoDelete = true; + { + // do not delete umgebungsmeldung, because we need it for restore after crash + if (a_handle->m_RadioTelegram->isNormalTelegram() && (a_handle->m_RadioTelegram->getTelID() == GEF_UMGEBUNGS_MELDUNG2)) + { + // store only the last Umgebungsmeldung + if (m_EnvironmentTelegram) + m_EnvironmentTelegram->m_DoDelete = true; + m_EnvironmentTelegram = a_handle; + } + else + a_handle->m_DoDelete = true; + } + + sendStorePermanentSignal(); } - sendStorePermanentSignal(); -} - -void PrtCnvDbThread::deleteTelegramsFromDbById(const QString &table) -{ - if (m_telegramsToDelete.empty()) - return; - - QStringList sl; - sl.reserve(m_telegramsToDelete.size()); - for (const int64_t telId : m_telegramsToDelete) - sl += QString::number(telId); - - NSqlQuery q(m_db); - q.exec(QStringLiteral("DELETE FROM %1 WHERE id IN (%2);").arg(table, sl.join(QLatin1Char(',')))); - - // cleanup - m_telegramsToDelete.clear(); -} - -void PrtCnvDbThread::updateTelegramsBroadcast(const QString &table) -{ - if (m_telegramsToUpdateBC.empty()) - return; - - NSqlQuery q(m_db); - q.prepare(QStringLiteral("UPDATE %1 SET broadcast_index = :broadcast_index WHERE id = :id").arg(table)); - for (const auto &p : m_telegramsToUpdateBC) + void PrtCnvDbThread::deleteTelegramsFromDbById(const QString &table) { - const qint64 telId = p.first; - const qint32 bcIndex = p.second; + if (m_telegramsToDelete.empty()) + return; - q.bindValue(QStringLiteral(":broadcast_index"), bcIndex); - q.bindValue(QStringLiteral(":id"), telId); - q.exec(); + QStringList sl; + sl.reserve(m_telegramsToDelete.size()); + for (const int64_t telId : m_telegramsToDelete) + sl += QString::number(telId); - DEBUG_LOG(m_logger) << "Update broadcastindex for id: " << telId << " to BC: " << bcIndex; + NSqlQuery q(m_db); + q.exec(QStringLiteral("DELETE FROM %1 WHERE id IN (%2);").arg(table, sl.join(QLatin1Char(',')))); + + // cleanup + m_telegramsToDelete.clear(); } - // cleanup - m_telegramsToUpdateBC.clear(); -} - -void PrtCnvDbThread::updateTelegramsWriteCounter(const QString &table) -{ - if (m_telegramsToUpdateCounter.empty()) - return; - - NSqlQuery q(m_db); - q.prepare(QStringLiteral("UPDATE %1 SET counter = :counter WHERE id = :id").arg(table)); - for (const auto &p : m_telegramsToUpdateCounter) + void PrtCnvDbThread::updateTelegramsBroadcast(const QString &table) { - const qint64 telId = p.first; - const qint32 writeCounter = p.second; + if (m_telegramsToUpdateBC.empty()) + return; - q.bindValue(QStringLiteral(":counter"), writeCounter); - q.bindValue(QStringLiteral(":id"), telId); - q.exec(); + NSqlQuery q(m_db); + q.prepare(QStringLiteral("UPDATE %1 SET broadcast_index = :broadcast_index WHERE id = :id").arg(table)); + for (const auto &p : m_telegramsToUpdateBC) + { + const qint64 telId = p.first; + const qint32 bcIndex = p.second; - DEBUG_LOG(m_logger) << "Update WriteCounter for id: " << telId << " to wc: " << writeCounter; + q.bindValue(QStringLiteral(":broadcast_index"), bcIndex); + q.bindValue(QStringLiteral(":id"), telId); + q.exec(); + + DEBUG_LOG(m_logger) << "Update broadcastindex for id: " << telId << " to BC: " << bcIndex; + } + + // cleanup + m_telegramsToUpdateBC.clear(); } - // cleanup - m_telegramsToUpdateCounter.clear(); -} + void PrtCnvDbThread::updateTelegramsWriteCounter(const QString &table) + { + if (m_telegramsToUpdateCounter.empty()) + return; -/** + NSqlQuery q(m_db); + q.prepare(QStringLiteral("UPDATE %1 SET counter = :counter WHERE id = :id").arg(table)); + for (const auto &p : m_telegramsToUpdateCounter) + { + const qint64 telId = p.first; + const qint32 writeCounter = p.second; + + q.bindValue(QStringLiteral(":counter"), writeCounter); + q.bindValue(QStringLiteral(":id"), telId); + q.exec(); + + DEBUG_LOG(m_logger) << "Update WriteCounter for id: " << telId << " to wc: " << writeCounter; + } + + // cleanup + m_telegramsToUpdateCounter.clear(); + } + + /** * Da SQL-Kommandos im Gegensatz zum Auslesen aus dem Socket zu langsam * ist und wir hier recht lange Lock-Zeiten haben, müssen wir uns mit einer * zweiteiligen Verarbeitung zufrieden geben @@ -826,830 +816,788 @@ void PrtCnvDbThread::updateTelegramsWriteCounter(const QString &table) * eines Crashes sowieso nicht alles puffern kann, sollte dies ok * sein. */ -void PrtCnvDbThread::storeCentralTelegrams() -{ - QMutexLocker l(&m_CentralListMutex); - - if (m_CentralList.empty()) - return; - - // DEBUG_LOG(m_logger) << "centralTelegrams.size=" << m_CentralList.size(); - int iEmptyCount = 0; - for (auto &storedCentralTelegram : m_CentralList) // reference is important to be able to make them a nullptr in the vector + void PrtCnvDbThread::storeCentralTelegrams() { - if (!storedCentralTelegram) - { - ++iEmptyCount; - continue; - } - const auto centralTelegram = storedCentralTelegram->m_CentralTelegram; + QMutexLocker l(&m_CentralListMutex); - if (0 == storedCentralTelegram->m_Id) - { - // new Telegram from Tetra, not yet in db -> insert it now - m_telegramsToInsert.emplace_back(std::make_pair(storedCentralTelegram, 0)); + if (m_CentralList.empty()) + return; - DEBUG_LOG(m_logger) << "Permanent Central-Telegram with id=" << storedCentralTelegram->m_Id - << " data=" << centralTelegram->data() - << " wc=" << storedCentralTelegram->m_WriteCounter; - } - else + // DEBUG_LOG(m_logger) << "centralTelegrams.size=" << m_CentralList.size(); + int iEmptyCount = 0; + for (auto &storedCentralTelegram : m_CentralList) // reference is important to be able to make them a nullptr in the vector { - // update counter for all sent central-telegrams - // --------------------------------------------- - const int centralAckCnt = m_CentralAckCounter; - if (storedCentralTelegram->m_WriteCounterChanged) + if (!storedCentralTelegram) { - m_telegramsToUpdateCounter.emplace_back(std::make_pair(storedCentralTelegram->m_Id, - storedCentralTelegram->m_WriteCounter)); - storedCentralTelegram->m_WriteCounterChanged = false; + ++iEmptyCount; + continue; + } + const auto centralTelegram = storedCentralTelegram->m_CentralTelegram; - DEBUG_LOG(m_logger) << "Update Central-Telegram with id=" << storedCentralTelegram->m_Id - << " data=" << centralTelegram->data() + if (0 == storedCentralTelegram->m_Id) + { + // new Telegram from Tetra, not yet in db -> insert it now + m_telegramsToInsert.emplace_back(std::make_pair(storedCentralTelegram, 0)); + + DEBUG_LOG(m_logger) << "Permanent Central-Telegram with id=" << storedCentralTelegram->m_Id << " data=" << centralTelegram->data() << " wc=" << storedCentralTelegram->m_WriteCounter; } - // delete all acked telegrams from central-list - // -------------------------------------------- - else if ((storedCentralTelegram->m_WriteCounter > 0 && - storedCentralTelegram->m_WriteCounter <= centralAckCnt) || - storedCentralTelegram->m_DoDelete) + else { - DEBUG_LOG(m_logger) << "Delete Central-Telegram with id=" << storedCentralTelegram->m_Id - << " data=" << storedCentralTelegram->m_CentralTelegram->data() - << " wc=" << storedCentralTelegram->m_WriteCounter; - - // no need for single delete when centralAckCnt is higher - will be deleted later with where counter <= ackCounter - if (storedCentralTelegram->m_WriteCounter > centralAckCnt) - m_telegramsToDelete.push_back(storedCentralTelegram->m_Id); - // Removing from vector and DB occours some lines down - delete storedCentralTelegram; - storedCentralTelegram = nullptr; - } - } - } - // clean up m_CentralList if really needed - if (iEmptyCount > 50) - { - const auto isNull = [](const PrtCnvStoredCentralTelegram *t) { return t == nullptr; }; - m_CentralList.erase(std::remove_if(m_CentralList.begin(), m_CentralList.end(), isNull), - m_CentralList.end()); - } - - l.unlock(); - // DEBUG_LOG(m_logger) << "ready: " << m_CentralList.size(); - - // insert new telegrams into db - if (!m_telegramsToInsert.empty()) - { - l.relock(); - NSqlQuery q(m_db); - q.prepare(QStringLiteral("INSERT INTO %1 (tel_id, counter, data)" - "VALUES(:tel_id, :counter, :data);").arg(toCentralTableName())); - - // TODO: ist das Locking mittels m_CentralListMutex überhaupt nötig? - // Wenn nein dann kann man dies hier etwas einfacher gestalten - - for (const auto &p : m_telegramsToInsert) - { - PrtCnvStoredCentralTelegram *storedCentralTelegram = p.first; - - storedCentralTelegram->m_WriteCounterChanged = false; - q.bindValue(QStringLiteral(":tel_id"), storedCentralTelegram->m_CentralTelegram->telegramId()); - q.bindValue(QStringLiteral(":counter"), storedCentralTelegram->m_WriteCounter); - q.bindValue(QStringLiteral(":data"), storedCentralTelegram->m_RadioTelegram->data()); - q.exec(); - storedCentralTelegram->m_Id = q.lastInsertId().toInt(); - } - l.unlock(); - // DEBUG_LOG(m_logger) << "added new telegrams to db: " << m_telegramsToInsert.size(); - m_telegramsToInsert.clear(); - } - - - // update write counter for a telegramm - updateTelegramsWriteCounter(toCentralTableName()); - // DEBUG_LOG(m_logger) << "updated write counter in db: " << m_telegramsToUpdateCounter.size(); - - // Jetzt alle Telegramme löschen die von der Zentrale bestätigt worden - // da m_CentralAckCounter von anderen Threads geändert werden kann, kann es - // sein dass schon mehr Telegramme aus der DB gelöscht werden als vorher - // aus m_CentralList. Dies wird aber im nächsten Aufruf wieder korrigiert - const unsigned int centralAckCnt = static_cast(m_CentralAckCounter); - if (centralAckCnt > m_OldCentralAckCounter) - { - m_OldCentralAckCounter = centralAckCnt; - // wir arbeiten mit m_OldCentralAckCounter da sich m_CentralAckCounter - // währenddessen schon ändern kann - DEBUG_LOG(m_logger) << "Central delete all counter <= " << m_OldCentralAckCounter; - - NSqlQuery q(m_db); - q.exec(QStringLiteral("DELETE FROM %1 WHERE counter > 0 AND counter <= %2;").arg(toCentralTableName()).arg(m_OldCentralAckCounter)); - } - - // remove all telegrams which were manually marked for deletion - deleteTelegramsFromDbById(toCentralTableName()); -} - -int32_t PrtCnvDbThread::storeRadioTelegrams() -{ - QMutexLocker l(&m_RadioListMutex); - - if (m_RadioList.empty()) - return 0; - - // M_DEBUG("Check for permanent actions on radio-list") - int32_t centralCounter = 0; - - NSqlQuery q(m_db); - q.prepare(QStringLiteral("INSERT INTO %1 (tel_id, counter, broadcast_index, reset_counter, data) " - "VALUES (:tel_id, :counter, :broadcast_index, :reset_counter, :data);").arg(toRadioTableName())); - - // DEBUG_LOG(m_logger) << "m_RadioList.size=" << m_RadioList.size(); - std::list::iterator radioIter = m_RadioList.begin(); - while (radioIter != m_RadioList.end()) - { - bool doDeleteThisItem = false; - PrtCnvStoredRadioTelegram *storedRadioTelegram = *radioIter; - const auto &radioTelegram = storedRadioTelegram->m_RadioTelegram; - - if (radioTelegram) - { - DEBUG_LOG(m_logger) << "Handling Radio-Telegram with id=" << storedRadioTelegram->m_Id - << " TelID: " << radioTelegram->getTelID() - << " rc: " << int(radioTelegram->zaehler()) - << " BC: " << storedRadioTelegram->m_BroadcastIndex - << " wc: " << int(storedRadioTelegram->m_WriteCounter); - - // store radio-telegrams permanent - // ------------------------------- - if (0 == storedRadioTelegram->m_Id) - { - if (storedRadioTelegram->m_ReadCounter > centralCounter) - centralCounter = storedRadioTelegram->m_ReadCounter; - - storedRadioTelegram->m_WriteCounterChanged = false; - q.bindValue(QStringLiteral(":tel_id"), radioTelegram->getTelID()); - q.bindValue(QStringLiteral(":counter"), storedRadioTelegram->m_WriteCounter); - q.bindValue(QStringLiteral(":broadcast_index"), storedRadioTelegram->m_BroadcastIndex); - q.bindValue(QStringLiteral(":reset_counter"), int(m_ResetCounter)); - q.bindValue(QStringLiteral(":data"), radioTelegram->data()); - q.exec(); - storedRadioTelegram->m_Id = q.lastInsertId().toInt(); - - DEBUG_LOG(m_logger) << "Stored Telegramm in DB, id: " << storedRadioTelegram->m_Id; - - // for broadcast-telegrams, we have 2 cases: - // 1. case: it will be written to DB, before it is sent to radio and then moved to broadcast-list of broadcast-manager - // 2. case: it will be sent to radio before it is written to DB. In this case we cannot remove it from m_RadioList until - // it is written to DB - // here we check whether case 2 has happenend - if (storedRadioTelegram->m_RadioTelegram->isMovedToBroadcastList()) + // update counter for all sent central-telegrams + // --------------------------------------------- + const int centralAckCnt = m_CentralAckCounter; + if (storedCentralTelegram->m_WriteCounterChanged) { - dumpTelegram(m_logger, - radioTelegram->getBroadcastCounter(), - storedRadioTelegram->m_RadioTelegram.get()); - DEBUG_LOG(m_logger) << "Removed Telegramm from radioList (place 1), id: " << storedRadioTelegram->m_Id; - doDeleteThisItem = true; + m_telegramsToUpdateCounter.emplace_back(std::make_pair(storedCentralTelegram->m_Id, storedCentralTelegram->m_WriteCounter)); + storedCentralTelegram->m_WriteCounterChanged = false; + + DEBUG_LOG(m_logger) << "Update Central-Telegram with id=" << storedCentralTelegram->m_Id << " data=" << centralTelegram->data() + << " wc=" << storedCentralTelegram->m_WriteCounter; + } + // delete all acked telegrams from central-list + // -------------------------------------------- + else if ((storedCentralTelegram->m_WriteCounter > 0 && storedCentralTelegram->m_WriteCounter <= centralAckCnt) || storedCentralTelegram->m_DoDelete) + { + DEBUG_LOG(m_logger) << "Delete Central-Telegram with id=" << storedCentralTelegram->m_Id << " data=" << storedCentralTelegram->m_CentralTelegram->data() + << " wc=" << storedCentralTelegram->m_WriteCounter; + + // no need for single delete when centralAckCnt is higher - will be deleted later with where counter <= ackCounter + if (storedCentralTelegram->m_WriteCounter > centralAckCnt) + m_telegramsToDelete.push_back(storedCentralTelegram->m_Id); + // Removing from vector and DB occours some lines down + delete storedCentralTelegram; + storedCentralTelegram = nullptr; + } + } + } + // clean up m_CentralList if really needed + if (iEmptyCount > 50) + { + const auto isNull = [](const PrtCnvStoredCentralTelegram *t) { return t == nullptr; }; + m_CentralList.erase(std::remove_if(m_CentralList.begin(), m_CentralList.end(), isNull), m_CentralList.end()); + } + + l.unlock(); + // DEBUG_LOG(m_logger) << "ready: " << m_CentralList.size(); + + // insert new telegrams into db + if (!m_telegramsToInsert.empty()) + { + l.relock(); + NSqlQuery q(m_db); + q.prepare(QStringLiteral("INSERT INTO %1 (tel_id, counter, data)" + "VALUES(:tel_id, :counter, :data);") + .arg(toCentralTableName())); + + // TODO: ist das Locking mittels m_CentralListMutex überhaupt nötig? + // Wenn nein dann kann man dies hier etwas einfacher gestalten + + for (const auto &p : m_telegramsToInsert) + { + PrtCnvStoredCentralTelegram *storedCentralTelegram = p.first; + + storedCentralTelegram->m_WriteCounterChanged = false; + q.bindValue(QStringLiteral(":tel_id"), storedCentralTelegram->m_CentralTelegram->telegramId()); + q.bindValue(QStringLiteral(":counter"), storedCentralTelegram->m_WriteCounter); + q.bindValue(QStringLiteral(":data"), storedCentralTelegram->m_RadioTelegram->data()); + q.exec(); + storedCentralTelegram->m_Id = q.lastInsertId().toInt(); + } + l.unlock(); + // DEBUG_LOG(m_logger) << "added new telegrams to db: " << m_telegramsToInsert.size(); + m_telegramsToInsert.clear(); + } + + + // update write counter for a telegramm + updateTelegramsWriteCounter(toCentralTableName()); + // DEBUG_LOG(m_logger) << "updated write counter in db: " << m_telegramsToUpdateCounter.size(); + + // Jetzt alle Telegramme löschen die von der Zentrale bestätigt worden + // da m_CentralAckCounter von anderen Threads geändert werden kann, kann es + // sein dass schon mehr Telegramme aus der DB gelöscht werden als vorher + // aus m_CentralList. Dies wird aber im nächsten Aufruf wieder korrigiert + const unsigned int centralAckCnt = static_cast(m_CentralAckCounter); + if (centralAckCnt > m_OldCentralAckCounter) + { + m_OldCentralAckCounter = centralAckCnt; + // wir arbeiten mit m_OldCentralAckCounter da sich m_CentralAckCounter + // währenddessen schon ändern kann + DEBUG_LOG(m_logger) << "Central delete all counter <= " << m_OldCentralAckCounter; + + NSqlQuery q(m_db); + q.exec(QStringLiteral("DELETE FROM %1 WHERE counter > 0 AND counter <= %2;").arg(toCentralTableName()).arg(m_OldCentralAckCounter)); + } + + // remove all telegrams which were manually marked for deletion + deleteTelegramsFromDbById(toCentralTableName()); + } + + int32_t PrtCnvDbThread::storeRadioTelegrams() + { + QMutexLocker l(&m_RadioListMutex); + + if (m_RadioList.empty()) + return 0; + + // M_DEBUG("Check for permanent actions on radio-list") + int32_t centralCounter = 0; + + NSqlQuery q(m_db); + q.prepare(QStringLiteral("INSERT INTO %1 (tel_id, counter, broadcast_index, reset_counter, data) " + "VALUES (:tel_id, :counter, :broadcast_index, :reset_counter, :data);") + .arg(toRadioTableName())); + + // DEBUG_LOG(m_logger) << "m_RadioList.size=" << m_RadioList.size(); + std::list::iterator radioIter = m_RadioList.begin(); + while (radioIter != m_RadioList.end()) + { + bool doDeleteThisItem = false; + PrtCnvStoredRadioTelegram *storedRadioTelegram = *radioIter; + const auto &radioTelegram = storedRadioTelegram->m_RadioTelegram; + + if (radioTelegram) + { + DEBUG_LOG(m_logger) << "Handling Radio-Telegram with id=" << storedRadioTelegram->m_Id << " TelID: " << radioTelegram->getTelID() + << " rc: " << int(radioTelegram->zaehler()) << " BC: " << storedRadioTelegram->m_BroadcastIndex + << " wc: " << int(storedRadioTelegram->m_WriteCounter); + + // store radio-telegrams permanent + // ------------------------------- + if (0 == storedRadioTelegram->m_Id) + { + if (storedRadioTelegram->m_ReadCounter > centralCounter) + centralCounter = storedRadioTelegram->m_ReadCounter; + + storedRadioTelegram->m_WriteCounterChanged = false; + q.bindValue(QStringLiteral(":tel_id"), radioTelegram->getTelID()); + q.bindValue(QStringLiteral(":counter"), storedRadioTelegram->m_WriteCounter); + q.bindValue(QStringLiteral(":broadcast_index"), storedRadioTelegram->m_BroadcastIndex); + q.bindValue(QStringLiteral(":reset_counter"), int(m_ResetCounter)); + q.bindValue(QStringLiteral(":data"), radioTelegram->data()); + q.exec(); + storedRadioTelegram->m_Id = q.lastInsertId().toInt(); + + DEBUG_LOG(m_logger) << "Stored Telegramm in DB, id: " << storedRadioTelegram->m_Id; + + // for broadcast-telegrams, we have 2 cases: + // 1. case: it will be written to DB, before it is sent to radio and then moved to broadcast-list of broadcast-manager + // 2. case: it will be sent to radio before it is written to DB. In this case we cannot remove it from m_RadioList until + // it is written to DB + // here we check whether case 2 has happenend + if (storedRadioTelegram->m_RadioTelegram->isMovedToBroadcastList()) + { + dumpTelegram(m_logger, radioTelegram->getBroadcastCounter(), storedRadioTelegram->m_RadioTelegram.get()); + DEBUG_LOG(m_logger) << "Removed Telegramm from radioList (place 1), id: " << storedRadioTelegram->m_Id; + doDeleteThisItem = true; + } + } + else + { + // delete all acked telegrams from radio-list + // ------------------------------------------ + // do we have to delete the radio-telegram in the list and DB? + // we do only delete if the telegram is stored permanent in db and therefore the ack to central is sent + if (storedRadioTelegram->m_DoDelete) + { + DEBUG_LOG(m_logger) << "Delete Telegramm from DB, id: " << storedRadioTelegram->m_Id; + m_telegramsToDelete.push_back(storedRadioTelegram->m_Id); + // delete the telegram in the list + delete storedRadioTelegram; + doDeleteThisItem = true; + } + // update write-counter for all sent radio-telegrams + // ------------------------------------------------- + else if (storedRadioTelegram->m_WriteCounterChanged) + { + m_telegramsToUpdateCounter.emplace_back(std::make_pair(storedRadioTelegram->m_Id, storedRadioTelegram->m_WriteCounter)); + if (storedRadioTelegram->m_BroadcastIndex) + m_telegramsToUpdateBC.emplace_back(std::make_pair(storedRadioTelegram->m_Id, storedRadioTelegram->m_BroadcastIndex)); + storedRadioTelegram->m_WriteCounterChanged = false; + + DEBUG_LOG(m_logger) << "Update Write counter in DB, id: " << storedRadioTelegram->m_Id << " New wc: " << int(storedRadioTelegram->m_WriteCounter) + << " new bc: " << storedRadioTelegram->m_BroadcastIndex; + + if (storedRadioTelegram->m_RadioTelegram->isMovedToBroadcastList()) + { + dumpTelegram(m_logger, storedRadioTelegram->m_BroadcastIndex, storedRadioTelegram->m_RadioTelegram.get()); + DEBUG_LOG(m_logger) << "Removed Telegramm from radioList (place 2), id: " << storedRadioTelegram->m_Id; + doDeleteThisItem = true; + } + } } } else { - // delete all acked telegrams from radio-list - // ------------------------------------------ - // do we have to delete the radio-telegram in the list and DB? - // we do only delete if the telegram is stored permanent in db and therefore the ack to central is sent - if (storedRadioTelegram->m_DoDelete) - { - DEBUG_LOG(m_logger) << "Delete Telegramm from DB, id: " << storedRadioTelegram->m_Id; - m_telegramsToDelete.push_back(storedRadioTelegram->m_Id); - // delete the telegram in the list - delete storedRadioTelegram; - doDeleteThisItem = true; - } - // update write-counter for all sent radio-telegrams - // ------------------------------------------------- - else if (storedRadioTelegram->m_WriteCounterChanged) - { - m_telegramsToUpdateCounter.emplace_back(std::make_pair(storedRadioTelegram->m_Id, - storedRadioTelegram->m_WriteCounter)); - if (storedRadioTelegram->m_BroadcastIndex) - m_telegramsToUpdateBC.emplace_back(std::make_pair(storedRadioTelegram->m_Id, - storedRadioTelegram->m_BroadcastIndex)); - storedRadioTelegram->m_WriteCounterChanged = false; - - DEBUG_LOG(m_logger) << "Update Write counter in DB, id: " << storedRadioTelegram->m_Id - << " New wc: " << int(storedRadioTelegram->m_WriteCounter) - << " new bc: " << storedRadioTelegram->m_BroadcastIndex; - - if (storedRadioTelegram->m_RadioTelegram->isMovedToBroadcastList()) - { - dumpTelegram(m_logger, - storedRadioTelegram->m_BroadcastIndex, - storedRadioTelegram->m_RadioTelegram.get()); - DEBUG_LOG(m_logger) << "Removed Telegramm from radioList (place 2), id: " << storedRadioTelegram->m_Id; - doDeleteThisItem = true; - } - } + // telegrams which will not be stored, but acked (i.e. Anforderung Nachforderungs Statistik) + if (storedRadioTelegram->m_ReadCounter > centralCounter) + centralCounter = storedRadioTelegram->m_ReadCounter; + delete storedRadioTelegram; + doDeleteThisItem = true; } + + if (doDeleteThisItem) + radioIter = m_RadioList.erase(radioIter); + else + ++radioIter; } - else + l.unlock(); + + // update write counter for a telegramm + static const QString &table = toRadioTableName(); + updateTelegramsWriteCounter(table); + // DEBUG_LOG(m_logger) << "updated write counter in db: " << m_telegramsToUpdateCounter.size(); + + // update BC for a telegramm + updateTelegramsBroadcast(table); + + // remove all telegrams which were manually marked for deletion + deleteTelegramsFromDbById(table); + + return centralCounter; + } + + void PrtCnvDbThread::handleSqlCommandList() + { + // M_DEBUG("Check for permanent actions on sql-command-list") + std::vector sqlCommandList; { - // telegrams which will not be stored, but acked (i.e. Anforderung Nachforderungs Statistik) - if (storedRadioTelegram->m_ReadCounter > centralCounter) - centralCounter = storedRadioTelegram->m_ReadCounter; - delete storedRadioTelegram; - doDeleteThisItem = true; + QMutexLocker l(&m_SqlCmdListMutex); + std::swap(m_SqlCommandList, sqlCommandList); } - if (doDeleteThisItem) - radioIter = m_RadioList.erase(radioIter); - else - ++radioIter; - } - l.unlock(); - - // update write counter for a telegramm - static const QString &table = toRadioTableName(); - updateTelegramsWriteCounter(table); - // DEBUG_LOG(m_logger) << "updated write counter in db: " << m_telegramsToUpdateCounter.size(); - - // update BC for a telegramm - updateTelegramsBroadcast(table); - - // remove all telegrams which were manually marked for deletion - deleteTelegramsFromDbById(table); - - return centralCounter; -} - -void PrtCnvDbThread::handleSqlCommandList() -{ - // M_DEBUG("Check for permanent actions on sql-command-list") - std::vector sqlCommandList; - { - QMutexLocker l(&m_SqlCmdListMutex); - std::swap(m_SqlCommandList, sqlCommandList); + if (sqlCommandList.empty()) + return; + NSqlQuery q(m_db); + for (const QString &sql : sqlCommandList) + { + DEBUG_LOG(m_logger) << "execute sql=" << sql; + q.exec(sql); + } } - if (sqlCommandList.empty()) - return; - NSqlQuery q(m_db); - for (const QString &sql : sqlCommandList) + // --------------------------------------------------------------- + // Stores the radio-telegrams, central-telegrams in Db and + // executes the sql-command-list. + // --------------------------------------------------------------- + void PrtCnvDbThread::storePermanent() { - DEBUG_LOG(m_logger) << "execute sql=" << sql; - q.exec(sql); - } -} + m_StorePermanentPending = 0; -// --------------------------------------------------------------- -// Stores the radio-telegrams, central-telegrams in Db and -// executes the sql-command-list. -// --------------------------------------------------------------- -void PrtCnvDbThread::storePermanent() -{ - m_StorePermanentPending = 0; + TRACE_LOG(m_logger) << "storePermanent m_DoClean=" << m_DoClean << " m_DoWaitUntilSqlWritten=" << m_DoWaitUntilSqlWritten; + if (m_DoClean) + { + m_DoWaitUntilSqlWritten = false; + return; + } - TRACE_LOG(m_logger) << "storePermanent m_DoClean=" << m_DoClean << " m_DoWaitUntilSqlWritten=" << m_DoWaitUntilSqlWritten; - if (m_DoClean) - { + // generate the sql-commands on permanent DB + // ----------------------------------------- + DBTransaction trans(m_db); + + // permanent DB-actions for central + // ================================ + storeCentralTelegrams(); + + // permanent DB-actions for radio + // ============================== + const int32_t centralCounter = storeRadioTelegrams(); + + // store the sql-commands (member) + // ====================== + handleSqlCommandList(); + + // ready + trans.commit(); + + // M_DEBUG("inform central-thread") + if (0 != centralCounter && centralCounter != m_OldCentralCounter) + { + m_OldCentralCounter = centralCounter; + emit permanentStored(centralCounter); + } m_DoWaitUntilSqlWritten = false; - return; + // M_DEBUG("End check for permanent actions") } - // generate the sql-commands on permanent DB - // ----------------------------------------- - DBTransaction trans(m_db); - // permanent DB-actions for central - // ================================ - storeCentralTelegrams(); - - // permanent DB-actions for radio - // ============================== - const int32_t centralCounter = storeRadioTelegrams(); - - // store the sql-commands (member) - // ====================== - handleSqlCommandList(); - - // ready - trans.commit(); - -// M_DEBUG("inform central-thread") - if (0 != centralCounter && centralCounter != m_OldCentralCounter) - { - m_OldCentralCounter = centralCounter; - emit permanentStored(centralCounter); - } - m_DoWaitUntilSqlWritten = false; -// M_DEBUG("End check for permanent actions") -} - - - -// --------------------------------------------------------------- -// Adds an sql-command in the sql-command-list. On next -// iteration of storePermanent() all command in list will be -// executed. -// --------------------------------------------------------------- -void PrtCnvDbThread::addSqlCommand(const QString &sql) -{ - QMutexLocker l(&m_SqlCmdListMutex); - m_SqlCommandList.push_back(sql); - - sendStorePermanentSignal(); -} - - - -// --------------------------------------------------------------- -// erases and initializes the database -// --------------------------------------------------------------- -void PrtCnvDbThread::cleanAndInit() -{ - // emit a signal to clean, so we can be sure that all pending signals are worked - m_DoClean = true; - emit doClean(); - // simply block until clean - while (m_DoClean) - QThread::sleep(1); - m_DoProceedCleanup = false; -} - - -// --------------------------------------------------------------- -// cleans up this thread and its childs -// --------------------------------------------------------------- -void PrtCnvDbThread::clean() -{ - NSqlQuery q(m_db); - INFO_LOG(m_logger) << "Delete CentralList"; - { - QMutexLocker l(&m_CentralListMutex); - for (PrtCnvStoredCentralTelegram *t : m_CentralList) - delete t; - m_CentralList.clear(); - q.exec(QStringLiteral("DELETE FROM %1;").arg(toCentralTableName())); - } - m_OldCentralCounter = 0; - - INFO_LOG(m_logger) << "Delete RadioList"; - m_EnvironmentTelegram = nullptr; - { - QMutexLocker l(&m_RadioListMutex); - for (PrtCnvStoredRadioTelegram *t : m_RadioList) - delete t; - m_RadioList.clear(); - q.exec(QStringLiteral("DELETE FROM %1;").arg(toRadioTableName())); - } - - INFO_LOG(m_logger) << "Delete BroadcastList"; - { - QMutexLocker l(&m_BroadcastMapMutex); - for (PrtCnvStoredRadioTelegram *t : m_BroadcastList) - delete t; - m_BroadcastList.clear(); - } - - // clean the members - // delete the member-maps + // --------------------------------------------------------------- + // Adds an sql-command in the sql-command-list. On next + // iteration of storePermanent() all command in list will be + // executed. + // --------------------------------------------------------------- + void PrtCnvDbThread::addSqlCommand(const QString &sql) { QMutexLocker l(&m_SqlCmdListMutex); - m_MemberListByISSI.clear(); - { - QMutexLocker l2(&m_MemberListByIdMutex); - for (const auto &p : m_MemberListById) - delete p.second; - m_MemberListById.clear(); - } - INFO_LOG(m_logger) << "Delete SqlList"; - m_SqlCommandList.clear(); - q.exec(QStringLiteral("DELETE FROM %1;").arg(memberTableName())); + m_SqlCommandList.push_back(sql); + + sendStorePermanentSignal(); } - // 'virtual' TNE for broadcasts - licenseMember(addMember(0, m_Config->getInteger(QStringLiteral("Radio"), QStringLiteral("BroadcastISSI"), 5000))); - m_DoClean = false; -} - - -// --------------------------------------------------------------- -// Checks whether central-telegrams have to be resent. If yes, -// all actions will be done, that getNextCentralTelegram() -// delivers the telegram(s) to be resent. -// Returns true if there must telegrams be resent. -// --------------------------------------------------------------- -bool PrtCnvDbThread::resendCentralTelegrams(const int32_t a_lastSendCounter) -{ - const int centralAckCnt = m_CentralAckCounter; - if (a_lastSendCounter > centralAckCnt) + // --------------------------------------------------------------- + // erases and initializes the database + // --------------------------------------------------------------- + void PrtCnvDbThread::cleanAndInit() { - bool warnOnce = true; - QMutexLocker l(&m_CentralListMutex); - int iCount = 0; - std::vector::const_iterator iter = m_CentralList.begin(); - std::vector::const_iterator end = m_CentralList.end(); - for (; iter != end && iCount < 50; ++iter) - { - PrtCnvStoredCentralTelegram *storedTelegram = *iter; - if (!storedTelegram) - continue; - ++iCount; - if (storedTelegram->m_WriteCounter > centralAckCnt) - { - if (warnOnce) - { - WARNING_LOG(m_logger) << "Resend central-telegrams from wc=" << a_lastSendCounter - << " centralAckCounter=" << centralAckCnt; - warnOnce = false; - } - INFO_LOG(m_logger) << "Resend central-telegram with telId=" - << storedTelegram->m_CentralTelegram->telegramId() - << " wc=" << storedTelegram->m_WriteCounter; - storedTelegram->m_DoResend = true; - } - } - return true; - } - return false; -} - - - -// --------------------------------------------------------------- -// Prepares the telegrams not yet acked from central for -// reconnection. This will be done by setting the write- -// counter to 0. -// --------------------------------------------------------------- -void PrtCnvDbThread::prepareCentralTelegramsForReconnection() -{ - INFO_LOG(m_logger) << "m_CentralAckCounter=" << m_CentralAckCounter; - waitUntilDbWritten(); - - INFO_LOG(m_logger) << "start"; - m_CentralAckCounter = 0; - m_OldCentralAckCounter = 0; - m_OldCentralCounter = 0; - QMutexLocker l(&m_CentralListMutex); - for (PrtCnvStoredCentralTelegram *storedTelegram : m_CentralList) - { - if (!storedTelegram) - continue; - if (storedTelegram->m_WriteCounter != 0) - { - INFO_LOG(m_logger) << "***Prepare central-telegram with id=" << storedTelegram->m_Id - << " telId=" << storedTelegram->m_CentralTelegram->telegramId() - << " wc=" << storedTelegram->m_WriteCounter << " wcChg=" - << storedTelegram->m_WriteCounterChanged - << " for resend after reconnection"; - storedTelegram->m_WriteCounter = 0; - storedTelegram->m_WriteCounterChanged = false; - storedTelegram->m_DoResend = false; - } - } - INFO_LOG(m_logger) << "Ready for reconnection"; -} - - -// --------------------------------------------------------------- -// Blocks until all SQL-commands were written to DB. -// --------------------------------------------------------------- -void PrtCnvDbThread::waitUntilDbWritten() -{ - m_DoWaitUntilSqlWritten = true; - emit doStorePermanent(); - while (m_DoWaitUntilSqlWritten) - QThread::usleep(10000); // 10 ms - - // we have to do this twice, to be sure - m_DoWaitUntilSqlWritten = true; - emit doStorePermanent(); - while (m_DoWaitUntilSqlWritten) - QThread::usleep(10000); // 10 ms -} - - - -// --------------------------------------------------------------- -// adds a member in the 2 maps, sorted by id and ISSI -// returns the new member -// --------------------------------------------------------------- -PrtCnv::PrtCnvMember *PrtCnvDbThread::addMember(const int a_identity, const int a_ISSI) -{ - PrtCnvMember *newMember = new PrtCnvMember(a_identity, a_ISSI); - { - QMutexLocker lSql(&m_SqlCmdListMutex); - QMutexLocker lId(&m_MemberListByIdMutex); - m_MemberListById.insert(std::make_pair(a_identity, newMember)); - m_MemberListByISSI.insert(std::make_pair(a_ISSI, newMember)); + // emit a signal to clean, so we can be sure that all pending signals are worked + m_DoClean = true; + emit doClean(); + // simply block until clean + while (m_DoClean) + QThread::sleep(1); + m_DoProceedCleanup = false; } - DEBUG_LOG(m_logger) << "Adding member with eqId " << a_identity - << " and issi " << a_ISSI - << ", store in db: " << m_DoStorePermanent; - // add also permanent in DB - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("INSERT INTO %1 (id, issi) VALUES(%2, %3)") - .arg(memberTableName()).arg(newMember->m_Id).arg(newMember->m_ISSI)); - return newMember; -} - - -// --------------------------------------------------------------- -// removes the member in the 2 maps, sorted by id and ISSI -// --------------------------------------------------------------- -void PrtCnvDbThread::removeMember(PrtCnv::PrtCnvMember *a_member) -{ - { - QMutexLocker lSql(&m_SqlCmdListMutex); - QMutexLocker lId(&m_MemberListByIdMutex); - auto iterId = m_MemberListById.find(a_member->m_Id); - if (iterId != m_MemberListById.end()) - m_MemberListById.erase(iterId); - else - ERROR_LOG(m_logger) << "Internal error: did not find the member by ID"; - auto iterIssi = m_MemberListByISSI.find(a_member->m_ISSI); - if (iterIssi != m_MemberListByISSI.end()) - m_MemberListByISSI.erase(iterIssi); - else - ERROR_LOG(m_logger) << "Internal error: did not find the member by ISSI"; - } - - DEBUG_LOG(m_logger) << "Removing member with eqId " << a_member->m_Id - << " and issi " << a_member->m_ISSI - << ", store in db: " << m_DoStorePermanent; - // remove also permanent in DB - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("DELETE FROM %1 WHERE id = %2 OR issi = %3") - .arg(memberTableName()).arg(a_member->m_Id).arg(a_member->m_ISSI)); - - delete a_member; -} - - -// --------------------------------------------------------------- -// Licenses the member -// --------------------------------------------------------------- -bool PrtCnvDbThread::licenseMember(PrtCnvMember *a_member, const bool a_doLicense) -{ - if (!a_member) - return false; - a_member->m_Licensed = a_doLicense; - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("UPDATE %1 SET licensed = %2 WHERE id = %3") - .arg(memberTableName()).arg(a_doLicense ? 1 : 0).arg(a_member->m_Id)); - return true; -} - -void PrtCnvDbThread::updateExerciseIdForMember(PrtCnvMember *a_member, int newExerciseId) -{ - if (!a_member) - return; - a_member->m_loggedInExerciseId = newExerciseId; - DEBUG_LOG(m_logger) << "Updating exerciseId member with eqId " << a_member->m_Id - << " and issi " << a_member->m_ISSI << " to " << newExerciseId - << ", store in db: " << m_DoStorePermanent; - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("UPDATE %1 SET exercise_id = %2 WHERE id = %3") - .arg(memberTableName()).arg(newExerciseId).arg(a_member->m_Id)); -} - - -// --------------------------------------------------------------- -// returns NULL if member not found -// --------------------------------------------------------------- -PrtCnv::PrtCnvMember *PrtCnvDbThread::getMemberById(const uint16_t a_id) -{ - QMutexLocker l(&m_MemberListByIdMutex); - auto iter = m_MemberListById.find(a_id); - if (iter != m_MemberListById.end()) - return iter->second; - - return nullptr; // no member found -} - - -// --------------------------------------------------------------- -// returns NULL if no member found -// --------------------------------------------------------------- -PrtCnv::PrtCnvMember *PrtCnvDbThread::getMemberByISSI(const uint32_t a_ISSI) const -{ - auto iter = m_MemberListByISSI.find(a_ISSI); - if (iter != m_MemberListByISSI.end()) - return iter->second; - - return nullptr; -} - - - -// --------------------------------------------------------------- -// Returns the actual reset-counter -// --------------------------------------------------------------- -uint8_t PrtCnvDbThread::getResetCounter() const -{ - return m_ResetCounter; -} - - -// --------------------------------------------------------------- -// Sets the actual reset-counter -// --------------------------------------------------------------- -void PrtCnvDbThread::setResetCounter(uint8_t newVal) -{ - m_ResetCounter = newVal; - if (m_DoStorePermanent) + // --------------------------------------------------------------- + // cleans up this thread and its childs + // --------------------------------------------------------------- + void PrtCnvDbThread::clean() { NSqlQuery q(m_db); - q.exec(QStringLiteral("UPDATE Status SET reset_counter = %1 WHERE id = 1") - .arg(int(newVal))); + INFO_LOG(m_logger) << "Delete CentralList"; + { + QMutexLocker l(&m_CentralListMutex); + for (PrtCnvStoredCentralTelegram *t : m_CentralList) + delete t; + m_CentralList.clear(); + q.exec(QStringLiteral("DELETE FROM %1;").arg(toCentralTableName())); + } + m_OldCentralCounter = 0; + + INFO_LOG(m_logger) << "Delete RadioList"; + m_EnvironmentTelegram = nullptr; + { + QMutexLocker l(&m_RadioListMutex); + for (PrtCnvStoredRadioTelegram *t : m_RadioList) + delete t; + m_RadioList.clear(); + q.exec(QStringLiteral("DELETE FROM %1;").arg(toRadioTableName())); + } + + INFO_LOG(m_logger) << "Delete BroadcastList"; + { + QMutexLocker l(&m_BroadcastMapMutex); + for (PrtCnvStoredRadioTelegram *t : m_BroadcastList) + delete t; + m_BroadcastList.clear(); + } + + // clean the members + // delete the member-maps + { + QMutexLocker l(&m_SqlCmdListMutex); + m_MemberListByISSI.clear(); + { + QMutexLocker l2(&m_MemberListByIdMutex); + for (const auto &p : m_MemberListById) + delete p.second; + m_MemberListById.clear(); + } + INFO_LOG(m_logger) << "Delete SqlList"; + m_SqlCommandList.clear(); + q.exec(QStringLiteral("DELETE FROM %1;").arg(memberTableName())); + } + + // 'virtual' TNE for broadcasts + licenseMember(addMember(0, m_Config->getInteger(QStringLiteral("Radio"), QStringLiteral("BroadcastISSI"), 5000))); + + m_DoClean = false; } - INFO_LOG(m_logger) << "Update resetCounter=" << (int)m_ResetCounter << " doStorePermanent=" << m_DoStorePermanent; -} -// --------------------------------------------------------------- -// The actual 'Betriebszustände Gefechtsfeld' which will be -// sent to TNEs periodically -// --------------------------------------------------------------- -uint8_t PrtCnvDbThread::getBattleFieldOperatingState() const -{ - QMutexLocker l(&m_BattleFieldOpStateMutex); - - return m_BattleFieldOperatingState; -} - - -// --------------------------------------------------------------- -// Sets or unsets pause, depending on a_doSet. -// --------------------------------------------------------------- -void PrtCnvDbThread::setPause(const bool a_doSet) -{ - QMutexLocker l(&m_BattleFieldOpStateMutex); - - if (a_doSet) - m_BattleFieldOperatingState = m_BattleFieldOperatingState | 0x80; // pause - else - m_BattleFieldOperatingState = m_BattleFieldOperatingState & 0x7F; // no pause - - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("UPDATE %1 SET ctas_operating_state = %2 WHERE id = 1") - .arg(statusTableName()).arg(int(m_BattleFieldOperatingState))); - - INFO_LOG(m_logger) << "Update battleFieldOperatingState=" << (int)m_BattleFieldOperatingState << " doStorePermanent=" << m_DoStorePermanent; -} - -// --------------------------------------------------------------- -// Set the inhibit time for position telegrams (1 .. 31 Seconds) -// --------------------------------------------------------------- -void PrtCnvDbThread::setPositionSendTime(unsigned int sendTime) -{ - QMutexLocker l(&m_BattleFieldOpStateMutex); - - if (sendTime > 31) - sendTime = 31; - if (sendTime < 1) - sendTime = 1; - - // mode zurücksetzen (Bits 2 - 6) - m_BattleFieldOperatingState &= 0x83; - // und neu setzen - m_BattleFieldOperatingState |= (sendTime << 2); -} - -// --------------------------------------------------------------- -// Set the current air load to be sent with the Umgebungsmeldung -// --------------------------------------------------------------- -void PrtCnvDbThread::setAirLoad(PrtCnvRadioThread::E_TrafficLoad airLoad) -{ - QMutexLocker l(&m_BattleFieldOpStateMutex); - - // mode zurücksetzen - m_BattleFieldOperatingState &= 0xFC; - // und neu setzen - m_BattleFieldOperatingState |= (static_cast(airLoad) & 0x03); -} - -// --------------------------------------------------------------- -// Returns true if the resetCounter itself is different than -// the reset-counter of the environment-telegram -// --------------------------------------------------------------- -bool PrtCnvDbThread::isEnvironmentResetCounterOld() const -{ - QMutexLocker l(&m_RadioListMutex); - - bool isOld = false; - if (m_EnvironmentTelegram) - isOld = getResetCounter() != m_EnvironmentTelegram->m_RadioTelegram->getPayloadDataUInt8(7); - return isOld; -} - -// --------------------------------------------------------------- -// Sets the resetcounter of the environment-telegram to the -// actual reset-counter. -// --------------------------------------------------------------- -void PrtCnvDbThread::setResetCounterOnEnvironment() -{ - QMutexLocker l(&m_RadioListMutex); - - if (m_EnvironmentTelegram) - m_EnvironmentTelegram->m_RadioTelegram->setPayloadDataWithIndex(7, getResetCounter(), 1); -} - -// --------------------------------------------------------------- -// Returns the actual Umgebungsmeldung -// --------------------------------------------------------------- -std::shared_ptr PrtCnvDbThread::getEnvironmentTelegram() -{ - QMutexLocker l(&m_RadioListMutex); - if (m_EnvironmentTelegram) - return std::make_shared(m_EnvironmentTelegram->m_RadioTelegram->data()); - return {}; -} - -// --------------------------------------------------------------- -// Fills the map with nachforderungsstatistic. -// Returns the number of elements in map. -// --------------------------------------------------------------- -std::map PrtCnvDbThread::getClaimStatistics() const -{ - std::map ret; - QMutexLocker l(&m_MemberListByIdMutex); - for (const auto &p : m_MemberListById) + // --------------------------------------------------------------- + // Checks whether central-telegrams have to be resent. If yes, + // all actions will be done, that getNextCentralTelegram() + // delivers the telegram(s) to be resent. + // Returns true if there must telegrams be resent. + // --------------------------------------------------------------- + bool PrtCnvDbThread::resendCentralTelegrams(const int32_t a_lastSendCounter) { - if (p.first != 0) - ret.insert(std::make_pair(p.first, p.second->m_ClaimCount)); + const int centralAckCnt = m_CentralAckCounter; + if (a_lastSendCounter > centralAckCnt) + { + bool warnOnce = true; + QMutexLocker l(&m_CentralListMutex); + int iCount = 0; + std::vector::const_iterator iter = m_CentralList.begin(); + std::vector::const_iterator end = m_CentralList.end(); + for (; iter != end && iCount < 50; ++iter) + { + PrtCnvStoredCentralTelegram *storedTelegram = *iter; + if (!storedTelegram) + continue; + ++iCount; + if (storedTelegram->m_WriteCounter > centralAckCnt) + { + if (warnOnce) + { + WARNING_LOG(m_logger) << "Resend central-telegrams from wc=" << a_lastSendCounter << " centralAckCounter=" << centralAckCnt; + warnOnce = false; + } + INFO_LOG(m_logger) << "Resend central-telegram with telId=" << storedTelegram->m_CentralTelegram->telegramId() << " wc=" << storedTelegram->m_WriteCounter; + storedTelegram->m_DoResend = true; + } + } + return true; + } + return false; } - return ret; -} -// --------------------------------------------------------------- -// Increments the counter for nachforderungen of the TNE with -// id a_identity. -// --------------------------------------------------------------- -void PrtCnvDbThread::incClaimCount(int a_identity) -{ - QMutexLocker l(&m_MemberListByIdMutex); - auto iter = m_MemberListById.find(a_identity); - if (iter != m_MemberListById.end()) + // --------------------------------------------------------------- + // Prepares the telegrams not yet acked from central for + // reconnection. This will be done by setting the write- + // counter to 0. + // --------------------------------------------------------------- + void PrtCnvDbThread::prepareCentralTelegramsForReconnection() { - iter->second->m_ClaimCount++; - if (m_DoStorePermanent) - addSqlCommand(QStringLiteral("UPDATE %1 SET claims = claims + 1 WHERE id = %2") - .arg(memberTableName()).arg(iter->second->m_Id)); + INFO_LOG(m_logger) << "m_CentralAckCounter=" << m_CentralAckCounter; + waitUntilDbWritten(); + + INFO_LOG(m_logger) << "start"; + m_CentralAckCounter = 0; + m_OldCentralAckCounter = 0; + m_OldCentralCounter = 0; + QMutexLocker l(&m_CentralListMutex); + for (PrtCnvStoredCentralTelegram *storedTelegram : m_CentralList) + { + if (!storedTelegram) + continue; + if (storedTelegram->m_WriteCounter != 0) + { + INFO_LOG(m_logger) << "***Prepare central-telegram with id=" << storedTelegram->m_Id << " telId=" << storedTelegram->m_CentralTelegram->telegramId() + << " wc=" << storedTelegram->m_WriteCounter << " wcChg=" << storedTelegram->m_WriteCounterChanged << " for resend after reconnection"; + storedTelegram->m_WriteCounter = 0; + storedTelegram->m_WriteCounterChanged = false; + storedTelegram->m_DoResend = false; + } + } + INFO_LOG(m_logger) << "Ready for reconnection"; } - else - ERROR_LOG(m_logger) << "Internal error: did not find TNE with id=" << a_identity; -} - - -// --------------------------------------------------------------- -// Sets the actual machine-state permanent, used to proceed -// cleaning db after a crash. -// --------------------------------------------------------------- -void PrtCnvDbThread::setMachineState(const int a_newMachineState) -{ - NSqlQuery q(m_db); - q.exec(QStringLiteral("UPDATE %1 SET machine_state = %2 WHERE id = 1") - .arg(statusTableName()).arg(a_newMachineState)); -} - - - -// --------------------------------------------------------------- -// Returns true if protocol-converter was crashed while -// cleanup DB. -// --------------------------------------------------------------- -bool PrtCnvDbThread::mustProceedCleanup() const -{ - return m_DoProceedCleanup; -} - - - -// --------------------------------------------------------------- -// Sends a signal storePermanent if not already such a signal -// is pending -// --------------------------------------------------------------- -void PrtCnvDbThread::sendStorePermanentSignal() -{ - if (m_StorePermanentPending.testAndSetOrdered(0, 1)) + // --------------------------------------------------------------- + // Blocks until all SQL-commands were written to DB. + // --------------------------------------------------------------- + void PrtCnvDbThread::waitUntilDbWritten() + { + m_DoWaitUntilSqlWritten = true; emit doStorePermanent(); -} + while (m_DoWaitUntilSqlWritten) + QThread::usleep(10000); // 10 ms -void PrtCnvDbThread::closeDb() -{ - if (m_db.isOpen()) + // we have to do this twice, to be sure + m_DoWaitUntilSqlWritten = true; + emit doStorePermanent(); + while (m_DoWaitUntilSqlWritten) + QThread::usleep(10000); // 10 ms + } + + + // --------------------------------------------------------------- + // adds a member in the 2 maps, sorted by id and ISSI + // returns the new member + // --------------------------------------------------------------- + PrtCnv::PrtCnvMember *PrtCnvDbThread::addMember(const int a_identity, const int a_ISSI) { - m_db.close(); - m_db = QSqlDatabase(); - QSqlDatabase::removeDatabase(QStringLiteral("PrtCnv")); + PrtCnvMember *newMember = new PrtCnvMember(a_identity, a_ISSI); + { + QMutexLocker lSql(&m_SqlCmdListMutex); + QMutexLocker lId(&m_MemberListByIdMutex); + m_MemberListById.insert(std::make_pair(a_identity, newMember)); + m_MemberListByISSI.insert(std::make_pair(a_ISSI, newMember)); + } + + DEBUG_LOG(m_logger) << "Adding member with eqId " << a_identity << " and issi " << a_ISSI << ", store in db: " << m_DoStorePermanent; + // add also permanent in DB + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("INSERT INTO %1 (id, issi) VALUES(%2, %3)").arg(memberTableName()).arg(newMember->m_Id).arg(newMember->m_ISSI)); + + return newMember; + } + + + // --------------------------------------------------------------- + // removes the member in the 2 maps, sorted by id and ISSI + // --------------------------------------------------------------- + void PrtCnvDbThread::removeMember(PrtCnv::PrtCnvMember *a_member) + { + { + QMutexLocker lSql(&m_SqlCmdListMutex); + QMutexLocker lId(&m_MemberListByIdMutex); + auto iterId = m_MemberListById.find(a_member->m_Id); + if (iterId != m_MemberListById.end()) + m_MemberListById.erase(iterId); + else + ERROR_LOG(m_logger) << "Internal error: did not find the member by ID"; + auto iterIssi = m_MemberListByISSI.find(a_member->m_ISSI); + if (iterIssi != m_MemberListByISSI.end()) + m_MemberListByISSI.erase(iterIssi); + else + ERROR_LOG(m_logger) << "Internal error: did not find the member by ISSI"; + } + + DEBUG_LOG(m_logger) << "Removing member with eqId " << a_member->m_Id << " and issi " << a_member->m_ISSI << ", store in db: " << m_DoStorePermanent; + // remove also permanent in DB + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("DELETE FROM %1 WHERE id = %2 OR issi = %3").arg(memberTableName()).arg(a_member->m_Id).arg(a_member->m_ISSI)); + + delete a_member; + } + + + // --------------------------------------------------------------- + // Licenses the member + // --------------------------------------------------------------- + bool PrtCnvDbThread::licenseMember(PrtCnvMember *a_member, const bool a_doLicense) + { + if (!a_member) + return false; + a_member->m_Licensed = a_doLicense; + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("UPDATE %1 SET licensed = %2 WHERE id = %3").arg(memberTableName()).arg(a_doLicense ? 1 : 0).arg(a_member->m_Id)); + return true; + } + + void PrtCnvDbThread::updateExerciseIdForMember(PrtCnvMember *a_member, int newExerciseId) + { + if (!a_member) + return; + a_member->m_loggedInExerciseId = newExerciseId; + DEBUG_LOG(m_logger) << "Updating exerciseId member with eqId " << a_member->m_Id << " and issi " << a_member->m_ISSI << " to " << newExerciseId + << ", store in db: " << m_DoStorePermanent; + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("UPDATE %1 SET exercise_id = %2 WHERE id = %3").arg(memberTableName()).arg(newExerciseId).arg(a_member->m_Id)); + } + + + // --------------------------------------------------------------- + // returns NULL if member not found + // --------------------------------------------------------------- + PrtCnv::PrtCnvMember *PrtCnvDbThread::getMemberById(const uint16_t a_id) + { + QMutexLocker l(&m_MemberListByIdMutex); + auto iter = m_MemberListById.find(a_id); + if (iter != m_MemberListById.end()) + return iter->second; + + return nullptr; // no member found + } + + + // --------------------------------------------------------------- + // returns NULL if no member found + // --------------------------------------------------------------- + PrtCnv::PrtCnvMember *PrtCnvDbThread::getMemberByISSI(const uint32_t a_ISSI) const + { + auto iter = m_MemberListByISSI.find(a_ISSI); + if (iter != m_MemberListByISSI.end()) + return iter->second; + + return nullptr; + } + + + // --------------------------------------------------------------- + // Returns the actual reset-counter + // --------------------------------------------------------------- + uint8_t PrtCnvDbThread::getResetCounter() const + { + return m_ResetCounter; + } + + + // --------------------------------------------------------------- + // Sets the actual reset-counter + // --------------------------------------------------------------- + void PrtCnvDbThread::setResetCounter(uint8_t newVal) + { + m_ResetCounter = newVal; + if (m_DoStorePermanent) + { + NSqlQuery q(m_db); + q.exec(QStringLiteral("UPDATE Status SET reset_counter = %1 WHERE id = 1").arg(int(newVal))); + } + INFO_LOG(m_logger) << "Update resetCounter=" << (int)m_ResetCounter << " doStorePermanent=" << m_DoStorePermanent; + } + + + // --------------------------------------------------------------- + // The actual 'Betriebszustände Gefechtsfeld' which will be + // sent to TNEs periodically + // --------------------------------------------------------------- + uint8_t PrtCnvDbThread::getBattleFieldOperatingState() const + { + QMutexLocker l(&m_BattleFieldOpStateMutex); + + return m_BattleFieldOperatingState; + } + + + // --------------------------------------------------------------- + // Sets or unsets pause, depending on a_doSet. + // --------------------------------------------------------------- + void PrtCnvDbThread::setPause(const bool a_doSet) + { + QMutexLocker l(&m_BattleFieldOpStateMutex); + + if (a_doSet) + m_BattleFieldOperatingState = m_BattleFieldOperatingState | 0x80; // pause + else + m_BattleFieldOperatingState = m_BattleFieldOperatingState & 0x7F; // no pause + + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("UPDATE %1 SET ctas_operating_state = %2 WHERE id = 1").arg(statusTableName()).arg(int(m_BattleFieldOperatingState))); + + INFO_LOG(m_logger) << "Update battleFieldOperatingState=" << (int)m_BattleFieldOperatingState << " doStorePermanent=" << m_DoStorePermanent; + } + + // --------------------------------------------------------------- + // Set the inhibit time for position telegrams (1 .. 31 Seconds) + // --------------------------------------------------------------- + void PrtCnvDbThread::setPositionSendTime(unsigned int sendTime) + { + QMutexLocker l(&m_BattleFieldOpStateMutex); + + if (sendTime > 31) + sendTime = 31; + if (sendTime < 1) + sendTime = 1; + + // mode zurücksetzen (Bits 2 - 6) + m_BattleFieldOperatingState &= 0x83; + // und neu setzen + m_BattleFieldOperatingState |= (sendTime << 2); + } + + // --------------------------------------------------------------- + // Set the current air load to be sent with the Umgebungsmeldung + // --------------------------------------------------------------- + void PrtCnvDbThread::setAirLoad(PrtCnvRadioThread::E_TrafficLoad airLoad) + { + QMutexLocker l(&m_BattleFieldOpStateMutex); + + // mode zurücksetzen + m_BattleFieldOperatingState &= 0xFC; + // und neu setzen + m_BattleFieldOperatingState |= (static_cast(airLoad) & 0x03); + } + + // --------------------------------------------------------------- + // Returns true if the resetCounter itself is different than + // the reset-counter of the environment-telegram + // --------------------------------------------------------------- + bool PrtCnvDbThread::isEnvironmentResetCounterOld() const + { + QMutexLocker l(&m_RadioListMutex); + + bool isOld = false; + if (m_EnvironmentTelegram) + isOld = getResetCounter() != m_EnvironmentTelegram->m_RadioTelegram->getPayloadDataUInt8(7); + return isOld; + } + + // --------------------------------------------------------------- + // Sets the resetcounter of the environment-telegram to the + // actual reset-counter. + // --------------------------------------------------------------- + void PrtCnvDbThread::setResetCounterOnEnvironment() + { + QMutexLocker l(&m_RadioListMutex); + + if (m_EnvironmentTelegram) + m_EnvironmentTelegram->m_RadioTelegram->setPayloadDataWithIndex(7, getResetCounter(), 1); + } + + // --------------------------------------------------------------- + // Returns the actual Umgebungsmeldung + // --------------------------------------------------------------- + std::shared_ptr PrtCnvDbThread::getEnvironmentTelegram() + { + QMutexLocker l(&m_RadioListMutex); + if (m_EnvironmentTelegram) + return std::make_shared(m_EnvironmentTelegram->m_RadioTelegram->data()); + return {}; + } + + // --------------------------------------------------------------- + // Fills the map with nachforderungsstatistic. + // Returns the number of elements in map. + // --------------------------------------------------------------- + std::map PrtCnvDbThread::getClaimStatistics() const + { + std::map ret; + QMutexLocker l(&m_MemberListByIdMutex); + for (const auto &p : m_MemberListById) + { + if (p.first != 0) + ret.insert(std::make_pair(p.first, p.second->m_ClaimCount)); + } + return ret; + } + + + // --------------------------------------------------------------- + // Increments the counter for nachforderungen of the TNE with + // id a_identity. + // --------------------------------------------------------------- + void PrtCnvDbThread::incClaimCount(int a_identity) + { + QMutexLocker l(&m_MemberListByIdMutex); + auto iter = m_MemberListById.find(a_identity); + if (iter != m_MemberListById.end()) + { + iter->second->m_ClaimCount++; + if (m_DoStorePermanent) + addSqlCommand(QStringLiteral("UPDATE %1 SET claims = claims + 1 WHERE id = %2").arg(memberTableName()).arg(iter->second->m_Id)); + } + else + ERROR_LOG(m_logger) << "Internal error: did not find TNE with id=" << a_identity; + } + + + // --------------------------------------------------------------- + // Sets the actual machine-state permanent, used to proceed + // cleaning db after a crash. + // --------------------------------------------------------------- + void PrtCnvDbThread::setMachineState(const int a_newMachineState) + { + NSqlQuery q(m_db); + q.exec(QStringLiteral("UPDATE %1 SET machine_state = %2 WHERE id = 1").arg(statusTableName()).arg(a_newMachineState)); + } + + + // --------------------------------------------------------------- + // Returns true if protocol-converter was crashed while + // cleanup DB. + // --------------------------------------------------------------- + bool PrtCnvDbThread::mustProceedCleanup() const + { + return m_DoProceedCleanup; + } + + + // --------------------------------------------------------------- + // Sends a signal storePermanent if not already such a signal + // is pending + // --------------------------------------------------------------- + void PrtCnvDbThread::sendStorePermanentSignal() + { + if (m_StorePermanentPending.testAndSetOrdered(0, 1)) + emit doStorePermanent(); + } + + void PrtCnvDbThread::closeDb() + { + if (m_db.isOpen()) + { + m_db.close(); + m_db = QSqlDatabase(); + QSqlDatabase::removeDatabase(QStringLiteral("PrtCnv")); + } } -} } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.hpp index 4b0960a18..ab9a99e46 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvDbThread.hpp @@ -37,7 +37,7 @@ namespace PrtCnv class PrtCnvStoredCentralTelegram; class PrtCnvStoredRadioTelegram; class PrtCnvMember; - /** + /** * Handles all data which must be stored permanent: * - central-telegrams * - radio-telegrams @@ -65,7 +65,7 @@ namespace PrtCnv const QString &schemaName, const QString &dbUserName, const QString &dbPassword, - PrtCnvThreadStarter* a_parent); + PrtCnvThreadStarter *a_parent); ~PrtCnvDbThread(); /** @@ -100,7 +100,7 @@ namespace PrtCnv * * @param a_handle */ - N_CoPrtCnv::CoPrtCnvCentralTelegram *getNextCentralTelegram(PrtCnvStoredCentralTelegram *& a_handle); + N_CoPrtCnv::CoPrtCnvCentralTelegram *getNextCentralTelegram(PrtCnvStoredCentralTelegram *&a_handle); /** * Marks the central-telegram as to be sent @@ -158,8 +158,7 @@ namespace PrtCnv * @param a_radioTelegram Must be the same telegram like the central-telegram * (used for storing the telegram in Db) */ - void storeCentralTelegram(const std::shared_ptr &a_centralTelegram, - const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram); + void storeCentralTelegram(const std::shared_ptr &a_centralTelegram, const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram); /** * Stores the telegram to be sent to radio in working-list and also in Db. @@ -220,14 +219,14 @@ namespace PrtCnv * * @param a_ISSI */ - PrtCnvMember* getMemberByISSI(const uint32_t a_ISSI) const; + PrtCnvMember *getMemberByISSI(const uint32_t a_ISSI) const; /** * returns NULL if member not found * * @param a_id */ - PrtCnvMember* getMemberById(const uint16_t a_id); + PrtCnvMember *getMemberById(const uint16_t a_id); /** * Licenses the member @@ -249,14 +248,14 @@ namespace PrtCnv * @param a_identity * @param a_ISSI */ - PrtCnvMember* addMember(const int a_identity, const int a_ISSI); + PrtCnvMember *addMember(const int a_identity, const int a_ISSI); /** * removes the member in the 2 maps, sorted by id and ISSI * * @param a_member */ - void removeMember(PrtCnvMember* a_member); + void removeMember(PrtCnvMember *a_member); /** * Returns the actual reset-counter @@ -349,17 +348,14 @@ namespace PrtCnv /** * List of telegrams to be sent to central */ - std::vector m_CentralList; + std::vector m_CentralList; - mutable QRecursiveMutex m_BattleFieldOpStateMutex; - mutable QRecursiveMutex m_MemberListByIdMutex; - mutable QRecursiveMutex m_CentralListMutex; @@ -380,22 +376,22 @@ namespace PrtCnv /** * List of telegrams to be sent to radio */ - std::list m_RadioList; - + std::list m_RadioList; + mutable QRecursiveMutex m_RadioListMutex; - + std::vector m_SqlCommandList; - + mutable QRecursiveMutex m_SqlCmdListMutex; - + mutable QRecursiveMutex m_BroadcastMapMutex; - - std::list m_BroadcastList; + + std::list m_BroadcastList; /** * Used to wait until cleaning is finished and to suppress storing data within * database while cleaning @@ -408,11 +404,11 @@ namespace PrtCnv /** * Holds all logged in members ordered by Id. */ - std::unordered_map m_MemberListById; + std::unordered_map m_MemberListById; /** * Holds all logged in members ordered by ISSI */ - std::unordered_map m_MemberListByISSI; + std::unordered_map m_MemberListByISSI; /** * Used to prevent data storing within DB while restoring after crash */ @@ -429,7 +425,7 @@ namespace PrtCnv /** * The actual telegram "Umgebungsmeldung" */ - PrtCnvStoredRadioTelegram* m_EnvironmentTelegram; + PrtCnvStoredRadioTelegram *m_EnvironmentTelegram; /** * True if cleanup has to be proceed after crash. */ @@ -537,9 +533,9 @@ namespace PrtCnv // note: std::vector.clear() does not release memory and therefore // a reallocation in the next turn is not neccessary std::vector m_telegramsToDelete; - std::vector > m_telegramsToUpdateCounter; - std::vector > m_telegramsToUpdateBC; - std::vector > m_telegramsToInsert; + std::vector> m_telegramsToUpdateCounter; + std::vector> m_telegramsToUpdateBC; + std::vector> m_telegramsToInsert; QString m_dbDriver; QString m_dbHostName; QString m_dbDatabaseName; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.cpp index 2e5e78ecb..8f7b65520 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.cpp @@ -22,64 +22,63 @@ namespace PrtCnv { -PrtCnvInjectionSocket::PrtCnvInjectionSocket() - : m_Socket(nullptr) - , m_Server(nullptr) - , m_logger(getLogger("PrtCnvInjectionSocket")) -{} - -PrtCnvInjectionSocket::~PrtCnvInjectionSocket() -{ - delete m_Socket; -} - -// --------------------------------------------------------------- -// Disconnects a TCP-client -// --------------------------------------------------------------- -void PrtCnvInjectionSocket::disconnectClient() -{ - INFO_LOG(m_logger) << "A client has disconnected from the injection-server"; - emit disconnected(this); -} - - -// --------------------------------------------------------------- -// Reads in TCP-data and handles them -// --------------------------------------------------------------- -void PrtCnvInjectionSocket::processInputData() -{ - INFO_LOG(m_logger) << "Injection-server has data received"; - N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader; - qint64 bytesRead = m_Socket->peek((char*)&injectionHeader, sizeof(injectionHeader)); - if (sizeof(injectionHeader) == bytesRead) + PrtCnvInjectionSocket::PrtCnvInjectionSocket() + : m_Socket(nullptr) + , m_Server(nullptr) + , m_logger(getLogger("PrtCnvInjectionSocket")) { - if (injectionHeader.isIdCorrect()) + } + + PrtCnvInjectionSocket::~PrtCnvInjectionSocket() + { + delete m_Socket; + } + + // --------------------------------------------------------------- + // Disconnects a TCP-client + // --------------------------------------------------------------- + void PrtCnvInjectionSocket::disconnectClient() + { + INFO_LOG(m_logger) << "A client has disconnected from the injection-server"; + emit disconnected(this); + } + + + // --------------------------------------------------------------- + // Reads in TCP-data and handles them + // --------------------------------------------------------------- + void PrtCnvInjectionSocket::processInputData() + { + INFO_LOG(m_logger) << "Injection-server has data received"; + N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader; + qint64 bytesRead = m_Socket->peek((char *)&injectionHeader, sizeof(injectionHeader)); + if (sizeof(injectionHeader) == bytesRead) { - // check whether all bytes are available - qint64 available = m_Socket->bytesAvailable(); - if (available < qint64(injectionHeader.m_Size + sizeof(injectionHeader))) - { - INFO_LOG(m_logger) << "not enough bytes available - waiting for more data: " - << "headersize=" << sizeof(injectionHeader) << " id1=" - << injectionHeader.m_Id1 << " id2=" << injectionHeader.m_Id2 - << " kind=" << (int)injectionHeader.m_Kind << " size=" - << injectionHeader.m_Size; - return; // try it later, when (maybe) enough bytes are available... - } - // enough bytes => read now all in - m_Socket->read((char*)&injectionHeader, sizeof(injectionHeader)); if (injectionHeader.isIdCorrect()) { - //INFO_LOG(m_logger) << "kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size; - - // read the data - QByteArray data(injectionHeader.m_Size, Qt::Uninitialized); - m_Socket->read(data.data(), injectionHeader.m_Size); - - switch (injectionHeader.m_Kind) + // check whether all bytes are available + qint64 available = m_Socket->bytesAvailable(); + if (available < qint64(injectionHeader.m_Size + sizeof(injectionHeader))) { - case N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral: - case N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio: + INFO_LOG(m_logger) << "not enough bytes available - waiting for more data: " + << "headersize=" << sizeof(injectionHeader) << " id1=" << injectionHeader.m_Id1 << " id2=" << injectionHeader.m_Id2 + << " kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size; + return; // try it later, when (maybe) enough bytes are available... + } + // enough bytes => read now all in + m_Socket->read((char *)&injectionHeader, sizeof(injectionHeader)); + if (injectionHeader.isIdCorrect()) + { + //INFO_LOG(m_logger) << "kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size; + + // read the data + QByteArray data(injectionHeader.m_Size, Qt::Uninitialized); + m_Socket->read(data.data(), injectionHeader.m_Size); + + switch (injectionHeader.m_Kind) + { + case N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral: + case N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio: { N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = new N_CoPrtCnv::CoPrtCnvCentralTelegram(data); @@ -97,31 +96,31 @@ void PrtCnvInjectionSocket::processInputData() } break; - default: - ERROR_LOG(m_logger) << "Unknown kind (" << injectionHeader.m_Kind << ") of injection-telegram"; - break; + default: + ERROR_LOG(m_logger) << "Unknown kind (" << injectionHeader.m_Kind << ") of injection-telegram"; + break; + } } } - } - else - { - ERROR_LOG(m_logger) << "Corrupt injection-telegram received => reconnect"; - m_Socket->disconnectFromHost(); + else + { + ERROR_LOG(m_logger) << "Corrupt injection-telegram received => reconnect"; + m_Socket->disconnectFromHost(); + } } } -} -// --------------------------------------------------------------- -void PrtCnvInjectionSocket::setSocket(QTcpSocket* a_socket, PrtCnvInjectionThread* a_server) -{ - m_Socket = a_socket; - m_Server = a_server; - connect(this, &PrtCnvInjectionSocket::disconnected, m_Server, &PrtCnvInjectionThread::disconnectClient, Qt::QueuedConnection); - if (m_Socket) + // --------------------------------------------------------------- + void PrtCnvInjectionSocket::setSocket(QTcpSocket *a_socket, PrtCnvInjectionThread *a_server) { - connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection); - connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection); + m_Socket = a_socket; + m_Server = a_server; + connect(this, &PrtCnvInjectionSocket::disconnected, m_Server, &PrtCnvInjectionThread::disconnectClient, Qt::QueuedConnection); + if (m_Socket) + { + connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection); + connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection); + } } -} } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.hpp index f2a917bd0..893585998 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionSocket.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -21,7 +21,7 @@ class QTcpSocket; namespace PrtCnv { class PrtCnvInjectionThread; - /** + /** * Used for receiving the socket signals * * @author alois.wismer @@ -32,7 +32,6 @@ namespace PrtCnv { Q_OBJECT public: - PrtCnvInjectionSocket(); ~PrtCnvInjectionSocket(); @@ -41,7 +40,7 @@ namespace PrtCnv * @param a_socket * @param a_server */ - void setSocket(QTcpSocket* a_socket, PrtCnvInjectionThread* a_server); + void setSocket(QTcpSocket *a_socket, PrtCnvInjectionThread *a_server); protected: QTcpSocket *m_Socket; @@ -67,9 +66,7 @@ namespace PrtCnv * * @param a_injectSocket */ - void disconnected(PrtCnvInjectionSocket* a_injectSocket); - - + void disconnected(PrtCnvInjectionSocket *a_injectSocket); }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.cpp index 5fddc8db6..ca23b7787 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.cpp @@ -23,160 +23,155 @@ namespace PrtCnv { -// --------------------------------------------------------------- -PrtCnvInjectionThread::PrtCnvInjectionThread(PrtCnvThreadStarter* a_parent) - : PrtCnvThread(a_parent, "PrtCnvInjectionThread") - , m_Port(46666) - , m_Enabled(false) - , m_Server(nullptr) - , m_CentralListMutex(nullptr) - , m_RadioListMutex(nullptr) -{ - m_Name = QStringLiteral("Injection"); -} - -PrtCnvInjectionThread::~PrtCnvInjectionThread() -{ - delete m_CentralListMutex; - delete m_RadioListMutex; -} - -// --------------------------------------------------------------- -int32_t PrtCnvInjectionThread::create(NGL::Settings *settings) -{ - INFO_LOG(m_logger) << "create"; - PrtCnvThread::create(settings); - - m_CentralListMutex = new QMutex; - m_RadioListMutex = new QMutex; - - m_Enabled = m_Config->getBoolean(getName(), QStringLiteral("Enable"), false); - - // prepare a tcp-server for simulating central - if (m_Enabled) + // --------------------------------------------------------------- + PrtCnvInjectionThread::PrtCnvInjectionThread(PrtCnvThreadStarter *a_parent) + : PrtCnvThread(a_parent, "PrtCnvInjectionThread") + , m_Port(46666) + , m_Enabled(false) + , m_Server(nullptr) + , m_CentralListMutex(nullptr) + , m_RadioListMutex(nullptr) { - m_Server = new QTcpServer(this); - if (m_Server) - connect(m_Server, &QTcpServer::newConnection, this, &PrtCnvInjectionThread::connectClient, Qt::QueuedConnection); + m_Name = QStringLiteral("Injection"); } - return 0; -} - - -// --------------------------------------------------------------- -int32_t PrtCnvInjectionThread::init() -{ - INFO_LOG(m_logger) << "init"; - PrtCnvThread::init(); - m_Port = m_Config->getInteger(getName(), QStringLiteral("Port"), 46666); - - return 0; -} - - - -// --------------------------------------------------------------- -// Starts the thread and listen for TCP-clients -// --------------------------------------------------------------- -int32_t PrtCnvInjectionThread::start() -{ - INFO_LOG(m_logger) << "Start"; - PrtCnvThread::start(); - - // start the TCP-server - if (m_Enabled) + PrtCnvInjectionThread::~PrtCnvInjectionThread() { - m_Server->setMaxPendingConnections(1); - m_Server->listen(QHostAddress::Any, m_Port); - INFO_LOG(m_logger) << "Injection-Server is listening on port " << m_Port; + delete m_CentralListMutex; + delete m_RadioListMutex; } - return 0; -} + // --------------------------------------------------------------- + int32_t PrtCnvInjectionThread::create(NGL::Settings *settings) + { + INFO_LOG(m_logger) << "create"; + PrtCnvThread::create(settings); + + m_CentralListMutex = new QMutex; + m_RadioListMutex = new QMutex; + + m_Enabled = m_Config->getBoolean(getName(), QStringLiteral("Enable"), false); + + // prepare a tcp-server for simulating central + if (m_Enabled) + { + m_Server = new QTcpServer(this); + if (m_Server) + connect(m_Server, &QTcpServer::newConnection, this, &PrtCnvInjectionThread::connectClient, Qt::QueuedConnection); + } + + return 0; + } + // --------------------------------------------------------------- + int32_t PrtCnvInjectionThread::init() + { + INFO_LOG(m_logger) << "init"; + PrtCnvThread::init(); + m_Port = m_Config->getInteger(getName(), QStringLiteral("Port"), 46666); -// --------------------------------------------------------------- -// Connects a TCP-client -// --------------------------------------------------------------- -void PrtCnvInjectionThread::connectClient() -{ - INFO_LOG(m_logger) << "A client has connected to the injection-server"; - PrtCnvInjectionSocket* injectSocket = new PrtCnvInjectionSocket; - m_SocketList.insert(injectSocket); - INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected"; - injectSocket->setSocket(m_Server->nextPendingConnection(), this); -} + return 0; + } + // --------------------------------------------------------------- + // Starts the thread and listen for TCP-clients + // --------------------------------------------------------------- + int32_t PrtCnvInjectionThread::start() + { + INFO_LOG(m_logger) << "Start"; + PrtCnvThread::start(); -// --------------------------------------------------------------- -// Disconnects a TCP-client -// --------------------------------------------------------------- -void PrtCnvInjectionThread::disconnectClient(PrtCnvInjectionSocket *a_injectionSocket) -{ - auto it = m_SocketList.find(a_injectionSocket); - if (it != m_SocketList.end()) - m_SocketList.erase(it); - INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected"; - delete a_injectionSocket; -} + // start the TCP-server + if (m_Enabled) + { + m_Server->setMaxPendingConnections(1); + m_Server->listen(QHostAddress::Any, m_Port); + INFO_LOG(m_logger) << "Injection-Server is listening on port " << m_Port; + } + + return 0; + } - -// --------------------------------------------------------------- -// Returns the next central-telegram to be injected. It will -// automatically be taken out of the list. -// The caller is responsible to delete the telegram, if no -// longer used. -// Returns NULL if no central-telegram available -// --------------------------------------------------------------- -N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextCentralInjectionTelegram() -{ - QMutexLocker l(m_CentralListMutex); - - if (m_CentralTelegramList.empty()) - return nullptr; - auto centralTelegram = m_CentralTelegramList.front(); - m_CentralTelegramList.pop(); - return centralTelegram; -} + // --------------------------------------------------------------- + // Connects a TCP-client + // --------------------------------------------------------------- + void PrtCnvInjectionThread::connectClient() + { + INFO_LOG(m_logger) << "A client has connected to the injection-server"; + PrtCnvInjectionSocket *injectSocket = new PrtCnvInjectionSocket; + m_SocketList.insert(injectSocket); + INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected"; + injectSocket->setSocket(m_Server->nextPendingConnection(), this); + } -// --------------------------------------------------------------- -// Returns the next radio-telegram to be injected. It will -// automatically be taken out of the list. -// The caller is responsible to delete the telegram, if no -// longer used. -// Returns NULL if no radio-telegram available -// --------------------------------------------------------------- -N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextRadioInjectionTelegram() -{ - QMutexLocker l(m_RadioListMutex); - - if (m_RadioTelegramList.empty()) - return nullptr; - auto radioTelegram = m_RadioTelegramList.front(); - m_RadioTelegramList.pop(); - return radioTelegram; -} + // --------------------------------------------------------------- + // Disconnects a TCP-client + // --------------------------------------------------------------- + void PrtCnvInjectionThread::disconnectClient(PrtCnvInjectionSocket *a_injectionSocket) + { + auto it = m_SocketList.find(a_injectionSocket); + if (it != m_SocketList.end()) + m_SocketList.erase(it); + INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected"; + delete a_injectionSocket; + } -// --------------------------------------------------------------- -void PrtCnvInjectionThread::addToCentralList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - QMutexLocker l(m_CentralListMutex); - m_CentralTelegramList.push(a_telegram); -} + // --------------------------------------------------------------- + // Returns the next central-telegram to be injected. It will + // automatically be taken out of the list. + // The caller is responsible to delete the telegram, if no + // longer used. + // Returns NULL if no central-telegram available + // --------------------------------------------------------------- + N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextCentralInjectionTelegram() + { + QMutexLocker l(m_CentralListMutex); + + if (m_CentralTelegramList.empty()) + return nullptr; + auto centralTelegram = m_CentralTelegramList.front(); + m_CentralTelegramList.pop(); + return centralTelegram; + } -// --------------------------------------------------------------- -void PrtCnvInjectionThread::addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) -{ - QMutexLocker l(m_RadioListMutex); - m_RadioTelegramList.push(a_telegram); -} + // --------------------------------------------------------------- + // Returns the next radio-telegram to be injected. It will + // automatically be taken out of the list. + // The caller is responsible to delete the telegram, if no + // longer used. + // Returns NULL if no radio-telegram available + // --------------------------------------------------------------- + N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextRadioInjectionTelegram() + { + QMutexLocker l(m_RadioListMutex); + + if (m_RadioTelegramList.empty()) + return nullptr; + auto radioTelegram = m_RadioTelegramList.front(); + m_RadioTelegramList.pop(); + return radioTelegram; + } + + + // --------------------------------------------------------------- + void PrtCnvInjectionThread::addToCentralList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) + { + QMutexLocker l(m_CentralListMutex); + m_CentralTelegramList.push(a_telegram); + } + + + // --------------------------------------------------------------- + void PrtCnvInjectionThread::addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram) + { + QMutexLocker l(m_RadioListMutex); + m_RadioTelegramList.push(a_telegram); + } } // namespace PrtCnv - diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.hpp index 53b8a981f..e29f17818 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvInjectionThread.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "PrtCnvThread.hpp" @@ -22,13 +22,13 @@ class QMutex; namespace N_CoPrtCnv { -class CoPrtCnvCentralTelegram; + class CoPrtCnvCentralTelegram; } namespace PrtCnv { class PrtCnvInjectionSocket; - /** + /** * This class represents a thread, which acts as TCP-Server. The LogView- * application can connect to it and send radio- or central-telegrams. The * telegrams will be stored within this class and can be taken by another thread. @@ -42,14 +42,13 @@ namespace PrtCnv { Q_OBJECT public: - ~PrtCnvInjectionThread(); /** * * @param a_parent */ - explicit PrtCnvInjectionThread(PrtCnvThreadStarter* a_parent); + explicit PrtCnvInjectionThread(PrtCnvThreadStarter *a_parent); int32_t create(NGL::Settings *settings) override; @@ -90,7 +89,7 @@ namespace PrtCnv */ void addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram); - protected: /** + protected: /** * The port of the injection-server (configurable with key 'Port' in group * [Injection]) */ @@ -111,22 +110,20 @@ namespace PrtCnv QMutex *m_RadioListMutex; - std::set m_SocketList; - + std::set m_SocketList; public slots: - /** + /** * Connects a TCP-client */ - void connectClient(); - /** + void connectClient(); + /** * Disconnects a TCP-client * * @param a_injectionSocket */ - void disconnectClient(PrtCnvInjectionSocket* a_injectionSocket); - + void disconnectClient(PrtCnvInjectionSocket *a_injectionSocket); }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMain.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMain.cpp index 823d1c8ca..60c25ac53 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMain.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMain.cpp @@ -40,16 +40,18 @@ static void daemonize() pid_t pid, sid; /* already a daemon */ - if ( getppid() == 1 ) + if (getppid() == 1) return; /* Fork off the parent process */ pid = fork(); - if (pid < 0) { + if (pid < 0) + { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ - if (pid > 0) { + if (pid > 0) + { exit(EXIT_SUCCESS); } @@ -60,20 +62,20 @@ static void daemonize() /* Create a new SID for the child process */ sid = setsid(); - if (sid < 0) { + if (sid < 0) + { exit(EXIT_FAILURE); } /* Change the current working directory. This prevents the current directory from being locked; hence not being able to remove it. */ - if ((chdir("/")) < 0) { + if ((chdir("/")) < 0) + { exit(EXIT_FAILURE); } - - if (freopen( "/dev/null", "r", stdin ) == nullptr - || freopen( "/dev/null", "w", stdout ) == nullptr - || freopen( "/dev/null", "w", stderr ) == nullptr) + + if (freopen("/dev/null", "r", stdin) == nullptr || freopen("/dev/null", "w", stdout) == nullptr || freopen("/dev/null", "w", stderr) == nullptr) { exit(EXIT_FAILURE); } @@ -84,25 +86,17 @@ class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser { public: CmdLineParser() - : LtsCommandLineParser(ProvideCommandLineParameterOptions(ExerciseId|CustomConfigFile)) + : LtsCommandLineParser(ProvideCommandLineParameterOptions(ExerciseId | CustomConfigFile)) { - addOption( { QStringList() << QStringLiteral("d") << QStringLiteral("daemonize"), - QStringLiteral("Start in background") } ); - addOption( { QStringList() << QStringLiteral("c") << QStringLiteral("cleandb"), - QStringLiteral("Start over with clean database") } ); + addOption({QStringList() << QStringLiteral("d") << QStringLiteral("daemonize"), QStringLiteral("Start in background")}); + addOption({QStringList() << QStringLiteral("c") << QStringLiteral("cleandb"), QStringLiteral("Start over with clean database")}); } - bool daemonize() const - { - return isSet(QStringLiteral("d")); - } - bool cleanDb() const - { - return isSet(QStringLiteral("c")); - } + bool daemonize() const { return isSet(QStringLiteral("d")); } + bool cleanDb() const { return isSet(QStringLiteral("c")); } }; -int main(int argc, char** argv) +int main(int argc, char **argv) { QNetworkProxy::setApplicationProxy(QNetworkProxy()); NGLCoreApplication app(argc, argv); diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.cpp index 51d03f522..10c293a7f 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.cpp @@ -1,16 +1,16 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // ************************************************************************** - + // manual class headers #include "PrtCnvMember.hpp" #include @@ -18,81 +18,80 @@ namespace PrtCnv { -// --------------------------------------------------------------- -// Constructor with id and ISSI as parameter -// --------------------------------------------------------------- -PrtCnvMember::PrtCnvMember(int a_id, int a_issi) - : m_ISSI(a_issi) - , m_ClaimCount(0) - , m_loggedInExerciseId(0) - , m_Id(a_id) - , m_Licensed(false) -{} - -PrtCnvMember::~PrtCnvMember() -{ - clearFragmentedList(); -} - - -// --------------------------------------------------------------- -// Adds a radio-telegram-fragment to this member. -// --------------------------------------------------------------- -void PrtCnvMember::addFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) -{ - m_FragmentedTelegramList.insert(std::make_pair(a_radioTelegram.getFragmentCounter(), - new N_CoPrtCnv::CoPrtCnvRadioTelegram(a_radioTelegram))); -} - - - -// --------------------------------------------------------------- -// Returns the telegram-Id of the fragmented telegram assiged -// to this member. -// If not evaluable: 0 will be returned. -// --------------------------------------------------------------- -gef_telegramm_id_et PrtCnvMember::getFragmentedTelegramId() const -{ - // the fragment with the highest counter is the first fragment - for (auto rit = m_FragmentedTelegramList.rbegin(); rit != m_FragmentedTelegramList.rend(); ++rit) + // --------------------------------------------------------------- + // Constructor with id and ISSI as parameter + // --------------------------------------------------------------- + PrtCnvMember::PrtCnvMember(int a_id, int a_issi) + : m_ISSI(a_issi) + , m_ClaimCount(0) + , m_loggedInExerciseId(0) + , m_Id(a_id) + , m_Licensed(false) { - N_CoPrtCnv::CoPrtCnvRadioTelegram *firstFragment = rit->second; - if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == firstFragment->getFragmentStatus()) - return firstFragment->getTelID(); } - return GEF_BESTAETIGUNG; // no telegram found => return 0 (= GEF_BESTAETIGUNG) -} + + PrtCnvMember::~PrtCnvMember() + { + clearFragmentedList(); + } -// --------------------------------------------------------------- -// Erases the radio-telegram-fragments assiged to this member. -// The fragments itself will be deleted. -// --------------------------------------------------------------- -void PrtCnvMember::clearFragmentedList() -{ - for (auto it : m_FragmentedTelegramList) - delete it.second; - m_FragmentedTelegramList.clear(); -} + // --------------------------------------------------------------- + // Adds a radio-telegram-fragment to this member. + // --------------------------------------------------------------- + void PrtCnvMember::addFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) + { + m_FragmentedTelegramList.insert(std::make_pair(a_radioTelegram.getFragmentCounter(), new N_CoPrtCnv::CoPrtCnvRadioTelegram(a_radioTelegram))); + } -// --------------------------------------------------------------- -// Returns the radio-telegram-fragments assembled to a only -// big radio-telegram. The fragments will not be deleted. -// Returns NULL if it was impossible to assemble the telegram. -// --------------------------------------------------------------- -QByteArray PrtCnvMember::getUnfragmentedTelegramData() const -{ - return N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(m_FragmentedTelegramList); -} + // --------------------------------------------------------------- + // Returns the telegram-Id of the fragmented telegram assiged + // to this member. + // If not evaluable: 0 will be returned. + // --------------------------------------------------------------- + gef_telegramm_id_et PrtCnvMember::getFragmentedTelegramId() const + { + // the fragment with the highest counter is the first fragment + for (auto rit = m_FragmentedTelegramList.rbegin(); rit != m_FragmentedTelegramList.rend(); ++rit) + { + N_CoPrtCnv::CoPrtCnvRadioTelegram *firstFragment = rit->second; + if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == firstFragment->getFragmentStatus()) + return firstFragment->getTelID(); + } + return GEF_BESTAETIGUNG; // no telegram found => return 0 (= GEF_BESTAETIGUNG) + } -// --------------------------------------------------------------- -// Returns true if the fragment-list is empty -// --------------------------------------------------------------- -bool PrtCnvMember::isFragmentedListEmpty() const -{ - return m_FragmentedTelegramList.empty(); -} + // --------------------------------------------------------------- + // Erases the radio-telegram-fragments assiged to this member. + // The fragments itself will be deleted. + // --------------------------------------------------------------- + void PrtCnvMember::clearFragmentedList() + { + for (auto it : m_FragmentedTelegramList) + delete it.second; + m_FragmentedTelegramList.clear(); + } + + + // --------------------------------------------------------------- + // Returns the radio-telegram-fragments assembled to a only + // big radio-telegram. The fragments will not be deleted. + // Returns NULL if it was impossible to assemble the telegram. + // --------------------------------------------------------------- + QByteArray PrtCnvMember::getUnfragmentedTelegramData() const + { + return N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(m_FragmentedTelegramList); + } + + + // --------------------------------------------------------------- + // Returns true if the fragment-list is empty + // --------------------------------------------------------------- + bool PrtCnvMember::isFragmentedListEmpty() const + { + return m_FragmentedTelegramList.empty(); + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.hpp index 1b88931d7..6bb277603 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvMember.hpp @@ -10,7 +10,7 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include @@ -37,7 +37,6 @@ namespace PrtCnv class PrtCnvMember final { public: - /** * The status of the member * @author wia @@ -102,7 +101,7 @@ namespace PrtCnv private: // Map of radio-telegram-fragments ordered by fragment-number - std::multimap m_FragmentedTelegramList; + std::multimap m_FragmentedTelegramList; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.cpp index 7d787fd52..9c585bb4d 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.cpp @@ -44,121 +44,111 @@ namespace PrtCnv { -static BiteError getBiteError(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram, - size_t iOffset) -{ + static BiteError getBiteError(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram, size_t iOffset) + { BiteError ret; ret.canDeviceNumber = a_radioTelegram.getPayloadDataUInt8(iOffset + 0); ret.subdeviceNumber = a_radioTelegram.getPayloadDataUInt8(iOffset + 1); - ret.uniqueId = a_radioTelegram.getPayloadDataUInt32(iOffset + 2, 4); - ret.errorNumber = a_radioTelegram.getPayloadDataUInt8(iOffset + 6); + ret.uniqueId = a_radioTelegram.getPayloadDataUInt32(iOffset + 2, 4); + ret.errorNumber = a_radioTelegram.getPayloadDataUInt8(iOffset + 6); return ret; -} + } -PrtCnvRadioThread::PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter *a_parent) : PrtCnvSocketThread(a_parent, "PrtCnvRadioThread"), - m_CentralThread(nullptr), - m_radioTrafficThread(nullptr), - m_SendCounter(0), - m_HostISSI(0), - START_COUNTER(0), - END_COUNTER(256), - m_EnvironmentTelegramTimer(nullptr), - m_BroadcastISSI(0), - m_LoginPathWithPrefix(QString()), - m_ExerciseId(exerciseId), - m_DoLicenseDespiteSelftestOrConfigFailure(false), - m_DoCheckIdentity(true), - m_DoDumpReceivedTelegrams(false), - m_DoDumpSentTelegrams(false), - m_DoUseSDSTL(false), - m_EmergencyCallISSI(0), - m_EnvironmentTelegram(nullptr), - m_SendLoad(E_TrafficLoad::Unknown), - m_SendQueueFullLoad(0), - m_SendQueueHighLoad(0), - m_SendTelegramsNormalLoad(100), - m_SendTelegramsHighLoad(50), - m_SendTelegramsFullLoad(10), - m_SentTelegrams(0), - m_SentBytes(0), - m_TickCounter(0), - m_TicksPerSecond(0), - m_AverageIndex(0), - m_ReceivedTelegrams(0), - m_ReceivedBytes(0), - m_bUseScrambling(false), - m_loggerStats(getLogger("PrtCnvRadioThread.statistic")), - m_exerciseEquipmentAssignmentMutex() { + PrtCnvRadioThread::PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter *a_parent) + : PrtCnvSocketThread(a_parent, "PrtCnvRadioThread") + , m_CentralThread(nullptr) + , m_radioTrafficThread(nullptr) + , m_SendCounter(0) + , m_HostISSI(0) + , START_COUNTER(0) + , END_COUNTER(256) + , m_EnvironmentTelegramTimer(nullptr) + , m_BroadcastISSI(0) + , m_LoginPathWithPrefix(QString()) + , m_ExerciseId(exerciseId) + , m_DoLicenseDespiteSelftestOrConfigFailure(false) + , m_DoCheckIdentity(true) + , m_DoDumpReceivedTelegrams(false) + , m_DoDumpSentTelegrams(false) + , m_DoUseSDSTL(false) + , m_EmergencyCallISSI(0) + , m_EnvironmentTelegram(nullptr) + , m_SendLoad(E_TrafficLoad::Unknown) + , m_SendQueueFullLoad(0) + , m_SendQueueHighLoad(0) + , m_SendTelegramsNormalLoad(100) + , m_SendTelegramsHighLoad(50) + , m_SendTelegramsFullLoad(10) + , m_SentTelegrams(0) + , m_SentBytes(0) + , m_TickCounter(0) + , m_TicksPerSecond(0) + , m_AverageIndex(0) + , m_ReceivedTelegrams(0) + , m_ReceivedBytes(0) + , m_bUseScrambling(false) + , m_loggerStats(getLogger("PrtCnvRadioThread.statistic")) + , m_exerciseEquipmentAssignmentMutex() + { m_Name = QStringLiteral("Radio"); for (int i = 0; i < AVERAGE_COUNT; ++i) { - m_SentBytesAverage[i] = 0; - m_ReceivedBytesAverage[i] = 0; + m_SentBytesAverage[i] = 0; + m_ReceivedBytesAverage[i] = 0; } qRegisterMetaType("N_CoPrtCnv::E_LicensingKind"); -} + } -// --------------------------------------------------------------- -// Creates all subcomponents and connects signals to slots -// --------------------------------------------------------------- -int32_t PrtCnvRadioThread::create(NGL::Settings *settings) -{ + // --------------------------------------------------------------- + // Creates all subcomponents and connects signals to slots + // --------------------------------------------------------------- + int32_t PrtCnvRadioThread::create(NGL::Settings *settings) + { INFO_LOG(m_logger) << "create"; PrtCnvSocketThread::create(settings); m_BroadcastManager.create(settings); m_CentralThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Central)); - connect(this, &PrtCnvRadioThread::checkSendToRadio, - this, &PrtCnvRadioThread::checkSend, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::checkMemberForValidLogin, - this, &PrtCnvRadioThread::onCheckMemberForValidLogin, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::checkSendToCentral, - m_CentralThread, &PrtCnvCentralThread::checkSend, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::stopped, - m_CentralThread, &PrtCnvCentralThread::radioStopped, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::cleant, - m_CentralThread, &PrtCnvCentralThread::radioCleant, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::tetraConnectionState, - m_CentralThread, &PrtCnvCentralThread::onTetraConnectionState, Qt::QueuedConnection); - connect(this, &PrtCnvRadioThread::playerLicencedChanged, - m_CentralThread, &PrtCnvCentralThread::onPlayerLicencedChanged, Qt::QueuedConnection); - connect(&m_BroadcastManager, &PrtCnvBroadcastMgr::areaEffectSimulationDeactivated, - this, &PrtCnvRadioThread::areaEffectSimulationDeactivated); - connect(&m_BroadcastManager, &PrtCnvBroadcastMgr::areaEffectSimulationActivated, - this, &PrtCnvRadioThread::areaEffectSimulationActivated); + connect(this, &PrtCnvRadioThread::checkSendToRadio, this, &PrtCnvRadioThread::checkSend, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::checkMemberForValidLogin, this, &PrtCnvRadioThread::onCheckMemberForValidLogin, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::checkSendToCentral, m_CentralThread, &PrtCnvCentralThread::checkSend, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::stopped, m_CentralThread, &PrtCnvCentralThread::radioStopped, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::cleant, m_CentralThread, &PrtCnvCentralThread::radioCleant, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::tetraConnectionState, m_CentralThread, &PrtCnvCentralThread::onTetraConnectionState, Qt::QueuedConnection); + connect(this, &PrtCnvRadioThread::playerLicencedChanged, m_CentralThread, &PrtCnvCentralThread::onPlayerLicencedChanged, Qt::QueuedConnection); + connect(&m_BroadcastManager, &PrtCnvBroadcastMgr::areaEffectSimulationDeactivated, this, &PrtCnvRadioThread::areaEffectSimulationDeactivated); + connect(&m_BroadcastManager, &PrtCnvBroadcastMgr::areaEffectSimulationActivated, this, &PrtCnvRadioThread::areaEffectSimulationActivated); auto mainApp = m_Parent->getMainApp(); - connect(mainApp, &PrtCnvApplication::outgoingBroadcastTelegramsRequest, - this, &PrtCnvRadioThread::onBroadcastTelegramsRequestFromCentral); + connect(mainApp, &PrtCnvApplication::outgoingBroadcastTelegramsRequest, this, &PrtCnvRadioThread::onBroadcastTelegramsRequestFromCentral); - connect(this, &PrtCnvRadioThread::warehouseMessageFromPtrCnv, - mainApp, &PrtCnvApplication::warehouseMessageFromPtrCnv); + connect(this, &PrtCnvRadioThread::warehouseMessageFromPtrCnv, mainApp, &PrtCnvApplication::warehouseMessageFromPtrCnv); static_assert(sizeof(N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader) == 4, - "This code expects a size of 4 for CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader (otherwise it will not work correct)" - ); + "This code expects a size of 4 for CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader (otherwise it will not work correct)"); return 0; -} + } -// --------------------------------------------------------------- -// Deallocates subcomponents. -// --------------------------------------------------------------- -int32_t PrtCnvRadioThread::destroy() -{ + // --------------------------------------------------------------- + // Deallocates subcomponents. + // --------------------------------------------------------------- + int32_t PrtCnvRadioThread::destroy() + { INFO_LOG(m_logger) << "Destroy"; PrtCnvSocketThread::destroy(); - delete m_EnvironmentTelegramTimer; m_EnvironmentTelegramTimer = nullptr; + delete m_EnvironmentTelegramTimer; + m_EnvironmentTelegramTimer = nullptr; return 0; -} + } -// --------------------------------------------------------------- -// Initializes the variables. -// --------------------------------------------------------------- -int32_t PrtCnvRadioThread::init() -{ + // --------------------------------------------------------------- + // Initializes the variables. + // --------------------------------------------------------------- + int32_t PrtCnvRadioThread::init() + { INFO_LOG(m_logger) << "init"; PrtCnvSocketThread::init(); m_BroadcastManager.setDbThread(m_DbThread); @@ -172,26 +162,26 @@ int32_t PrtCnvRadioThread::init() m_BroadcastISSI = m_Config->getInteger(getName(), QStringLiteral("BroadcastISSI"), 5000); m_EmergencyCallISSI = m_Config->getInteger(getName(), QStringLiteral("EmergencyCallISSI"), 9000); if (m_DoCleanDb) - m_DbThread->licenseMember(m_DbThread->addMember(0, m_BroadcastISSI)); + m_DbThread->licenseMember(m_DbThread->addMember(0, m_BroadcastISSI)); QString groupString = m_Config->getString(getName(), QStringLiteral("ListenGroups"), QString()); const QStringList groups = groupString.split(QLatin1Char(','), Qt::SkipEmptyParts); for (const QString &sr : groups) { - uint32_t group = sr.toUInt(); - if (group > 0) - m_ListenGroups.insert(group); + uint32_t group = sr.toUInt(); + if (group > 0) + m_ListenGroups.insert(group); } if (m_ListenGroups.size() > 5) { - while (m_ListenGroups.size() > 5) - m_ListenGroups.erase(m_ListenGroups.end()); - WARNING_LOG(m_logger) << "More than 5 ListenGroups defined - ignoring all except the first 5"; + while (m_ListenGroups.size() > 5) + m_ListenGroups.erase(m_ListenGroups.end()); + WARNING_LOG(m_logger) << "More than 5 ListenGroups defined - ignoring all except the first 5"; } m_LoginPathWithPrefix = m_Config->getString(QStringLiteral("Login"), QStringLiteral("LoginFilePathWithPrefix"), QStringLiteral("login")); if (!QDir::isAbsolutePath(m_LoginPathWithPrefix)) - m_LoginPathWithPrefix = QCoreApplication::applicationDirPath() + QLatin1String("/../") + m_LoginPathWithPrefix; + m_LoginPathWithPrefix = QCoreApplication::applicationDirPath() + QLatin1String("/../") + m_LoginPathWithPrefix; // create the login-path when it not yet exists m_LoginPathWithPrefix = QDir::cleanPath(QDir::fromNativeSeparators(m_LoginPathWithPrefix)); QString path = m_LoginPathWithPrefix.left(m_LoginPathWithPrefix.lastIndexOf(QLatin1Char('/'))); @@ -214,35 +204,34 @@ int32_t PrtCnvRadioThread::init() m_SendLoad = E_TrafficLoad::Unknown; if (!m_DoCleanDb) - m_BroadcastManager.restoreAfterCrash(); + m_BroadcastManager.restoreAfterCrash(); emit initDone(); return 0; -} + } -// --------------------------------------------------------------- -// Starts the thread and connects to TCP-server -// --------------------------------------------------------------- -int32_t PrtCnvRadioThread::start() -{ + // --------------------------------------------------------------- + // Starts the thread and connects to TCP-server + // --------------------------------------------------------------- + int32_t PrtCnvRadioThread::start() + { INFO_LOG(m_logger) << "Start"; PrtCnvSocketThread::start(); connectSocket(); return 0; -} + } - -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvRadioThread::connected() -{ + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvRadioThread::connected() + { INFO_LOG(m_logger) << "Radio-Socket connected m_Socket=" << m_Socket; m_ReceiveCounter = END_COUNTER - 1; // start with counter 0 (preincrement) - m_SendCounter = END_COUNTER; // start with counter 0 + m_SendCounter = END_COUNTER; // start with counter 0 m_SentTelegrams = 0; m_SentBytes = 0; m_ReceivedTelegrams = 0; @@ -250,237 +239,234 @@ void PrtCnvRadioThread::connected() m_TickCounter = 0; for (int i = 0; i < AVERAGE_COUNT; i++) { - m_SentBytesAverage[i] = 0; - m_ReceivedBytesAverage[i] = 0; + m_SentBytesAverage[i] = 0; + m_ReceivedBytesAverage[i] = 0; } m_AverageIndex = 0; doRegister(); startTickTimer(); m_ConnectionTimer->stop(); m_State = PrtCnvSocketThread::e_REGISTERING; -} + } -// --------------------------------------------------------------- -// Makes empty the message-queue faster, because the messages -// will be consumed without action. -// --------------------------------------------------------------- -void PrtCnvRadioThread::prepareCleanUp() -{ + // --------------------------------------------------------------- + // Makes empty the message-queue faster, because the messages + // will be consumed without action. + // --------------------------------------------------------------- + void PrtCnvRadioThread::prepareCleanUp() + { m_DoCleanup = true; -} + } -// --------------------------------------------------------------- -// Stops work for cleaning DB -// --------------------------------------------------------------- -void PrtCnvRadioThread::doStop() -{ + // --------------------------------------------------------------- + // Stops work for cleaning DB + // --------------------------------------------------------------- + void PrtCnvRadioThread::doStop() + { m_DoCleanup = true; if (m_EnvironmentTelegramTimer) - m_EnvironmentTelegramTimer->stop(); + m_EnvironmentTelegramTimer->stop(); m_TickTimer->stop(); disconnectSocket(); -} + } -// --------------------------------------------------------------- -// bc nachforderung from Wls -// --------------------------------------------------------------- -void PrtCnvRadioThread::onBroadcastTelegramsRequestFromCentral(int equipmentNumber, int broadcastIndex, int resetCounter) -{ + // --------------------------------------------------------------- + // bc nachforderung from Wls + // --------------------------------------------------------------- + void PrtCnvRadioThread::onBroadcastTelegramsRequestFromCentral(int equipmentNumber, int broadcastIndex, int resetCounter) + { m_BroadcastManager.handleNachforderungBroadcastTelegram(equipmentNumber, broadcastIndex, resetCounter); -} + } -// --------------------------------------------------------------- -// Clean the DB. -// --------------------------------------------------------------- -void PrtCnvRadioThread::doClean() -{ + // --------------------------------------------------------------- + // Clean the DB. + // --------------------------------------------------------------- + void PrtCnvRadioThread::doClean() + { INFO_LOG(m_logger) << "doClean"; m_BroadcastManager.cleanAndInit(true); m_DbThread->setResetCounter(m_DbThread->getResetCounter() + 1); emit cleant(); -} + } -// --------------------------------------------------------------- -// Restart work after cleaning Db -// --------------------------------------------------------------- -void PrtCnvRadioThread::doStart() -{ + // --------------------------------------------------------------- + // Restart work after cleaning Db + // --------------------------------------------------------------- + void PrtCnvRadioThread::doStart() + { m_DoCleanup = false; connectSocket(); if (m_EnvironmentTelegramTimer && m_EnvironmentTelegramTimer->interval() > 0) - m_EnvironmentTelegramTimer->start(); -} + m_EnvironmentTelegramTimer->start(); + } -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvRadioThread::disconnected() -{ + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvRadioThread::disconnected() + { INFO_LOG(m_logger) << "Radio-Socket disconnected m_Socket=" << m_Socket; // for the case central is disconnecting, we have to disconnect also, otherwise // we could send rubish (still resisting in buffers) after a reconnection if (e_WORKING == m_State || e_REGISTERING == m_State) { - m_Socket->disconnectFromHost(); - if (m_Socket->state() != QAbstractSocket::UnconnectedState) - m_Socket->waitForDisconnected(); + m_Socket->disconnectFromHost(); + if (m_Socket->state() != QAbstractSocket::UnconnectedState) + m_Socket->waitForDisconnected(); } m_State = e_DISCONNECTING; if (m_DoCleanup) { - m_ConnectionTimer->stop(); - emit stopped(); + m_ConnectionTimer->stop(); + emit stopped(); } else - connectSocket(); + connectSocket(); emit tetraConnectionState(false); -} + } -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvRadioThread::readyRead() -{ + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvRadioThread::readyRead() + { N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader header; while (true) { - if (m_DoCleanup) - break; + if (m_DoCleanup) + break; - // read the 4-byte frame-header for find out the length of whole telegram - qint64 bytesRead = m_Socket->peek(reinterpret_cast(&header), sizeof(header)); + // read the 4-byte frame-header for find out the length of whole telegram + qint64 bytesRead = m_Socket->peek(reinterpret_cast(&header), sizeof(header)); - // no more data - if (0 == bytesRead) - break; + // no more data + if (0 == bytesRead) + break; - // not yet enough data - if (sizeof(header) != bytesRead) - break; + // not yet enough data + if (sizeof(header) != bytesRead) + break; - // frame-header must begin with the magic number - if (N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER != header.m_MagicNumber) - { - ERROR_LOG(m_logger) << "Reconnect because radio-Telegram does not begin with magic-number 0xA5: I got 0x" - << QString::number(header.m_MagicNumber, 16); - disconnectSocket(); - break; - } + // frame-header must begin with the magic number + if (N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER != header.m_MagicNumber) + { + ERROR_LOG(m_logger) << "Reconnect because radio-Telegram does not begin with magic-number 0xA5: I got 0x" << QString::number(header.m_MagicNumber, 16); + disconnectSocket(); + break; + } - // is the length plausible - if (!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(header.m_Length)) - WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length - << ", but I proceed with this telegram."; + // is the length plausible + if (!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(header.m_Length)) + WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length << ", but I proceed with this telegram."; - // prepare data-bucket for entire telegram - uint16_t dataSize = header.m_Length + sizeof(header); - if (m_Socket->bytesAvailable() < dataSize) - { - INFO_LOG(m_logger) << "not enough bytes available - waiting for more data"; - break; - } - QByteArray buf(dataSize, Qt::Uninitialized); - // read the telegram with header - bytesRead = 0; - while (bytesRead < dataSize) - { - qint64 br = m_Socket->read(&buf.data()[bytesRead], dataSize - bytesRead); - bytesRead += br; - } + // prepare data-bucket for entire telegram + uint16_t dataSize = header.m_Length + sizeof(header); + if (m_Socket->bytesAvailable() < dataSize) + { + INFO_LOG(m_logger) << "not enough bytes available - waiting for more data"; + break; + } + QByteArray buf(dataSize, Qt::Uninitialized); + // read the telegram with header + bytesRead = 0; + while (bytesRead < dataSize) + { + qint64 br = m_Socket->read(&buf.data()[bytesRead], dataSize - bytesRead); + bytesRead += br; + } - if (!checkAndUpdateReceiveCounter(header.m_Counter, END_COUNTER, START_COUNTER)) - { - // log the telegram - m_LogThread->writeRadioTelegramLog(buf, true, 1); - ERROR_LOG(m_logger) << "Reconnect because frame-counter of received radio-telegram was wrong"; - disconnectSocket(); - break; - } + if (!checkAndUpdateReceiveCounter(header.m_Counter, END_COUNTER, START_COUNTER)) + { + // log the telegram + m_LogThread->writeRadioTelegramLog(buf, true, 1); + ERROR_LOG(m_logger) << "Reconnect because frame-counter of received radio-telegram was wrong"; + disconnectSocket(); + break; + } - // all checks were successful => use the telegram - // ---------------------------------------------- - handleReceivedTelegram(buf); + // all checks were successful => use the telegram + // ---------------------------------------------- + handleReceivedTelegram(buf); - // update statistics-data for traffic-control - m_ReceivedTelegrams++; - m_ReceivedBytes += dataSize; + // update statistics-data for traffic-control + m_ReceivedTelegrams++; + m_ReceivedBytes += dataSize; } -} + } -// --------------------------------------------------------------- -// After calling this function, the caller must no longer use -// a_data, because this function 'consumes' a_data and will -// delete a_data, when no longer needed. -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleReceivedTelegram(const QByteArray &data) -{ + // --------------------------------------------------------------- + // After calling this function, the caller must no longer use + // a_data, because this function 'consumes' a_data and will + // delete a_data, when no longer needed. + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleReceivedTelegram(const QByteArray &data) + { if (m_DoDumpReceivedTelegrams) { - INFO_LOG(m_logger) << "Received radio-telegram:"; - NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, data); + INFO_LOG(m_logger) << "Received radio-telegram:"; + NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, data); } // evaluate PDU-Type switch (data.at(4)) { - // response to register indication - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: + // response to register indication + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp: handleRegisterRsp(data.at(5)); // registration status m_State = e_WORKING; break; // payload telegram - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: handleDataIndReq(data, true); emit checkSendToCentral(); return; // no telegram log due to unscrambling // ack-telegram - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq: handleReportIndReq(data); break; // status-telegram - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_StatusIndReq: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_StatusIndReq: handleStatusIndReq(data); break; // air-interface-load-telegram - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq: handleAirInterfaceLoadReq(data); break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirLoadHyterra: // ignore for now + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirLoadHyterra: // ignore for now break; - default: - ERROR_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << data.at(4) - << " not implemented!"; + default: + ERROR_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << data.at(4) << " not implemented!"; break; } m_LogThread->writeRadioTelegramLog(data, true, 1); -} + } -// --------------------------------------------------------------- -// Processes the data-indication-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleDataIndReq(const QByteArray &data, bool bIsMaybeScrambled) -{ + // --------------------------------------------------------------- + // Processes the data-indication-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleDataIndReq(const QByteArray &data, bool bIsMaybeScrambled) + { N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(data); const uint32_t dstISSI = radioTelegram.getDestISSI(); if (m_bUseScrambling && bIsMaybeScrambled && m_EmergencyCallISSI != dstISSI) { - if (!unscrambleContent(radioTelegram)) - return; + if (!unscrambleContent(radioTelegram)) + return; } // after unscrambling... @@ -488,192 +474,176 @@ void PrtCnvRadioThread::handleDataIndReq(const QByteArray &data, bool bIsMaybeSc // TrafficLoad keine Fehlermeldung wenn nicht lizensiert if (radioTelegram.isNormalTelegram() && radioTelegram.getTelID() == GEF_ESW_MELDUNG) - return; + return; if (m_HostISSI == dstISSI || m_ListenGroups.find(dstISSI) != m_ListenGroups.end()) { - if (!m_radioTrafficThread) - m_radioTrafficThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_RadioTraffic)); - if (m_radioTrafficThread) - m_radioTrafficThread->newTelegramArrived(radioTelegram.getPayloadSize()); - // check whether the TPU is logged in (login telegrams will always be accepted) - // we do not check whether the ausstattungsnummer is correct (id from map[issi] == id from telegram), we simply trust the TNE - PrtCnvMember *member = m_DbThread->getMemberByISSI(radioTelegram.getSrcISSI()); // because of fragmented telegrams we have to use the ISSI (fragmented telegrams have no ausstattungsnummer) - if (radioTelegram.isLoginTelegram() || (member != nullptr)) + if (!m_radioTrafficThread) + m_radioTrafficThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_RadioTraffic)); + if (m_radioTrafficThread) + m_radioTrafficThread->newTelegramArrived(radioTelegram.getPayloadSize()); + // check whether the TPU is logged in (login telegrams will always be accepted) + // we do not check whether the ausstattungsnummer is correct (id from map[issi] == id from telegram), we simply trust the TNE + PrtCnvMember *member = m_DbThread->getMemberByISSI( + radioTelegram.getSrcISSI()); // because of fragmented telegrams we have to use the ISSI (fragmented telegrams have no ausstattungsnummer) + if (radioTelegram.isLoginTelegram() || (member != nullptr)) + { + switch (radioTelegram.getFragmentStatus()) { - switch (radioTelegram.getFragmentStatus()) + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment: + // check whether the member is licensed + if (member->m_Licensed) + handleFragmentedTelegram(radioTelegram); + else { - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment: - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment: - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment: - // check whether the member is licensed - if (member->m_Licensed) - handleFragmentedTelegram(radioTelegram); - else - { - // the TNE tries to send a telegramm without beeing licensed => unlicense the TNE - sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, - N_CoPrtCnv::E_LicensingKind::Unlicense, - N_CoPrtCnv::E_LicensingErrorCode::Unlicense); - // and send fehlermeldungGefechtsfeld to central - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, - N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == radioTelegram.getFragmentStatus() ? - radioTelegram.getTelID() : GEF_BESTAETIGUNG); - WARNING_LOG(m_logger) << "TNE with id=" << member->m_Id - << " tries to send a fragmented telegramm without beeing licensed"; - } - break; - - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented: - if (radioTelegram.isLoginTelegram()) - handleLoginTelegram(radioTelegram); - else if (radioTelegram.isNormalTelegram()) - { - if (radioTelegram.isCrcOk()) - { - radioTelegram.fixupTelegramIdForEts(false); - // check whether the member is licensed or whether it is the BITE-telegram for NEUE_ANMELDUNG or WIEDER_ANMELDUNG - gef_telegramm_id_et telId = radioTelegram.getTelID(); - // BITE must be send to central - no matter if licensed or not - bool bIsBite = (GEF_BITE_MELDUNG2 == telId); - - if (member->m_Licensed || bIsBite) - { - // check whether the content of telegram is correct - if (radioTelegram.isContentValid()) - { - // handle nachforderung broadcasts - if (m_BroadcastManager.handleRadioTelegram(radioTelegram)) - { - std::shared_ptr - centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); - if (centralTelegram) - { - // for some telegrams the protocol-converter has to send a response - // we have to generate this answer before storing, because storeCentralTelegram() overtakes - // centralTelegram and deletes it if no longer used. - if (sendAnswer(radioTelegram)) - { - // save data in persistent database - //storeCentralTelegram(centralTelegram, radioTelegram); - m_DbThread->storeCentralTelegram(centralTelegram, radioTelegram); - } - } - } - } - else - { - // and send fehlermeldungGefechtsfeld to central - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::InvalidByteCount, - telId); - ERROR_LOG(m_logger) << "The content of received telegram is wrong => thrown away"; - } - } - else - { - // the TNE tries to send a telegramm without beeing licensed => unlicense the TNE - sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, - N_CoPrtCnv::E_LicensingKind::Unlicense, - N_CoPrtCnv::E_LicensingErrorCode::Unlicense); - // and send fehlermeldungGefechtsfeld to central - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, - telId); - WARNING_LOG(m_logger) << "TNE with id=" << member->m_Id - << " tries to send a telegramm without beeing licensed"; - } - } - else - { - ERROR_LOG(m_logger) << "CRC of received telegram is wrong => thrown away"; - sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::WrongCrc, - radioTelegram.getTelID()); - } - } - else - { - ERROR_LOG(m_logger) << "Unknown non-fragmented telegram-type: 0x" - << QString::number(radioTelegram.getFragmentCounter(), 16); - sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - radioTelegram.getTelID()); - } - break; - default: - ERROR_LOG(m_logger) << "Unknown payload-status: " << radioTelegram.getFragmentStatus(); - sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - radioTelegram.getTelID()); - break; + // the TNE tries to send a telegramm without beeing licensed => unlicense the TNE + sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); + // and send fehlermeldungGefechtsfeld to central + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, + TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, + N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == radioTelegram.getFragmentStatus() ? radioTelegram.getTelID() + : GEF_BESTAETIGUNG); + WARNING_LOG(m_logger) << "TNE with id=" << member->m_Id << " tries to send a fragmented telegramm without beeing licensed"; } + break; + + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented: + if (radioTelegram.isLoginTelegram()) + handleLoginTelegram(radioTelegram); + else if (radioTelegram.isNormalTelegram()) + { + if (radioTelegram.isCrcOk()) + { + radioTelegram.fixupTelegramIdForEts(false); + // check whether the member is licensed or whether it is the BITE-telegram for NEUE_ANMELDUNG or WIEDER_ANMELDUNG + gef_telegramm_id_et telId = radioTelegram.getTelID(); + // BITE must be send to central - no matter if licensed or not + bool bIsBite = (GEF_BITE_MELDUNG2 == telId); + + if (member->m_Licensed || bIsBite) + { + // check whether the content of telegram is correct + if (radioTelegram.isContentValid()) + { + // handle nachforderung broadcasts + if (m_BroadcastManager.handleRadioTelegram(radioTelegram)) + { + std::shared_ptr centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); + if (centralTelegram) + { + // for some telegrams the protocol-converter has to send a response + // we have to generate this answer before storing, because storeCentralTelegram() overtakes + // centralTelegram and deletes it if no longer used. + if (sendAnswer(radioTelegram)) + { + // save data in persistent database + //storeCentralTelegram(centralTelegram, radioTelegram); + m_DbThread->storeCentralTelegram(centralTelegram, radioTelegram); + } + } + } + } + else + { + // and send fehlermeldungGefechtsfeld to central + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, TrainingAreaBase::TetraIcd::CtaDataError::Reason::InvalidByteCount, telId); + ERROR_LOG(m_logger) << "The content of received telegram is wrong => thrown away"; + } + } + else + { + // the TNE tries to send a telegramm without beeing licensed => unlicense the TNE + sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); + // and send fehlermeldungGefechtsfeld to central + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, telId); + WARNING_LOG(m_logger) << "TNE with id=" << member->m_Id << " tries to send a telegramm without beeing licensed"; + } + } + else + { + ERROR_LOG(m_logger) << "CRC of received telegram is wrong => thrown away"; + sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::WrongCrc, radioTelegram.getTelID()); + } + } + else + { + ERROR_LOG(m_logger) << "Unknown non-fragmented telegram-type: 0x" << QString::number(radioTelegram.getFragmentCounter(), 16); + sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), + TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, + radioTelegram.getTelID()); + } + break; + default: + ERROR_LOG(m_logger) << "Unknown payload-status: " << radioTelegram.getFragmentStatus(); + sendFehlermeldungGefechtsfeldToCentral(radioTelegram.getIdentity(), + TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, + radioTelegram.getTelID()); + break; } - else - { - ERROR_LOG(m_logger) << "The TPU with id=" << radioTelegram.getIdentity() - << " and ISSI=" << radioTelegram.getSrcISSI() - << " has sent a telegram without be logged in"; - // middle or last fragments have on identity => use identity 0 instead - bool hasId = !(radioTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment || radioTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment); - sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, hasId ? radioTelegram.getIdentity() : 0, radioTelegram.getSrcISSI()); - } + } + else + { + ERROR_LOG(m_logger) << "The TPU with id=" << radioTelegram.getIdentity() << " and ISSI=" << radioTelegram.getSrcISSI() + << " has sent a telegram without be logged in"; + // middle or last fragments have on identity => use identity 0 instead + bool hasId = !(radioTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment || + radioTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment); + sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, hasId ? radioTelegram.getIdentity() : 0, radioTelegram.getSrcISSI()); + } } else { - if (m_EmergencyCallISSI == dstISSI) - { - /* + if (m_EmergencyCallISSI == dstISSI) + { + /* 0000: a5 33 20 00 02 a4 0f 00 0008: 00 28 23 00 00 0a 17 0f 0010: 00 00 00 00 00 00 54 00 0018: 0a 00 00 65 38 e2 5b a2 0020: 49 00 00 2f */ - uint32_t arr[10]; - // payload starts at 27, byte 26 is fragment status in normal telegram but we need it here -> -1 - for (int i = 0; i < 10; ++i) - arr[i] = static_cast(radioTelegram.getPayloadDataUInt8(i - 1)); - for (int i = 0; i < 10; ++i) - DEBUG_LOG(m_logger) << "arr[" << i << "] = 0x" << QString::number(arr[i], 16); + uint32_t arr[10]; + // payload starts at 27, byte 26 is fragment status in normal telegram but we need it here -> -1 + for (int i = 0; i < 10; ++i) + arr[i] = static_cast(radioTelegram.getPayloadDataUInt8(i - 1)); + for (int i = 0; i < 10; ++i) + DEBUG_LOG(m_logger) << "arr[" << i << "] = 0x" << QString::number(arr[i], 16); - uint32_t x, y; - x = (arr[0] << 24) + (arr[1] << 16) + (arr[2] << 8) + arr[3]; - x = (x >> 3) & 0x1FFFFFF; - y = (arr[3] << 24) + (arr[4] << 16) + (arr[5] << 8) + arr[6]; - y = (y >> 3) & 0xFFFFFF; + uint32_t x, y; + x = (arr[0] << 24) + (arr[1] << 16) + (arr[2] << 8) + arr[3]; + x = (x >> 3) & 0x1FFFFFF; + y = (arr[3] << 24) + (arr[4] << 16) + (arr[5] << 8) + arr[6]; + y = (y >> 3) & 0xFFFFFF; - TrainingAreaBase::TetraIcd::EmergencyCall data; - double longitude = x * (360 / pow(2, 25)); - double latitude = y * (180 / pow(2, 24)); - data.absPosition.lon = longitude * (M_PI / 180.0); - data.absPosition.lat = latitude * (M_PI / 180.0); - data.issi = radioTelegram.getSrcISSI(); - data.timeStamp = QDateTime::currentMSecsSinceEpoch(); - auto tele(std::make_shared(data)); + TrainingAreaBase::TetraIcd::EmergencyCall data; + double longitude = x * (360 / pow(2, 25)); + double latitude = y * (180 / pow(2, 24)); + data.absPosition.lon = longitude * (M_PI / 180.0); + data.absPosition.lat = latitude * (M_PI / 180.0); + data.issi = radioTelegram.getSrcISSI(); + data.timeStamp = QDateTime::currentMSecsSinceEpoch(); + auto tele(std::make_shared(data)); - DEBUG_LOG(m_logger) << "Notruf lon: " << data.absPosition.lon << ", lat: " << data.absPosition.lat << ", issi: " << data.issi; + DEBUG_LOG(m_logger) << "Notruf lon: " << data.absPosition.lon << ", lat: " << data.absPosition.lat << ", issi: " << data.issi; - m_DbThread->storeCentralTelegram(tele, radioTelegram); - } - else - { - ERROR_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << QString::number(data.at(4)) - << " and telId=" << radioTelegram.getTelID() - << " is for another host: " << radioTelegram.getDestISSI() - << " (we are " << m_HostISSI << ")"; - - } + m_DbThread->storeCentralTelegram(tele, radioTelegram); + } + else + { + ERROR_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << QString::number(data.at(4)) << " and telId=" << radioTelegram.getTelID() + << " is for another host: " << radioTelegram.getDestISSI() << " (we are " << m_HostISSI << ")"; + } } -} + } -// --------------------------------------------------------------- -// Processes the login-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleLoginTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram) -{ + // --------------------------------------------------------------- + // Processes the login-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleLoginTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram) + { using namespace N_CoPrtCnv; uint16_t identity = a_loginTelegram.getIdentity(); @@ -681,31 +651,30 @@ void PrtCnvRadioThread::handleLoginTelegram(const N_CoPrtCnv::CoPrtCnvRadioTeleg // is it a login request? if (CoPrtCnvRadioTelegram::e_LoginRequest != (a_loginTelegram.getPayloadDataUInt8(2) & CoPrtCnvRadioTelegram::e_LoginStatusMask)) { - ERROR_LOG(m_logger) << QStringLiteral("Unexpected login-status: 0x%1").arg(a_loginTelegram.getPayloadDataUInt8(2), 2, 16, QLatin1Char('0')); - return; + ERROR_LOG(m_logger) << QStringLiteral("Unexpected login-status: 0x%1").arg(a_loginTelegram.getPayloadDataUInt8(2), 2, 16, QLatin1Char('0')); + return; } // tries a TNE to use the identity or ISSI used for broadcast? if (0 == identity || m_BroadcastISSI == issi) { - sendLoginResponse(CoPrtCnvRadioTelegram::e_LoginReject, identity, issi); - sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorLoginEquipmentNumber); - writeLoginLog(a_loginTelegram, - QStringLiteral("Login-failure: New TPU with Id=%1 and ISSI=%2 tries to use broadcast-id or -issi => rejected").arg(identity).arg(issi)); - return; + sendLoginResponse(CoPrtCnvRadioTelegram::e_LoginReject, identity, issi); + sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorLoginEquipmentNumber); + writeLoginLog(a_loginTelegram, + QStringLiteral("Login-failure: New TPU with Id=%1 and ISSI=%2 tries to use broadcast-id or -issi => rejected").arg(identity).arg(issi)); + return; } const bool bIsMasteringFlag = (a_loginTelegram.getPayloadDataUInt8(2) & CoPrtCnvRadioTelegram::e_LoginMastering) == CoPrtCnvRadioTelegram::e_LoginMastering; PrtCnvMember *member = m_DbThread->getMemberById(identity); PrtCnvMember *issiMember = m_DbThread->getMemberByISSI(issi); - DEBUG_LOG(m_logger) << "TPU with id=" << identity << " and ISSI=" - << issi << " tries to log in, mastering: " << bIsMasteringFlag; + DEBUG_LOG(m_logger) << "TPU with id=" << identity << " and ISSI=" << issi << " tries to log in, mastering: " << bIsMasteringFlag; if (bIsMasteringFlag && member != issiMember) { - removeMasteringMember(a_loginTelegram, member, issiMember, identity, issi); - member = nullptr; - issiMember = nullptr; + removeMasteringMember(a_loginTelegram, member, issiMember, identity, issi); + member = nullptr; + issiMember = nullptr; } const int tpuExId = exerciseIdForIdentity(identity); @@ -714,196 +683,180 @@ void PrtCnvRadioThread::handleLoginTelegram(const N_CoPrtCnv::CoPrtCnvRadioTeleg // is a TPU with same ID or ISSI already logged in? if (member || issiMember) { - // TPU already logged in - // is it a relogin of the same TPU? - if (member && (issi == uint32_t(member->m_ISSI))) + // TPU already logged in + // is it a relogin of the same TPU? + if (member && (issi == uint32_t(member->m_ISSI))) + { + // relogin of a TPU + // ---------------- + // relogin happens when a TPU was powered off and on again, therefore it should no longer be licensed + if (member->m_Licensed) + m_DbThread->licenseMember(member, false); + m_DbThread->updateExerciseIdForMember(member, m_ExerciseId); + // send answer to TPU + sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); + } + else + { + if (bIsMasteringFlag) { - // relogin of a TPU - // ---------------- - // relogin happens when a TPU was powered off and on again, therefore it should no longer be licensed - if (member->m_Licensed) - m_DbThread->licenseMember(member, false); - m_DbThread->updateExerciseIdForMember(member, m_ExerciseId); - // send answer to TPU - sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); + // accept new TPU + m_DbThread->addMember(identity, issi); + // send answer to TNE + sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); + sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::InfoLoginMasteringFlag); } else { - if (bIsMasteringFlag) - { - // accept new TPU - m_DbThread->addMember(identity, issi); - // send answer to TNE - sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); - sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::InfoLoginMasteringFlag); - } - else - { - // mastering-bit is not set => reject the new TPU - // ---------------------------------------------- - int rejectCause = 0; - if (issiMember) - rejectCause |= CoPrtCnvRadioTelegram::e_LoginOtherISSI; - else if (member) - rejectCause |= CoPrtCnvRadioTelegram::e_LoginOtherEqId; - else - rejectCause |= CoPrtCnvRadioTelegram::e_LoginMastering; // can not happen - rejectCause |= CoPrtCnvRadioTelegram::e_LoginReject; + // mastering-bit is not set => reject the new TPU + // ---------------------------------------------- + int rejectCause = 0; + if (issiMember) + rejectCause |= CoPrtCnvRadioTelegram::e_LoginOtherISSI; + else if (member) + rejectCause |= CoPrtCnvRadioTelegram::e_LoginOtherEqId; + else + rejectCause |= CoPrtCnvRadioTelegram::e_LoginMastering; // can not happen + rejectCause |= CoPrtCnvRadioTelegram::e_LoginReject; - sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(rejectCause), - identity, issi); - sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorLoginEquipmentNumber); - writeLoginLog(a_loginTelegram, - QStringLiteral("Login-failure: Another TPU with Id=%1 and ISSI=%2 without mastering tried to log in => rejected").arg(identity).arg(issi)); - } + sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(rejectCause), identity, issi); + sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorLoginEquipmentNumber); + writeLoginLog(a_loginTelegram, + QStringLiteral("Login-failure: Another TPU with Id=%1 and ISSI=%2 without mastering tried to log in => rejected").arg(identity).arg(issi)); } + } } else { - // TPU not yet logged in => add new TPU - // ------------------------------------ - m_DbThread->addMember(identity, issi); - m_DbThread->updateExerciseIdForMember(issiMember, m_ExerciseId); - // send answer to TNE - sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); + // TPU not yet logged in => add new TPU + // ------------------------------------ + m_DbThread->addMember(identity, issi); + m_DbThread->updateExerciseIdForMember(issiMember, m_ExerciseId); + // send answer to TNE + sendLoginAccept(identity, issi, tpuExId, bIsMasteringFlag); } -} + } -// --------------------------------------------------------------- -// Processes a fragment of a telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_fragmentedTelegram) -{ + // --------------------------------------------------------------- + // Processes a fragment of a telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_fragmentedTelegram) + { PrtCnvMember *member = m_DbThread->getMemberByISSI(a_fragmentedTelegram.getSrcISSI()); if (member) { - if (a_fragmentedTelegram.isCrcOk()) + if (a_fragmentedTelegram.isCrcOk()) + { + bool doAddFragment = true; + if (a_fragmentedTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment) { - bool doAddFragment = true; - if (a_fragmentedTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment) + // first fragment => check whether the previous fragmented telegram was complete + // -------------- + if (!member->isFragmentedListEmpty()) + { + ERROR_LOG(m_logger) << "Did not get the last radio-telegram-fragment"; + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, member->getFragmentedTelegramId()); + member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself + } + } + else if (a_fragmentedTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment) + { + // last fragment => check whether at least one fragment was received + // ------------- + if (member->isFragmentedListEmpty()) + { + ERROR_LOG(m_logger) << "Got a lonely last radio-telegram-fragment"; + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, member->getFragmentedTelegramId()); + } + else + { + // it seems we got all fragments => build the not fragmented telegram + member->addFragmentedTelegram(a_fragmentedTelegram); + const QByteArray unfragmentedRadioTelegramData = member->getUnfragmentedTelegramData(); + if (!unfragmentedRadioTelegramData.isEmpty()) { - // first fragment => check whether the previous fragmented telegram was complete - // -------------- - if (!member->isFragmentedListEmpty()) - { - ERROR_LOG(m_logger) << "Did not get the last radio-telegram-fragment"; - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - member->getFragmentedTelegramId()); - member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself - } - } - else if (a_fragmentedTelegram.getFragmentStatus() == N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment) - { - // last fragment => check whether at least one fragment was received - // ------------- - if (member->isFragmentedListEmpty()) - { - ERROR_LOG(m_logger) << "Got a lonely last radio-telegram-fragment"; - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - member->getFragmentedTelegramId()); - } - else - { - // it seems we got all fragments => build the not fragmented telegram - member->addFragmentedTelegram(a_fragmentedTelegram); - const QByteArray unfragmentedRadioTelegramData = member->getUnfragmentedTelegramData(); - if (!unfragmentedRadioTelegramData.isEmpty()) - { - // last but not least, handle the new build unfragmented telegram - // size = 0 is ok - it's a payload tleegram and size will be calculated later on - handleDataIndReq(unfragmentedRadioTelegramData, false); - } - else - sendFehlermeldungGefechtsfeldToCentral(member->m_Id, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - member->getFragmentedTelegramId()); - } - member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself - doAddFragment = false; + // last but not least, handle the new build unfragmented telegram + // size = 0 is ok - it's a payload tleegram and size will be calculated later on + handleDataIndReq(unfragmentedRadioTelegramData, false); } else - { - // middle-fragment => check whether the first fragment was received - // --------------- - if (member->isFragmentedListEmpty()) - { - ERROR_LOG(m_logger) << "Did not get the first radio-telegram-fragment"; - // wait with the error-message (FehlermeldungGefechtsfeld) to central until the last fragment is received, otherwise we get for every fragment an error - member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself - doAddFragment = false; - } - } - - // simply add the fragment to its member - if (doAddFragment) - { - member->addFragmentedTelegram(a_fragmentedTelegram); - } + sendFehlermeldungGefechtsfeldToCentral(member->m_Id, + TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, + member->getFragmentedTelegramId()); + } + member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself + doAddFragment = false; } else - ERROR_LOG(m_logger) << "CRC of received fragmented telegram is wrong => thorw away"; + { + // middle-fragment => check whether the first fragment was received + // --------------- + if (member->isFragmentedListEmpty()) + { + ERROR_LOG(m_logger) << "Did not get the first radio-telegram-fragment"; + // wait with the error-message (FehlermeldungGefechtsfeld) to central until the last fragment is received, otherwise we get for every fragment an error + member->clearFragmentedList(); // deletes also the fragmented radio-telegrams itself + doAddFragment = false; + } + } + + // simply add the fragment to its member + if (doAddFragment) + { + member->addFragmentedTelegram(a_fragmentedTelegram); + } + } + else + ERROR_LOG(m_logger) << "CRC of received fragmented telegram is wrong => thorw away"; } else - ERROR_LOG(m_logger) << "Internal error: Did not found the TNE with ISSI=" << a_fragmentedTelegram.getSrcISSI() << " in member-list"; -} + ERROR_LOG(m_logger) << "Internal error: Did not found the TNE with ISSI=" << a_fragmentedTelegram.getSrcISSI() << " in member-list"; + } -// --------------------------------------------------------------- -// Processes the BITE extended-telegram -// --------------------------------------------------------------- -bool PrtCnvRadioThread::handleBITEEXT_Telegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_BITE_RadioTelegram) -{ - auto anmeldeart = static_cast(a_BITE_RadioTelegram.getPayloadDataUInt32(7, 1)); - uint32_t ergebnisCAN = a_BITE_RadioTelegram.getPayloadDataUInt32(8, 3); - uint32_t ergebnisAusstattung = a_BITE_RadioTelegram.getPayloadDataUInt8(11); + // --------------------------------------------------------------- + // Processes the BITE extended-telegram + // --------------------------------------------------------------- + bool PrtCnvRadioThread::handleBITEEXT_Telegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_BITE_RadioTelegram) + { + auto anmeldeart = static_cast(a_BITE_RadioTelegram.getPayloadDataUInt32(7, 1)); + uint32_t ergebnisCAN = a_BITE_RadioTelegram.getPayloadDataUInt32(8, 3); + uint32_t ergebnisAusstattung = a_BITE_RadioTelegram.getPayloadDataUInt8(11); uint32_t konfigurationsvergleich = a_BITE_RadioTelegram.getPayloadDataUInt8(23); - uint32_t aktuelleKonfiguration = a_BITE_RadioTelegram.getPayloadDataUInt32(24, 3); + uint32_t aktuelleKonfiguration = a_BITE_RadioTelegram.getPayloadDataUInt32(24, 3); //rad all byte errors for warehouse traffic light? QList fehlerListe; const auto nonDynamic = getBiteError(a_BITE_RadioTelegram, 12); - if (nonDynamic.errorNumber != 0 || - nonDynamic.canDeviceNumber != 0 || - nonDynamic.subdeviceNumber != 0 || - nonDynamic.uniqueId != 0) - fehlerListe.append(nonDynamic); + if (nonDynamic.errorNumber != 0 || nonDynamic.canDeviceNumber != 0 || nonDynamic.subdeviceNumber != 0 || nonDynamic.uniqueId != 0) + fehlerListe.append(nonDynamic); const uint8_t fehlerLen = a_BITE_RadioTelegram.getPayloadDataUInt8(19); for (uint8_t i = 0; i < fehlerLen; ++i) { - const uint8_t iPos = 27 + i * 7; - fehlerListe.append(getBiteError(a_BITE_RadioTelegram, iPos)); + const uint8_t iPos = 27 + i * 7; + fehlerListe.append(getBiteError(a_BITE_RadioTelegram, iPos)); } - return handleBITE_Telegram(a_BITE_RadioTelegram, - anmeldeart, - ergebnisCAN, - ergebnisAusstattung, - aktuelleKonfiguration, - konfigurationsvergleich, - fehlerListe - ); -} + return handleBITE_Telegram(a_BITE_RadioTelegram, anmeldeart, ergebnisCAN, ergebnisAusstattung, aktuelleKonfiguration, konfigurationsvergleich, fehlerListe); + } -bool PrtCnvRadioThread::handleBITE_Telegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_BITE_RadioTelegram, - TrainingAreaBase::TetraIcd::BiteReport::LoginType anmeldeart, - uint32_t ergebnisCAN, - uint32_t ergebnisAusstattung, - uint32_t aktuelleKonfiguration, - uint32_t konfigurationsvergleich, - const QList &fehlerListe - ) -{ + bool PrtCnvRadioThread::handleBITE_Telegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_BITE_RadioTelegram, + TrainingAreaBase::TetraIcd::BiteReport::LoginType anmeldeart, + uint32_t ergebnisCAN, + uint32_t ergebnisAusstattung, + uint32_t aktuelleKonfiguration, + uint32_t konfigurationsvergleich, + const QList &fehlerListe) + { switch (anmeldeart) { - case TrainingAreaBase::TetraIcd::BiteReport::LoginType::InvalidLogin: // should not be sent + case TrainingAreaBase::TetraIcd::BiteReport::LoginType::InvalidLogin: // should not be sent return true; - case TrainingAreaBase::TetraIcd::BiteReport::LoginType::NoLogin: - case TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin: - case TrainingAreaBase::TetraIcd::BiteReport::LoginType::Relogin: - { + case TrainingAreaBase::TetraIcd::BiteReport::LoginType::NoLogin: + case TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin: + case TrainingAreaBase::TetraIcd::BiteReport::LoginType::Relogin: + { const uint16_t identity = a_BITE_RadioTelegram.getIdentity(); bool doForwardBiteMeldung = true; QString logText(QStringLiteral("Licensing: The TPU with Id=%1 and ISSI=%2").arg(identity).arg(a_BITE_RadioTelegram.getSrcISSI())); @@ -912,198 +865,191 @@ bool PrtCnvRadioThread::handleBITE_Telegram(const N_CoPrtCnv::CoPrtCnvRadioTeleg PrtCnvMember *member = m_DbThread->getMemberById(identity); if (member) { - // TPU is logged in - // is the ISSI correct? - if (a_BITE_RadioTelegram.getSrcISSI() == uint32_t(member->m_ISSI)) + // TPU is logged in + // is the ISSI correct? + if (a_BITE_RadioTelegram.getSrcISSI() == uint32_t(member->m_ISSI)) + { + // the ISSI is correct + // is the identity vaild? + if (isIdentityValid(identity)) { - // the ISSI is correct - // is the identity vaild? - if (isIdentityValid(identity)) - { - m_DbThread->updateExerciseIdForMember(member, m_ExerciseId); - // already licensed? - if (!member->m_Licensed) - { - m_DbThread->licenseMember(member); - if (TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin == anmeldeart) - logText += QStringLiteral(" is now licensed"); - else - logText += QStringLiteral(" is now licensed (WIEDER_ANMELDUNG instead NEUE_ANMELDUNG used!)"); - } - else - { - if (TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin == anmeldeart) - logText += QStringLiteral(" is now relicensed (NEUE_ANMELDUNG instead WIEDER_ANMELDUNG used!)"); - else - logText += QStringLiteral(" is now relicensed"); - } - // check the configuration and selftest - N_CoPrtCnv::E_LicensingErrorCode errorCode = N_CoPrtCnv::E_LicensingErrorCode::Ok; // ask ehrlicher (16): inform RDE about the error-codes - // Error-Code in aufsteigender Prioritaet! - if (ergebnisAusstattung != 1) - { - // battery-warning - errorCode = N_CoPrtCnv::E_LicensingErrorCode::Battery; - logText += QStringLiteral(", has battery-Warning"); - } - if ((ergebnisCAN & aktuelleKonfiguration) != aktuelleKonfiguration) - { - // failure in selftest - errorCode = N_CoPrtCnv::E_LicensingErrorCode::Selftest; - logText += QStringLiteral(", but selftest is failed"); - } - if (konfigurationsvergleich != 0) - { - // configuraton-failure - errorCode = N_CoPrtCnv::E_LicensingErrorCode::Configuration; - logText += QStringLiteral(", but has configuration-failure: "); - } - bool selftestOrConfigError = (errorCode == N_CoPrtCnv::E_LicensingErrorCode::Configuration || errorCode == N_CoPrtCnv::E_LicensingErrorCode::Selftest); - bool doLicense = !(selftestOrConfigError && !m_DoLicenseDespiteSelftestOrConfigFailure); - - prepareWareHouseMessage(identity, doLicense, ergebnisCAN, ergebnisAusstattung, aktuelleKonfiguration, konfigurationsvergleich, fehlerListe); - if (anmeldeart == TrainingAreaBase::TetraIcd::BiteReport::LoginType::NoLogin) - return true; - // send the FehlermeldungGefechtsfeld message to central - // send the Lizensierung-TNE telegram to TPU - sendLizenzierungTneToRadio(identity, member->m_ISSI, - doLicense ? N_CoPrtCnv::E_LicensingKind::Success : N_CoPrtCnv::E_LicensingKind::Rejected, - errorCode); - - // set active position response - if (doLicense) - m_DoNeedActPosResp.insert(identity); - if (selftestOrConfigError) - sendFehlermeldungGefechtsfeldToCentral(identity, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorConfigSelfTest, - a_BITE_RadioTelegram.getTelID()); - - - // generate the login-log-entry - if (selftestOrConfigError && !m_DoLicenseDespiteSelftestOrConfigFailure) - { - logText = QStringLiteral("Licensing: The TPU with Id=%1 and ISSI=%2").arg(identity).arg(a_BITE_RadioTelegram.getSrcISSI()); - logText += QStringLiteral(" could not be licensed, because "); - if (errorCode == N_CoPrtCnv::E_LicensingErrorCode::Configuration) - logText += QStringLiteral("of configuration-failure"); - else - logText += QStringLiteral("selftest failed"); - } - } + m_DbThread->updateExerciseIdForMember(member, m_ExerciseId); + // already licensed? + if (!member->m_Licensed) + { + m_DbThread->licenseMember(member); + if (TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin == anmeldeart) + logText += QStringLiteral(" is now licensed"); else - { - // identity is not vaild => send the Lizenzierung-TNE.Abmeldung telegram to TPU and Fehlermeldung to central - sendLizenzierungTneToRadio(identity, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Rejected, N_CoPrtCnv::E_LicensingErrorCode::IdentityDenied); - sendFehlermeldungGefechtsfeldToCentral(identity, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorSendingNamelist, - a_BITE_RadioTelegram.getTelID()); - logText += QStringLiteral(" could not be licensed because PlayerID is not allowed"); - } + logText += QStringLiteral(" is now licensed (WIEDER_ANMELDUNG instead NEUE_ANMELDUNG used!)"); + } + else + { + if (TrainingAreaBase::TetraIcd::BiteReport::LoginType::NewLogin == anmeldeart) + logText += QStringLiteral(" is now relicensed (NEUE_ANMELDUNG instead WIEDER_ANMELDUNG used!)"); + else + logText += QStringLiteral(" is now relicensed"); + } + // check the configuration and selftest + N_CoPrtCnv::E_LicensingErrorCode errorCode = N_CoPrtCnv::E_LicensingErrorCode::Ok; // ask ehrlicher (16): inform RDE about the error-codes + // Error-Code in aufsteigender Prioritaet! + if (ergebnisAusstattung != 1) + { + // battery-warning + errorCode = N_CoPrtCnv::E_LicensingErrorCode::Battery; + logText += QStringLiteral(", has battery-Warning"); + } + if ((ergebnisCAN & aktuelleKonfiguration) != aktuelleKonfiguration) + { + // failure in selftest + errorCode = N_CoPrtCnv::E_LicensingErrorCode::Selftest; + logText += QStringLiteral(", but selftest is failed"); + } + if (konfigurationsvergleich != 0) + { + // configuraton-failure + errorCode = N_CoPrtCnv::E_LicensingErrorCode::Configuration; + logText += QStringLiteral(", but has configuration-failure: "); + } + bool selftestOrConfigError = (errorCode == N_CoPrtCnv::E_LicensingErrorCode::Configuration || errorCode == N_CoPrtCnv::E_LicensingErrorCode::Selftest); + bool doLicense = !(selftestOrConfigError && !m_DoLicenseDespiteSelftestOrConfigFailure); + + prepareWareHouseMessage(identity, doLicense, ergebnisCAN, ergebnisAusstattung, aktuelleKonfiguration, konfigurationsvergleich, fehlerListe); + if (anmeldeart == TrainingAreaBase::TetraIcd::BiteReport::LoginType::NoLogin) + return true; + // send the FehlermeldungGefechtsfeld message to central + // send the Lizensierung-TNE telegram to TPU + sendLizenzierungTneToRadio(identity, member->m_ISSI, doLicense ? N_CoPrtCnv::E_LicensingKind::Success : N_CoPrtCnv::E_LicensingKind::Rejected, errorCode); + + // set active position response + if (doLicense) + m_DoNeedActPosResp.insert(identity); + if (selftestOrConfigError) + sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorConfigSelfTest, a_BITE_RadioTelegram.getTelID()); + + + // generate the login-log-entry + if (selftestOrConfigError && !m_DoLicenseDespiteSelftestOrConfigFailure) + { + logText = QStringLiteral("Licensing: The TPU with Id=%1 and ISSI=%2").arg(identity).arg(a_BITE_RadioTelegram.getSrcISSI()); + logText += QStringLiteral(" could not be licensed, because "); + if (errorCode == N_CoPrtCnv::E_LicensingErrorCode::Configuration) + logText += QStringLiteral("of configuration-failure"); + else + logText += QStringLiteral("selftest failed"); + } } else { - // ISSIs are different => send a login-reject-telegram to this TPU - sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, identity, a_BITE_RadioTelegram.getSrcISSI()); - logText += QStringLiteral(" could not be licensed because ISSI is wrong"); - doForwardBiteMeldung = false; + // identity is not vaild => send the Lizenzierung-TNE.Abmeldung telegram to TPU and Fehlermeldung to central + sendLizenzierungTneToRadio(identity, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Rejected, N_CoPrtCnv::E_LicensingErrorCode::IdentityDenied); + sendFehlermeldungGefechtsfeldToCentral(identity, TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorSendingNamelist, a_BITE_RadioTelegram.getTelID()); + logText += QStringLiteral(" could not be licensed because PlayerID is not allowed"); } + } + else + { + // ISSIs are different => send a login-reject-telegram to this TPU + sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, identity, a_BITE_RadioTelegram.getSrcISSI()); + logText += QStringLiteral(" could not be licensed because ISSI is wrong"); + doForwardBiteMeldung = false; + } } else { - // TPU is not logged in => send a login-reject-telegram to this TPU - sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, identity, a_BITE_RadioTelegram.getSrcISSI()); - logText += QStringLiteral(" wants to be licensed but is not logged in"); - doForwardBiteMeldung = false; + // TPU is not logged in => send a login-reject-telegram to this TPU + sendLoginResponse(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginReject, identity, a_BITE_RadioTelegram.getSrcISSI()); + logText += QStringLiteral(" wants to be licensed but is not logged in"); + doForwardBiteMeldung = false; } writeLoginLog(a_BITE_RadioTelegram, logText); return doForwardBiteMeldung; - } + } } ERROR_LOG(m_logger) << "BITE-Meldung contains unknown anmeldeart: " << static_cast(anmeldeart); return true; -} + } -// --------------------------------------------------------------- -// Checks whether a normal telegram must be sent and sends it. -// --------------------------------------------------------------- -void PrtCnvRadioThread::checkSend() -{ + // --------------------------------------------------------------- + // Checks whether a normal telegram must be sent and sends it. + // --------------------------------------------------------------- + void PrtCnvRadioThread::checkSend() + { // eat all pending timeoutAck if (m_DoCleanup) - return; + return; if (PrtCnvSocketThread::e_WORKING != m_State) - return; + return; if (isSendLimitReached()) - return; + return; PrtCnvStoredRadioTelegram *handle = nullptr; const auto radioTelegram = m_DbThread->getNextRadioTelegram(handle); if (radioTelegram) { - // for normal (not fragmented, no login-) telegrams from central we could have to do special action - // which will be done before sending - if (radioTelegram->isNormalTelegram()) + // for normal (not fragmented, no login-) telegrams from central we could have to do special action + // which will be done before sending + if (radioTelegram->isNormalTelegram()) + { + switch (radioTelegram->getTelID()) { - switch (radioTelegram->getTelID()) + case GEF_UMGEBUNGS_MELDUNG2: + { + const int exerciseId = radioTelegram->getPayloadDataUInt32(5, 2); + if (m_ExerciseId != exerciseId) { - case GEF_UMGEBUNGS_MELDUNG2: - { - const int exerciseId = radioTelegram->getPayloadDataUInt32(5, 2); - if (m_ExerciseId != exerciseId) - { - ERROR_LOG(m_logger) << "Started with exercise Id " << m_ExerciseId << " but got environment telegram for exercise " << exerciseId; - exit(5); - } + ERROR_LOG(m_logger) << "Started with exercise Id " << m_ExerciseId << " but got environment telegram for exercise " << exerciseId; + exit(5); + } - if (m_ExerciseId > 0 && !m_EnvironmentTelegramTimer) - { - m_EnvironmentTelegramTimer = new QTimer(this); - connect(m_EnvironmentTelegramTimer, &QTimer::timeout, this, &PrtCnvRadioThread::timeoutEnvironmentTelegram, Qt::QueuedConnection); - } - // start the timer - if (m_EnvironmentTelegramTimer) - { - INFO_LOG(m_logger) << "I got the Umgebungsmeldung-Telegram => I start now sending Umgebungsmeldung periodically"; - m_EnvironmentTelegramTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("CyclicEnvironmentTime"), 30) * 1000); - m_EnvironmentTelegramTimer->start(); - } - // if we would not set here the resetCounter, the Umgebungsmeldung would be sent twice - radioTelegram->setPayloadDataWithIndex(7, m_DbThread->getResetCounter(), 1); - break; - } - case GEF_WIRKFELD_STATUS_MINENSPERRE: + if (m_ExerciseId > 0 && !m_EnvironmentTelegramTimer) { - uint16_t wirkfeldKennung = radioTelegram->getPayloadDataUInt32(5, 2); - if (m_BroadcastManager.isEffectSimulationIdDeactivated(wirkfeldKennung)) - { - WARNING_LOG(m_logger) << "Special Handling for GEF_WIRKFELD_STATUS_MINENSPERRE with id " << wirkfeldKennung - << " -> do not send to CTA"; - m_DbThread->radioTelegramSent(m_SendCounter, handle, 0); // mark as sent in DB without BC - return; // GEF_WIRKFELD_STATUS_MINENSPERRE for already deactivated mine areas are not send - } - break; + m_EnvironmentTelegramTimer = new QTimer(this); + connect(m_EnvironmentTelegramTimer, &QTimer::timeout, this, &PrtCnvRadioThread::timeoutEnvironmentTelegram, Qt::QueuedConnection); } - default: - // no special action - break; + // start the timer + if (m_EnvironmentTelegramTimer) + { + INFO_LOG(m_logger) << "I got the Umgebungsmeldung-Telegram => I start now sending Umgebungsmeldung periodically"; + m_EnvironmentTelegramTimer->setInterval(m_Config->getInteger(getName(), QStringLiteral("CyclicEnvironmentTime"), 30) * 1000); + m_EnvironmentTelegramTimer->start(); } + // if we would not set here the resetCounter, the Umgebungsmeldung would be sent twice + radioTelegram->setPayloadDataWithIndex(7, m_DbThread->getResetCounter(), 1); + break; + } + case GEF_WIRKFELD_STATUS_MINENSPERRE: + { + uint16_t wirkfeldKennung = radioTelegram->getPayloadDataUInt32(5, 2); + if (m_BroadcastManager.isEffectSimulationIdDeactivated(wirkfeldKennung)) + { + WARNING_LOG(m_logger) << "Special Handling for GEF_WIRKFELD_STATUS_MINENSPERRE with id " << wirkfeldKennung << " -> do not send to CTA"; + m_DbThread->radioTelegramSent(m_SendCounter, handle, 0); // mark as sent in DB without BC + return; // GEF_WIRKFELD_STATUS_MINENSPERRE for already deactivated mine areas are not send + } + break; + } + default: + // no special action + break; } + } - sendTelegram(radioTelegram, handle); + sendTelegram(radioTelegram, handle); - emit checkSendToRadio(); + emit checkSendToRadio(); } -} + } -// --------------------------------------------------------------- -// Processes the periodical stuff, like broadcasts and -// nachforderungen -// --------------------------------------------------------------- -void PrtCnvRadioThread::timeoutTick() -{ + // --------------------------------------------------------------- + // Processes the periodical stuff, like broadcasts and + // nachforderungen + // --------------------------------------------------------------- + void PrtCnvRadioThread::timeoutTick() + { // INFO_LOG(m_logger) << "tick"; // todo: /* - jede sekunde statistik-daten updaten (achtung tick is 500ms und konfigurierbar) @@ -1112,104 +1058,104 @@ void PrtCnvRadioThread::timeoutTick() - broadcast-manager muss window abhängig von load ändern */ // eat all pending timeoutAck - if (m_DoCleanup) return; + if (m_DoCleanup) + return; startTickTimer(); // send normal broadcasts checkSend(); if (!isSendLimitReached()) { - time_t currentTime = time(nullptr); - auto broadcastTelegram = m_BroadcastManager.getNextBroadcastTelegramToSend(0, currentTime); - while (broadcastTelegram) - { - uint16_t broadcastIndex = broadcastTelegram->getBroadcastIndex(); - sendTelegram(broadcastTelegram, nullptr, false); // false => do not check whether expired + time_t currentTime = time(nullptr); + auto broadcastTelegram = m_BroadcastManager.getNextBroadcastTelegramToSend(0, currentTime); + while (broadcastTelegram) + { + uint16_t broadcastIndex = broadcastTelegram->getBroadcastIndex(); + sendTelegram(broadcastTelegram, nullptr, false); // false => do not check whether expired - if (isSendLimitReached()) - broadcastTelegram = nullptr; - else - broadcastTelegram = m_BroadcastManager.getNextBroadcastTelegramToSend(broadcastIndex, currentTime); - } + if (isSendLimitReached()) + broadcastTelegram = nullptr; + else + broadcastTelegram = m_BroadcastManager.getNextBroadcastTelegramToSend(broadcastIndex, currentTime); + } } else - INFO_LOG(m_logger) << "send limit reached"; + INFO_LOG(m_logger) << "send limit reached"; // send nachforderung m_BroadcastManager.incTickAndSetTrafficLoad(E_TrafficLoad::HighLoad == m_SendLoad, E_TrafficLoad::FullLoad == m_SendLoad); if (!isSendLimitReached()) { - auto radioTelegram = m_BroadcastManager.getNextNachforderungTelegramToSend(); - if (radioTelegram) - sendTelegram(radioTelegram, nullptr, false); // false => do not check whether expired + auto radioTelegram = m_BroadcastManager.getNextNachforderungTelegramToSend(); + if (radioTelegram) + sendTelegram(radioTelegram, nullptr, false); // false => do not check whether expired } // do we have to inject a radio-telegram? try { - N_CoPrtCnv::CoPrtCnvCentralTelegram *radioInjectTelegram; - while ((radioInjectTelegram = m_InjectionThread->getNextRadioInjectionTelegram())) + N_CoPrtCnv::CoPrtCnvCentralTelegram *radioInjectTelegram; + while ((radioInjectTelegram = m_InjectionThread->getNextRadioInjectionTelegram())) + { + if (radioInjectTelegram->telegramId() == TrainingAreaBase::TetraIcd::TelegramId::NACHFORDERUNG_BROADCAST_TELEGRAMME) { - if (radioInjectTelegram->telegramId() == TrainingAreaBase::TetraIcd::TelegramId::NACHFORDERUNG_BROADCAST_TELEGRAMME) - { - const auto tele = TrainingAreaBase::TetraIcd::RequestBroadcastTelegrams::fromJson(radioInjectTelegram->jsonData()); - onBroadcastTelegramsRequestFromCentral(tele.header.equipmentNumber, tele.broadcastIndex, tele.resetCounter); - delete radioInjectTelegram; - continue; - } - std::shared_ptr - radioTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(radioInjectTelegram)); - if (radioTelegram) - sendTelegram(radioTelegram, nullptr, false); - delete radioInjectTelegram; + const auto tele = TrainingAreaBase::TetraIcd::RequestBroadcastTelegrams::fromJson(radioInjectTelegram->jsonData()); + onBroadcastTelegramsRequestFromCentral(tele.header.equipmentNumber, tele.broadcastIndex, tele.resetCounter); + delete radioInjectTelegram; + continue; } + std::shared_ptr radioTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(radioInjectTelegram)); + if (radioTelegram) + sendTelegram(radioTelegram, nullptr, false); + delete radioInjectTelegram; + } } catch (std::exception &e) { - ERROR_LOG(m_logger) << "Catched an unexpected exception: " << e.what() << " => could not inject radio-telegram, but we proceed..."; + ERROR_LOG(m_logger) << "Catched an unexpected exception: " << e.what() << " => could not inject radio-telegram, but we proceed..."; } // send imediately the umgebungsmeldung, when the reset-counter changes if (m_DbThread->isEnvironmentResetCounterOld()) - timeoutEnvironmentTelegram(); + timeoutEnvironmentTelegram(); computeAndLogTrafficStatistics(); -} + } -// --------------------------------------------------------------- -// see base-class -// --------------------------------------------------------------- -void PrtCnvRadioThread::timeoutAliveAndConnection() -{ + // --------------------------------------------------------------- + // see base-class + // --------------------------------------------------------------- + void PrtCnvRadioThread::timeoutAliveAndConnection() + { INFO_LOG(m_logger) << "timeoutAliveAndConnection socketState=" << m_Socket->state() << " m_State=" << m_State; switch (m_State) { - case e_CONNECTING: + case e_CONNECTING: connectSocket(); break; - case e_REGISTERING: - case e_WORKING: + case e_REGISTERING: + case e_WORKING: break; - case e_DISCONNECTING: + case e_DISCONNECTING: m_Socket->abort(); break; - default: + default: ERROR_LOG(m_logger) << "timeoutAlive for m_State=" << m_State << " not implemented"; } -} + } -// --------------------------------------------------------------- -// Sends a telegram to radio. It will be fragmented if needed. -// It will be checked, whether the receiver is logged in, -// licensed, the content is valid and the telegram is not -// expired and an error-message will be sent to central if -// needed. It will be tested, whether the maximal broadcast- -// counter is reached and if it is, the needed action will be -// done. -// --------------------------------------------------------------- + // --------------------------------------------------------------- + // Sends a telegram to radio. It will be fragmented if needed. + // It will be checked, whether the receiver is logged in, + // licensed, the content is valid and the telegram is not + // expired and an error-message will be sent to central if + // needed. It will be tested, whether the maximal broadcast- + // counter is reached and if it is, the needed action will be + // done. + // --------------------------------------------------------------- -void PrtCnvRadioThread::sendTelegram(const std::shared_ptr &a_telegram, - PrtCnvStoredRadioTelegram *a_handle, - const bool a_doCheckWhetherExpired) -{ + void PrtCnvRadioThread::sendTelegram(const std::shared_ptr &a_telegram, + PrtCnvStoredRadioTelegram *a_handle, + const bool a_doCheckWhetherExpired) + { uint16_t broadcastIndex = 0; // is the TNE logged in? bool isSpecialTelegram = !a_telegram->isNormalTelegram(); @@ -1217,124 +1163,117 @@ void PrtCnvRadioThread::sendTelegram(const std::shared_ptrgetMemberById(a_telegram->getIdentity()); - isLicensing = (GEF_LIZENSIERUNG_TNE == a_telegram->getTelID()); + member = m_DbThread->getMemberById(a_telegram->getIdentity()); + isLicensing = (GEF_LIZENSIERUNG_TNE == a_telegram->getTelID()); } // is the TNE logged in? register and login-telegrams will always be sent if (member || isSpecialTelegram || isLicensing) { - // is the TNE licensed? register-, login-, broadcast- and LizenzierungTNE-telegrams will anyway be sent - if (!a_telegram->needsLicensing() || (member && member->m_Licensed)) + // is the TNE licensed? register-, login-, broadcast- and LizenzierungTNE-telegrams will anyway be sent + if (!a_telegram->needsLicensing() || (member && member->m_Licensed)) + { + if (!a_telegram->hasExpired() || !a_doCheckWhetherExpired) { - if (!a_telegram->hasExpired() || !a_doCheckWhetherExpired) - { - if (a_telegram->isContentValid()) - { - // must the telegram be fragmented? - if (a_telegram->mustBeFragmented()) - sendFragmentedTelegram(a_telegram); - else - broadcastIndex = sendToSocket(a_telegram); - // log telegram into telegram log-file - m_LogThread->writeRadioTelegramLog(a_telegram->data(), false, a_telegram->getPriority()); - } - else - { - sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::WrongParameter, - a_telegram->getTelID()); - INFO_LOG(m_logger) << "Telegram with telId=" << a_telegram->getTelID() << " is invalid => thrown away"; - } - } + if (a_telegram->isContentValid()) + { + // must the telegram be fragmented? + if (a_telegram->mustBeFragmented()) + sendFragmentedTelegram(a_telegram); else - { - if (a_telegram->getBroadcastIndex() == 0) - sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::TelegramOutdated, - a_telegram->getTelID()); - INFO_LOG(m_logger) << "Telegram with telId=" << a_telegram->getTelID() << " has expired => thrown away"; - } + broadcastIndex = sendToSocket(a_telegram); + // log telegram into telegram log-file + m_LogThread->writeRadioTelegramLog(a_telegram->data(), false, a_telegram->getPriority()); + } + else + { + sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::WrongParameter, a_telegram->getTelID()); + INFO_LOG(m_logger) << "Telegram with telId=" << a_telegram->getTelID() << " is invalid => thrown away"; + } } else { - sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, - a_telegram->getTelID()); - ERROR_LOG(m_logger) << "Central tries to send a telegram with telId=" << a_telegram->getTelID() << " to TNE with id=" << a_telegram->getIdentity() << ", but the TNE is not licensed!"; + if (a_telegram->getBroadcastIndex() == 0) + sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::TelegramOutdated, a_telegram->getTelID()); + INFO_LOG(m_logger) << "Telegram with telId=" << a_telegram->getTelID() << " has expired => thrown away"; } + } + else + { + sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLicensed, a_telegram->getTelID()); + ERROR_LOG(m_logger) << "Central tries to send a telegram with telId=" << a_telegram->getTelID() << " to TNE with id=" << a_telegram->getIdentity() + << ", but the TNE is not licensed!"; + } } else { - sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLoggedIn, - a_telegram->getTelID()); - ERROR_LOG(m_logger) << "Central tries to send a telegram to TNE with id=" << a_telegram->getIdentity() << ", but the TNE is not logged in!"; - // hexDumpHelper(m_logger, NGL::LogLevel::Info, a_telegram->data()); + sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorNotLoggedIn, a_telegram->getTelID()); + ERROR_LOG(m_logger) << "Central tries to send a telegram to TNE with id=" << a_telegram->getIdentity() << ", but the TNE is not logged in!"; + // hexDumpHelper(m_logger, NGL::LogLevel::Info, a_telegram->data()); } if (a_handle) - m_DbThread->radioTelegramSent(m_SendCounter, a_handle, broadcastIndex); + m_DbThread->radioTelegramSent(m_SendCounter, a_handle, broadcastIndex); if (broadcastIndex >= MAX_BROADCAST_INDEX) { - m_BroadcastManager.handleOverrunOfBroadcastCounter(); - sendFehlermeldungGefechtsfeldToCentral(0, TrainingAreaBase::TetraIcd::CtaDataError::Reason::BroadcastCounterOverflow); - timeoutEnvironmentTelegram(); + m_BroadcastManager.handleOverrunOfBroadcastCounter(); + sendFehlermeldungGefechtsfeldToCentral(0, TrainingAreaBase::TetraIcd::CtaDataError::Reason::BroadcastCounterOverflow); + timeoutEnvironmentTelegram(); } -} + } -// --------------------------------------------------------------- -// Sends the register-indication to TETRA -// --------------------------------------------------------------- -void PrtCnvRadioThread::doRegister() -{ + // --------------------------------------------------------------- + // Sends the register-indication to TETRA + // --------------------------------------------------------------- + void PrtCnvRadioThread::doRegister() + { auto registerIndTelegram(std::make_shared(m_HostISSI)); sendTelegram(registerIndTelegram, nullptr); INFO_LOG(m_logger) << "Send Radio-Telegram Register-Ind with hostISSI=" << m_HostISSI; -} + } -// --------------------------------------------------------------- -// Register to specific message groups (max. 5) -// --------------------------------------------------------------- -void PrtCnvRadioThread::registerGroups() -{ + // --------------------------------------------------------------- + // Register to specific message groups (max. 5) + // --------------------------------------------------------------- + void PrtCnvRadioThread::registerGroups() + { if (m_ListenGroups.empty()) - return; + return; auto registerGroupIndTelegram(std::make_shared(m_HostISSI, m_ListenGroups)); sendTelegram(registerGroupIndTelegram, nullptr); -} + } -// --------------------------------------------------------------- -// Processes the register-response-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleRegisterRsp(const uint8_t a_regsitrationStatus) -{ + // --------------------------------------------------------------- + // Processes the register-response-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleRegisterRsp(const uint8_t a_regsitrationStatus) + { INFO_LOG(m_logger) << "Got Radio-Telegram Register-Rsp with status=" << std::to_string(a_regsitrationStatus); std::stringstream logText; switch (a_regsitrationStatus) { - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_IssiSuccessfulRegistered: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_IssiSuccessfulRegistered: emit tetraConnectionState(true); registerGroups(); return; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DuplicateISSI: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DuplicateISSI: logText << "TETRA: Register-Response: Status=Duplicate ISSI"; break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidISSI: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidISSI: logText << "TETRA: Register-Response: Status=Invalid ISSI"; break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidIpAddress: + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidIpAddress: logText << "TETRA: Register-Response: Status=Invalid IP address => Configure TETRA for accepting our IP-address ("; - { - const QList ipList = QNetworkInterface::allAddresses(); - for (const QHostAddress &addr : ipList) + { + const QList ipList = QNetworkInterface::allAddresses(); + for (const QHostAddress &addr : ipList) logText << addr.toString().toStdString() << ", "; - logText << ")..."; - } + logText << ")..."; + } break; - default: + default: logText << "Unknown registration status: " << std::to_string(a_regsitrationStatus); break; } @@ -1343,188 +1282,182 @@ void PrtCnvRadioThread::handleRegisterRsp(const uint8_t a_regsitrationStatus) FATAL_LOG(m_logger) << logText.str(); std::cerr << logText.str() << std::endl; exit(1); -} + } -std::ostream &operator<<(std::ostream &os, const PrtCnvRadioThread::E_TrafficLoad tl) -{ + std::ostream &operator<<(std::ostream &os, const PrtCnvRadioThread::E_TrafficLoad tl) + { switch (tl) { - case PrtCnvRadioThread::E_TrafficLoad::FullLoad: + case PrtCnvRadioThread::E_TrafficLoad::FullLoad: os << "E_TrafficLoad::FullLoad"; return os; - case PrtCnvRadioThread::E_TrafficLoad::HighLoad: + case PrtCnvRadioThread::E_TrafficLoad::HighLoad: os << "E_TrafficLoad::HighLoad"; return os; - case PrtCnvRadioThread::E_TrafficLoad::NormalLoad: + case PrtCnvRadioThread::E_TrafficLoad::NormalLoad: os << "E_TrafficLoad::NormalLoad"; return os; - case PrtCnvRadioThread::E_TrafficLoad::Unknown: + case PrtCnvRadioThread::E_TrafficLoad::Unknown: os << "E_TrafficLoad::Unknown"; return os; } Q_ASSERT(false); os << std::to_string(static_cast(tl)); return os; -} + } -// --------------------------------------------------------------- -// generates an answer to TNE from protocoll-converter for -// some special radio-telegrams (i.e. NachforderungBroadcast, -// BITE-Meldung) -// returns true when the telegram must be sent to central -// --------------------------------------------------------------- -bool PrtCnvRadioThread::sendAnswer(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) -{ + // --------------------------------------------------------------- + // generates an answer to TNE from protocoll-converter for + // some special radio-telegrams (i.e. NachforderungBroadcast, + // BITE-Meldung) + // returns true when the telegram must be sent to central + // --------------------------------------------------------------- + bool PrtCnvRadioThread::sendAnswer(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram) + { switch (a_radioTelegram.getTelID()) { - case GEF_BITE_MELDUNG2: + case GEF_BITE_MELDUNG2: return handleBITEEXT_Telegram(a_radioTelegram); - case GEF_DEAKTIVIERUNG_EINZELMINE: - { + case GEF_DEAKTIVIERUNG_EINZELMINE: + { // if any TNE is sending DEAKTIVIERUNG_EINZELMINE, we immediately need to send this message // as broadcast to all TNEs auto radioTelegram(std::make_shared(GEF_DEAKTIVIERUNG_EINZELMINE, 13, 0)); - radioTelegram->setPayload2Byte(0); // broadcast-index will be set when sending + radioTelegram->setPayload2Byte(0); // broadcast-index will be set when sending radioTelegram->setPayloadData(a_radioTelegram.getPayloadDataPtr(5), 8); // copy the telegram-content storeRadioTelegram(radioTelegram, 0); emit checkSendToRadio(); break; - } - case GEF_POSITIONS_MELDUNG: - case GEF_POSITIONS_MELDUNG_LFZ: - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: - case GEF_IPS_POSITIONSDATEN: - { + } + case GEF_POSITIONS_MELDUNG: + case GEF_POSITIONS_MELDUNG_LFZ: + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: + case GEF_IPS_POSITIONSDATEN: + { auto it = m_DoNeedActPosResp.find(a_radioTelegram.getIdentity()); if (it != m_DoNeedActPosResp.end()) { - auto radioTelegram(std::make_shared(GEF_ALLGEMEINE_NACHRICHT, 9, a_radioTelegram.getIdentity())); - radioTelegram->setPayload2Byte(0); // broadcast-index will be set when sending the radio-telegram - radioTelegram->setPayload1Byte(3); // length 3 - radioTelegram->setPayload1Byte(0); // index 0 -> indexed text - radioTelegram->setPayload2Byte(8); // index 1 16 Bit - storeRadioTelegram(radioTelegram, 0); - emit checkSendToRadio(); - m_DoNeedActPosResp.erase(it); + auto radioTelegram(std::make_shared(GEF_ALLGEMEINE_NACHRICHT, 9, a_radioTelegram.getIdentity())); + radioTelegram->setPayload2Byte(0); // broadcast-index will be set when sending the radio-telegram + radioTelegram->setPayload1Byte(3); // length 3 + radioTelegram->setPayload1Byte(0); // index 0 -> indexed text + radioTelegram->setPayload2Byte(8); // index 1 16 Bit + storeRadioTelegram(radioTelegram, 0); + emit checkSendToRadio(); + m_DoNeedActPosResp.erase(it); } break; - } - default: + } + default: // nothing break; } return true; -} + } -// --------------------------------------------------------------- -// Returns the ISSI of TNE with a_TNE_Id -// --------------------------------------------------------------- -uint32_t PrtCnvRadioThread::getDestinationISSI(const uint16_t a_TNE_Id) const -{ + // --------------------------------------------------------------- + // Returns the ISSI of TNE with a_TNE_Id + // --------------------------------------------------------------- + uint32_t PrtCnvRadioThread::getDestinationISSI(const uint16_t a_TNE_Id) const + { // INFO_LOG(m_logger) << "Get ISSI for TNE-Id: " << a_TNE_Id; PrtCnvMember *member = m_DbThread->getMemberById(a_TNE_Id); if (member) - return member->m_ISSI; // TPU found + return member->m_ISSI; // TPU found ERROR_LOG(m_logger) << "TPU with id=" << a_TNE_Id << " not logged in."; return 0; // TPU not found -} + } -// --------------------------------------------------------------- -// Processes the periodical sending of Umgebungsmeldung -// --------------------------------------------------------------- -void PrtCnvRadioThread::timeoutEnvironmentTelegram() -{ + // --------------------------------------------------------------- + // Processes the periodical sending of Umgebungsmeldung + // --------------------------------------------------------------- + void PrtCnvRadioThread::timeoutEnvironmentTelegram() + { // eat all pending timeoutAck - if (m_DoCleanup) return; - if (PrtCnvSocketThread::e_WORKING != m_State) return; + if (m_DoCleanup) + return; + if (PrtCnvSocketThread::e_WORKING != m_State) + return; auto envTelegram = m_DbThread->getEnvironmentTelegram(); if (envTelegram) { - INFO_LOG(m_logger) << "It is time to send the Umgebungsmeldung"; - sendTelegram(envTelegram, nullptr); + INFO_LOG(m_logger) << "It is time to send the Umgebungsmeldung"; + sendTelegram(envTelegram, nullptr); } else { - WARNING_LOG(m_logger) << "Got no Umgebungsmeldung from DB-Thread..."; + WARNING_LOG(m_logger) << "Got no Umgebungsmeldung from DB-Thread..."; } -} + } -// --------------------------------------------------------------- -// Sends a telegram "FehlermeldungGefechtsfeld" to central -// --------------------------------------------------------------- -void PrtCnvRadioThread::sendFehlermeldungGefechtsfeldToCentral(const uint16_t a_identity, - const TrainingAreaBase::TetraIcd::CtaDataError::Reason a_errorCause, - const gef_telegramm_id_et a_telegramId) -{ + // --------------------------------------------------------------- + // Sends a telegram "FehlermeldungGefechtsfeld" to central + // --------------------------------------------------------------- + void PrtCnvRadioThread::sendFehlermeldungGefechtsfeldToCentral(const uint16_t a_identity, + const TrainingAreaBase::TetraIcd::CtaDataError::Reason a_errorCause, + const gef_telegramm_id_et a_telegramId) + { N_CoPrtCnv::CoPrtCnvRadioTelegram radioTelegram(GEF_FEHLERMELDUNG_GFD, 9, a_identity); - radioTelegram.setPayload4Byte(time(nullptr)); // GPS-Zeit + radioTelegram.setPayload4Byte(time(nullptr)); // GPS-Zeit radioTelegram.setPayload1Byte(static_cast(a_errorCause)); // Ursache - radioTelegram.setPayload1Byte(a_telegramId); // Telegrammkennung + radioTelegram.setPayload1Byte(a_telegramId); // Telegrammkennung - std::shared_ptr - centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); + std::shared_ptr centralTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(&radioTelegram)); if (centralTelegram) { - m_DbThread->storeCentralTelegram(centralTelegram, radioTelegram); - emit checkSendToCentral(); + m_DbThread->storeCentralTelegram(centralTelegram, radioTelegram); + emit checkSendToCentral(); } -} + } -// --------------------------------------------------------------- -// Writes the login of a TNE to the login-logfile -// --------------------------------------------------------------- -void PrtCnvRadioThread::writeLoginLog(uint32_t identity, uint32_t issi, const QString &a_prosaText) -{ + // --------------------------------------------------------------- + // Writes the login of a TNE to the login-logfile + // --------------------------------------------------------------- + void PrtCnvRadioThread::writeLoginLog(uint32_t identity, uint32_t issi, const QString &a_prosaText) + { const QDateTime dtCur(QDateTime::currentDateTimeUtc()); - QString txt = - QString::number(dtCur.toSecsSinceEpoch()) + QLatin1Char(';') + - QString::number(issi) + QLatin1Char(';') + - QString::number(identity) + QLatin1Char(';') + - QLatin1Char(';') + - a_prosaText + QLatin1Char(';') + dtCur.toString(); + QString txt = QString::number(dtCur.toSecsSinceEpoch()) + QLatin1Char(';') + QString::number(issi) + QLatin1Char(';') + QString::number(identity) + QLatin1Char(';') + + QLatin1Char(';') + a_prosaText + QLatin1Char(';') + dtCur.toString(); writeLoginLog(nullptr, txt); -} + } -void PrtCnvRadioThread::writeLoginLog(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram, const QString &a_prosaText) -{ + void PrtCnvRadioThread::writeLoginLog(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram, const QString &a_prosaText) + { writeLoginLog(&a_radioTelegram, a_prosaText); -} + } -void PrtCnvRadioThread::writeLoginLog(const N_CoPrtCnv::CoPrtCnvRadioTelegram *a_radioTelegram, const QString &a_prosaText) -{ + void PrtCnvRadioThread::writeLoginLog(const N_CoPrtCnv::CoPrtCnvRadioTelegram *a_radioTelegram, const QString &a_prosaText) + { QByteArray logData; if (a_radioTelegram) { - // important data of telegram - int len = 3; - if (a_radioTelegram->getTelID() == GEF_BITE_MELDUNG2) - len = 27; - QStringList sl; - sl.reserve(len); - for (int i = 0; i < len; i++) - { - uint8_t data = a_radioTelegram->getPayloadDataUInt8(i); - sl += QStringLiteral("0x%1").arg(data, 2, 16, QLatin1Char('0')); - } + // important data of telegram + int len = 3; + if (a_radioTelegram->getTelID() == GEF_BITE_MELDUNG2) + len = 27; + QStringList sl; + sl.reserve(len); + for (int i = 0; i < len; i++) + { + uint8_t data = a_radioTelegram->getPayloadDataUInt8(i); + sl += QStringLiteral("0x%1").arg(data, 2, 16, QLatin1Char('0')); + } - const QDateTime dtCur(QDateTime::currentDateTimeUtc()); - // generate the logline: :;;; - logData = - QByteArray::number(dtCur.toSecsSinceEpoch()) + ";" + - QByteArray::number(a_radioTelegram->getSrcISSI()) + ";" + - QByteArray::number(a_radioTelegram->getIdentity()) + ";" + - sl.join(QLatin1Char(',')).toUtf8() + ";" + - a_prosaText.toUtf8() + ";" + dtCur.toString().toUtf8(); + const QDateTime dtCur(QDateTime::currentDateTimeUtc()); + // generate the logline: :;;; + logData = QByteArray::number(dtCur.toSecsSinceEpoch()) + ";" + QByteArray::number(a_radioTelegram->getSrcISSI()) + ";" + + QByteArray::number(a_radioTelegram->getIdentity()) + ";" + sl.join(QLatin1Char(',')).toUtf8() + ";" + a_prosaText.toUtf8() + ";" + + dtCur.toString().toUtf8(); } else { - logData = a_prosaText.toUtf8(); + logData = a_prosaText.toUtf8(); } logData += "\n"; @@ -1539,224 +1472,220 @@ void PrtCnvRadioThread::writeLoginLog(const N_CoPrtCnv::CoPrtCnvRadioTelegram *a (void)file.open(QIODevice::Append); file.write(logData); file.close(); -} + } -// --------------------------------------------------------------- -// Sends a login-telegram to radio -// --------------------------------------------------------------- -void PrtCnvRadioThread::sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, - const uint16_t a_identity, const uint32_t a_ISSI) -{ + // --------------------------------------------------------------- + // Sends a login-telegram to radio + // --------------------------------------------------------------- + void PrtCnvRadioThread::sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, + const uint16_t a_identity, + const uint32_t a_ISSI) + { auto answerTelegram(std::make_shared(a_loginTelegramStatus, a_identity, a_ISSI)); storeRadioTelegram(answerTelegram, 0); emit checkSendToRadio(); -} + } -void PrtCnvRadioThread::sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, - const uint16_t a_identity, const uint32_t a_ISSI, const TrainingAreaBase::TetraIcd::GroupIssiInformation &group) -{ + void PrtCnvRadioThread::sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, + const uint16_t a_identity, + const uint32_t a_ISSI, + const TrainingAreaBase::TetraIcd::GroupIssiInformation &group) + { using namespace N_CoPrtCnv; auto answerTelegram(std::make_shared(a_loginTelegramStatus, a_identity, a_ISSI)); if ((a_loginTelegramStatus & CoPrtCnvRadioTelegram::e_LoginOtherExercise) == CoPrtCnvRadioTelegram::e_LoginOtherExercise) { - NOTICE_LOG(m_logger) << "sendLoginResponse for " << a_identity << " with issi " << a_ISSI - << " and groups " << group.serverIssi << "/" << group.broadcastIssi1 - << "/" << group.broadcastIssi2; - answerTelegram->setLoginIssis(group.serverIssi, group.broadcastIssi1, group.broadcastIssi2); + NOTICE_LOG(m_logger) << "sendLoginResponse for " << a_identity << " with issi " << a_ISSI << " and groups " << group.serverIssi << "/" << group.broadcastIssi1 + << "/" << group.broadcastIssi2; + answerTelegram->setLoginIssis(group.serverIssi, group.broadcastIssi1, group.broadcastIssi2); } storeRadioTelegram(answerTelegram, 0); emit checkSendToRadio(); -} + } - - -// --------------------------------------------------------------- -// Sends a telegram "LizenzierungTNE" to radio -// --------------------------------------------------------------- -void PrtCnvRadioThread::sendLizenzierungTneToRadio(const uint16_t a_identity, const uint32_t a_issi, - const N_CoPrtCnv::E_LicensingKind a_licensingKind, - const N_CoPrtCnv::E_LicensingErrorCode a_errorCause) -{ + // --------------------------------------------------------------- + // Sends a telegram "LizenzierungTNE" to radio + // --------------------------------------------------------------- + void PrtCnvRadioThread::sendLizenzierungTneToRadio(const uint16_t a_identity, + const uint32_t a_issi, + const N_CoPrtCnv::E_LicensingKind a_licensingKind, + const N_CoPrtCnv::E_LicensingErrorCode a_errorCause) + { auto radioTelegram(std::make_shared(GEF_LIZENSIERUNG_TNE, 7, a_identity)); - radioTelegram->setPayload1Byte(static_cast(a_licensingKind)); // Lizenzierungsart - radioTelegram->setPayload1Byte(static_cast(a_errorCause)); // Fehlercode Lizenzierung: Index auf ADAG - radioTelegram->setPayload2Byte(0x0013); // Fehlercode Lizenzierung: Index auf ADAG + radioTelegram->setPayload1Byte(static_cast(a_licensingKind)); // Lizenzierungsart + radioTelegram->setPayload1Byte(static_cast(a_errorCause)); // Fehlercode Lizenzierung: Index auf ADAG + radioTelegram->setPayload2Byte(0x0013); // Fehlercode Lizenzierung: Index auf ADAG radioTelegram->setDestISSI(a_issi); storeRadioTelegram(radioTelegram, 0); emit checkSendToRadio(); emit playerLicencedChanged(a_identity, a_licensingKind); -} + } -// --------------------------------------------------------------- -// Receives the file with allowed playerId, or the lowest and -// hightest allowed playerIds -// --------------------------------------------------------------- -void PrtCnvRadioThread::initIdentityArray() -{ + // --------------------------------------------------------------- + // Receives the file with allowed playerId, or the lowest and + // hightest allowed playerIds + // --------------------------------------------------------------- + void PrtCnvRadioThread::initIdentityArray() + { const QString loginGroup(QStringLiteral("login")); // do we check the identify? if (m_Config->getBoolean(loginGroup, QStringLiteral("DoCheckPlayerId"), true)) { - // reset the array - m_AllowedIdentities.clear(); - // use we min/max identify or a file with allowed identites? - QString identifyFileName = m_Config->getString(loginGroup, QStringLiteral("PlayerIdFilePath"), QString()); - if (identifyFileName.isEmpty()) + // reset the array + m_AllowedIdentities.clear(); + // use we min/max identify or a file with allowed identites? + QString identifyFileName = m_Config->getString(loginGroup, QStringLiteral("PlayerIdFilePath"), QString()); + if (identifyFileName.isEmpty()) + { + // we use min/max + uint32_t lowest = m_Config->getInteger(loginGroup, QStringLiteral("LowestPlayerId"), 1); + uint32_t highest = m_Config->getInteger(loginGroup, QStringLiteral("HighestPlayerId"), MAX_IDENTITY); + for (uint32_t i = lowest; i <= highest; i++) + setIdentityVaild(i); + INFO_LOG(m_logger) << "PlayerIds from " << lowest << " .. " << highest << " will be used."; + } + else + { + // we use the file + INFO_LOG(m_logger) << "PlayerId-file '" << identifyFileName << "' will be used."; + + // get path relative from bin-path + QString path = identifyFileName; + if (!QDir::isAbsolutePath(path)) + path = QCoreApplication::applicationDirPath() + QLatin1Char('/') + path; + + // read in the player-ids + QFile file(path); + if (file.open(QIODevice::ReadOnly)) { - // we use min/max - uint32_t lowest = m_Config->getInteger(loginGroup, QStringLiteral("LowestPlayerId"), 1); - uint32_t highest = m_Config->getInteger(loginGroup, QStringLiteral("HighestPlayerId"), MAX_IDENTITY); - for (uint32_t i = lowest; i <= highest; i++) - setIdentityVaild(i); - INFO_LOG(m_logger) << "PlayerIds from " << lowest << " .. " << highest << " will be used."; + uint32_t lineCount = 0; + while (!file.atEnd()) + { + lineCount++; + QByteArray line(file.readLine()); + int hashPos = line.indexOf('#'); + if (-1 != hashPos) + line = line.left(hashPos); + if (!line.trimmed().isEmpty()) + { + int pos = line.indexOf('-'); + if (-1 == pos) + { + // playerID + setIdentityVaild(readIdentity(line, lineCount, identifyFileName)); + } + else + { + // playerID - playerID + QByteArray playerId = line.left(pos).trimmed(); + uint16_t left = readIdentity(playerId, lineCount, identifyFileName); + playerId = line.right(line.length() - pos - 1).trimmed(); + uint16_t right = readIdentity(playerId, lineCount, identifyFileName); + for (int i = left; i <= right; i++) + setIdentityVaild(i); + } + } + } + file.close(); } else { - // we use the file - INFO_LOG(m_logger) << "PlayerId-file '" << identifyFileName << "' will be used."; - - // get path relative from bin-path - QString path = identifyFileName; - if (!QDir::isAbsolutePath(path)) - path = QCoreApplication::applicationDirPath() + QLatin1Char('/') + path; - - // read in the player-ids - QFile file(path); - if (file.open(QIODevice::ReadOnly)) - { - uint32_t lineCount = 0; - while (!file.atEnd()) - { - lineCount++; - QByteArray line(file.readLine()); - int hashPos = line.indexOf('#'); - if (-1 != hashPos) - line = line.left(hashPos); - if (!line.trimmed().isEmpty()) - { - int pos = line.indexOf('-'); - if (-1 == pos) - { - // playerID - setIdentityVaild(readIdentity(line, lineCount, identifyFileName)); - } - else - { - // playerID - playerID - QByteArray playerId = line.left(pos).trimmed(); - uint16_t left = readIdentity(playerId, lineCount, identifyFileName); - playerId = line.right(line.length() - pos - 1).trimmed(); - uint16_t right = readIdentity(playerId, lineCount, identifyFileName); - for (int i = left; i <= right; i++) - setIdentityVaild(i); - } - } - } - file.close(); - } - else - { - ERROR_LOG(m_logger) << "Could not open the PlayerId-file '" << identifyFileName << "'!"; - std::cout << std::endl << "Error: Could not open the PlayerId-file '" << qPrintable(identifyFileName) << "'!" << std::endl; - exit(-1); - } + ERROR_LOG(m_logger) << "Could not open the PlayerId-file '" << identifyFileName << "'!"; + std::cout << std::endl << "Error: Could not open the PlayerId-file '" << qPrintable(identifyFileName) << "'!" << std::endl; + exit(-1); } + } } else { - // no we do not check => simply set all identifies to vaild - for (uint32_t i = 0; i <= MAX_IDENTITY; i++) - setIdentityVaild(i); + // no we do not check => simply set all identifies to vaild + for (uint32_t i = 0; i <= MAX_IDENTITY; i++) + setIdentityVaild(i); } -} + } -// --------------------------------------------------------------- -// Reads one line of the playerId-file. -// Aborts when not successful -// --------------------------------------------------------------- -uint16_t PrtCnvRadioThread::readIdentity(const QByteArray &a_idAsText, const uint32_t a_line, const QString &a_fileName) -{ + // --------------------------------------------------------------- + // Reads one line of the playerId-file. + // Aborts when not successful + // --------------------------------------------------------------- + uint16_t PrtCnvRadioThread::readIdentity(const QByteArray &a_idAsText, const uint32_t a_line, const QString &a_fileName) + { ulong playerId = a_idAsText.toULong(); if (0 == playerId || playerId > MAX_IDENTITY) { - // abort when we have a failure - if (0 == playerId) - { - FATAL_LOG(m_logger) << a_fileName << ":" << a_line << ": could not read playerID - '" - << a_idAsText << "'"; - } - else - { - FATAL_LOG(m_logger) << a_fileName << ":" << a_line << ": PlayerID too big - '" - << a_idAsText << "'"; - } - exit(1); + // abort when we have a failure + if (0 == playerId) + { + FATAL_LOG(m_logger) << a_fileName << ":" << a_line << ": could not read playerID - '" << a_idAsText << "'"; + } + else + { + FATAL_LOG(m_logger) << a_fileName << ":" << a_line << ": PlayerID too big - '" << a_idAsText << "'"; + } + exit(1); } return playerId; -} + } -// --------------------------------------------------------------- -// Checks whether the playerId is allowd. -// --------------------------------------------------------------- -bool PrtCnvRadioThread::isIdentityValid(uint16_t a_identity) const -{ + // --------------------------------------------------------------- + // Checks whether the playerId is allowd. + // --------------------------------------------------------------- + bool PrtCnvRadioThread::isIdentityValid(uint16_t a_identity) const + { return m_AllowedIdentities.find(a_identity) != m_AllowedIdentities.end(); -} + } -// --------------------------------------------------------------- -// Allows this playerId. -// --------------------------------------------------------------- -void PrtCnvRadioThread::setIdentityVaild(uint16_t a_identity) -{ + // --------------------------------------------------------------- + // Allows this playerId. + // --------------------------------------------------------------- + void PrtCnvRadioThread::setIdentityVaild(uint16_t a_identity) + { m_AllowedIdentities.insert(a_identity); -} + } -// --------------------------------------------------------------- -// Fragment a telegram and sends the fragments to radio. -// --------------------------------------------------------------- -void PrtCnvRadioThread::sendFragmentedTelegram(const std::shared_ptr &a_telegram) -{ + // --------------------------------------------------------------- + // Fragment a telegram and sends the fragments to radio. + // --------------------------------------------------------------- + void PrtCnvRadioThread::sendFragmentedTelegram(const std::shared_ptr &a_telegram) + { // send fragmented telegrams uint8_t fragmentCounter = 0; N_CoPrtCnv::CoPrtCnvRadioTelegram::E_FragmentStatus fragmentStatus; do { - bool error = false; - auto fragmentedTelegram(std::make_shared(a_telegram, fragmentCounter++, error)); - if (!error) - { - fragmentedTelegram->setDestISSI(getDestinationISSI(a_telegram->getIdentity())); - // now call the normal sendTelegram-function again - sendTelegram(fragmentedTelegram, nullptr); - fragmentStatus = fragmentedTelegram->getFragmentStatus(); - } - else - { - sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), - TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, - a_telegram->getTelID()); - return; - } - } - while (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment != fragmentStatus); -} + bool error = false; + auto fragmentedTelegram(std::make_shared(a_telegram, fragmentCounter++, error)); + if (!error) + { + fragmentedTelegram->setDestISSI(getDestinationISSI(a_telegram->getIdentity())); + // now call the normal sendTelegram-function again + sendTelegram(fragmentedTelegram, nullptr); + fragmentStatus = fragmentedTelegram->getFragmentStatus(); + } + else + { + sendFehlermeldungGefechtsfeldToCentral(a_telegram->getIdentity(), TrainingAreaBase::TetraIcd::CtaDataError::Reason::FragmentationError, a_telegram->getTelID()); + return; + } + } while (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment != fragmentStatus); + } -// --------------------------------------------------------------- -// sends the telegram to radio-socket -// returns the broadcastIndex (0 if it was no broadcast) -// --------------------------------------------------------------- -uint16_t PrtCnvRadioThread::sendToSocket(const std::shared_ptr &a_telegram) -{ + // --------------------------------------------------------------- + // sends the telegram to radio-socket + // returns the broadcastIndex (0 if it was no broadcast) + // --------------------------------------------------------------- + uint16_t PrtCnvRadioThread::sendToSocket(const std::shared_ptr &a_telegram) + { // increment the counter and wrap if needed if (++m_SendCounter >= END_COUNTER) - m_SendCounter = START_COUNTER; + m_SendCounter = START_COUNTER; a_telegram->setZaehler(m_SendCounter); // set our ISSI a_telegram->setSrcISSI(m_HostISSI); @@ -1764,94 +1693,92 @@ uint16_t PrtCnvRadioThread::sendToSocket(const std::shared_ptrisNormalTelegram() ? a_telegram->getTelID() : GEF_BESTAETIGUNG; if (a_telegram->isNormalTelegram()) { - // set ISSI of destination - if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq == a_telegram->getPDU_Type()) + // set ISSI of destination + if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq == a_telegram->getPDU_Type()) + { + if (GEF_LIZENSIERUNG_TNE != a_telegram->getTelID()) + a_telegram->setDestISSI(getDestinationISSI(a_telegram->getIdentity())); + } + if (GEF_TEILNEHMERMODE_SETZEN == telId && a_telegram->getDestISSI() != m_BroadcastISSI) + { + DEBUG_LOG(m_logger) << "Got MODE with bci: " << a_telegram->getBroadcastIndex(); + if (a_telegram->getBroadcastIndex() <= 0) + a_telegram->setBroadcastIndex(m_BroadcastManager.getBroadcastIndex()); + DEBUG_LOG(m_logger) << "MODE with bci is now: " << a_telegram->getBroadcastIndex(); + } + // set broadcastindex + if (GEF_UMGEBUNGS_MELDUNG2 == telId) + { + // exception: Umgebungsmeldung does not increment the broadcastindex and must never be stored + a_telegram->setBroadcastIndex(m_BroadcastManager.getBroadcastIndex()); + a_telegram->setPayloadDataWithIndex(7, m_DbThread->getResetCounter(), 1); + a_telegram->setPayloadDataWithIndex(8, m_DbThread->getBattleFieldOperatingState(), 1); + a_telegram->setPayloadDataWithIndex(16, (uint32_t)time(nullptr), 4); + m_DbThread->setResetCounterOnEnvironment(); + } + else + { + // init-telegrams are special: they are broadcast-telegrams without broadcast-index, + // which will only be sent once + if (GEF_INIT != telId && a_telegram->mustBroadcastBeSet()) { - if (GEF_LIZENSIERUNG_TNE != a_telegram->getTelID()) - a_telegram->setDestISSI(getDestinationISSI(a_telegram->getIdentity())); + broadcastIndex = m_BroadcastManager.getNextBroadcastIndex(); + a_telegram->setBroadcastIndex(broadcastIndex); } - if (GEF_TEILNEHMERMODE_SETZEN == telId && a_telegram->getDestISSI() != m_BroadcastISSI) - { - DEBUG_LOG(m_logger) << "Got MODE with bci: " << a_telegram->getBroadcastIndex(); - if (a_telegram->getBroadcastIndex()<= 0) - a_telegram->setBroadcastIndex(m_BroadcastManager.getBroadcastIndex()); - DEBUG_LOG(m_logger) << "MODE with bci is now: " << a_telegram->getBroadcastIndex(); - } - // set broadcastindex - if (GEF_UMGEBUNGS_MELDUNG2 == telId) - { - // exception: Umgebungsmeldung does not increment the broadcastindex and must never be stored - a_telegram->setBroadcastIndex(m_BroadcastManager.getBroadcastIndex()); - a_telegram->setPayloadDataWithIndex(7, m_DbThread->getResetCounter(), 1); - a_telegram->setPayloadDataWithIndex(8, m_DbThread->getBattleFieldOperatingState(), 1); - a_telegram->setPayloadDataWithIndex(16, (uint32_t)time(nullptr), 4); - m_DbThread->setResetCounterOnEnvironment(); - } - else - { - // init-telegrams are special: they are broadcast-telegrams without broadcast-index, - // which will only be sent once - if (GEF_INIT != telId && - a_telegram->mustBroadcastBeSet()) - { - broadcastIndex = m_BroadcastManager.getNextBroadcastIndex(); - a_telegram->setBroadcastIndex(broadcastIndex); - } - } - a_telegram->fixupTelegramIdForEts(true); + } + a_telegram->fixupTelegramIdForEts(true); } // send telegram to radio DEBUG_LOG(m_logger) << "Send telegram to radio: telId=" << telId << " wcounter=" << int(a_telegram->zaehler()) << " size=" << a_telegram->getSize(); if (m_DoUseSDSTL && N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq == a_telegram->getPDU_Type()) { - a_telegram->setProtocolIdentifier(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_SimpleTextMessagingUsingSDS_TL); - a_telegram->setMessageReference(telId); + a_telegram->setProtocolIdentifier(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_SimpleTextMessagingUsingSDS_TL); + a_telegram->setMessageReference(telId); } if (m_DoDumpSentTelegrams) { - INFO_LOG(m_logger) << "Send radio-telegram with size " << a_telegram->getSize() - << " and payload size " << a_telegram->getPayloadSize(); - NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, a_telegram->data()); + INFO_LOG(m_logger) << "Send radio-telegram with size " << a_telegram->getSize() << " and payload size " << a_telegram->getPayloadSize(); + NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, a_telegram->data()); } Q_ASSERT(QThread::currentThreadId() == m_currentThreadId); if (m_bUseScrambling && a_telegram->getPDU_Type() == N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type::e_DataIndReq) - sendScrambledContent(a_telegram); + sendScrambledContent(a_telegram); else - m_Socket->write(a_telegram->data()); + m_Socket->write(a_telegram->data()); // update statistics-data for traffic-control m_SentTelegrams++; m_SentBytes += a_telegram->getSize(); if (a_telegram->isNormalTelegram()) - a_telegram->fixupTelegramIdForEts(false); + a_telegram->fixupTelegramIdForEts(false); return broadcastIndex; -} + } -// according to guezfk50-tn0100 -static inline void scramble(const unsigned char *dataIn, unsigned char *dataOut, size_t len, uint32_t initial, uint32_t polynom) -{ + // according to guezfk50-tn0100 + static inline void scramble(const unsigned char *dataIn, unsigned char *dataOut, size_t len, uint32_t initial, uint32_t polynom) + { uint32_t lfsr = initial; for (size_t j = 0; j < len; ++j) { - for (int i = 0; i < 8; ++i) - { - unsigned char lsbBit = (lfsr & 0x01); - lfsr >>= 1; - if (lsbBit) - lfsr ^= polynom; - } - dataOut[len - j - 1] = dataIn[len - j - 1] ^ static_cast(lfsr); + for (int i = 0; i < 8; ++i) + { + unsigned char lsbBit = (lfsr & 0x01); + lfsr >>= 1; + if (lsbBit) + lfsr ^= polynom; + } + dataOut[len - j - 1] = dataIn[len - j - 1] ^ static_cast(lfsr); } -} + } -// according to guezfk50-tn0100 -void PrtCnvRadioThread::sendScrambledContent(const std::shared_ptr &a_telegram) const -{ + // according to guezfk50-tn0100 + void PrtCnvRadioThread::sendScrambledContent(const std::shared_ptr &a_telegram) const + { const uint32_t initial = (a_telegram->getSrcISSI() % 0xFFFF) + 1; constexpr uint32_t polynom = 0x8016; unsigned char dataOut[N_CoPrtCnv::CoPrtCnvRadioTelegram::MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH]; @@ -1861,17 +1788,17 @@ void PrtCnvRadioThread::sendScrambledContent(const std::shared_ptr(dataOut), scrambleLen); + QByteArray tmp(reinterpret_cast(dataOut), scrambleLen); DEBUG_LOG(m_logger) << "Raw scrambled data: " << tmp.toHex(' '); m_Socket->write(a_telegram->getData(), payloadOffset); m_Socket->write(reinterpret_cast(dataOut), scrambleLen); -} + } -bool PrtCnvRadioThread::unscrambleContent(N_CoPrtCnv::CoPrtCnvRadioTelegram &a_telegram) const -{ + bool PrtCnvRadioThread::unscrambleContent(N_CoPrtCnv::CoPrtCnvRadioTelegram &a_telegram) const + { const uint32_t initial = (a_telegram.getSrcISSI() % 0xFFFF) + 1; constexpr uint32_t polynom = 0x8016; const uint32_t payloadOffset = N_CoPrtCnv::CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH - 1; @@ -1881,10 +1808,10 @@ bool PrtCnvRadioThread::unscrambleContent(N_CoPrtCnv::CoPrtCnvRadioTelegram &a_t if (scrambleLen > N_CoPrtCnv::CoPrtCnvRadioTelegram::MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH) { - ERROR_LOG(m_logger) << "Telegram length does not match - can't unscramble content, len: " << scrambleLen; - NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Error, a_telegram.data()); - Q_ASSERT(false); - return false; + ERROR_LOG(m_logger) << "Telegram length does not match - can't unscramble content, len: " << scrambleLen; + NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Error, a_telegram.data()); + Q_ASSERT(false); + return false; } // ERROR_LOG(m_logger) << "Unscrambling... " << a_telegram.getSrcISSI() << " " << payloadOffset << " " << scrambleLen << " " << qint64(a_telegram->getData()) << " " << qint64(dataIn); @@ -1898,46 +1825,52 @@ bool PrtCnvRadioThread::unscrambleContent(N_CoPrtCnv::CoPrtCnvRadioTelegram &a_t // NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Error, a_telegram.data()); return true; -} + } -// --------------------------------------------------------------- -// Processes the report-indication-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleReportIndReq(const QByteArray &data) -{ + // --------------------------------------------------------------- + // Processes the report-indication-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleReportIndReq(const QByteArray &data) + { const uint8_t *a_data = reinterpret_cast(data.data()); uint32_t srcISSI = *(uint32_t *)&a_data[5]; uint32_t destISSI = *(uint32_t *)&a_data[9]; if (m_HostISSI == destISSI) { - N_CoPrtCnv::CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report delivery = (N_CoPrtCnv::CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report)a_data[16]; - switch (delivery) - { + N_CoPrtCnv::CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report delivery = (N_CoPrtCnv::CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report)a_data[16]; + switch (delivery) + { case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DeliveryFailed: { - uint8_t messageReference = a_data[14]; // messageReference contains the telegramId - uint16_t identity = 0; - PrtCnvMember *member = m_DbThread->getMemberByISSI(srcISSI); - if (member) - identity = member->m_Id; - sendFehlermeldungGefechtsfeldToCentral(identity, - TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorSendingToExerciseControl, - static_cast(messageReference)); - break; + uint8_t messageReference = a_data[14]; // messageReference contains the telegramId + uint16_t identity = 0; + PrtCnvMember *member = m_DbThread->getMemberByISSI(srcISSI); + if (member) + identity = member->m_Id; + sendFehlermeldungGefechtsfeldToCentral(identity, + TrainingAreaBase::TetraIcd::CtaDataError::Reason::ErrorSendingToExerciseControl, + static_cast(messageReference)); + break; } default: - ERROR_LOG(m_logger) << "reaction to delivery " << (int)a_data[16] << " not implemented"; - break; - } + ERROR_LOG(m_logger) << "reaction to delivery " << (int)a_data[16] << " not implemented"; + break; + } } else - ERROR_LOG(m_logger) << "Radio-Ack-Telegram from " << srcISSI << " is for another host: " << destISSI << " (we are " << m_HostISSI << ")"; -} + ERROR_LOG(m_logger) << "Radio-Ack-Telegram from " << srcISSI << " is for another host: " << destISSI << " (we are " << m_HostISSI << ")"; + } -void PrtCnvRadioThread::prepareWareHouseMessage(qint32 equipNr, bool doLicence, qint64 ergebnisCAN, qint64 ergebnisAusstattung, qint64 aktuelleKonfiguration, qint64 konfigurationsvergleich, const QList &fehlerListe) -{ + void PrtCnvRadioThread::prepareWareHouseMessage(qint32 equipNr, + bool doLicence, + qint64 ergebnisCAN, + qint64 ergebnisAusstattung, + qint64 aktuelleKonfiguration, + qint64 konfigurationsvergleich, + const QList &fehlerListe) + { QJsonObject obj; obj.insert(QStringLiteral("equipNo"), equipNr); obj.insert(QStringLiteral("doLicence"), doLicence); @@ -1947,41 +1880,40 @@ void PrtCnvRadioThread::prepareWareHouseMessage(qint32 equipNr, bool doLicence, obj.insert(QStringLiteral("configError"), konfigurationsvergleich); QJsonArray errorArr; // ERROR_LOG(m_logger) << "ERROR LIST SIZE= " << fehlerListe.size(); - for (const auto &error: fehlerListe) + for (const auto &error : fehlerListe) { - QJsonObject errorObj; - errorObj.insert(QStringLiteral("errorNumber"), error.errorNumber); - errorObj.insert(QStringLiteral("canDeviceNumber"), error.canDeviceNumber); - errorObj.insert(QStringLiteral("subdeviceNumber"), error.subdeviceNumber); - errorObj.insert(QStringLiteral("uniqueId"), error.uniqueId); - errorArr.append(errorObj); + QJsonObject errorObj; + errorObj.insert(QStringLiteral("errorNumber"), error.errorNumber); + errorObj.insert(QStringLiteral("canDeviceNumber"), error.canDeviceNumber); + errorObj.insert(QStringLiteral("subdeviceNumber"), error.subdeviceNumber); + errorObj.insert(QStringLiteral("uniqueId"), error.uniqueId); + errorArr.append(errorObj); } obj.insert(QStringLiteral("biteError"), errorArr); QJsonDocument doc(obj); emit warehouseMessageFromPtrCnv(doc.toJson()); -} + } -// --------------------------------------------------------------- -// Processes the status-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleStatusIndReq(const QByteArray &data) -{ + // --------------------------------------------------------------- + // Processes the status-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleStatusIndReq(const QByteArray &data) + { const uint8_t *a_data = reinterpret_cast(data.data()); uint32_t srcISSI = *(uint32_t *)&a_data[5]; uint32_t dstISSI = *(uint32_t *)&a_data[9]; - uint16_t status = *(uint16_t *)&a_data[13]; - INFO_LOG(m_logger) << "Received Status from " << srcISSI << " for " - << dstISSI << " - status: " << status; -} + uint16_t status = *(uint16_t *)&a_data[13]; + INFO_LOG(m_logger) << "Received Status from " << srcISSI << " for " << dstISSI << " - status: " << status; + } -// --------------------------------------------------------------- -// Processes the air-interface-report-telegram -// --------------------------------------------------------------- -void PrtCnvRadioThread::handleAirInterfaceLoadReq(const QByteArray &data) -{ + // --------------------------------------------------------------- + // Processes the air-interface-report-telegram + // --------------------------------------------------------------- + void PrtCnvRadioThread::handleAirInterfaceLoadReq(const QByteArray &data) + { const uint8_t *a_data = reinterpret_cast(data.data()); // get the number of reports @@ -1992,282 +1924,292 @@ void PrtCnvRadioThread::handleAirInterfaceLoadReq(const QByteArray &data) uint16_t index = 7; for (int i = 0; i < nbrOfReports; i++) { - uint8_t networkIndex = a_data[index++]; - uint16_t baseStationID = *(uint16_t *)&a_data[index]; - index += 2; - uint8_t channelID = a_data[index++]; - uint8_t queueLength = a_data[index++]; - INFO_LOG(m_logger) << "AirInterface-report[" << i << "]: networkIndex=" << (int)networkIndex << " baseStationID=" << baseStationID << " channelID=" << (int)channelID << " queueLength=" << (int)queueLength; - if (1 == networkIndex) - sdsQueueLength = queueLength; + uint8_t networkIndex = a_data[index++]; + uint16_t baseStationID = *(uint16_t *)&a_data[index]; + index += 2; + uint8_t channelID = a_data[index++]; + uint8_t queueLength = a_data[index++]; + INFO_LOG(m_logger) << "AirInterface-report[" << i << "]: networkIndex=" << (int)networkIndex << " baseStationID=" << baseStationID + << " channelID=" << (int)channelID << " queueLength=" << (int)queueLength; + if (1 == networkIndex) + sdsQueueLength = queueLength; } E_TrafficLoad newLoad; // decide the actual load-factor if (sdsQueueLength > m_SendQueueFullLoad) { - newLoad = E_TrafficLoad::FullLoad; - INFO_LOG(m_logger) << "Set send-load to Full"; + newLoad = E_TrafficLoad::FullLoad; + INFO_LOG(m_logger) << "Set send-load to Full"; } else if (sdsQueueLength > m_SendQueueHighLoad) { - newLoad = E_TrafficLoad::HighLoad; - INFO_LOG(m_logger) << "Set send-load to High"; + newLoad = E_TrafficLoad::HighLoad; + INFO_LOG(m_logger) << "Set send-load to High"; } else { - newLoad = E_TrafficLoad::NormalLoad; - INFO_LOG(m_logger) << "Set send-load to Normal"; + newLoad = E_TrafficLoad::NormalLoad; + INFO_LOG(m_logger) << "Set send-load to Normal"; } m_SendLoad = newLoad; -} + } -// --------------------------------------------------------------- -// Computes and logs the sent- and receive-statistics -// --------------------------------------------------------------- -void PrtCnvRadioThread::computeAndLogTrafficStatistics() -{ + // --------------------------------------------------------------- + // Computes and logs the sent- and receive-statistics + // --------------------------------------------------------------- + void PrtCnvRadioThread::computeAndLogTrafficStatistics() + { if (++m_TickCounter >= m_TicksPerSecond) { - m_TickCounter = 0; - m_SentBytesAverage[m_AverageIndex] = m_SentBytes; - m_ReceivedBytesAverage[m_AverageIndex] = m_ReceivedBytes; - if (++m_AverageIndex >= AVERAGE_COUNT) m_AverageIndex = 0; - uint32_t sendAverage = 0; - uint32_t receiveAverage = 0; - for (int i = 0; i < AVERAGE_COUNT; i++) - { - sendAverage += m_SentBytesAverage[i]; - receiveAverage += m_ReceivedBytesAverage[i]; - } - DEBUG_LOG(m_loggerStats) << "Send-Statistics: " << m_SentTelegrams << " telegrams (" << m_SentBytes << "/" << sendAverage << " bytes) sent; " << (sendAverage / 10) << " kB/s"; - DEBUG_LOG(m_loggerStats) << "Receive-Statistics: " << m_ReceivedTelegrams << " telegrams (" << m_ReceivedBytes << "/" << receiveAverage << " bytes) received; " << (receiveAverage / 10) << " kB/s"; - m_SentBytes = 0; - m_SentTelegrams = 0; - m_ReceivedBytes = 0; - m_ReceivedTelegrams = 0; + m_TickCounter = 0; + m_SentBytesAverage[m_AverageIndex] = m_SentBytes; + m_ReceivedBytesAverage[m_AverageIndex] = m_ReceivedBytes; + if (++m_AverageIndex >= AVERAGE_COUNT) + m_AverageIndex = 0; + uint32_t sendAverage = 0; + uint32_t receiveAverage = 0; + for (int i = 0; i < AVERAGE_COUNT; i++) + { + sendAverage += m_SentBytesAverage[i]; + receiveAverage += m_ReceivedBytesAverage[i]; + } + DEBUG_LOG(m_loggerStats) << "Send-Statistics: " << m_SentTelegrams << " telegrams (" << m_SentBytes << "/" << sendAverage << " bytes) sent; " << (sendAverage / 10) + << " kB/s"; + DEBUG_LOG(m_loggerStats) << "Receive-Statistics: " << m_ReceivedTelegrams << " telegrams (" << m_ReceivedBytes << "/" << receiveAverage << " bytes) received; " + << (receiveAverage / 10) << " kB/s"; + m_SentBytes = 0; + m_SentTelegrams = 0; + m_ReceivedBytes = 0; + m_ReceivedTelegrams = 0; } -} + } - -// --------------------------------------------------------------- -// returns true, if at the moment no more telegrams should be -// sent -// --------------------------------------------------------------- -bool PrtCnvRadioThread::isSendLimitReached() const -{ + // --------------------------------------------------------------- + // returns true, if at the moment no more telegrams should be + // sent + // --------------------------------------------------------------- + bool PrtCnvRadioThread::isSendLimitReached() const + { switch (m_SendLoad) { - case E_TrafficLoad::NormalLoad: + case E_TrafficLoad::NormalLoad: return m_SentTelegrams >= m_SendTelegramsNormalLoad; - case E_TrafficLoad::HighLoad: + case E_TrafficLoad::HighLoad: return m_SentTelegrams >= m_SendTelegramsHighLoad; - case E_TrafficLoad::FullLoad: + case E_TrafficLoad::FullLoad: return m_SentTelegrams >= m_SendTelegramsFullLoad; - case E_TrafficLoad::Unknown: + case E_TrafficLoad::Unknown: return false; } Q_ASSERT(false); return false; -} + } -// --------------------------------------------------------------- -// Immediatelly send the environment telegramm to inform the -// players about the new state -// --------------------------------------------------------------- -void PrtCnvRadioThread::sendEnvironmentTelegramTimerNow() -{ + // --------------------------------------------------------------- + // Immediatelly send the environment telegramm to inform the + // players about the new state + // --------------------------------------------------------------- + void PrtCnvRadioThread::sendEnvironmentTelegramTimerNow() + { // switch thread QTimer::singleShot(0, this, &PrtCnvRadioThread::onSendEnvironmentTelegramTimerNow); -} + } -void PrtCnvRadioThread::onSendEnvironmentTelegramTimerNow() -{ + void PrtCnvRadioThread::onSendEnvironmentTelegramTimerNow() + { if (!m_EnvironmentTelegramTimer || !m_EnvironmentTelegramTimer->isActive()) - return; + return; timeoutEnvironmentTelegram(); -} + } -template -void removeFromContainer(T &cont, int id) -{ + template void removeFromContainer(T &cont, int id) + { auto it = cont.find(id); if (it != cont.end()) - cont.erase(it); -} + cont.erase(it); + } -void PrtCnvRadioThread::exerciseEquipmentChanged(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) -{ + void PrtCnvRadioThread::exerciseEquipmentChanged(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data) + { QMutexLocker l(&m_exerciseEquipmentAssignmentMutex); m_exerciseEquipmentAssignments = data.exerciseEquipmentAssignments; for (const auto &info : data.groupIssiInformation) - m_groupIssiInformation[info.exerciseId] = info; + m_groupIssiInformation[info.exerciseId] = info; emit checkMemberForValidLogin(-1, -1); -} + } -void PrtCnvRadioThread::onCheckMemberForValidLogin(int identity, int issi) -{ + void PrtCnvRadioThread::onCheckMemberForValidLogin(int identity, int issi) + { QMutexLocker l(&m_exerciseEquipmentAssignmentMutex); if (identity == -1) { - const auto knownIdentities = m_DbThread->getClaimStatistics(); - for (const auto &p : knownIdentities) - { - if (p.first <= 0) - continue; - onCheckMemberForValidLogin(p.first, -1); - } + const auto knownIdentities = m_DbThread->getClaimStatistics(); + for (const auto &p : knownIdentities) + { + if (p.first <= 0) + continue; + onCheckMemberForValidLogin(p.first, -1); + } } else { - if (isIdentityInCurrentExercise(identity)) - { - DEBUG_LOG(m_logger) << "onCheckMemberForValidLogin: eqid: " << identity << " is in current exercise " << m_ExerciseId; - return; - } - PrtCnv::PrtCnvMember *member = m_DbThread->getMemberById(identity); - if (!member) - return; - issi = member->m_ISSI; + if (isIdentityInCurrentExercise(identity)) + { + DEBUG_LOG(m_logger) << "onCheckMemberForValidLogin: eqid: " << identity << " is in current exercise " << m_ExerciseId; + return; + } + PrtCnv::PrtCnvMember *member = m_DbThread->getMemberById(identity); + if (!member) + return; + issi = member->m_ISSI; - const int newExerciseId = exerciseIdForIdentity(identity); - if (newExerciseId != 0 && newExerciseId != member->m_loggedInExerciseId) - sendLoginAccept(identity, issi, newExerciseId, false); + const int newExerciseId = exerciseIdForIdentity(identity); + if (newExerciseId != 0 && newExerciseId != member->m_loggedInExerciseId) + sendLoginAccept(identity, issi, newExerciseId, false); } -} + } -void PrtCnvRadioThread::sendLoginAccept(int identity, int issi, int exerciseId, bool bWithMastering) -{ + void PrtCnvRadioThread::sendLoginAccept(int identity, int issi, int exerciseId, bool bWithMastering) + { using namespace N_CoPrtCnv; auto response = 0; if (bWithMastering) - response |= CoPrtCnvRadioTelegram::e_LoginMastering; + response |= CoPrtCnvRadioTelegram::e_LoginMastering; PrtCnvMember *member = m_DbThread->getMemberById(identity); const auto it = m_groupIssiInformation.find(exerciseId); if (it == m_groupIssiInformation.end() || exerciseId == 0) { - // no gissi information found or no exercise assigned - QString log; - if (exerciseId == 0) - log = QStringLiteral("Denied Login of TPU with Id=%1 and ISSI=%2 - Id is not assigned in any exercise.") - .arg(identity).arg(issi); - else - log = QStringLiteral("TPU with Id=%1 and ISSI=%2 should be in exercise %3 but could not find valid group information for this exercise!") - .arg(identity).arg(issi).arg(exerciseId); - if (bWithMastering) - log += QStringLiteral(" Mastering-Bit is set"); - WARNING_LOG(m_logger) << log; - writeLoginLog(identity, issi, log); - if (m_ExerciseId != exerciseId) - response |= CoPrtCnvRadioTelegram::e_LoginNoExerciseAssignment; - response |= CoPrtCnvRadioTelegram::e_LoginReject; - sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(response), identity, issi); - if (m_ExerciseId == 0) - m_DbThread->updateExerciseIdForMember(member, exerciseId); - else - m_DbThread->removeMember(member); - return; + // no gissi information found or no exercise assigned + QString log; + if (exerciseId == 0) + log = QStringLiteral("Denied Login of TPU with Id=%1 and ISSI=%2 - Id is not assigned in any exercise.").arg(identity).arg(issi); + else + log = QStringLiteral("TPU with Id=%1 and ISSI=%2 should be in exercise %3 but could not find valid group information for this exercise!") + .arg(identity) + .arg(issi) + .arg(exerciseId); + if (bWithMastering) + log += QStringLiteral(" Mastering-Bit is set"); + WARNING_LOG(m_logger) << log; + writeLoginLog(identity, issi, log); + if (m_ExerciseId != exerciseId) + response |= CoPrtCnvRadioTelegram::e_LoginNoExerciseAssignment; + response |= CoPrtCnvRadioTelegram::e_LoginReject; + sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(response), identity, issi); + if (m_ExerciseId == 0) + m_DbThread->updateExerciseIdForMember(member, exerciseId); + else + m_DbThread->removeMember(member); + return; } const TrainingAreaBase::TetraIcd::GroupIssiInformation &gi = it->second; QString log; if (m_ExerciseId != exerciseId) - log = QStringLiteral("TPU with Id=%1 and ISSI=%2 should switch to exercise %3 (%4/%5).") - .arg(identity).arg(issi).arg(exerciseId).arg(gi.broadcastIssi1).arg(gi.broadcastIssi2); + log = QStringLiteral("TPU with Id=%1 and ISSI=%2 should switch to exercise %3 (%4/%5).") + .arg(identity) + .arg(issi) + .arg(exerciseId) + .arg(gi.broadcastIssi1) + .arg(gi.broadcastIssi2); else - log = QStringLiteral("(Re)Login of TPU with Id=%1 and ISSI=%2.") - .arg(identity).arg(issi); + log = QStringLiteral("(Re)Login of TPU with Id=%1 and ISSI=%2.").arg(identity).arg(issi); if (bWithMastering) - log += QStringLiteral(" Mastering-Bit is set"); + log += QStringLiteral(" Mastering-Bit is set"); DEBUG_LOG(m_logger) << log; writeLoginLog(identity, issi, log); if (m_ExerciseId != exerciseId) - response |= CoPrtCnvRadioTelegram::e_LoginOtherExercise; + response |= CoPrtCnvRadioTelegram::e_LoginOtherExercise; response |= CoPrtCnvRadioTelegram::e_LoginAccept; sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(response), identity, issi, gi); if (m_ExerciseId == 0) - m_DbThread->updateExerciseIdForMember(member, exerciseId); -} + m_DbThread->updateExerciseIdForMember(member, exerciseId); + } -bool PrtCnvRadioThread::isIdentityInCurrentExercise(int identity) const -{ + bool PrtCnvRadioThread::isIdentityInCurrentExercise(int identity) const + { QMutexLocker l(&m_exerciseEquipmentAssignmentMutex); if (m_exerciseEquipmentAssignments.empty()) // no assignments at all -> fallback to old behaviour - return true; + return true; const auto it = m_exerciseEquipmentAssignments.find(m_ExerciseId); if (it == m_exerciseEquipmentAssignments.end()) - return false; + return false; const auto itIdentity = it->second.find(identity); return (itIdentity != it->second.end()); -} + } -int PrtCnvRadioThread::exerciseIdForIdentity(int identity) const -{ + int PrtCnvRadioThread::exerciseIdForIdentity(int identity) const + { QMutexLocker l(&m_exerciseEquipmentAssignmentMutex); for (const auto &s : m_exerciseEquipmentAssignments) { - auto it = s.second.find(identity); - if (it != s.second.end()) - return s.first; + auto it = s.second.find(identity); + if (it != s.second.end()) + return s.first; } return 0; -} + } -void PrtCnvRadioThread::removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram, - PrtCnvMember *member, - PrtCnvMember *issiMember, - int masterIdentity, - int masterIssi) -{ + void PrtCnvRadioThread::removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram, + PrtCnvMember *member, + PrtCnvMember *issiMember, + int masterIdentity, + int masterIssi) + { using namespace N_CoPrtCnv; // remove old member if (member) { - m_DbThread->updateExerciseIdForMember(member, 0); - // unlicense the old TPU - if (member->m_Licensed) - { - sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); - INFO_LOG(m_logger) << "Unlicense TPU with already used ID. Id=" - << member->m_Id << " ISSI=" << member->m_ISSI; - } - // reject old TPU - sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(CoPrtCnvRadioTelegram::e_LoginReject | CoPrtCnvRadioTelegram::e_LoginOtherEqId), - member->m_Id, member->m_ISSI); - INFO_LOG(m_logger) << "Reject TPU with already used ID. Id=" - << member->m_Id << " ISSI=" << member->m_ISSI; - writeLoginLog(a_loginTelegram, - QStringLiteral("Login-failure: TPU with Id=%1 and ISSI=%2 was removed from TETRA due to Mastering-Bit from Id=%3 and ISSI=%4") - .arg(member->m_Id).arg(member->m_ISSI).arg(masterIdentity).arg(masterIssi)); - m_DbThread->removeMember(member); + m_DbThread->updateExerciseIdForMember(member, 0); + // unlicense the old TPU + if (member->m_Licensed) + { + sendLizenzierungTneToRadio(member->m_Id, member->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); + INFO_LOG(m_logger) << "Unlicense TPU with already used ID. Id=" << member->m_Id << " ISSI=" << member->m_ISSI; + } + // reject old TPU + sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(CoPrtCnvRadioTelegram::e_LoginReject | CoPrtCnvRadioTelegram::e_LoginOtherEqId), + member->m_Id, + member->m_ISSI); + INFO_LOG(m_logger) << "Reject TPU with already used ID. Id=" << member->m_Id << " ISSI=" << member->m_ISSI; + writeLoginLog(a_loginTelegram, + QStringLiteral("Login-failure: TPU with Id=%1 and ISSI=%2 was removed from TETRA due to Mastering-Bit from Id=%3 and ISSI=%4") + .arg(member->m_Id) + .arg(member->m_ISSI) + .arg(masterIdentity) + .arg(masterIssi)); + m_DbThread->removeMember(member); } // remove old issi member if (issiMember) { - m_DbThread->updateExerciseIdForMember(issiMember, 0); - // unlicense the old TPU - if (issiMember->m_Licensed) - { - sendLizenzierungTneToRadio(issiMember->m_Id, issiMember->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); - INFO_LOG(m_logger) << "Unlicense TPU with already used ISSI. Id=" - << issiMember->m_Id << " ISSI=" << issiMember->m_ISSI; - } - // reject old TPU - sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(CoPrtCnvRadioTelegram::e_LoginReject | CoPrtCnvRadioTelegram::e_LoginOtherISSI), - issiMember->m_Id, issiMember->m_ISSI); - INFO_LOG(m_logger) << "Reject TPU with already used ISSI. Id=" - << issiMember->m_Id << " ISSI=" << issiMember->m_ISSI; - writeLoginLog(a_loginTelegram, - QStringLiteral("Login-failure: TPU with Id=%1 and ISSI=%2 was removed from TETRA due to Mastering-Bit from Id=%3 and ISSI=%4") - .arg(issiMember->m_Id).arg(issiMember->m_ISSI).arg(masterIdentity).arg(masterIssi)); - m_DbThread->removeMember(issiMember); + m_DbThread->updateExerciseIdForMember(issiMember, 0); + // unlicense the old TPU + if (issiMember->m_Licensed) + { + sendLizenzierungTneToRadio(issiMember->m_Id, issiMember->m_ISSI, N_CoPrtCnv::E_LicensingKind::Unlicense, N_CoPrtCnv::E_LicensingErrorCode::Unlicense); + INFO_LOG(m_logger) << "Unlicense TPU with already used ISSI. Id=" << issiMember->m_Id << " ISSI=" << issiMember->m_ISSI; + } + // reject old TPU + sendLoginResponse(CoPrtCnvRadioTelegram::E_LoginStatus(CoPrtCnvRadioTelegram::e_LoginReject | CoPrtCnvRadioTelegram::e_LoginOtherISSI), + issiMember->m_Id, + issiMember->m_ISSI); + INFO_LOG(m_logger) << "Reject TPU with already used ISSI. Id=" << issiMember->m_Id << " ISSI=" << issiMember->m_ISSI; + writeLoginLog(a_loginTelegram, + QStringLiteral("Login-failure: TPU with Id=%1 and ISSI=%2 was removed from TETRA due to Mastering-Bit from Id=%3 and ISSI=%4") + .arg(issiMember->m_Id) + .arg(issiMember->m_ISSI) + .arg(masterIdentity) + .arg(masterIssi)); + m_DbThread->removeMember(issiMember); } -} + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.hpp index e683021a0..8fe8fb175 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioThread.hpp @@ -26,19 +26,19 @@ namespace PrtCnv { -struct BiteError -{ - int errorNumber = 0; - int canDeviceNumber = 0; - int subdeviceNumber = 0; - int uniqueId = 0; -}; + struct BiteError + { + int errorNumber = 0; + int canDeviceNumber = 0; + int subdeviceNumber = 0; + int uniqueId = 0; + }; class PrtCnvCentralThread; class PrtCnvMember; class PrtCnvRadioTrafficThread; class PrtCnvStoredRadioTelegram; - /** + /** * This class handles the protocol to radio. This includes: * - handle login and licensing of TNEs * - send and receive normal telegrams @@ -53,9 +53,8 @@ struct BiteError { Q_OBJECT -public: - - PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter* a_parent); + public: + PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter *a_parent); /** * Creates all subcomponents and connects signals to slots */ @@ -86,12 +85,14 @@ public: void sendEnvironmentTelegramTimerNow(); void exerciseEquipmentChanged(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data); + protected: void onCheckMemberForValidLogin(int identity, int issi); void sendLoginAccept(int identity, int issi, int exerciseId, bool bWithMastering); bool isIdentityInCurrentExercise(int identity) const; int exerciseIdForIdentity(int identity) const; - void removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram, PrtCnvMember *member, + void removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram, + PrtCnvMember *member, PrtCnvMember *issiMember, int masterIdentity, int masterIssi); @@ -107,8 +108,7 @@ public: */ PrtCnvRadioTrafficThread *m_radioTrafficThread; -public: - + public: Q_SIGNALS: /** * Signal to start sending a telegram to central @@ -147,6 +147,7 @@ public: // a player was (un)licensed void playerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind); void warehouseMessageFromPtrCnv(const QByteArray &jsonData); + protected: /** * Counts the sended telegrams @@ -250,7 +251,6 @@ public: void handleRegisterRsp(const uint8_t a_regsitrationStatus); public: - /** * @author alois.wismer * @version 1.0 @@ -263,6 +263,7 @@ public: HighLoad, FullLoad }; + protected: /** * Holds the radio-telegram for sending Umgebungsmeldung periodically @@ -405,8 +406,7 @@ public: uint32_t ergebnisAusstattung, uint32_t aktuelleKonfiguration, uint32_t konfigurationsvergleich, - const QList &fehlerListe - ); + const QList &fehlerListe); /** * Sends a login-telegram to radio @@ -417,7 +417,9 @@ public: */ void sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, const uint32_t a_ISSI); void sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, - const uint16_t a_identity, const uint32_t a_ISSI, const TrainingAreaBase::TetraIcd::GroupIssiInformation &group); + const uint16_t a_identity, + const uint32_t a_ISSI, + const TrainingAreaBase::TetraIcd::GroupIssiInformation &group); /** * Sends a telegram "LizenzierungTNE" to radio @@ -427,7 +429,8 @@ public: * @param a_licensingKind * @param a_errorCause */ - void sendLizenzierungTneToRadio(const uint16_t a_identity, const uint32_t a_issi, + void sendLizenzierungTneToRadio(const uint16_t a_identity, + const uint32_t a_issi, const N_CoPrtCnv::E_LicensingKind a_licensingKind, const N_CoPrtCnv::E_LicensingErrorCode a_errorCause); @@ -453,7 +456,7 @@ public: * @param a_line * @param a_fileName */ - uint16_t readIdentity(const QByteArray& a_idAsText, const uint32_t a_line, const QString& a_fileName); + uint16_t readIdentity(const QByteArray &a_idAsText, const uint32_t a_line, const QString &a_fileName); /** * Checks whether the playerId is allowd. * diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.cpp index 27d8dee4d..d279bf517 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.cpp @@ -23,186 +23,183 @@ namespace PrtCnv { -PrtCnvRadioTrafficThread::PrtCnvRadioTrafficThread(PrtCnvThreadStarter* a_parent) - : PrtCnvThread(a_parent, "PrtCnvRadioTrafficThread") - , m_receiveLoad(PrtCnvRadioThread::E_TrafficLoad::Unknown) - , m_fullLoad(100) - , m_highLoad(50) - , m_hystLoad(5) - , m_calcTimeout(1000) - , m_cleanupTimeout(5000) - , m_mutex() -{} - -void PrtCnvRadioTrafficThread::newTelegramArrived(unsigned int size) -{ - time_t curTime = time(nullptr); - - QMutexLocker l(&m_mutex); - DEBUG_LOG(m_logger) << "newTelegramArrived with size " << size << " at " << curTime; - m_data[curTime] += size; - m_telegrams[curTime]++; -} - -int32_t PrtCnvRadioTrafficThread::start() -{ - // read data from m_Config - const QString trafficControlGroup(QStringLiteral("TrafficControl")); - int highLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHighLoad"), 60); - int fullLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueFullLoad"), 80); - int hystLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHysteresis"), 5); - int avgTime = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveAveragingTime"), 5); - float trafficPerReceiverKB = m_Config->getFloat(trafficControlGroup, QStringLiteral("ReceiveThroughput"), 3.6f); - int cntTransceiver = m_Config->getInteger(trafficControlGroup, QStringLiteral("TransceiverCount"), 6); - - // sanity checks - if (highLoad < 0 || highLoad > 100) - highLoad = 60; - if (fullLoad < highLoad || fullLoad > 100) - fullLoad = 80; - if (hystLoad < 0 || hystLoad > 10) - hystLoad = 5; - if (avgTime <= 0 || avgTime > 60) - avgTime = 5; - if (trafficPerReceiverKB < 1 || trafficPerReceiverKB > 1000) - trafficPerReceiverKB = 3.6f; - if (cntTransceiver < 1 || cntTransceiver > 100) - cntTransceiver = 6; - - float maxTrafficBytes = trafficPerReceiverKB * cntTransceiver * 1024; - - m_fullLoad = maxTrafficBytes * fullLoad / 100.f; - m_highLoad = maxTrafficBytes * highLoad / 100.f; - m_hystLoad = maxTrafficBytes * hystLoad / 100.f; - m_cleanupTimeout = avgTime * 1000; // ms - - DEBUG_LOG(m_logger) << "Read config ReceiveQueueHighLoad: " << highLoad; - DEBUG_LOG(m_logger) << "Read config ReceiveQueueFullLoad: " << fullLoad; - DEBUG_LOG(m_logger) << "Read config ReceiveQueueHysteresis: " << hystLoad; - DEBUG_LOG(m_logger) << "Read config ReceiveAveragingTime: " << avgTime; - DEBUG_LOG(m_logger) << "Read config ReceiveThroughput: " << trafficPerReceiverKB; - DEBUG_LOG(m_logger) << "Read config TransceiverCount: " << cntTransceiver; - - INFO_LOG(m_logger) << "Using to following limits: high - " << m_highLoad - << " full - " << m_fullLoad - << " hyst - " << m_hystLoad - << " avg. time - " << m_cleanupTimeout / 1000; - - QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad); - QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout); - return 0; -} - -void PrtCnvRadioTrafficThread::onCalculateTrafficLoad() -{ - const time_t curTime = time(nullptr); - - unsigned int payload = 0; + PrtCnvRadioTrafficThread::PrtCnvRadioTrafficThread(PrtCnvThreadStarter *a_parent) + : PrtCnvThread(a_parent, "PrtCnvRadioTrafficThread") + , m_receiveLoad(PrtCnvRadioThread::E_TrafficLoad::Unknown) + , m_fullLoad(100) + , m_highLoad(50) + , m_hystLoad(5) + , m_calcTimeout(1000) + , m_cleanupTimeout(5000) + , m_mutex() { + } + + void PrtCnvRadioTrafficThread::newTelegramArrived(unsigned int size) + { + time_t curTime = time(nullptr); + QMutexLocker l(&m_mutex); - // fuer aktuelle Sekunde haben wir noch nicht alle Daten - for (int i = 1; i <= m_cleanupTimeout / 1000; ++i) - payload += m_data.value(curTime - i); + DEBUG_LOG(m_logger) << "newTelegramArrived with size " << size << " at " << curTime; + m_data[curTime] += size; + m_telegrams[curTime]++; } - // Durchschnitt ... - payload /= (m_cleanupTimeout / 1000); - - INFO_LOG(m_logger) << "Average Payload in the last " - << m_cleanupTimeout << " Milliseconds: " - << payload << " Bytes/sec, last sec: " - << m_data[curTime - 1] << " Bytes, #telegrams: " << m_telegrams[curTime - 1]; - - PrtCnvRadioThread::E_TrafficLoad newReceiveLoad; - if (payload >= m_fullLoad) + int32_t PrtCnvRadioTrafficThread::start() { - // full load - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad; - // Hysterese nach oben - if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad) - { - // wenn cnt in Bereich m_fullLoad ... m_fullLoad + m_hystLoad - // -> noch warten - if(payload < m_fullLoad + m_hystLoad) - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; - } + // read data from m_Config + const QString trafficControlGroup(QStringLiteral("TrafficControl")); + int highLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHighLoad"), 60); + int fullLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueFullLoad"), 80); + int hystLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHysteresis"), 5); + int avgTime = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveAveragingTime"), 5); + float trafficPerReceiverKB = m_Config->getFloat(trafficControlGroup, QStringLiteral("ReceiveThroughput"), 3.6f); + int cntTransceiver = m_Config->getInteger(trafficControlGroup, QStringLiteral("TransceiverCount"), 6); + + // sanity checks + if (highLoad < 0 || highLoad > 100) + highLoad = 60; + if (fullLoad < highLoad || fullLoad > 100) + fullLoad = 80; + if (hystLoad < 0 || hystLoad > 10) + hystLoad = 5; + if (avgTime <= 0 || avgTime > 60) + avgTime = 5; + if (trafficPerReceiverKB < 1 || trafficPerReceiverKB > 1000) + trafficPerReceiverKB = 3.6f; + if (cntTransceiver < 1 || cntTransceiver > 100) + cntTransceiver = 6; + + float maxTrafficBytes = trafficPerReceiverKB * cntTransceiver * 1024; + + m_fullLoad = maxTrafficBytes * fullLoad / 100.f; + m_highLoad = maxTrafficBytes * highLoad / 100.f; + m_hystLoad = maxTrafficBytes * hystLoad / 100.f; + m_cleanupTimeout = avgTime * 1000; // ms + + DEBUG_LOG(m_logger) << "Read config ReceiveQueueHighLoad: " << highLoad; + DEBUG_LOG(m_logger) << "Read config ReceiveQueueFullLoad: " << fullLoad; + DEBUG_LOG(m_logger) << "Read config ReceiveQueueHysteresis: " << hystLoad; + DEBUG_LOG(m_logger) << "Read config ReceiveAveragingTime: " << avgTime; + DEBUG_LOG(m_logger) << "Read config ReceiveThroughput: " << trafficPerReceiverKB; + DEBUG_LOG(m_logger) << "Read config TransceiverCount: " << cntTransceiver; + + INFO_LOG(m_logger) << "Using to following limits: high - " << m_highLoad << " full - " << m_fullLoad << " hyst - " << m_hystLoad << " avg. time - " + << m_cleanupTimeout / 1000; + + QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad); + QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout); + return 0; } - else if (payload >= m_highLoad) - { - // high load - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; - // Hysterese nach oben - if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::NormalLoad) - { - // wenn cnt in Bereich m_highLoad ... m_highLoad + m_hystLoad - // -> noch warten - if (payload < m_highLoad + m_hystLoad) - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad; - } - // Hysterese nach unten - if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::FullLoad) - { - // wenn cnt in Bereich m_fullLoad ... m_fullLoad - m_hystLoad - // -> noch warten - if (payload >= m_fullLoad - m_hystLoad) - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad; - } - } - else - { - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad; - // Hysterese nach unten - if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad) - { - // wenn cnt in Bereich m_highLoad ... m_highLoad - m_hystLoad - // -> noch warten - if(payload >= m_highLoad - m_hystLoad) - newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; - } - } - if (m_receiveLoad != newReceiveLoad) - { - m_receiveLoad = newReceiveLoad; - // Achtung: Nicht mehr als 31 Sekunden erlaubt - unsigned int wartezeit_posmldg = (static_cast(m_receiveLoad) * 10) + 1; - INFO_LOG(m_logger) << "New traffic load: " << m_receiveLoad; - PrtCnvDbThread *dbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); - if (dbThread) - { - dbThread->setAirLoad(m_receiveLoad); - dbThread->setPositionSendTime(wartezeit_posmldg); + void PrtCnvRadioTrafficThread::onCalculateTrafficLoad() + { + const time_t curTime = time(nullptr); - Q_ASSERT(QThread::currentThreadId() == m_currentThreadId); + unsigned int payload = 0; + { + QMutexLocker l(&m_mutex); + // fuer aktuelle Sekunde haben wir noch nicht alle Daten + for (int i = 1; i <= m_cleanupTimeout / 1000; ++i) + payload += m_data.value(curTime - i); + } + + // Durchschnitt ... + payload /= (m_cleanupTimeout / 1000); + + INFO_LOG(m_logger) << "Average Payload in the last " << m_cleanupTimeout << " Milliseconds: " << payload << " Bytes/sec, last sec: " << m_data[curTime - 1] + << " Bytes, #telegrams: " << m_telegrams[curTime - 1]; + + PrtCnvRadioThread::E_TrafficLoad newReceiveLoad; + if (payload >= m_fullLoad) + { + // full load + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad; + // Hysterese nach oben + if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad) + { + // wenn cnt in Bereich m_fullLoad ... m_fullLoad + m_hystLoad + // -> noch warten + if (payload < m_fullLoad + m_hystLoad) + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; + } + } + else if (payload >= m_highLoad) + { + // high load + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; + // Hysterese nach oben + if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::NormalLoad) + { + // wenn cnt in Bereich m_highLoad ... m_highLoad + m_hystLoad + // -> noch warten + if (payload < m_highLoad + m_hystLoad) + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad; + } + // Hysterese nach unten + if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::FullLoad) + { + // wenn cnt in Bereich m_fullLoad ... m_fullLoad - m_hystLoad + // -> noch warten + if (payload >= m_fullLoad - m_hystLoad) + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad; + } } else - ERROR_LOG(m_logger) << "Could not get PrtCnvDbThread!"; - } - - QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad); -} - -void PrtCnvRadioTrafficThread::onCleanupTimeout() -{ - const time_t curTime = time(nullptr); - { - QMutexLocker l(&m_mutex); - QMap::iterator it = m_data.begin(); - while (it != m_data.end()) { - const time_t key = it.key(); - // 10 als Puffer (siehe auch onCalculateTrafficLoad()) - if (key < curTime - m_cleanupTimeout - 10) + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad; + // Hysterese nach unten + if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad) { - m_data.erase(it++); - m_telegrams.remove(key); - continue; + // wenn cnt in Bereich m_highLoad ... m_highLoad - m_hystLoad + // -> noch warten + if (payload >= m_highLoad - m_hystLoad) + newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad; } - break; // arbitrarily ordered } + if (m_receiveLoad != newReceiveLoad) + { + m_receiveLoad = newReceiveLoad; + // Achtung: Nicht mehr als 31 Sekunden erlaubt + unsigned int wartezeit_posmldg = (static_cast(m_receiveLoad) * 10) + 1; + + INFO_LOG(m_logger) << "New traffic load: " << m_receiveLoad; + PrtCnvDbThread *dbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); + if (dbThread) + { + dbThread->setAirLoad(m_receiveLoad); + dbThread->setPositionSendTime(wartezeit_posmldg); + + Q_ASSERT(QThread::currentThreadId() == m_currentThreadId); + } + else + ERROR_LOG(m_logger) << "Could not get PrtCnvDbThread!"; + } + + QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad); } - QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout); -} + void PrtCnvRadioTrafficThread::onCleanupTimeout() + { + const time_t curTime = time(nullptr); + { + QMutexLocker l(&m_mutex); + QMap::iterator it = m_data.begin(); + while (it != m_data.end()) + { + const time_t key = it.key(); + // 10 als Puffer (siehe auch onCalculateTrafficLoad()) + if (key < curTime - m_cleanupTimeout - 10) + { + m_data.erase(it++); + m_telegrams.remove(key); + continue; + } + break; // arbitrarily ordered + } + } + + QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout); + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.hpp index 1a4762fe2..5fcede697 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvRadioTrafficThread.hpp @@ -21,76 +21,75 @@ namespace PrtCnv { -/** + /** * This class handles the traffic counting for the * incoming radio data */ -class PrtCnvRadioTrafficThread final : public PrtCnvThread -{ - Q_OBJECT -public: - explicit PrtCnvRadioTrafficThread(PrtCnvThreadStarter* a_parent); + class PrtCnvRadioTrafficThread final : public PrtCnvThread + { + Q_OBJECT + public: + explicit PrtCnvRadioTrafficThread(PrtCnvThreadStarter *a_parent); - /** + /** * A new telegram arrived. */ - void newTelegramArrived(unsigned int size); + void newTelegramArrived(unsigned int size); - /** + /** * Start the thread handling */ - int32_t start() override; + int32_t start() override; -protected Q_SLOTS: - /** + protected Q_SLOTS: + /** * Timeout to recalculate traffic load */ - void onCalculateTrafficLoad(); + void onCalculateTrafficLoad(); - /** + /** * Timeout to throw away old data */ - void onCleanupTimeout(); + void onCleanupTimeout(); -protected: - /** + protected: + /** * The current traffic load */ - PrtCnvRadioThread::E_TrafficLoad m_receiveLoad; + PrtCnvRadioThread::E_TrafficLoad m_receiveLoad; - /** + /** * Full load */ - unsigned int m_fullLoad; + unsigned int m_fullLoad; - /** + /** * High load */ - unsigned int m_highLoad; + unsigned int m_highLoad; - /** + /** * Hysterese */ - unsigned int m_hystLoad; + unsigned int m_hystLoad; - /** + /** * Timeout for recalculation */ - int m_calcTimeout; + int m_calcTimeout; - /** + /** * Timeout until data is thrown away */ - int m_cleanupTimeout; + int m_cleanupTimeout; - - QRecursiveMutex m_mutex; + QRecursiveMutex m_mutex; - /** + /** * map */ - QMap m_data; - QMap m_telegrams; -}; + QMap m_data; + QMap m_telegrams; + }; } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.cpp index 93cbc9e79..d571fb1d0 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.cpp @@ -25,359 +25,359 @@ namespace PrtCnv { -// --------------------------------------------------------------- -// Constructor with pointer to thread-starter as parameter -// --------------------------------------------------------------- -PrtCnvSocketThread::PrtCnvSocketThread(PrtCnv::PrtCnvThreadStarter* a_parent, const char *loggerName) - : PrtCnvThread(a_parent, loggerName) - , m_ConnectionTimer(nullptr) - , m_Socket(nullptr) - , m_TickTimer(nullptr) - , m_ReceiveCounter(0) - , m_ReceiveAckCounter(0) - , m_State(PrtCnvSocketThread::e_INITIAL) - , m_DbThread(nullptr) - , m_ConnectTimeout(2000) - , m_DisconnectTimeout(10000) - , m_AliveTimeout(3000) - , m_TickTimeout(900) - , m_DoCleanup(false) - , m_LogThread(nullptr) - , m_InjectionThread(nullptr) - , m_currentHostAdressIndex(0) -{} - - - -PrtCnvSocketThread::~PrtCnvSocketThread() -{ - cleanup(); -} - -// --------------------------------------------------------------- -// Creates all subcomponents and connects signals to slots -// --------------------------------------------------------------- -int32_t PrtCnvSocketThread::create(NGL::Settings *settings) -{ - PrtCnvThread::create(settings); - - createNewSocket(); - - m_ConnectionTimer = new QTimer(this); - connect(m_ConnectionTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutAliveAndConnection); - - m_TickTimer = new QTimer(this); - connect(m_TickTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutTick); - - m_DbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); - m_LogThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Log)); - m_InjectionThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Injection)); - - return 0; -} - -// --------------------------------------------------------------- -// Creates a new socket to avoid getting old stuff from the -// former socket when reconnecting -// --------------------------------------------------------------- -void PrtCnvSocketThread::createNewSocket() -{ - INFO_LOG(m_logger) << "createNewSocket m_oldSocket=" << m_Socket; - Q_ASSERT(QThread::currentThreadId() == m_currentThreadId); - - if (m_Socket) + // --------------------------------------------------------------- + // Constructor with pointer to thread-starter as parameter + // --------------------------------------------------------------- + PrtCnvSocketThread::PrtCnvSocketThread(PrtCnv::PrtCnvThreadStarter *a_parent, const char *loggerName) + : PrtCnvThread(a_parent, loggerName) + , m_ConnectionTimer(nullptr) + , m_Socket(nullptr) + , m_TickTimer(nullptr) + , m_ReceiveCounter(0) + , m_ReceiveAckCounter(0) + , m_State(PrtCnvSocketThread::e_INITIAL) + , m_DbThread(nullptr) + , m_ConnectTimeout(2000) + , m_DisconnectTimeout(10000) + , m_AliveTimeout(3000) + , m_TickTimeout(900) + , m_DoCleanup(false) + , m_LogThread(nullptr) + , m_InjectionThread(nullptr) + , m_currentHostAdressIndex(0) { - m_Socket->disconnectFromHost(); // Falls noch connected - m_Socket->disconnect(); // Alle Signals/Slots aufräumen - if (m_Socket->state() != QAbstractSocket::UnconnectedState) - m_Socket->waitForDisconnected(); - m_Socket->deleteLater(); // und weg damit } - m_Socket = new QTcpSocket(this); - qRegisterMetaType("QAbstractSocket::SocketError"); - qRegisterMetaType("QAbstractSocket::SocketState"); - connect(m_Socket, &QTcpSocket::connected, this, &PrtCnvSocketThread::connected, Qt::QueuedConnection); - connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvSocketThread::disconnected, Qt::QueuedConnection); - connect(m_Socket, &QAbstractSocket::errorOccurred, this, &PrtCnvSocketThread::error, Qt::QueuedConnection); - connect(m_Socket, &QTcpSocket::hostFound, this, &PrtCnvSocketThread::hostFound, Qt::QueuedConnection); - connect(m_Socket, &QTcpSocket::stateChanged, this, &PrtCnvSocketThread::stateChanged); - connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvSocketThread::readyRead, Qt::QueuedConnection); -} - -// --------------------------------------------------------------- -// Deallocates subcomponents. -// --------------------------------------------------------------- -int32_t PrtCnvSocketThread::destroy() -{ - PrtCnvThread::destroy(); - cleanup(); - return 0; -} - -void PrtCnvSocketThread::cleanup() -{ - delete m_Socket; m_Socket = nullptr; - delete m_ConnectionTimer; m_ConnectionTimer = nullptr; - delete m_TickTimer; m_TickTimer = nullptr; - -} - -// --------------------------------------------------------------- -// Initializes the variables. -// --------------------------------------------------------------- -int32_t PrtCnvSocketThread::init() -{ - INFO_LOG(m_logger) << "PrtCnvSocketThread::init()"; - PrtCnvThread::init(); - m_State = e_INITIAL; - - m_ConnectTimeout = m_Config->getInteger(getName(), QStringLiteral("ConnectTimeout"), 2000); - m_DisconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000); - m_AliveTimeout = m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000); - - return 0; -} - -// --------------------------------------------------------------- -// Connect as client to a TCP-server on ip-address configured -// as HostName and Port configured as Port -// --------------------------------------------------------------- -void PrtCnvSocketThread::connectSocket() -{ - int sockState = m_Socket ? m_Socket->state() : -1; - INFO_LOG(m_logger) << "connectSocket m_Socket=" << m_Socket << " state=" << m_State << " socketState=" << sockState; - if (e_WORKING != m_State && e_REGISTERING != m_State) + PrtCnvSocketThread::~PrtCnvSocketThread() { - if (m_Socket) - { - m_Socket->disconnectFromHost(); // Falls noch connected - if (m_Socket->state() != QAbstractSocket::UnconnectedState) - m_Socket->waitForDisconnected(); - } + cleanup(); + } + + // --------------------------------------------------------------- + // Creates all subcomponents and connects signals to slots + // --------------------------------------------------------------- + int32_t PrtCnvSocketThread::create(NGL::Settings *settings) + { + PrtCnvThread::create(settings); createNewSocket(); - if(m_hostAdresses.isEmpty()) - readHostAdresses(); - const QString hostname = m_hostAdresses.at(m_currentHostAdressIndex).first; - const uint16_t port = m_hostAdresses.at(m_currentHostAdressIndex).second; - m_currentHostAdressIndex = ((m_currentHostAdressIndex + 1) % m_hostAdresses.size()); - INFO_LOG(m_logger) << "Connecting to " << hostname << ":" << port << " m_Socket=" << m_Socket; - m_Socket->connectToHost(hostname, port); - m_State = e_CONNECTING; - startConnectionTimer(); + m_ConnectionTimer = new QTimer(this); + connect(m_ConnectionTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutAliveAndConnection); + + m_TickTimer = new QTimer(this); + connect(m_TickTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutTick); + + m_DbThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Db)); + m_LogThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Log)); + m_InjectionThread = qobject_cast(m_Parent->getOtherThread(PrtCnvApplication::e_Injection)); + + return 0; } - else + + // --------------------------------------------------------------- + // Creates a new socket to avoid getting old stuff from the + // former socket when reconnecting + // --------------------------------------------------------------- + void PrtCnvSocketThread::createNewSocket() { - WARNING_LOG(m_logger) << getName() << ": connectSocket called, but m_State is " << m_State; - } -} + INFO_LOG(m_logger) << "createNewSocket m_oldSocket=" << m_Socket; + Q_ASSERT(QThread::currentThreadId() == m_currentThreadId); -// --------------------------------------------------------------- -// Disconnects from TCP-server -// --------------------------------------------------------------- -void PrtCnvSocketThread::disconnectSocket() -{ - m_Socket->disconnectFromHost(); - startDisconnectionTimer(); - m_State = e_DISCONNECTING; -} - - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when we have connected to -// TCP-server -// --------------------------------------------------------------- -void PrtCnvSocketThread::connected() -{ - INFO_LOG(m_logger) << "connected (implement connected() in inherited class, if you want use this signal...)"; -} - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when we have disconnected -// to TCP-server -// --------------------------------------------------------------- -void PrtCnvSocketThread::disconnected() -{ - INFO_LOG(m_logger) << "got signal 'disconnected' (implement disconnected() in inherited class, if you want use this signal...)"; -} - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when we have have read -// data over socket -// --------------------------------------------------------------- -void PrtCnvSocketThread::readyRead() -{ - INFO_LOG(m_logger) << "got signal 'newData' (implement newData() in inherited class, if you want use this signal...)"; -} - - -// --------------------------------------------------------------- -// this slot is used for connection, disconnection and alive -// timeouts -// --------------------------------------------------------------- -void PrtCnvSocketThread::timeoutAliveAndConnection() -{ - INFO_LOG(m_logger) << "got signal 'reconnectTimeout' (implement reconnectTimeout() in inherited class, if you want use this signal...)"; -} - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when we have a socket-error -// --------------------------------------------------------------- -void PrtCnvSocketThread::error(QAbstractSocket::SocketError a_socketError) -{ - switch (a_socketError) - { - case QAbstractSocket::ConnectionRefusedError: - ERROR_LOG(m_logger) << getName() << ": ConnectionRefusedError m_State=" << m_State; - break; - case QAbstractSocket::RemoteHostClosedError: - ERROR_LOG(m_logger) << getName() << ": RemoteHostClosedError"; - break; - case QAbstractSocket::HostNotFoundError: - //ERROR_LOG(m_logger) << getName() << ": HostNotFoundError"; - break; - default: - ERROR_LOG(m_logger) << getName() << ": got signal 'error(QAbstractSocket::SocketError=" << a_socketError << ")'"; - } -} - - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when the host was found -// --------------------------------------------------------------- -void PrtCnvSocketThread::hostFound() -{ -// INFO_LOG(m_logger) << "got signal 'hostFound' (implement hostFound() in inherited class, if you want use this signal...)"; -} - -// --------------------------------------------------------------- -// Will be called from Qt-Framework when socket-state has -// changed -// --------------------------------------------------------------- -void PrtCnvSocketThread::stateChanged(QAbstractSocket::SocketState a_socketState) -{ - Q_UNUSED(a_socketState); -// INFO_LOG(m_logger) << "got signal 'stateChanged(" << ao_socketState << ")' (implement stateChanged() in inherited class, if you want use this signal...)"; -} - - -// --------------------------------------------------------------- -// calls storeRadioTelegram of DbThread, see there -// --------------------------------------------------------------- -void PrtCnvSocketThread::storeRadioTelegram(const std::shared_ptr &a_telegram, - const uint32_t a_readCounter) -{ - m_DbThread->storeRadioTelegram(a_telegram, a_readCounter); -} - - -// --------------------------------------------------------------- -// used to check whether the other side is still alive -// --------------------------------------------------------------- -void PrtCnvSocketThread::startAliveTimer() -{ - m_ConnectionTimer->setInterval(m_AliveTimeout); - m_ConnectionTimer->start(); -} - - -// --------------------------------------------------------------- -// used to retry connection -// --------------------------------------------------------------- -void PrtCnvSocketThread::startConnectionTimer() -{ - m_ConnectionTimer->setInterval(m_ConnectTimeout); - m_ConnectionTimer->start(); -} - - -// --------------------------------------------------------------- -// used to abort connection, when normal disconnection is not -// successful -// --------------------------------------------------------------- -void PrtCnvSocketThread::startDisconnectionTimer() -{ - m_ConnectionTimer->setInterval(m_DisconnectTimeout); - m_ConnectionTimer->start(); -} - - -// --------------------------------------------------------------- -// used for periodically ticks (i.e. for acks or sending -// nachforderungen) -// --------------------------------------------------------------- -void PrtCnvSocketThread::startTickTimer() -{ -// INFO_LOG(m_logger) << "start timer"; - m_TickTimer->setInterval(m_TickTimeout); - m_TickTimer->start(); -} - - -// --------------------------------------------------------------- -// The counter will be set to a_startCounter if a_maxCounter -// is reached -// returns true if receive-counter is ok -// returns false if a telegram is repeated or lost -// --------------------------------------------------------------- -bool PrtCnvSocketThread::checkAndUpdateReceiveCounter(const uint32_t a_counter, const uint32_t a_maxCounter, const uint32_t a_startCounter) -{ - TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter; - // check for wrap - if (a_maxCounter == ++m_ReceiveCounter) - { - m_ReceiveCounter = a_startCounter; - } - // has the counter the expected value? - if (m_ReceiveCounter != a_counter) - { - //if (m_ReceiveCounter != 1) + if (m_Socket) { - if (m_ReceiveCounter > a_counter) - { - ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from " - << getName() << "! Expected: " << m_ReceiveCounter; - } - else - { - ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName() - << ": receive-counter of received telegram: " << a_counter << "; Expected: " << m_ReceiveCounter; - } + m_Socket->disconnectFromHost(); // Falls noch connected + m_Socket->disconnect(); // Alle Signals/Slots aufräumen + if (m_Socket->state() != QAbstractSocket::UnconnectedState) + m_Socket->waitForDisconnected(); + m_Socket->deleteLater(); // und weg damit } + + m_Socket = new QTcpSocket(this); + qRegisterMetaType("QAbstractSocket::SocketError"); + qRegisterMetaType("QAbstractSocket::SocketState"); + + connect(m_Socket, &QTcpSocket::connected, this, &PrtCnvSocketThread::connected, Qt::QueuedConnection); + connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvSocketThread::disconnected, Qt::QueuedConnection); + connect(m_Socket, &QAbstractSocket::errorOccurred, this, &PrtCnvSocketThread::error, Qt::QueuedConnection); + connect(m_Socket, &QTcpSocket::hostFound, this, &PrtCnvSocketThread::hostFound, Qt::QueuedConnection); + connect(m_Socket, &QTcpSocket::stateChanged, this, &PrtCnvSocketThread::stateChanged); + connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvSocketThread::readyRead, Qt::QueuedConnection); + } + + // --------------------------------------------------------------- + // Deallocates subcomponents. + // --------------------------------------------------------------- + int32_t PrtCnvSocketThread::destroy() + { + PrtCnvThread::destroy(); + cleanup(); + return 0; + } + + void PrtCnvSocketThread::cleanup() + { + delete m_Socket; + m_Socket = nullptr; + delete m_ConnectionTimer; + m_ConnectionTimer = nullptr; + delete m_TickTimer; + m_TickTimer = nullptr; + } + + // --------------------------------------------------------------- + // Initializes the variables. + // --------------------------------------------------------------- + int32_t PrtCnvSocketThread::init() + { + INFO_LOG(m_logger) << "PrtCnvSocketThread::init()"; + PrtCnvThread::init(); + m_State = e_INITIAL; + + m_ConnectTimeout = m_Config->getInteger(getName(), QStringLiteral("ConnectTimeout"), 2000); + m_DisconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000); + m_AliveTimeout = m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000); + + return 0; + } + + // --------------------------------------------------------------- + // Connect as client to a TCP-server on ip-address configured + // as HostName and Port configured as Port + // --------------------------------------------------------------- + void PrtCnvSocketThread::connectSocket() + { + int sockState = m_Socket ? m_Socket->state() : -1; + INFO_LOG(m_logger) << "connectSocket m_Socket=" << m_Socket << " state=" << m_State << " socketState=" << sockState; + if (e_WORKING != m_State && e_REGISTERING != m_State) + { + if (m_Socket) + { + m_Socket->disconnectFromHost(); // Falls noch connected + if (m_Socket->state() != QAbstractSocket::UnconnectedState) + m_Socket->waitForDisconnected(); + } + + createNewSocket(); + + if (m_hostAdresses.isEmpty()) + readHostAdresses(); + const QString hostname = m_hostAdresses.at(m_currentHostAdressIndex).first; + const uint16_t port = m_hostAdresses.at(m_currentHostAdressIndex).second; + m_currentHostAdressIndex = ((m_currentHostAdressIndex + 1) % m_hostAdresses.size()); + INFO_LOG(m_logger) << "Connecting to " << hostname << ":" << port << " m_Socket=" << m_Socket; + m_Socket->connectToHost(hostname, port); + m_State = e_CONNECTING; + startConnectionTimer(); + } + else + { + WARNING_LOG(m_logger) << getName() << ": connectSocket called, but m_State is " << m_State; + } + } + + // --------------------------------------------------------------- + // Disconnects from TCP-server + // --------------------------------------------------------------- + void PrtCnvSocketThread::disconnectSocket() + { + m_Socket->disconnectFromHost(); + startDisconnectionTimer(); + m_State = e_DISCONNECTING; + } + + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when we have connected to + // TCP-server + // --------------------------------------------------------------- + void PrtCnvSocketThread::connected() + { + INFO_LOG(m_logger) << "connected (implement connected() in inherited class, if you want use this signal...)"; + } + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when we have disconnected + // to TCP-server + // --------------------------------------------------------------- + void PrtCnvSocketThread::disconnected() + { + INFO_LOG(m_logger) << "got signal 'disconnected' (implement disconnected() in inherited class, if you want use this signal...)"; + } + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when we have have read + // data over socket + // --------------------------------------------------------------- + void PrtCnvSocketThread::readyRead() + { + INFO_LOG(m_logger) << "got signal 'newData' (implement newData() in inherited class, if you want use this signal...)"; + } + + + // --------------------------------------------------------------- + // this slot is used for connection, disconnection and alive + // timeouts + // --------------------------------------------------------------- + void PrtCnvSocketThread::timeoutAliveAndConnection() + { + INFO_LOG(m_logger) << "got signal 'reconnectTimeout' (implement reconnectTimeout() in inherited class, if you want use this signal...)"; + } + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when we have a socket-error + // --------------------------------------------------------------- + void PrtCnvSocketThread::error(QAbstractSocket::SocketError a_socketError) + { + switch (a_socketError) + { + case QAbstractSocket::ConnectionRefusedError: + ERROR_LOG(m_logger) << getName() << ": ConnectionRefusedError m_State=" << m_State; + break; + case QAbstractSocket::RemoteHostClosedError: + ERROR_LOG(m_logger) << getName() << ": RemoteHostClosedError"; + break; + case QAbstractSocket::HostNotFoundError: + //ERROR_LOG(m_logger) << getName() << ": HostNotFoundError"; + break; + default: + ERROR_LOG(m_logger) << getName() << ": got signal 'error(QAbstractSocket::SocketError=" << a_socketError << ")'"; + } + } + + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when the host was found + // --------------------------------------------------------------- + void PrtCnvSocketThread::hostFound() + { + // INFO_LOG(m_logger) << "got signal 'hostFound' (implement hostFound() in inherited class, if you want use this signal...)"; + } + + // --------------------------------------------------------------- + // Will be called from Qt-Framework when socket-state has + // changed + // --------------------------------------------------------------- + void PrtCnvSocketThread::stateChanged(QAbstractSocket::SocketState a_socketState) + { + Q_UNUSED(a_socketState); + // INFO_LOG(m_logger) << "got signal 'stateChanged(" << ao_socketState << ")' (implement stateChanged() in inherited class, if you want use this signal...)"; + } + + + // --------------------------------------------------------------- + // calls storeRadioTelegram of DbThread, see there + // --------------------------------------------------------------- + void PrtCnvSocketThread::storeRadioTelegram(const std::shared_ptr &a_telegram, const uint32_t a_readCounter) + { + m_DbThread->storeRadioTelegram(a_telegram, a_readCounter); + } + + + // --------------------------------------------------------------- + // used to check whether the other side is still alive + // --------------------------------------------------------------- + void PrtCnvSocketThread::startAliveTimer() + { + m_ConnectionTimer->setInterval(m_AliveTimeout); + m_ConnectionTimer->start(); + } + + + // --------------------------------------------------------------- + // used to retry connection + // --------------------------------------------------------------- + void PrtCnvSocketThread::startConnectionTimer() + { + m_ConnectionTimer->setInterval(m_ConnectTimeout); + m_ConnectionTimer->start(); + } + + + // --------------------------------------------------------------- + // used to abort connection, when normal disconnection is not + // successful + // --------------------------------------------------------------- + void PrtCnvSocketThread::startDisconnectionTimer() + { + m_ConnectionTimer->setInterval(m_DisconnectTimeout); + m_ConnectionTimer->start(); + } + + + // --------------------------------------------------------------- + // used for periodically ticks (i.e. for acks or sending + // nachforderungen) + // --------------------------------------------------------------- + void PrtCnvSocketThread::startTickTimer() + { + // INFO_LOG(m_logger) << "start timer"; + m_TickTimer->setInterval(m_TickTimeout); + m_TickTimer->start(); + } + + + // --------------------------------------------------------------- + // The counter will be set to a_startCounter if a_maxCounter + // is reached + // returns true if receive-counter is ok + // returns false if a telegram is repeated or lost + // --------------------------------------------------------------- + bool PrtCnvSocketThread::checkAndUpdateReceiveCounter(const uint32_t a_counter, const uint32_t a_maxCounter, const uint32_t a_startCounter) + { + TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter; + // check for wrap + if (a_maxCounter == ++m_ReceiveCounter) + { + m_ReceiveCounter = a_startCounter; + } + // has the counter the expected value? + if (m_ReceiveCounter != a_counter) + { + //if (m_ReceiveCounter != 1) + { + if (m_ReceiveCounter > a_counter) + { + ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from " << getName() << "! Expected: " << m_ReceiveCounter; + } + else + { + ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName() << ": receive-counter of received telegram: " << a_counter + << "; Expected: " << m_ReceiveCounter; + } + } #if 0 m_ReceiveCounter--; return false; // failure #else - m_ReceiveCounter = a_counter; - return true; + m_ReceiveCounter = a_counter; + return true; #endif + } + return true; // all ok } - return true; // all ok -} -void PrtCnvSocketThread::readHostAdresses() -{ - QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("127.0.0.1")); - uint16_t port = m_Config->getInteger(getName(), QStringLiteral("Port"), 4934); - m_hostAdresses.push_back(qMakePair(host, port)); - for (int i = 1; i < 10; ++i) { - const QString hostName = QLatin1String("HostName") + QString::number(i); - const QString portName = QLatin1String("Port") + QString::number(i); - host = m_Config->getString(getName(), hostName, QString()); - port = m_Config->getInteger(getName(), portName, 0); - if (host.isEmpty() || port == 0) - continue; + void PrtCnvSocketThread::readHostAdresses() + { + QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("127.0.0.1")); + uint16_t port = m_Config->getInteger(getName(), QStringLiteral("Port"), 4934); m_hostAdresses.push_back(qMakePair(host, port)); + for (int i = 1; i < 10; ++i) + { + const QString hostName = QLatin1String("HostName") + QString::number(i); + const QString portName = QLatin1String("Port") + QString::number(i); + host = m_Config->getString(getName(), hostName, QString()); + port = m_Config->getInteger(getName(), portName, 0); + if (host.isEmpty() || port == 0) + continue; + m_hostAdresses.push_back(qMakePair(host, port)); + } + for (const auto &p : std::as_const(m_hostAdresses)) + { + INFO_LOG(m_logger) << "Read Host Adress " << p.first << ":" << p.second << " from settings"; + } } - for (const auto &p : std::as_const(m_hostAdresses)) { - INFO_LOG(m_logger) << "Read Host Adress " << p.first - << ":" << p.second - << " from settings"; - } -} -} // namespace PrtCnv +} // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.hpp index cbf2efa33..f0538d060 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvSocketThread.hpp @@ -49,7 +49,6 @@ namespace PrtCnv { Q_OBJECT public: - /** * The different states for the state-event-machine * @@ -71,7 +70,7 @@ namespace PrtCnv * * @param a_parent */ - PrtCnvSocketThread(PrtCnvThreadStarter* a_parent, const char *loggerName); + PrtCnvSocketThread(PrtCnvThreadStarter *a_parent, const char *loggerName); ~PrtCnvSocketThread(); /** * Creates all subcomponents and connects signals to slots @@ -199,7 +198,7 @@ namespace PrtCnv /** * A vector with hostname - port pairs to connect to */ - QVector > m_hostAdresses; + QVector> m_hostAdresses; /** * The current index to connect to in m_hostAdresses diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredCentralTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredCentralTelegram.hpp index a60f62150..86def9f1a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredCentralTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredCentralTelegram.hpp @@ -13,39 +13,40 @@ namespace PrtCnv { -class PrtCnvStoredCentralTelegram : public PrtCnv::PrtCnvStoredTelegram -{ -public: - PrtCnvStoredCentralTelegram(const std::shared_ptr &a_centralTelegram, - const std::shared_ptr &a_radioTelegram) - : PrtCnvStoredTelegram(a_radioTelegram) - , m_CentralTelegram(a_centralTelegram) - {} + class PrtCnvStoredCentralTelegram : public PrtCnv::PrtCnvStoredTelegram + { + public: + PrtCnvStoredCentralTelegram(const std::shared_ptr &a_centralTelegram, + const std::shared_ptr &a_radioTelegram) + : PrtCnvStoredTelegram(a_radioTelegram) + , m_CentralTelegram(a_centralTelegram) + { + } - int writeCounter() const { return m_WriteCounter; } + int writeCounter() const { return m_WriteCounter; } - /** + /** * Assigned central-telegram. */ - std::shared_ptr m_CentralTelegram; - /** + std::shared_ptr m_CentralTelegram; + /** * The number of unsuccessful attempts to send the telegram to central */ - uint32_t m_Attempts = 0; - /** + uint32_t m_Attempts = 0; + /** * The counter while sending this telegram to central */ - int m_WriteCounter = 0; - /** + int m_WriteCounter = 0; + /** * True if the telegram must be resent. */ - bool m_DoResend = false; - /** + bool m_DoResend = false; + /** * True if the telegram must be deleted. * Use this boolean only if you want delete a telegram as an exception (i.e. * corrupt telegram, which cannot be sent) */ - bool m_DoDelete = false; -}; + bool m_DoDelete = false; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredRadioTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredRadioTelegram.hpp index 484f4ce3c..12cd87685 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredRadioTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredRadioTelegram.hpp @@ -12,32 +12,32 @@ namespace PrtCnv { -class PrtCnvStoredRadioTelegram : public PrtCnv::PrtCnvStoredTelegram -{ -public: - using PrtCnv::PrtCnvStoredTelegram::PrtCnvStoredTelegram; + class PrtCnvStoredRadioTelegram : public PrtCnv::PrtCnvStoredTelegram + { + public: + using PrtCnv::PrtCnvStoredTelegram::PrtCnvStoredTelegram; - /** + /** * The counter while reading this telegram from central */ - int32_t m_ReadCounter = 0; - /** + int32_t m_ReadCounter = 0; + /** * The broadcast index if it is a broadcast-telegram and it was sent first time, * otherwise 0. */ - uint16_t m_BroadcastIndex = 0; - /** + uint16_t m_BroadcastIndex = 0; + /** * The frame-counter while sending this telegram to radio. */ - uint8_t m_WriteCounter = 0; - /** + uint8_t m_WriteCounter = 0; + /** * True if telegram must be deleted. */ - bool m_DoDelete = false; - /** + bool m_DoDelete = false; + /** * True if telegram was sent. */ - bool m_IsSent = false; -}; + bool m_IsSent = false; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredTelegram.hpp index 560689b8f..18d5d1555 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvStoredTelegram.hpp @@ -13,16 +13,17 @@ namespace PrtCnv { -class PrtCnvStoredTelegram -{ -public: - explicit PrtCnvStoredTelegram(const std::shared_ptr &a_telegram) - : m_RadioTelegram(a_telegram) - {} + class PrtCnvStoredTelegram + { + public: + explicit PrtCnvStoredTelegram(const std::shared_ptr &a_telegram) + : m_RadioTelegram(a_telegram) + { + } - std::shared_ptr m_RadioTelegram; - int64_t m_Id = 0; - bool m_WriteCounterChanged = false; -}; + std::shared_ptr m_RadioTelegram; + int64_t m_Id = 0; + bool m_WriteCounterChanged = false; + }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.cpp index e12cb41b9..8764ac637 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.cpp @@ -27,7 +27,8 @@ static int gettimeofday(struct timeval *__p, void *__t) { - union { + union + { unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */ FILETIME ft; } now; @@ -48,135 +49,126 @@ static int gettimeofday(struct timeval *__p, void *__t) namespace PrtCnv { -// --------------------------------------------------------------- -PrtCnvTelegramLogThread::PrtCnvTelegramLogThread(PrtCnvThreadStarter* a_parent) - : PrtCnvThread(a_parent, "PrtCnvTelegramLogThread") - , m_DoLogCentralTelegram(true) - , m_DoLogWlsTelegram(true) - , m_DoLogRadioTelegram(true) -{ - m_Name = QStringLiteral("TelegramLog"); -} + // --------------------------------------------------------------- + PrtCnvTelegramLogThread::PrtCnvTelegramLogThread(PrtCnvThreadStarter *a_parent) + : PrtCnvThread(a_parent, "PrtCnvTelegramLogThread") + , m_DoLogCentralTelegram(true) + , m_DoLogWlsTelegram(true) + , m_DoLogRadioTelegram(true) + { + m_Name = QStringLiteral("TelegramLog"); + } -// --------------------------------------------------------------- -int32_t PrtCnvTelegramLogThread::create(NGL::Settings *settings) -{ - PrtCnvThread::create(settings); + // --------------------------------------------------------------- + int32_t PrtCnvTelegramLogThread::create(NGL::Settings *settings) + { + PrtCnvThread::create(settings); - connect(this, &PrtCnvTelegramLogThread::telegramLogReceived, - this, &PrtCnvTelegramLogThread::writeTelegramLog, - Qt::QueuedConnection); + connect(this, &PrtCnvTelegramLogThread::telegramLogReceived, this, &PrtCnvTelegramLogThread::writeTelegramLog, Qt::QueuedConnection); - return 0; -} + return 0; + } -// --------------------------------------------------------------- -int32_t PrtCnvTelegramLogThread::init() -{ - PrtCnvThread::init(); - m_DoLogCentralTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogCentralTelegrams"), true); - m_DoLogWlsTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogWlsTelegrams"), true); - m_DoLogRadioTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogRadioTelegrams"), true); - QString path = m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPath"), QStringLiteral(".")); - if (!QDir::isAbsolutePath(path)) - path = QCoreApplication::applicationDirPath() + QStringLiteral("/../") + path; + // --------------------------------------------------------------- + int32_t PrtCnvTelegramLogThread::init() + { + PrtCnvThread::init(); + m_DoLogCentralTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogCentralTelegrams"), true); + m_DoLogWlsTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogWlsTelegrams"), true); + m_DoLogRadioTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogRadioTelegrams"), true); + QString path = m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPath"), QStringLiteral(".")); + if (!QDir::isAbsolutePath(path)) + path = QCoreApplication::applicationDirPath() + QStringLiteral("/../") + path; - m_LogTelegramPathWithPrefix = path + QLatin1Char('/') + m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPrefix"), QStringLiteral("PrtCnv_")); - if (!m_LogTelegramPathWithPrefix.endsWith(QLatin1Char('_'))) - m_LogTelegramPathWithPrefix += QLatin1Char('_'); + m_LogTelegramPathWithPrefix = path + QLatin1Char('/') + m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPrefix"), QStringLiteral("PrtCnv_")); + if (!m_LogTelegramPathWithPrefix.endsWith(QLatin1Char('_'))) + m_LogTelegramPathWithPrefix += QLatin1Char('_'); - // create the telegram-log-path when it not yet exists - QFileInfo fileInfo(m_LogTelegramPathWithPrefix); - QDir dir; - dir.mkpath(fileInfo.absolutePath()); + // create the telegram-log-path when it not yet exists + QFileInfo fileInfo(m_LogTelegramPathWithPrefix); + QDir dir; + dir.mkpath(fileInfo.absolutePath()); - INFO_LOG(m_logger); + INFO_LOG(m_logger); - return 0; -} + return 0; + } -static inline int setSend(int protocol, bool bIsSend) -{ - return (protocol | (bIsSend ? N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend : N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive)); -} + static inline int setSend(int protocol, bool bIsSend) + { + return (protocol | (bIsSend ? N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend : N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive)); + } -// --------------------------------------------------------------- -// Writes a received or sent central-telegram into log-file -// --------------------------------------------------------------- -void PrtCnvTelegramLogThread::writeCentralTelegramLog(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_centralTelegram, bool a_isSend, int a_priority) -{ - if (!m_DoLogCentralTelegram) - return; + // --------------------------------------------------------------- + // Writes a received or sent central-telegram into log-file + // --------------------------------------------------------------- + void PrtCnvTelegramLogThread::writeCentralTelegramLog(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_centralTelegram, bool a_isSend, int a_priority) + { + if (!m_DoLogCentralTelegram) + return; - emit telegramLogReceived(a_centralTelegram->data(), - setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, a_isSend), - a_priority); -} + emit telegramLogReceived(a_centralTelegram->data(), setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, a_isSend), a_priority); + } -// --------------------------------------------------------------- -// Writes a received or sent wls-telegram into log-file -// --------------------------------------------------------------- -void PrtCnvTelegramLogThread::writeWlsTelegramLog(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool a_isSend, int a_priority) -{ - if (!m_DoLogWlsTelegram) - return; + // --------------------------------------------------------------- + // Writes a received or sent wls-telegram into log-file + // --------------------------------------------------------------- + void PrtCnvTelegramLogThread::writeWlsTelegramLog(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool a_isSend, int a_priority) + { + if (!m_DoLogWlsTelegram) + return; - N_CoPrtCnv::CoPrtCnvCentralTelegram central(*tele); - emit telegramLogReceived(central.data(), - setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls, a_isSend), - a_priority); -} + N_CoPrtCnv::CoPrtCnvCentralTelegram central(*tele); + emit telegramLogReceived(central.data(), setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls, a_isSend), a_priority); + } -// --------------------------------------------------------------- -// Writes a received or sent radio-telegram into log-file -// --------------------------------------------------------------- -void PrtCnvTelegramLogThread::writeRadioTelegramLog(const QByteArray &tele, bool a_isSend, int a_priority) -{ - if (!m_DoLogRadioTelegram) - return; + // --------------------------------------------------------------- + // Writes a received or sent radio-telegram into log-file + // --------------------------------------------------------------- + void PrtCnvTelegramLogThread::writeRadioTelegramLog(const QByteArray &tele, bool a_isSend, int a_priority) + { + if (!m_DoLogRadioTelegram) + return; - emit telegramLogReceived(tele, - setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra, a_isSend), - a_priority); -} + emit telegramLogReceived(tele, setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra, a_isSend), a_priority); + } -// --------------------------------------------------------------- -// Writes the telegram to the file -// --------------------------------------------------------------- -void PrtCnvTelegramLogThread::writeTelegramLog(const QByteArray &a_data, int a_protocolType, int a_priority) -{ - // get time with microseconds - timeval tv; - gettimeofday(&tv, nullptr); - uint64_t exactTime = tv.tv_sec; - exactTime = exactTime << 32; - exactTime += tv.tv_usec; + // --------------------------------------------------------------- + // Writes the telegram to the file + // --------------------------------------------------------------- + void PrtCnvTelegramLogThread::writeTelegramLog(const QByteArray &a_data, int a_protocolType, int a_priority) + { + // get time with microseconds + timeval tv; + gettimeofday(&tv, nullptr); + uint64_t exactTime = tv.tv_sec; + exactTime = exactTime << 32; + exactTime += tv.tv_usec; - // generate the filename of the telegram-file: "PrefixYYMMDD_HH.krlog" - QString fileName = QStringLiteral("%1%2.krlog") - .arg(m_LogTelegramPathWithPrefix, QDateTime::fromSecsSinceEpoch(tv.tv_sec).toString(QStringLiteral("yyMMdd_hh"))); + // generate the filename of the telegram-file: "PrefixYYMMDD_HH.krlog" + QString fileName = QStringLiteral("%1%2.krlog").arg(m_LogTelegramPathWithPrefix, QDateTime::fromSecsSinceEpoch(tv.tv_sec).toString(QStringLiteral("yyMMdd_hh"))); - // open the log-file - QFile telegramFile(fileName); - (void)telegramFile.open(QIODevice::WriteOnly | QIODevice::Append); + // open the log-file + QFile telegramFile(fileName); + (void)telegramFile.open(QIODevice::WriteOnly | QIODevice::Append); - // write header - N_CoPrtCnv::CoPrtCnvLogHeader lh; - lh.m_Length = a_data.size() + sizeof(N_CoPrtCnv::CoPrtCnvLogHeader); - lh.m_Version = 3; - lh.m_Priority = a_priority; - lh.m_Protocol = a_protocolType; - lh.m_Time = exactTime; - lh.m_Reserved = 0; - telegramFile.write(reinterpret_cast(&lh), sizeof(N_CoPrtCnv::CoPrtCnvLogHeader)); + // write header + N_CoPrtCnv::CoPrtCnvLogHeader lh; + lh.m_Length = a_data.size() + sizeof(N_CoPrtCnv::CoPrtCnvLogHeader); + lh.m_Version = 3; + lh.m_Priority = a_priority; + lh.m_Protocol = a_protocolType; + lh.m_Time = exactTime; + lh.m_Reserved = 0; + telegramFile.write(reinterpret_cast(&lh), sizeof(N_CoPrtCnv::CoPrtCnvLogHeader)); - // write telegram-data - telegramFile.write(a_data); - telegramFile.close(); -} + // write telegram-data + telegramFile.write(a_data); + telegramFile.close(); + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.hpp index c4d09fb3b..2f180d79a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvTelegramLogThread.hpp @@ -10,27 +10,27 @@ // $LastChangedRevision$ // // ************************************************************************** - + #pragma once #include "PrtCnvThread.hpp" namespace N_CoPrtCnv { -class CoPrtCnvCentralTelegram; + class CoPrtCnvCentralTelegram; } namespace TrainingAreaBase { -namespace TetraIcd -{ -struct TrainingAreaTelegram; -} + namespace TetraIcd + { + struct TrainingAreaTelegram; + } } namespace PrtCnv { - /** + /** * This thread is used to log telegrams in a log-file. This action is separated * from central/radio-thead because of 2 reasons: * @@ -49,7 +49,7 @@ namespace PrtCnv * * @param a_parent */ - explicit PrtCnvTelegramLogThread(PrtCnvThreadStarter* a_parent); + explicit PrtCnvTelegramLogThread(PrtCnvThreadStarter *a_parent); int32_t create(NGL::Settings *settings) override; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.cpp index 184b4a49a..07ba01a7d 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.cpp @@ -18,57 +18,57 @@ namespace PrtCnv { -bool PrtCnvThread::m_DoCleanDb = false; + bool PrtCnvThread::m_DoCleanDb = false; -// --------------------------------------------------------------- -// Constructor with thread-starter as parameter -// --------------------------------------------------------------- -PrtCnvThread::PrtCnvThread(PrtCnv::PrtCnvThreadStarter* a_parent, const char *loggerName) - : m_Parent(a_parent) - , m_currentThreadId(nullptr) - , m_logger(getLogger(loggerName)) -{} + // --------------------------------------------------------------- + // Constructor with thread-starter as parameter + // --------------------------------------------------------------- + PrtCnvThread::PrtCnvThread(PrtCnv::PrtCnvThreadStarter *a_parent, const char *loggerName) + : m_Parent(a_parent) + , m_currentThreadId(nullptr) + , m_logger(getLogger(loggerName)) + { + } -int32_t PrtCnvThread::create(NGL::Settings *settings) -{ - m_currentThreadId = QThread::currentThreadId(); - m_Config = settings; + int32_t PrtCnvThread::create(NGL::Settings *settings) + { + m_currentThreadId = QThread::currentThreadId(); + m_Config = settings; - INFO_LOG(m_logger) << "create " << m_Name - << " - current thread id is " << m_currentThreadId; - return 0; -} + INFO_LOG(m_logger) << "create " << m_Name << " - current thread id is " << m_currentThreadId; + return 0; + } -int32_t PrtCnvThread::init() -{ - INFO_LOG(m_logger) << "init " << m_Name; - return 0; -} + int32_t PrtCnvThread::init() + { + INFO_LOG(m_logger) << "init " << m_Name; + return 0; + } -int32_t PrtCnvThread::start() -{ - INFO_LOG(m_logger) << "start " << m_Name; - return 0; -} + int32_t PrtCnvThread::start() + { + INFO_LOG(m_logger) << "start " << m_Name; + return 0; + } -int32_t PrtCnvThread::stop() -{ - return 0; -} + int32_t PrtCnvThread::stop() + { + return 0; + } -int32_t PrtCnvThread::deinit() -{ - return 0; -} + int32_t PrtCnvThread::deinit() + { + return 0; + } -int32_t PrtCnvThread::destroy() -{ - return 0; -} + int32_t PrtCnvThread::destroy() + { + return 0; + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.hpp index 1f223f86a..8f583cc2c 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThread.hpp @@ -21,7 +21,7 @@ namespace PrtCnv { class PrtCnvThreadStarter; - /** + /** * The father-class of all threads in protocol-converter. It implements access to * config-system and knows whether we have a restart after crash or a normal start * (from scratch). @@ -29,14 +29,16 @@ namespace PrtCnv * @version 1.0 * @updated 21-Jan-2010 08:38:23 */ - class PrtCnvThread : public QObject, public N_AppComponent::IAppComponent + class PrtCnvThread + : public QObject + , public N_AppComponent::IAppComponent { Q_OBJECT -protected: + protected: /** * Used to get configuration-parameter */ - NGL::Settings* m_Config; + NGL::Settings *m_Config; /** * Pointer to ThreadStarter */ @@ -47,6 +49,7 @@ protected: Qt::HANDLE m_currentThreadId; NGL::INGLLogger &m_logger; + public: /** * Indicates what happens with the DB while startup. True => it will be cleant; @@ -59,7 +62,7 @@ protected: * * @param a_parent */ - PrtCnvThread(PrtCnvThreadStarter* a_parent, const char *loggerName); + PrtCnvThread(PrtCnvThreadStarter *a_parent, const char *loggerName); int32_t create(NGL::Settings *settings) override; @@ -68,7 +71,7 @@ protected: int32_t init() override; - int32_t start() override; + int32_t start() override; int32_t stop() override; @@ -78,7 +81,6 @@ protected: int32_t destroy() override; - }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.cpp index b1cabe9da..35038599a 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.cpp @@ -1,14 +1,14 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // Implementation of the Class PrtCnvThreadStarter // ************************************************************************** #include "PrtCnvThreadStarter.hpp" @@ -23,103 +23,101 @@ namespace PrtCnv { -// --------------------------------------------------------------- -// Constructor with id and ptr to main-app as parameters. -// --------------------------------------------------------------- -PrtCnvThreadStarter::PrtCnvThreadStarter(const PrtCnv::PrtCnvApplication::E_ThreadId a_id, - const QString &configFileName, - PrtCnv::PrtCnvApplication* a_mainApp) - : m_Thread(nullptr) - , m_Application(a_mainApp) - , m_Id(a_id) - , m_settings(new NGL::Settings(configFileName)) - , m_logger(getLogger("PrtCnvThreadStarter")) -{ - DEBUG_LOG(m_logger) << "Using Config file '" << configFileName << "'"; -} - - -PrtCnvThreadStarter::~PrtCnvThreadStarter() -{ - delete m_settings; -} - - -// --------------------------------------------------------------- -// The run()-function, which will be called by Qt-Framework, -// when starting the thread. -// --------------------------------------------------------------- -void PrtCnvThreadStarter::run() -{ - INFO_LOG(m_logger) << "Entering event loop for thread " << this << ", id: " << m_Id; - // allocate the thread - switch (m_Id) + // --------------------------------------------------------------- + // Constructor with id and ptr to main-app as parameters. + // --------------------------------------------------------------- + PrtCnvThreadStarter::PrtCnvThreadStarter(const PrtCnv::PrtCnvApplication::E_ThreadId a_id, const QString &configFileName, PrtCnv::PrtCnvApplication *a_mainApp) + : m_Thread(nullptr) + , m_Application(a_mainApp) + , m_Id(a_id) + , m_settings(new NGL::Settings(configFileName)) + , m_logger(getLogger("PrtCnvThreadStarter")) { - case PrtCnvApplication::e_Central: - m_Thread = new PrtCnvCentralThread(this); - break; - - case PrtCnvApplication::e_Radio: - m_Thread = new PrtCnvRadioThread(m_Application->exerciseId(), this); - break; - - case PrtCnvApplication::e_Db: - m_Thread = new PrtCnvDbThread(m_Application->databaseDriver(), - m_Application->databaseHostName(), - m_Application->databaseName(), - m_Application->databaseSchemaName(), - m_Application->databaseUserName(), - m_Application->databasePassword(), - this); - break; - - case PrtCnvApplication::e_Log: - m_Thread = new PrtCnvTelegramLogThread(this); - break; - - case PrtCnvApplication::e_Injection: - m_Thread = new PrtCnvInjectionThread(this); - break; - - case PrtCnvApplication::e_RadioTraffic: - m_Thread = new PrtCnvRadioTrafficThread(this); - break; - - case PrtCnvApplication::e_ThreadIdMax: - break; + DEBUG_LOG(m_logger) << "Using Config file '" << configFileName << "'"; } - if (!m_Thread) + + PrtCnvThreadStarter::~PrtCnvThreadStarter() { - ERROR_LOG(m_logger) << "Unknown threadId: " << m_Id; - return; + delete m_settings; } - while (!m_Application) - sleep(1); - m_Application->waitForCreate(m_Id); - m_Thread->create(m_settings); - m_Application->waitForInit(m_Id); - m_Thread->init(); - m_Application->waitForStart(m_Id); - m_Thread->start(); - m_Application->waitForExec(m_Id); + // --------------------------------------------------------------- + // The run()-function, which will be called by Qt-Framework, + // when starting the thread. + // --------------------------------------------------------------- + void PrtCnvThreadStarter::run() + { + INFO_LOG(m_logger) << "Entering event loop for thread " << this << ", id: " << m_Id; + // allocate the thread + switch (m_Id) + { + case PrtCnvApplication::e_Central: + m_Thread = new PrtCnvCentralThread(this); + break; - exec(); + case PrtCnvApplication::e_Radio: + m_Thread = new PrtCnvRadioThread(m_Application->exerciseId(), this); + break; - INFO_LOG(m_logger) << "Leaving event loop for thread " << this << ", id: " << m_Id; - delete m_Thread; - m_Thread = nullptr; -} + case PrtCnvApplication::e_Db: + m_Thread = new PrtCnvDbThread(m_Application->databaseDriver(), + m_Application->databaseHostName(), + m_Application->databaseName(), + m_Application->databaseSchemaName(), + m_Application->databaseUserName(), + m_Application->databasePassword(), + this); + break; + + case PrtCnvApplication::e_Log: + m_Thread = new PrtCnvTelegramLogThread(this); + break; + + case PrtCnvApplication::e_Injection: + m_Thread = new PrtCnvInjectionThread(this); + break; + + case PrtCnvApplication::e_RadioTraffic: + m_Thread = new PrtCnvRadioTrafficThread(this); + break; + + case PrtCnvApplication::e_ThreadIdMax: + break; + } + + if (!m_Thread) + { + ERROR_LOG(m_logger) << "Unknown threadId: " << m_Id; + return; + } + + while (!m_Application) + sleep(1); + + m_Application->waitForCreate(m_Id); + m_Thread->create(m_settings); + m_Application->waitForInit(m_Id); + m_Thread->init(); + m_Application->waitForStart(m_Id); + m_Thread->start(); + m_Application->waitForExec(m_Id); + + exec(); + + INFO_LOG(m_logger) << "Leaving event loop for thread " << this << ", id: " << m_Id; + delete m_Thread; + m_Thread = nullptr; + } -// --------------------------------------------------------------- -// Returns the desired thread. -// --------------------------------------------------------------- -PrtCnvThread *PrtCnvThreadStarter::getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const -{ - return m_Application->getThreadStarter(a_threadId)->m_Thread; -} + // --------------------------------------------------------------- + // Returns the desired thread. + // --------------------------------------------------------------- + PrtCnvThread *PrtCnvThreadStarter::getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const + { + return m_Application->getThreadStarter(a_threadId)->m_Thread; + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.hpp index 959452ba7..c651b365c 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/PrtCnvThreadStarter.hpp @@ -1,14 +1,14 @@ // ************************************************************************** -// +// // (C) Copyright 2009 Swiss SIMTEC AG -// +// // ************************************************************************** -// +// // $HeadURL$ // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ -// +// // Implementation of the Class PrtCnvThreadStarter // ************************************************************************** #pragma once @@ -16,14 +16,15 @@ #include "PrtCnvApplication.hpp" #include -namespace NGL { +namespace NGL +{ class Settings; } namespace PrtCnv { class PrtCnvThread; - /** + /** * This class is responsible for starting threads. It also impelements an access * to other threads. * @author wia @@ -33,7 +34,7 @@ namespace PrtCnv class PrtCnvThreadStarter : public QThread { Q_OBJECT -protected: + protected: /** * Pointer to the started thread */ @@ -52,6 +53,7 @@ protected: NGL::Settings *m_settings; NGL::INGLLogger &m_logger; + public: /** * Constructor with id and ptr to main-app as parameters. @@ -59,9 +61,7 @@ protected: * @param a_id * @param a_mainApp The pointer to the main-app */ - PrtCnvThreadStarter(const PrtCnvApplication::E_ThreadId a_id, - const QString &settingsFile, - PrtCnvApplication *a_mainApp); + PrtCnvThreadStarter(const PrtCnvApplication::E_ThreadId a_id, const QString &settingsFile, PrtCnvApplication *a_mainApp); ~PrtCnvThreadStarter(); @@ -73,6 +73,7 @@ protected: * @param a_threadId The id of the desired thread. */ PrtCnvThread *getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const; + protected: /** * The run()-function, which will be called by Qt-Framework, when starting the diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/main.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/main.cpp index f4e1c4ca5..88c806b8e 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/main.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/main.cpp @@ -31,97 +31,77 @@ int main(int argc, char **argv) LtsCommandLineParser::LtsCommandLineParser options(LtsCommandLineParser::LtsCommandLineParser::CustomConfigFile); - options.addOption({ QStringList() << QLatin1String("p") << QLatin1String("player") - , QLatin1String("number of players to be simulated.") - , QLatin1String("Default value") - , QLatin1String("5") - }); + options.addOption({QStringList() << QLatin1String("p") << QLatin1String("player"), + QLatin1String("number of players to be simulated."), + QLatin1String("Default value"), + QLatin1String("5")}); - options.addOption({ QStringList() << QLatin1String("n") << QLatin1String("northing") - , QLatin1String("initial position UTM north.") - , QLatin1String("Default value") - , QLatin1String("77777") - }); + options.addOption({QStringList() << QLatin1String("n") << QLatin1String("northing"), + QLatin1String("initial position UTM north."), + QLatin1String("Default value"), + QLatin1String("77777")}); - options.addOption({ QStringList() << QLatin1String("e") << QLatin1String("easting") - , QLatin1String("initial position UTM east.") - , QLatin1String("Default value") - , QLatin1String("99999") - }); + options.addOption({QStringList() << QLatin1String("e") << QLatin1String("easting"), + QLatin1String("initial position UTM east."), + QLatin1String("Default value"), + QLatin1String("99999")}); - options.addOption({ QStringList() << QLatin1String("f") << QLatin1String("first-id") - , QLatin1String("first equipment ID to use.") - , QLatin1String("Default value") - , QLatin1String("1101") - }); + options.addOption({QStringList() << QLatin1String("f") << QLatin1String("first-id"), + QLatin1String("first equipment ID to use."), + QLatin1String("Default value"), + QLatin1String("1101")}); - options.addOption({ QStringList() << QLatin1String("r") << QLatin1String("pprow") - , QLatin1String("players per row.") - , QLatin1String("Default value") - , QLatin1String("25") - }); + options.addOption( + {QStringList() << QLatin1String("r") << QLatin1String("pprow"), QLatin1String("players per row."), QLatin1String("Default value"), QLatin1String("25")}); - options.addOption({ QStringList() << QLatin1String("s") << QLatin1String("pspacing") - , QLatin1String("utm based spacing between the players.") - , QLatin1String("Default value") - , QLatin1String("100") - }); + options.addOption({QStringList() << QLatin1String("s") << QLatin1String("pspacing"), + QLatin1String("utm based spacing between the players."), + QLatin1String("Default value"), + QLatin1String("100")}); - options.addOption({ QStringList() << QLatin1String("z") << QLatin1String("issi") - , QLatin1String("DestinationIssi / HostISSI") - , QLatin1String("Default value") - , QLatin1String("2") - }); + options.addOption( + {QStringList() << QLatin1String("z") << QLatin1String("issi"), QLatin1String("DestinationIssi / HostISSI"), QLatin1String("Default value"), QLatin1String("2")}); - options.addOption({ QStringList() << QLatin1String("m") << QLatin1String("movements") - , QLatin1String("how many movements per milliseconds to make.") - , QLatin1String("Default value") - , QLatin1String("2000") - }); + options.addOption({QStringList() << QLatin1String("m") << QLatin1String("movements"), + QLatin1String("how many movements per milliseconds to make."), + QLatin1String("Default value"), + QLatin1String("2000")}); - options.addOption({ QStringList() << QLatin1String("d") << QLatin1String("death") - , QLatin1String("minimum times, after the movements timer is triggered, a dead player can revive.") - , QLatin1String("Default value") - , QLatin1String("100") - }); + options.addOption({QStringList() << QLatin1String("d") << QLatin1String("death"), + QLatin1String("minimum times, after the movements timer is triggered, a dead player can revive."), + QLatin1String("Default value"), + QLatin1String("100")}); - options.addOption({ QStringList() << QLatin1String("o") << QLatin1String("death-offset") - , QLatin1String("maximum times, after the movements timer is triggered, a dead player can revive.") - , QLatin1String("(0 -> identical to min)") - , QLatin1String("0") - }); + options.addOption({QStringList() << QLatin1String("o") << QLatin1String("death-offset"), + QLatin1String("maximum times, after the movements timer is triggered, a dead player can revive."), + QLatin1String("(0 -> identical to min)"), + QLatin1String("0")}); - options.addOption({ QStringList() << QLatin1String("t") << QLatin1String("pattern") - , QLatin1String("pattern the player has to walk [enter pattern by hand or pattern alias-name from settings file]\r\nfor more info, enter '--pattern-help'.") - , QLatin1String("Default value") - , QLatin1String("3,30,20#3,30,-20#3,-30,-20#3,-30,20") - }); + options.addOption( + {QStringList() << QLatin1String("t") << QLatin1String("pattern"), + QLatin1String("pattern the player has to walk [enter pattern by hand or pattern alias-name from settings file]\r\nfor more info, enter '--pattern-help'."), + QLatin1String("Default value"), + QLatin1String("3,30,20#3,30,-20#3,-30,-20#3,-30,20")}); - options.addOption({ QStringList() << QLatin1String("demand-old-broadcast-telegrams") - , QLatin1String("player demand old broadcast telegrams starting at BCI ") - , QLatin1String("Default value") - , QLatin1String("0") - }); + options.addOption({QStringList() << QLatin1String("demand-old-broadcast-telegrams"), + QLatin1String("player demand old broadcast telegrams starting at BCI "), + QLatin1String("Default value"), + QLatin1String("0")}); - options.addOption({ QStringList() << QLatin1String("deactivate-single-mines") - , QLatin1String("the first player deactivates single mines with ids from minimum-mine-id to maximum-mine-id") - }); + options.addOption({QStringList() << QLatin1String("deactivate-single-mines"), + QLatin1String("the first player deactivates single mines with ids from minimum-mine-id to maximum-mine-id")}); - options.addOption({ QStringList() << QLatin1String("minimum-mine-id") - , QLatin1String("sets the value for minimum-mine-id used within deactivate-single-mines command") - , QLatin1String("Default value") - , QLatin1String("minimum-mine-id 2048") - }); + options.addOption({QStringList() << QLatin1String("minimum-mine-id"), + QLatin1String("sets the value for minimum-mine-id used within deactivate-single-mines command"), + QLatin1String("Default value"), + QLatin1String("minimum-mine-id 2048")}); - options.addOption({ QStringList() << QLatin1String("maximum-mine-id") - , QLatin1String("sets the value for maximum-mine-Id used within deactivate-single-mines command") - , QLatin1String("Default value") - , QLatin1String("maximum-mine-id 2100") - }); + options.addOption({QStringList() << QLatin1String("maximum-mine-id"), + QLatin1String("sets the value for maximum-mine-Id used within deactivate-single-mines command"), + QLatin1String("Default value"), + QLatin1String("maximum-mine-id 2100")}); - options.addOption({ QStringList() << QLatin1String("pattern-help") - , QLatin1String("help for the pattern interpreter.") - }); + options.addOption({QStringList() << QLatin1String("pattern-help"), QLatin1String("help for the pattern interpreter.")}); if (!options.init()) @@ -166,8 +146,7 @@ int main(int argc, char **argv) WARNING_LOG(logger) << " ... DestinationIssi/HostIssi: " << ttsArgs.destIssi; WARNING_LOG(logger) << " ... on Position n/e: " << ttsArgs.position.y() << "/" << ttsArgs.position.x(); WARNING_LOG(logger) << " ... first equipmentID is: " << ttsArgs.eqIdStart; - WARNING_LOG(logger) << " ... player is reborn randomly after minimum " << ttsArgs.minimumDeathTicks - << " ticks and maximum " << ttsArgs.maximumDeathTicks << " ticks"; + WARNING_LOG(logger) << " ... player is reborn randomly after minimum " << ttsArgs.minimumDeathTicks << " ticks and maximum " << ttsArgs.maximumDeathTicks << " ticks"; WARNING_LOG(logger) << " ... pattern = " << ttsArgs.pattern; WARNING_LOG(logger) << " ... max. " << ttsArgs.pprow << " players per row"; WARNING_LOG(logger) << " ... spacing of '" << ttsArgs.pspacing << " UTM east' between players"; @@ -177,8 +156,7 @@ int main(int argc, char **argv) if (!s->listen(QHostAddress::Any, serverSettings.value(QLatin1String("Radio/Port"), 4200).toInt())) { - ERROR_LOG(logger) << "Error listening on localhost:" << serverSettings.value(QLatin1String("Radio/Port"), 52010).toInt() << ": " - << s->errorString(); + ERROR_LOG(logger) << "Error listening on localhost:" << serverSettings.value(QLatin1String("Radio/Port"), 52010).toInt() << ": " << s->errorString(); delete s; return -1; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.cpp index 403186bd6..5295a17e6 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.cpp @@ -14,9 +14,9 @@ TTServer::TTServer(const TTSArgs &ttsArgs) : m_ttsArgs(ttsArgs) .getNGLLogger("TTServer")), - m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) { - connect(this, &TTServer::newConnection, - this, &TTServer::onNewConnection); + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) +{ + connect(this, &TTServer::newConnection, this, &TTServer::onNewConnection); } void TTServer::onNewConnection() @@ -24,16 +24,13 @@ void TTServer::onNewConnection() QTcpSocket *sock = nextPendingConnection(); if (!sock) return; - NOTICE_LOG(m_logger) << "New incoming connection from " - << sock->peerName() << ":" - << sock->peerPort(); + NOTICE_LOG(m_logger) << "New incoming connection from " << sock->peerName() << ":" << sock->peerPort(); TTWorker *ttw = new TTWorker(sock, m_ttsArgs); if (!ttw->init()) exit(5); - connect(sock, &QTcpSocket::disconnected, - this, &TTServer::onDisconnect); + connect(sock, &QTcpSocket::disconnected, this, &TTServer::onDisconnect); } void TTServer::onDisconnect() diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.h b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.h index 4de0a7caf..96bad4932 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/server.h @@ -24,9 +24,9 @@ struct runningPattern struct TTSArgs { - QPointF position; - QString pattern; - QSettings *settings = nullptr; + QPointF position; + QString pattern; + QSettings *settings = nullptr; int destIssi = 0; unsigned int cntPlayer = 0; unsigned int eqIdStart = 0; @@ -37,9 +37,9 @@ struct TTSArgs unsigned int movs_per_msec = ~0U; unsigned int minimumMineId = 0; unsigned int maximumMineId = 0; - bool demandOldBraodcastTelegrams = false; - int demandOldBraodcastTelegramsCounter = 0; - bool deactivationSingleMines = false; + bool demandOldBraodcastTelegrams = false; + int demandOldBraodcastTelegramsCounter = 0; + bool deactivationSingleMines = false; }; class TTServer : public QTcpServer @@ -53,7 +53,6 @@ protected Q_SLOTS: void onDisconnect(); protected: - -NGL::INGLLogger &m_logger; + NGL::INGLLogger &m_logger; TTSArgs m_ttsArgs; }; diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.cpp index 6200becca..de74fc389 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.cpp @@ -33,14 +33,10 @@ TTWorker::TTWorker(QTcpSocket *socket, const TTSArgs &ttsArgs) bool TTWorker::init() { - connect(m_socket, &QTcpSocket::disconnected, - this, &TTWorker::deleteLater); - connect(m_socket, &QAbstractSocket::errorOccurred, - this, &TTWorker::onSocketError); - connect(m_socket, &QTcpSocket::readyRead, - this, &TTWorker::onReadyRead); - connect(m_timer, &QTimer::timeout, - this, &TTWorker::onSendPlayerPositions); + connect(m_socket, &QTcpSocket::disconnected, this, &TTWorker::deleteLater); + connect(m_socket, &QAbstractSocket::errorOccurred, this, &TTWorker::onSocketError); + connect(m_socket, &QTcpSocket::readyRead, this, &TTWorker::onReadyRead); + connect(m_timer, &QTimer::timeout, this, &TTWorker::onSendPlayerPositions); if (m_ttsArgs.movs_per_msec < 200) { @@ -74,9 +70,9 @@ void TTWorker::startExecution() if (m_ttsArgs.demandOldBraodcastTelegrams) QTimer::singleShot(1000, this, &TTWorker::onSendNachforderungBroadcastTelegramm); -// QTimer::singleShot(25000, this , &TTWorker::onSendNlosSimulatorDirection); -// QTimer::singleShot(120000, this , &TTWorker::onSendNlosFireResult); - } + // QTimer::singleShot(25000, this , &TTWorker::onSendNlosSimulatorDirection); + // QTimer::singleShot(120000, this , &TTWorker::onSendNlosFireResult); +} QVector TTWorker::interpretPattern(QString pattern) const { @@ -106,11 +102,11 @@ QVector TTWorker::interpretPattern(QString pattern) const if (pattern.at(pattern.count() - 1) == QLatin1Char('#')) // delete the character ';' if there is one at the end of string - because of strtok/split pattern.remove(pattern.count() - 1, 1); - QVector newPatternList; // list we give back to replace the patternList in this class - runningPattern rp; // pattern we use (and reuse) to add a new runningPattern instance to the patternList + QVector newPatternList; // list we give back to replace the patternList in this class + runningPattern rp; // pattern we use (and reuse) to add a new runningPattern instance to the patternList QStringList strings = pattern.split(QLatin1Char('#')); // list of pattern (f.g. "1,2,3", "1,2,3"); - QStringList stringy; // list of pattern-ingredients ;) (f.g. "1", "2", "3") - int i; // counter, global because of error message at the end of this function (see variable "strings") + QStringList stringy; // list of pattern-ingredients ;) (f.g. "1", "2", "3") + int i; // counter, global because of error message at the end of this function (see variable "strings") for (i = 0; i < strings.count(); i++) { @@ -121,14 +117,20 @@ QVector TTWorker::interpretPattern(QString pattern) const bool ok = true; - rp.steps = stringy.at(0).toInt(&ok); if (!ok) break; // is not a number, so throw an error and exit this application - rp.ethering = stringy.at(1).toInt(&ok); if (!ok) break; // ^ - rp.northering = stringy.at(2).toInt(&ok); if (!ok) break; // ^ + rp.steps = stringy.at(0).toInt(&ok); + if (!ok) + break; // is not a number, so throw an error and exit this application + rp.ethering = stringy.at(1).toInt(&ok); + if (!ok) + break; // ^ + rp.northering = stringy.at(2).toInt(&ok); + if (!ok) + break; // ^ newPatternList.append(rp); // add a new instance to the list (i hope this will create an instance and does not use a reference !!1) if (i == strings.count() - 1) // are we at the end of the strings.count ? if yes, then return the list - important to NOT throw a error message - return newPatternList; // IMPORTANT! Or an wrong error message will be thrown + return newPatternList; // IMPORTANT! Or an wrong error message will be thrown } ERROR_LOG(m_logger) << "INVALID PATTERN: '" << strings.at(i) << "'. Cannot start without correct pattern!"; @@ -158,16 +160,14 @@ void TTWorker::onReadyRead() if (N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER != header.m_MagicNumber) { - ERROR_LOG(m_logger) << "Disconnect because radio-Telegram does not begin with magic-number A5: I got " - << header.m_MagicNumber; + ERROR_LOG(m_logger) << "Disconnect because radio-Telegram does not begin with magic-number A5: I got " << header.m_MagicNumber; m_socket->disconnectFromHost(); return; } if (!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(header.m_Length)) { - WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length - << " - but I proceed with this telegram."; + WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length << " - but I proceed with this telegram."; } // prepare data-bucket for entire telegram @@ -197,20 +197,19 @@ void TTWorker::handleReceivedTelegram(const QByteArray &data) // evaluate PDU-Type switch (data.at(4)) { - // response to register indication - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd: - handleRegisterInd(); - startExecution(); - break; + // response to register indication + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd: + handleRegisterInd(); + startExecution(); + break; - case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: - handleDataIndReq(data); // tele->getDestISSI() == ISSI an des angesprochenen Teilnehmers - // data is deleted inside handleDataIndReq() - break; - default: - INFO_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << (int)data[4] - << " not implemented!"; - break; + case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq: + handleDataIndReq(data); // tele->getDestISSI() == ISSI an des angesprochenen Teilnehmers + // data is deleted inside handleDataIndReq() + break; + default: + INFO_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << (int)data[4] << " not implemented!"; + break; } } @@ -231,15 +230,14 @@ void TTWorker::onSendNachforderungBroadcastTelegramm() if (p->isLogin) { - N_CoPrtCnv::CoPrtCnvRadioTelegram tel(GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME, - 10, p->eqId); + N_CoPrtCnv::CoPrtCnvRadioTelegram tel(GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME, 10, p->eqId); tel.setZaehler(0); tel.setBroadcastIndex(0); tel.setDestISSI(m_ttsArgs.destIssi); tel.setSrcISSI(p->issi); - tel.setPayload4Byte(0); // gps_zeit - tel.setPayload1Byte(0); // ruecksetzzaehler - tel.setPayload2Byte(m_ttsArgs.demandOldBraodcastTelegramsCounter); // broadcast index + tel.setPayload4Byte(0); // gps_zeit + tel.setPayload1Byte(0); // ruecksetzzaehler + tel.setPayload2Byte(m_ttsArgs.demandOldBraodcastTelegramsCounter); // broadcast index m_socket->write(tel.data()); } else @@ -366,7 +364,6 @@ void TTWorker::sendSanitationReport(uint32_t eqId, uint32_t issi) mat.emplace_back(i); tele.sanitaryMaterialStock = mat; sendTelegram(tele, issi); - } // void TTWorker::sendSanitation(uint32_t eqId, uint32_t issi) @@ -426,103 +423,105 @@ void TTWorker::handleDataIndReq(const QByteArray &data) return; } #endif - case GEF_TAKTISCHER_STATUS: // just resend this one to answer the station's question - { - N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); - TrainingAreaBase::TetraIcd::StateChange sc = TrainingAreaBase::TetraIcd::StateChange::fromJson(tele->jsonData()); - delete tele; - DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got state: " << static_cast(sc.vulnerabilityState) << " and this bits here: " << sc.vulnerabilityBits; - - sc.header.timeStamp = time(nullptr) * 1000; - uint32_t issi = 0; - for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId + case GEF_TAKTISCHER_STATUS: // just resend this one to answer the station's question { - if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) + N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); + TrainingAreaBase::TetraIcd::StateChange sc = TrainingAreaBase::TetraIcd::StateChange::fromJson(tele->jsonData()); + delete tele; + DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got state: " << static_cast(sc.vulnerabilityState) + << " and this bits here: " << sc.vulnerabilityBits; + + sc.header.timeStamp = time(nullptr) * 1000; + uint32_t issi = 0; + for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId { - issi = m_playerList.at(i)->issi; - break; + if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) + { + issi = m_playerList.at(i)->issi; + break; + } } + + ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << static_cast(sc.vulnerabilityState) + << " and this bits here: " << sc.vulnerabilityBits; + sendTelegram(sc, issi); // resend + return; } - - ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << static_cast(sc.vulnerabilityState) << " and this bits here: " << sc.vulnerabilityBits; - sendTelegram(sc, issi); // resend - return; - } - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: - { - N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); - TrainingAreaBase::TetraIcd::Sanitation sc = TrainingAreaBase::TetraIcd::Sanitation::fromJson(tele->jsonData()); - delete tele; - - DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got procedure: " << sc.proceduresTaken; - - sc.header.timeStamp = time(nullptr) * 1000; - uint32_t issi = 0; - for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: { - if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) - { - issi = m_playerList.at(i)->issi; - break; - } - } + N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); + TrainingAreaBase::TetraIcd::Sanitation sc = TrainingAreaBase::TetraIcd::Sanitation::fromJson(tele->jsonData()); + delete tele; - ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << sc.proceduresTaken; - sendTelegram(sc, issi); // resend - return; - } - case GEF_TREFFER_AUSLOESUNG: // we have got a new status (f.g. wounded lying) and send back our new status - case GEF_INIT: // ?? .. or just act like this is a treffer ausloesung ....... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - { - TrainingAreaBase::TetraIcd::StateChange tele; - uint32_t issi = 0; - for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId + DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got procedure: " << sc.proceduresTaken; + + sc.header.timeStamp = time(nullptr) * 1000; + uint32_t issi = 0; + for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId + { + if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) + { + issi = m_playerList.at(i)->issi; + break; + } + } + + ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << sc.proceduresTaken; + sendTelegram(sc, issi); // resend + return; + } + case GEF_TREFFER_AUSLOESUNG: // we have got a new status (f.g. wounded lying) and send back our new status + case GEF_INIT: // ?? .. or just act like this is a treffer ausloesung ....... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ { - if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) + TrainingAreaBase::TetraIcd::StateChange tele; + uint32_t issi = 0; + for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId { - issi = m_playerList.at(i)->issi; - break; + if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId) + { + issi = m_playerList.at(i)->issi; + break; + } } + TrainingAreaBase::TetraIcd::VulnerabilityState state = (telID == GEF_TREFFER_AUSLOESUNG) + ? static_cast(radioTelegram->getPayloadDataUInt8(7)) + : TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady; //get vbg from radio + + tele.originatorType = TrainingAreaBase::TetraIcd::OriginatorType::Initialisation; //set origin + tele.header.equipmentNumber = radioTelegram->getIdentity(); //set header + tele.header.timeStamp = time(nullptr) * 1000; + uint32_t vulcomplete = radioTelegram->getPayloadDataUInt32(8, 2); + uint32_t vitality = vulcomplete &= 0xF000; + vitality >>= 12; + + tele.tasVulnerabilityKindId = vulcomplete &= 0x0FFF; + //including vitality + tele.tasVulnerabilityKindId <<= 16; + tele.tasVulnerabilityKindId |= 0xB1; + + tele.tasVitality = (vitality - 1) * 10; + if (tele.tasVitality < 0) + tele.tasVitality = 100; + + if (state == TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && vitality > 0) + tele.vulnerabilityState = TrainingAreaBase::TetraIcd::VulnerabilityState::MediumDamage; + else + tele.vulnerabilityState = state; + + sendTelegram(tele, issi); // send new status + return; } - TrainingAreaBase::TetraIcd::VulnerabilityState state = (telID == GEF_TREFFER_AUSLOESUNG) - ? static_cast(radioTelegram->getPayloadDataUInt8(7)) - : TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady; //get vbg from radio + // case GEF_NLOS_DATENVERKEHR_TDS_GEF: + // { + // ERROR_LOG(m_logger) << "NlosTargetData empfangen"; + // N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); + // TrainingAreaBase::TetraIcd::NlosTargetData sc = TrainingAreaBase::TetraIcd::NlosTargetData::fromJson(tele->jsonData()); + // delete tele; + // QJsonDocument doc(sc.toJson()); + // ERROR_LOG(m_logger) << "Receive NlosTargetData Size: " << radioTelegram.data()->getSize() << "\n Structure: " << doc.toJson(QJsonDocument::Indented); + // return; - tele.originatorType = TrainingAreaBase::TetraIcd::OriginatorType::Initialisation; //set origin - tele.header.equipmentNumber = radioTelegram->getIdentity(); //set header - tele.header.timeStamp = time(nullptr) * 1000; - uint32_t vulcomplete = radioTelegram->getPayloadDataUInt32(8, 2); - uint32_t vitality = vulcomplete &= 0xF000; - vitality >>= 12; - - tele.tasVulnerabilityKindId = vulcomplete &= 0x0FFF; - //including vitality - tele.tasVulnerabilityKindId <<= 16; - tele.tasVulnerabilityKindId |= 0xB1; - - tele.tasVitality = (vitality - 1) * 10; - if (tele.tasVitality < 0) - tele.tasVitality = 100; - - if (state == TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && vitality > 0) - tele.vulnerabilityState = TrainingAreaBase::TetraIcd::VulnerabilityState::MediumDamage; - else - tele.vulnerabilityState = state; - - sendTelegram(tele, issi); // send new status - return; - } - // case GEF_NLOS_DATENVERKEHR_TDS_GEF: - // { - // ERROR_LOG(m_logger) << "NlosTargetData empfangen"; - // N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data()); - // TrainingAreaBase::TetraIcd::NlosTargetData sc = TrainingAreaBase::TetraIcd::NlosTargetData::fromJson(tele->jsonData()); - // delete tele; - // QJsonDocument doc(sc.toJson()); - // ERROR_LOG(m_logger) << "Receive NlosTargetData Size: " << radioTelegram.data()->getSize() << "\n Structure: " << doc.toJson(QJsonDocument::Indented); - // return; - - // } + // } } // miscellaneous messages.. @@ -555,8 +554,7 @@ void TTWorker::handleDataIndReq(const QByteArray &data) static void fillHeader(char *data, int len) { - N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *hdr - = (N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *)data; + N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *hdr = (N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *)data; hdr->m_MagicNumber = N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER; hdr->m_Counter = 0; hdr->m_Length = len; @@ -582,12 +580,14 @@ void TTWorker::movePlayer(Player *p) // move the player like the pattern says // use all variables from the Player POINTER (do not use new instances) if (p->patternInList > m_patternList.count() - 1) // if patternInList is HIGHER than the list-count is, then jump back to position 0 to start again - p->patternInList = 0; // set to list-start + p->patternInList = 0; // set to list-start else { - if (p->stepInPattern > m_patternList.at(p->patternInList).steps) // if we have less steps than the stepInPattern says, then we have obsolved all wnted steps, so we can jump to the new pattern in the List + if (p->stepInPattern > + m_patternList.at(p->patternInList) + .steps) // if we have less steps than the stepInPattern says, then we have obsolved all wnted steps, so we can jump to the new pattern in the List { - p->stepInPattern = 1; // reset steps for the new pattern + p->stepInPattern = 1; // reset steps for the new pattern if (p->patternInList == m_patternList.count() - 1) // if there is NOT a next pattern, then reset pattern counter to 0 p->patternInList = 0; else @@ -595,10 +595,8 @@ void TTWorker::movePlayer(Player *p) // move the player like the pattern says } } - p->posUTM.setX(p->posUTM.x() + - m_patternList.at(p->patternInList).northering); // increase northering as the pattern says - p->posUTM.setY(p->posUTM.y() + - m_patternList.at(p->patternInList).ethering); // ^^^^^^^^ ethering ^^^^^^^^^^^^^^^^^^^ + p->posUTM.setX(p->posUTM.x() + m_patternList.at(p->patternInList).northering); // increase northering as the pattern says + p->posUTM.setY(p->posUTM.y() + m_patternList.at(p->patternInList).ethering); // ^^^^^^^^ ethering ^^^^^^^^^^^^^^^^^^^ p->stepInPattern++; // increase the step counter before we leave, so the player can be moved the next time!! } @@ -621,8 +619,13 @@ void TTWorker::onSendPlayerPositions() playerCount++; // respawn : - if (p->vbg != TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && p->isEndOfTicks()) // only count to zero (isEndOfTicks = are the ticks running out ?) for respawn, if Player is NOT alive! - sendTaktischerStatus(p->eqId, p->issi, TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady); // only give rebirth, do not kill //(unsigned short)!p->isAlive); // kill Player if he is alive, give rebirth to Player if he is dead + if (p->vbg != TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && + p->isEndOfTicks()) // only count to zero (isEndOfTicks = are the ticks running out ?) for respawn, if Player is NOT alive! + sendTaktischerStatus( + p->eqId, + p->issi, + TrainingAreaBase::TetraIcd::VulnerabilityState:: + CombatReady); // only give rebirth, do not kill //(unsigned short)!p->isAlive); // kill Player if he is alive, give rebirth to Player if he is dead tele.header.equipmentNumber = p->eqId; if (m_toogle) diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.h b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.h index 9128a8809..c9b61e756 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/TetraTestServer/worker.h @@ -27,17 +27,14 @@ class QTimer; class Player { private: -NGL::INGLLogger &m_logger; - void randomizeDeathTicks() - { - deathTicks = ((qrand() % (maximumDeathTicks - minimumDeathTicks + 1)) + minimumDeathTicks); - } + NGL::INGLLogger &m_logger; + void randomizeDeathTicks() { deathTicks = ((qrand() % (maximumDeathTicks - minimumDeathTicks + 1)) + minimumDeathTicks); } public: // PU simulation vars: uint32_t eqId; uint32_t issi; - QPointF posUTM; + QPointF posUTM; // PU login-state vars: bool isLogin; @@ -54,17 +51,17 @@ public: uint32_t maximumDeathTicks; Player(int eqId_, int issi_, uint32_t minimumDeathTicks_, uint32_t maximumDeathTicks_, const QPointF &posUTM_) - : eqId(eqId_) - , issi(issi_) - , posUTM(posUTM_) - , isLogin(false) - , isValidBITE(false) - , vbg(TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady) - , patternInList(0) - , stepInPattern(1) - , deathTicks(0) - , minimumDeathTicks(minimumDeathTicks_) - , maximumDeathTicks(maximumDeathTicks_) + : eqId(eqId_) + , issi(issi_) + , posUTM(posUTM_) + , isLogin(false) + , isValidBITE(false) + , vbg(TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady) + , patternInList(0) + , stepInPattern(1) + , deathTicks(0) + , minimumDeathTicks(minimumDeathTicks_) + , maximumDeathTicks(maximumDeathTicks_) { randomizeDeathTicks(); } @@ -107,8 +104,7 @@ protected: void handleDataIndReq(const QByteArray &data); void sendTelegram(N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram, uint32_t issi); - template - void sendTelegram(const T &tele, uint32_t issi) + template void sendTelegram(const T &tele, uint32_t issi) { N_CoPrtCnv::CoPrtCnvCentralTelegram ct(tele); sendTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(&ct), issi); diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.cpp index bdc2d5757..1cd0bcbe0 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.cpp @@ -13,23 +13,24 @@ namespace PrtCnv { -LOGGER_T getLogger(const char *name) -{ - static const char ns[] = "PRT."; - std::string loggerName; - const size_t len = strlen(name); - loggerName.reserve(sizeof(ns) + len); - loggerName.append(ns, sizeof(ns) - 1); - loggerName.append(name, len); - - try { - return NGL::NGLLoggerBootstrap::getNGLRootLogger(). - getNGLLogger( loggerName ); - } catch ( const std::exception &ex ) + LOGGER_T getLogger(const char *name) { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); + static const char ns[] = "PRT."; + std::string loggerName; + const size_t len = strlen(name); + loggerName.reserve(sizeof(ns) + len); + loggerName.append(ns, sizeof(ns) - 1); + loggerName.append(name, len); + + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception &ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } -} } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.h b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.h index e3bd12365..1c5a271af 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.h +++ b/qt6-after/qt6-migrated-legatus/TetraIF/PrtCnv/logger.h @@ -13,11 +13,11 @@ namespace PrtCnv { -typedef NGL::INGLLogger& LOGGER_T; + typedef NGL::INGLLogger &LOGGER_T; -LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) -{ - return getLogger(loggerName.toUtf8().constData()); -} + LOGGER_T getLogger(const char *name); + inline LOGGER_T getLogger(const QString &loggerName) + { + return getLogger(loggerName.toUtf8().constData()); + } } // namespace PrtCnv diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h index 8519801ee..f0250f47b 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h @@ -19,9 +19,10 @@ namespace NGL { -class INGLLogger; -// keep in sync with log4qt/level.h -enum class LogLevel { + class INGLLogger; + // keep in sync with log4qt/level.h + enum class LogLevel + { Undefined = 0, Trace = 64, Debug = 96, @@ -29,41 +30,44 @@ enum class LogLevel { Warning = 150, Error = 182, Fatal = 214, -}; + }; -class LogStreamHelper -{ + class LogStreamHelper + { public: - inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line, - const char* const function) - : m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function) + inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function) + : m_logger(logger) + , m_level(level) + , m_line(line) + , m_file(file) + , m_func(function) { } inline ~LogStreamHelper(); // after INGLLogger class definition - template inline LogStreamHelper& operator<<(const T& val); + template inline LogStreamHelper &operator<<(const T &val); private: std::ostringstream m_buffer; - NGL::INGLLogger& m_logger; + NGL::INGLLogger &m_logger; const LogLevel m_level; const int m_line; - const char* const m_file; - const char* const m_func; -}; + const char *const m_file; + const char *const m_func; + }; -// Interface class for source code logging. -// Use NGLLoggerBootstrap to create an instance of this interface. -// Look below in this headerfile for the macros with which to insert logging -// code into your source code. -// Lookup the log4cxx documentation (http://logging.apache.org/log4cxx/) for -// information on logger-hierarchies, logging-levels, and configuration files. -class INGLLogger -{ + // Interface class for source code logging. + // Use NGLLoggerBootstrap to create an instance of this interface. + // Look below in this headerfile for the macros with which to insert logging + // code into your source code. + // Lookup the log4cxx documentation (http://logging.apache.org/log4cxx/) for + // information on logger-hierarchies, logging-levels, and configuration files. + class INGLLogger + { public: - INGLLogger(const INGLLogger&) = delete; - INGLLogger& operator=(const INGLLogger&) = delete; + INGLLogger(const INGLLogger &) = delete; + INGLLogger &operator=(const INGLLogger &) = delete; INGLLogger() = default; virtual ~INGLLogger() = default; @@ -73,8 +77,8 @@ class INGLLogger // a dottet sequence (i.e. "NGL.thisandthat.mylogger"). The same name will // always return the same interface-instance. It is not required to create // the parent nodes. - virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0; - virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0; + virtual INGLLogger &getNGLLogger(const char *fullqualifiedname) = 0; + virtual INGLLogger &getNGLLogger(const std::string &fullqualifiedname) = 0; // True if this level is enabled. virtual bool isTraceEnabled() const = 0; @@ -87,147 +91,136 @@ class INGLLogger // Submit a LOG message. // Use __FILE__ and __NAME__ macros. - virtual void log(LogLevel level, const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit an TRACE message. - virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit an DEBUG message. - virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit an INFO message. - virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit a WARNING message. - virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit an ERROR message. - virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Submit a FATAL message. - virtual void logFatal(const INGLLogger::String& message, const char* file = nullptr, int line = -1, - const char* function = nullptr) = 0; + virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; // Writes a startup message into the logfile - virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0; + virtual void logStartup(const char *file, int line, const char *function = nullptr) = 0; // Writes a shutdown message into the logfile - virtual void logShutdown(const char* file, int line, const char* function = nullptr) = 0; + virtual void logShutdown(const char *file, int line, const char *function = nullptr) = 0; // Get this loggers fullqualified name. virtual std::string getLoggerName() const = 0; virtual void setNoSpace(bool bNoSpace) = 0; virtual bool noSpace() const = 0; -}; + }; -// -// LogStreamHelper -// -inline LogStreamHelper::~LogStreamHelper() -{ + // + // LogStreamHelper + // + inline LogStreamHelper::~LogStreamHelper() + { m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func); -} + } -template inline LogStreamHelper& LogStreamHelper::operator<<(const T& val) -{ + template inline LogStreamHelper &LogStreamHelper::operator<<(const T &val) + { m_buffer << val; if (!m_logger.noSpace()) - m_buffer << " "; + m_buffer << " "; return *this; -} + } } // namespace NGL -inline std::ostream& operator<<(std::ostream& stream, const QByteArray& str) +inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str) { - stream << std::string(str.data(), str.size()); - return stream; + stream << std::string(str.data(), str.size()); + return stream; } // // operator to ease logging (at least via NglLogging) // -inline std::ostream& operator<<(std::ostream& stream, const QPointF& value) +inline std::ostream &operator<<(std::ostream &stream, const QPointF &value) { - stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" - << QString::number(value.y(), 'f', 6).toStdString() << ")"; - return stream; + stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")"; + return stream; } //---------------------------------------------------------------------------- -inline std::ostream& operator<<(std::ostream& stream, const QPoint& value) +inline std::ostream &operator<<(std::ostream &stream, const QPoint &value) { - stream << "QPoint(" << value.x() << "#" << value.y() << ")"; - return stream; + stream << "QPoint(" << value.x() << "#" << value.y() << ")"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QSize& value) +inline std::ostream &operator<<(std::ostream &stream, const QSize &value) { - stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; - return stream; + stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value) +inline std::ostream &operator<<(std::ostream &stream, const QSizeF &value) { - stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString() - << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")"; - return stream; + stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString() << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QRect& value) +inline std::ostream &operator<<(std::ostream &stream, const QRect &value) { - stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height() - << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")"; - return stream; + stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height() << " bottomLeft=" << value.bottomLeft() + << " topRight=" << value.topRight() << ")"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QRectF& value) +inline std::ostream &operator<<(std::ostream &stream, const QRectF &value) { - stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString() - << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft() - << " topRight=" << value.topRight() << ")"; - return stream; + stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString() + << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QList& value) +inline std::ostream &operator<<(std::ostream &stream, const QList &value) { - stream << "QList(" << value.size() << "): "; - for (int i : value) - stream << i << ";"; - return stream; + stream << "QList(" << value.size() << "): "; + for (int i : value) + stream << i << ";"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QList& value) +inline std::ostream &operator<<(std::ostream &stream, const QList &value) { - stream << "QList(" << value.size() << "): "; - for (const QPointF& item : value) - stream << item << ";"; - return stream; + stream << "QList(" << value.size() << "): "; + for (const QPointF &item : value) + stream << item << ";"; + return stream; } -inline std::ostream& operator<<(std::ostream& stream, const QString& str) +inline std::ostream &operator<<(std::ostream &stream, const QString &str) { - return stream << str.toUtf8(); + return stream << str.toUtf8(); } namespace NGL { -namespace NGLLoggerHelper -{ -NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data, - const unsigned int a_size); + namespace NGLLoggerHelper + { + NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger, NGL::LogLevel level, const void *a_data, const unsigned int a_size); -inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data) -{ - return hexDumpHelper(logger, level, data.data(), data.size()); -} -} // namespace NGLLoggerHelper + inline void hexDumpHelper(NGL::INGLLogger &logger, NGL::LogLevel level, const QByteArray &data) + { + return hexDumpHelper(logger, level, data.data(), data.size()); + } + } // namespace NGLLoggerHelper -NGLLOGGER_EXPORT NGL::INGLLogger& getMemoryLogger(); -NGLLOGGER_EXPORT std::string getMemoryData(); + NGLLOGGER_EXPORT NGL::INGLLogger &getMemoryLogger(); + NGLLOGGER_EXPORT std::string getMemoryData(); } // namespace NGL @@ -241,43 +234,43 @@ NGLLOGGER_EXPORT std::string getMemoryData(); #define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) #ifdef LTS_DEBUG -#define TRACE_LOG(logger) \ - for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #else -#define TRACE_LOG(logger) \ - for (; false;) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (; false;) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #endif -#define DEBUG_LOG(logger) \ - for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ - ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Debug, __FILE__, __LINE__, Q_FUNC_INFO) +#define DEBUG_LOG(logger) \ + for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ + ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Debug, __FILE__, __LINE__, Q_FUNC_INFO) -#define INFO_LOG(logger) \ - for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ - ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) +#define INFO_LOG(logger) \ + for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ + ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) -#define WARNING_LOG(logger) \ - for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ - ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Warning, __FILE__, __LINE__, Q_FUNC_INFO) +#define WARNING_LOG(logger) \ + for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ + ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Warning, __FILE__, __LINE__, Q_FUNC_INFO) -#define ERROR_LOG(logger) \ - for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ - ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Error, __FILE__, __LINE__, Q_FUNC_INFO) +#define ERROR_LOG(logger) \ + for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ + ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Error, __FILE__, __LINE__, Q_FUNC_INFO) -#define FATAL_LOG(logger) \ - for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ - ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO) +#define FATAL_LOG(logger) \ + for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ + ::NGL::LogStreamHelper(logger, ::NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO) -#define STARTUP_LOG(logger) \ - { \ - (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \ - } -#define SHUTDOWN_LOG(logger) \ - { \ - (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \ - } +#define STARTUP_LOG(logger) \ + { \ + (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \ + } +#define SHUTDOWN_LOG(logger) \ + { \ + (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \ + } //============================================================================== @@ -286,10 +279,8 @@ NGLLOGGER_EXPORT std::string getMemoryData(); // do something nasty // MEMORY_LOG() << " after something nasty"; -#define MEMORY_LOG() \ - for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \ - log_level_enabled = false) \ - NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \ - << NGL::getMemoryData() +#define MEMORY_LOG() \ + for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) << NGL::getMemoryData() //============================================================================== diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.cpp b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.cpp old mode 100755 new mode 100644 index ef141dd82..7b29e4c52 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.cpp @@ -1,77 +1,58 @@ - - - - - - - - - - - - - - - - #include "MurmurHash2.h" #include namespace NGL { -unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed ) -{ - - + unsigned int MurmurHash2(const void *key, int len, unsigned int seed) + { - const unsigned int m = 0x5bd1e995; - const int r = 24; - + const unsigned int m = 0x5bd1e995; + const int r = 24; - unsigned int h = seed ^ len; - + unsigned int h = seed ^ len; - const unsigned char * data = (const unsigned char *)key; - while(len >= 4) - { - unsigned int k = *(reinterpret_cast(data)); + const unsigned char *data = (const unsigned char *)key; - k *= m; - k ^= k >> r; - k *= m; + while (len >= 4) + { + unsigned int k = *(reinterpret_cast(data)); - h *= m; - h ^= k; + k *= m; + k ^= k >> r; + k *= m; - data += 4; - len -= 4; - } + h *= m; + h ^= k; - + data += 4; + len -= 4; + } - switch(len) - { - case 3: h ^= data[2] << 16; - Q_FALLTHROUGH(); - case 2: h ^= data[1] << 8; - Q_FALLTHROUGH(); - case 1: h ^= data[0]; - h *= m; - }; - - - - h ^= h >> 13; + switch (len) + { + case 3: + h ^= data[2] << 16; + Q_FALLTHROUGH(); + case 2: + h ^= data[1] << 8; + Q_FALLTHROUGH(); + case 1: + h ^= data[0]; h *= m; - h ^= h >> 15; + }; - return h; + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; + } } -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.h old mode 100755 new mode 100644 index bee979b26..af798885f --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/MurmurHash2.h @@ -5,5 +5,5 @@ namespace NGL { -unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed = 0 ); + unsigned int MurmurHash2(const void *key, int len, unsigned int seed = 0); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.cpp b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.cpp old mode 100755 new mode 100644 index 485fbabe7..8364f1cf8 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.cpp @@ -27,82 +27,73 @@ namespace NGL { -void LtsRollingFileAppender::setLtsLogfileName(const QString <sLogfileName) -{ - m_ltsLogfileName = ltsLogfileName; -} + void LtsRollingFileAppender::setLtsLogfileName(const QString <sLogfileName) + { + m_ltsLogfileName = ltsLogfileName; + } -void LtsRollingFileAppender::activateOptions() -{ - if (!m_ltsLogfileName.isEmpty()) - setFile(m_ltsLogfileName); + void LtsRollingFileAppender::activateOptions() + { + if (!m_ltsLogfileName.isEmpty()) + setFile(m_ltsLogfileName); #ifdef HAVE_LOG4QT - Log4Qt::RollingFileAppender::activateOptions(); + Log4Qt::RollingFileAppender::activateOptions(); #endif -} + } -QString LtsRollingFileAppender::m_ltsLogfileName; + QString LtsRollingFileAppender::m_ltsLogfileName; #ifdef HAVE_LOG4QT -static Log4Qt::Appender *createLtsRollingFileAppender() -{ - auto ret = new LtsRollingFileAppender; - ret->setAppendFile(true); - return ret; -} + static Log4Qt::Appender *createLtsRollingFileAppender() + { + auto ret = new LtsRollingFileAppender; + ret->setAppendFile(true); + return ret; + } #endif + class CleanupHelper final + { + public: + CleanupHelper() = default; + ~CleanupHelper(); + std::mutex &getLoggerMapMutex(); + + std::unordered_map m_loggermap; + + protected: + std::mutex m_loggermapmutex; + }; + NGL::NGLLogger *NGL::NGLLogger::rootlogger_ptr = nullptr; -class CleanupHelper final -{ -public: - CleanupHelper() = default; - ~CleanupHelper(); - std::mutex &getLoggerMapMutex(); - - std::unordered_map m_loggermap; -protected: - std::mutex m_loggermapmutex; -}; + NGL::CleanupHelper NGL::NGLLogger::s_cleanup; + CleanupHelper::~CleanupHelper() + { + std::lock_guard lock(m_loggermapmutex); + for (auto it : m_loggermap) + delete it.second; + m_loggermap.clear(); + delete NGL::NGLLogger::rootlogger_ptr; + NGL::NGLLogger::rootlogger_ptr = nullptr; + } -NGL::NGLLogger *NGL::NGLLogger::rootlogger_ptr = nullptr; - -NGL::CleanupHelper NGL::NGLLogger::s_cleanup; - - - - -CleanupHelper::~CleanupHelper() -{ - std::lock_guard lock(m_loggermapmutex); - - for (auto it : m_loggermap) - delete it.second; - m_loggermap.clear(); - - delete NGL::NGLLogger::rootlogger_ptr; - NGL::NGLLogger::rootlogger_ptr = nullptr; + std::mutex &CleanupHelper::getLoggerMapMutex() + { + return m_loggermapmutex; + } } -std::mutex &CleanupHelper::getLoggerMapMutex() -{ - return m_loggermapmutex; -} -} - - - NGL::NGLLogger::NGLLogger(const std::string &fullqualifiedname) - : name(fullqualifiedname) - , currentLevel(LogLevel::Undefined) - , m_bNoSpace(true) + : name(fullqualifiedname) + , currentLevel(LogLevel::Undefined) + , m_bNoSpace(true) { #ifdef HAVE_LOG4QT if (!fullqualifiedname.empty()) @@ -113,17 +104,13 @@ NGL::NGLLogger::NGLLogger(const std::string &fullqualifiedname) else { logger_ptr = Log4Qt::LogManager::loggerRepository()->rootLogger(); - } #endif - + configChanged(); } - - - NGL::INGLLogger &NGL::NGLLogger::getNGLLogger(const char *fullqualifiedname) { std::lock_guard lock(s_cleanup.getLoggerMapMutex()); @@ -135,9 +122,6 @@ NGL::INGLLogger &NGL::NGLLogger::getNGLLogger(const char *fullqualifiedname) } - - - NGL::INGLLogger &NGL::NGLLogger::getNGLLogger(const std::string &fullqualifiedname) { std::lock_guard lock(s_cleanup.getLoggerMapMutex()); @@ -149,9 +133,6 @@ NGL::INGLLogger &NGL::NGLLogger::getNGLLogger(const std::string &fullqualifiedna } - - - void NGL::NGLLogger::log(LogLevel level, const INGLLogger::String &message, const char *file, int line, const char *function) { #ifdef HAVE_LOG4QT @@ -182,9 +163,6 @@ void NGL::NGLLogger::log(LogLevel level, const INGLLogger::String &message, cons } - - - void NGL::NGLLogger::logTrace(const INGLLogger::String &message, const char *file, int line, const char *function) { if (currentLevel >= LogLevel::Trace) @@ -192,9 +170,6 @@ void NGL::NGLLogger::logTrace(const INGLLogger::String &message, const char *fil } - - - void NGL::NGLLogger::logDebug(const INGLLogger::String &message, const char *file, int line, const char *function) { if (currentLevel >= LogLevel::Debug) @@ -202,9 +177,6 @@ void NGL::NGLLogger::logDebug(const INGLLogger::String &message, const char *fil } - - - void NGL::NGLLogger::logInfo(const INGLLogger::String &message, const char *file, int line, const char *function) { if (currentLevel >= LogLevel::Info) @@ -212,9 +184,6 @@ void NGL::NGLLogger::logInfo(const INGLLogger::String &message, const char *file } - - - void NGL::NGLLogger::logWarning(const INGLLogger::String &message, const char *file, int line, const char *function) { if (currentLevel >= LogLevel::Warning) @@ -222,9 +191,6 @@ void NGL::NGLLogger::logWarning(const INGLLogger::String &message, const char *f } - - - void NGL::NGLLogger::logError(const INGLLogger::String &message, const char *file, int line, const char *function) { if (currentLevel >= LogLevel::Error) @@ -232,17 +198,12 @@ void NGL::NGLLogger::logError(const INGLLogger::String &message, const char *fil } - - - void NGL::NGLLogger::logFatal(const INGLLogger::String &message, const char *file, int line, const char *function) { log(LogLevel::Fatal, message, file, line, function); } - - #ifndef LTS_VERSION_MAJOR #define LTS_VERSION_MAJOR "undefined" #endif @@ -266,52 +227,58 @@ static const char ver_jenkins[] = JENKINS_BUILD_NUMBER; void NGL::NGLLogger::logStartup(const char *file, int line, const char *function) { - log(LogLevel::Info, QStringLiteral("Application is started (%1.%2-%3 rev%4 from %5)") - .arg(QString::fromLatin1(ver_major), - QString::fromLatin1(ver_minor), - QString::fromLatin1(ver_jenkins), - QString::fromLatin1(ver_patch), - QString::fromLatin1(ver_date)).toUtf8().constData(), file, line, function); + log(LogLevel::Info, + QStringLiteral("Application is started (%1.%2-%3 rev%4 from %5)") + .arg(QString::fromLatin1(ver_major), + QString::fromLatin1(ver_minor), + QString::fromLatin1(ver_jenkins), + QString::fromLatin1(ver_patch), + QString::fromLatin1(ver_date)) + .toUtf8() + .constData(), + file, + line, + function); } - - void NGL::NGLLogger::logShutdown(const char *file, int line, const char *function) { - log(LogLevel::Info, QStringLiteral("Application is shut down (%1.%2-%3 rev%4 from %5)") - .arg(QString::fromLatin1(ver_major), - QString::fromLatin1(ver_minor), - QString::fromLatin1(ver_jenkins), - QString::fromLatin1(ver_patch), - QString::fromLatin1(ver_date)).toUtf8().constData(), file, line, function); + log(LogLevel::Info, + QStringLiteral("Application is shut down (%1.%2-%3 rev%4 from %5)") + .arg(QString::fromLatin1(ver_major), + QString::fromLatin1(ver_minor), + QString::fromLatin1(ver_jenkins), + QString::fromLatin1(ver_patch), + QString::fromLatin1(ver_date)) + .toUtf8() + .constData(), + file, + line, + function); } - - - NGL::NGLLogger &NGL::NGLLogger::getNGLRootLogger() { - if (!rootlogger_ptr) throw NotCreatedError(); + if (!rootlogger_ptr) + throw NotCreatedError(); return *rootlogger_ptr; } - - #ifdef HAVE_LOG4QT static QString findConfigFile(const QString &configfilename) { if (configfilename.isEmpty()) return QString(); - + QFileInfo fi(configfilename); if (fi.isFile() && fi.isReadable()) return fi.absoluteFilePath(); - + QString p = QCoreApplication::applicationDirPath() + QLatin1Char('/') + configfilename; fi.setFile(p); if (fi.isFile() && fi.isReadable()) @@ -322,16 +289,12 @@ static QString findConfigFile(const QString &configfilename) #endif - - -NGL::NGLLogger &NGL::NGLLogger::createNGLRootLogger(const QString &configfilename, - bool ignorealreadycreated, - const QString &logOutputName, - bool quiet) +NGL::NGLLogger &NGL::NGLLogger::createNGLRootLogger(const QString &configfilename, bool ignorealreadycreated, const QString &logOutputName, bool quiet) { if (rootlogger_ptr) { - if (!ignorealreadycreated) throw AlreadyCreatedError(); + if (!ignorealreadycreated) + throw AlreadyCreatedError(); } else { @@ -344,8 +307,7 @@ NGL::NGLLogger &NGL::NGLLogger::createNGLRootLogger(const QString &configfilenam if (!filename.isEmpty()) { Log4Qt::PropertyConfigurator::configureAndWatch(filename); - QObject::connect(Log4Qt::ConfiguratorHelper::instance(), &Log4Qt::ConfiguratorHelper::configurationFileChanged, - []() { configurationFileChanged(); }); + QObject::connect(Log4Qt::ConfiguratorHelper::instance(), &Log4Qt::ConfiguratorHelper::configurationFileChanged, []() { configurationFileChanged(); }); const auto l = Log4Qt::ConfiguratorHelper::instance()->configureError(); for (const auto &t : l) std::cerr << t.message().toUtf8().data() << std::endl; @@ -355,19 +317,14 @@ NGL::NGLLogger &NGL::NGLLogger::createNGLRootLogger(const QString &configfilenam else { if (!quiet) - std::cerr << "Could not find log4cxx configuration file " << configfilename << std::endl - << "Using default logging to stdout" << std::endl; + std::cerr << "Could not find log4cxx configuration file " << configfilename << std::endl << "Using default logging to stdout" << std::endl; + - Log4Qt::Properties props; - props.setProperty(QLatin1String("log4j.rootLogger"), - QLatin1String("WARN, stdout")); - props.setProperty(QLatin1String("log4j.appender.stdout"), - QLatin1String("org.apache.log4j.ConsoleAppender")); - props.setProperty(QLatin1String("log4j.appender.stdout.layout"), - QLatin1String("org.apache.log4j.PatternLayout")); - props.setProperty(QLatin1String("log4j.appender.stdout.layout.ConversionPattern"), - QLatin1String("%d %-5p %c |#| %m (%.50F:%L) %n")); + props.setProperty(QLatin1String("log4j.rootLogger"), QLatin1String("WARN, stdout")); + props.setProperty(QLatin1String("log4j.appender.stdout"), QLatin1String("org.apache.log4j.ConsoleAppender")); + props.setProperty(QLatin1String("log4j.appender.stdout.layout"), QLatin1String("org.apache.log4j.PatternLayout")); + props.setProperty(QLatin1String("log4j.appender.stdout.layout.ConversionPattern"), QLatin1String("%d %-5p %c |#| %m (%.50F:%L) %n")); Log4Qt::PropertyConfigurator::configure(props); } rootlogger_ptr->configChanged(); @@ -407,82 +364,80 @@ void NGL::NGLLogger::configChanged() namespace NGL { -namespace NGLLoggerHelper -{ - -void hexDumpHelper(NGL::INGLLogger &logger, NGL::LogLevel level, - const void *a_data, const unsigned int a_size) -{ - if (!logger.isLevelEnabled(level) || !a_data) - return; - - unsigned char *data = (unsigned char *)a_data; - QByteArray baBuf; - for (unsigned int i = 0; i < a_size; i++) + namespace NGLLoggerHelper { - if (0 == (i % 8)) - baBuf = QByteArray::number(i, 16).rightJustified(8, '0').toUpper(); - baBuf += " " + QByteArray::number(data[i], 16).rightJustified(2, '0').toUpper(); - if (7 == (i % 8)) - logger.log(level, baBuf.constData(), __FILE__, __LINE__); + + void hexDumpHelper(NGL::INGLLogger &logger, NGL::LogLevel level, const void *a_data, const unsigned int a_size) + { + if (!logger.isLevelEnabled(level) || !a_data) + return; + + unsigned char *data = (unsigned char *)a_data; + QByteArray baBuf; + for (unsigned int i = 0; i < a_size; i++) + { + if (0 == (i % 8)) + baBuf = QByteArray::number(i, 16).rightJustified(8, '0').toUpper(); + baBuf += " " + QByteArray::number(data[i], 16).rightJustified(2, '0').toUpper(); + if (7 == (i % 8)) + logger.log(level, baBuf.constData(), __FILE__, __LINE__); + } + if (a_size % 8) + logger.log(level, baBuf.constData(), __FILE__, __LINE__); + } + } - if (a_size % 8) - logger.log(level, baBuf.constData(), __FILE__, __LINE__); -} - -} -NGL::INGLLogger& getMemoryLogger() -{ - try + NGL::INGLLogger &getMemoryLogger() { - return NGLLogger::getNGLRootLogger().getNGLLogger("memorystate"); - + try + { + return NGLLogger::getNGLRootLogger().getNGLLogger("memorystate"); + } + catch (const std::exception &ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } - catch (const std::exception &ex) + + int parseLine(char *line) { - fprintf(stderr, "Error retrieving logger: %s", ex.what()); - abort(); + + int i = strlen(line); + const char *p = line; + while (*p < '0' || *p > '9') + p++; + line[i - 3] = '\0'; + i = atoi(p); + return i; } -} -int parseLine(char* line){ - - int i = strlen(line); - const char* p = line; - while (*p <'0' || *p > '9') p++; - line[i-3] = '\0'; - i = atoi(p); - return i; -} + int getMemoryValue() + { -int getMemoryValue() -{ - - FILE* file = fopen("/proc/self/status", "r"); - int result = -1; - char line[128]; + FILE *file = fopen("/proc/self/status", "r"); + int result = -1; + char line[128]; - while (fgets(line, 128, file) != NULL){ + while (fgets(line, 128, file) != NULL) + { - if (strncmp(line, "VmRSS:", 6) == 0){ + if (strncmp(line, "VmRSS:", 6) == 0) + { result = parseLine(line); break; } } fclose(file); return result; + } + + std::string getMemoryData() + { + return QStringLiteral("VmRSS: %1 kB #").arg(QString::number(getMemoryValue())).toStdString(); + } + + } - -std::string getMemoryData() -{ - return QStringLiteral("VmRSS: %1 kB #").arg(QString::number(getMemoryValue())).toStdString(); -} - - -} - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.h old mode 100755 new mode 100644 index 03b50bc6b..ff935b437 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger.h @@ -21,85 +21,90 @@ namespace NGL { -class CleanupHelper; + class CleanupHelper; #ifdef HAVE_LOG4QT -class LtsRollingFileAppender final : public Log4Qt::RollingFileAppender -{ - Q_OBJECT -public: - using Log4Qt::RollingFileAppender::RollingFileAppender; + class LtsRollingFileAppender final : public Log4Qt::RollingFileAppender + { + Q_OBJECT + public: + using Log4Qt::RollingFileAppender::RollingFileAppender; #else -class LtsRollingFileAppender final : public Log4Qt::RollingFileAppender -{ -public: - explicit LtsRollingFileAppender(QObject *parent = nullptr) : Log4Qt::RollingFileAppender(parent) {} + class LtsRollingFileAppender final : public Log4Qt::RollingFileAppender + { + public: + explicit LtsRollingFileAppender(QObject *parent = nullptr) + : Log4Qt::RollingFileAppender(parent) + { + } #endif - static void setLtsLogfileName(const QString <sLogfileName); - void activateOptions() override; -private: - static QString m_ltsLogfileName; -}; + static void setLtsLogfileName(const QString <sLogfileName); + void activateOptions() override; -class NGLLogger final : public INGLLogger -{ - explicit NGLLogger(const std::string &fullqualifiedname); -public: + private: + static QString m_ltsLogfileName; + }; - class NotCreatedError {}; - class AlreadyCreatedError {}; + class NGLLogger final : public INGLLogger + { + explicit NGLLogger(const std::string &fullqualifiedname); - INGLLogger &getNGLLogger(const char *fullqualifiedname) override; - INGLLogger &getNGLLogger(const std::string &fullqualifiedname) override; + public: + class NotCreatedError + { + }; + class AlreadyCreatedError + { + }; - inline bool isTraceEnabled() const override { return currentLevel <= LogLevel::Trace; } - inline bool isDebugEnabled() const override { return currentLevel <= LogLevel::Debug; } - inline bool isInfoEnabled() const override { return currentLevel <= LogLevel::Info; } - inline bool isWarningEnabled() const override { return currentLevel <= LogLevel::Warning; } - inline bool isErrorEnabled() const override { return currentLevel <= LogLevel::Error; } - inline bool isFatalEnabled() const override { return currentLevel <= LogLevel::Fatal; } - inline bool isLevelEnabled(LogLevel level) const override { return currentLevel <= level; } + INGLLogger &getNGLLogger(const char *fullqualifiedname) override; + INGLLogger &getNGLLogger(const std::string &fullqualifiedname) override; - void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + inline bool isTraceEnabled() const override { return currentLevel <= LogLevel::Trace; } + inline bool isDebugEnabled() const override { return currentLevel <= LogLevel::Debug; } + inline bool isInfoEnabled() const override { return currentLevel <= LogLevel::Info; } + inline bool isWarningEnabled() const override { return currentLevel <= LogLevel::Warning; } + inline bool isErrorEnabled() const override { return currentLevel <= LogLevel::Error; } + inline bool isFatalEnabled() const override { return currentLevel <= LogLevel::Fatal; } + inline bool isLevelEnabled(LogLevel level) const override { return currentLevel <= level; } - void logStartup(const char *file, int line, const char *function = nullptr) override; - void logShutdown(const char *file, int line, const char *function = nullptr) override; + void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; + void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) override; - inline void setNoSpace(bool bNoSpace) override { m_bNoSpace = bNoSpace; } - inline bool noSpace() const override { return m_bNoSpace; } + void logStartup(const char *file, int line, const char *function = nullptr) override; + void logShutdown(const char *file, int line, const char *function = nullptr) override; - inline std::string getLoggerName() const override { return name; } + inline void setNoSpace(bool bNoSpace) override { m_bNoSpace = bNoSpace; } + inline bool noSpace() const override { return m_bNoSpace; } - static NGLLogger &getNGLRootLogger(); - static NGLLogger &createNGLRootLogger(const QString &configfilename, - bool ignorealreadycreated, - const QString &logOutputName = QString(), - bool quiet = false); + inline std::string getLoggerName() const override { return name; } - Log4Qt::Logger *log4qtLogger() { return logger_ptr; } -protected: - static void configurationFileChanged(); - void configChanged(); + static NGLLogger &getNGLRootLogger(); + static NGLLogger &createNGLRootLogger(const QString &configfilename, bool ignorealreadycreated, const QString &logOutputName = QString(), bool quiet = false); -private: + Log4Qt::Logger *log4qtLogger() { return logger_ptr; } - Log4Qt::Logger *logger_ptr; - const std::string name; - LogLevel currentLevel; - bool m_bNoSpace; + protected: + static void configurationFileChanged(); + void configChanged(); - static NGLLogger *rootlogger_ptr; + private: + Log4Qt::Logger *logger_ptr; + const std::string name; + LogLevel currentLevel; + bool m_bNoSpace; - friend class CleanupHelper; - static CleanupHelper s_cleanup; + static NGLLogger *rootlogger_ptr; - friend class XMLWatchdog; -}; + friend class CleanupHelper; + static CleanupHelper s_cleanup; -} + friend class XMLWatchdog; + }; + +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.cpp b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.cpp old mode 100755 new mode 100644 index 8631bff4a..61b131f82 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.cpp @@ -5,26 +5,13 @@ #include "NGLLogger.h" - - - -NGL::INGLLogger & NGL::NGLLoggerBootstrap::getNGLRootLogger() +NGL::INGLLogger &NGL::NGLLoggerBootstrap::getNGLRootLogger() { return NGL::NGLLogger::getNGLRootLogger(); } - - - -NGL::INGLLogger & NGL::NGLLoggerBootstrap::createNGLRootLogger(const QString &configfilename, - bool ignorealreadycreated, - const QString &logOutputName, - bool quiet) +NGL::INGLLogger &NGL::NGLLoggerBootstrap::createNGLRootLogger(const QString &configfilename, bool ignorealreadycreated, const QString &logOutputName, bool quiet) { return NGL::NGLLogger::createNGLRootLogger(configfilename, ignorealreadycreated, logOutputName, quiet); } - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h index fc74587cf..a6fc74302 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h @@ -9,36 +9,31 @@ namespace NGL { -namespace NGLLoggerBootstrap -{ -class AlreadyCreatedError final : public std::exception -{ - const char* what() const noexcept override + namespace NGLLoggerBootstrap + { + class AlreadyCreatedError final : public std::exception { - return "NGLLogger rootlogger already created!"; - } -}; + const char *what() const noexcept override { return "NGLLogger rootlogger already created!"; } + }; -class NotCreatedError final : public std::exception -{ - const char* what() const noexcept override + class NotCreatedError final : public std::exception { - return "NGLLogger rootlogger not yet created!"; + const char *what() const noexcept override { return "NGLLogger rootlogger not yet created!"; } + }; + + NGLLOGGER_EXPORT INGLLogger &getNGLRootLogger(); + + NGLLOGGER_EXPORT INGLLogger &createNGLRootLogger(const QString &configfilename, + bool ignorealreadycreated, + const QString &logOutputName = QString(), + bool quiet = false); + + inline INGLLogger &createNGLRootLogger(const char *configfilename, bool ignorealreadycreated, const QString &logOutputName = QString()) + { + return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName); } -}; -NGLLOGGER_EXPORT INGLLogger& getNGLRootLogger(); - -NGLLOGGER_EXPORT INGLLogger& createNGLRootLogger(const QString& configfilename, bool ignorealreadycreated, - const QString& logOutputName = QString(), bool quiet = false); - -inline INGLLogger& createNGLRootLogger(const char* configfilename, bool ignorealreadycreated, - const QString& logOutputName = QString()) -{ - return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName); -} - -} // namespace NGLLoggerBootstrap + } // namespace NGLLoggerBootstrap } // namespace NGL diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger_export.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger_export.h old mode 100755 new mode 100644 index 87c287c73..cdfb68df9 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLogger_export.h @@ -4,19 +4,19 @@ #define NGLLOGGER_EXPORT_H #ifndef NGLLOGGER_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLLOGGER_EXPORT -# else -# ifdef WIN32 -# ifdef MAKE_NGLLOGGER_LIB -# define NGLLOGGER_EXPORT __declspec(dllexport) -# else -# define NGLLOGGER_EXPORT __declspec(dllimport) -# endif -# else -# define NGLLOGGER_EXPORT __attribute__((visibility("default"))) -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLLOGGER_EXPORT +#else +#ifdef WIN32 +#ifdef MAKE_NGLLOGGER_LIB +#define NGLLOGGER_EXPORT __declspec(dllexport) +#else +#define NGLLOGGER_EXPORT __declspec(dllimport) +#endif +#else +#define NGLLOGGER_EXPORT __attribute__((visibility("default"))) +#endif +#endif #endif -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/log4qt_stub.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/log4qt_stub.h index cf331f92f..488cc3af7 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/log4qt_stub.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/log4qt_stub.h @@ -8,106 +8,123 @@ #include #include -namespace Log4Qt { - -// Minimal Logger class stub (no Q_OBJECT to avoid MOC requirements) -class Logger +namespace Log4Qt { -public: + + // Minimal Logger class stub (no Q_OBJECT to avoid MOC requirements) + class Logger + { + public: explicit Logger(QObject *parent = nullptr) { Q_UNUSED(parent); } virtual ~Logger() = default; - + inline void trace(const QString &message) { Q_UNUSED(message); } inline void debug(const QString &message) { qDebug() << message; } inline void info(const QString &message) { qDebug() << message; } inline void warning(const QString &message) { qWarning() << message; } inline void error(const QString &message) { qCritical() << message; } inline void fatal(const QString &message) { qCritical() << message; } - + inline bool isTraceEnabled() const { return true; } inline bool isDebugEnabled() const { return true; } inline bool isInfoEnabled() const { return true; } inline bool isWarnEnabled() const { return true; } inline bool isErrorEnabled() const { return true; } -}; + }; -// Minimal RollingFileAppender stub -class RollingFileAppender : public Logger -{ -public: - explicit RollingFileAppender(QObject *parent = nullptr) : Logger(parent) {} + // Minimal RollingFileAppender stub + class RollingFileAppender : public Logger + { + public: + explicit RollingFileAppender(QObject *parent = nullptr) + : Logger(parent) + { + } ~RollingFileAppender() override = default; - + inline void setFile(const QString &filename) { Q_UNUSED(filename); } inline void setAppendFile(bool append) { Q_UNUSED(append); } virtual void activateOptions() {} -}; + }; -// Minimal LogManager stub -class LogManager -{ -public: - static LogManager *instance() { - static LogManager inst; - return &inst; + // Minimal LogManager stub + class LogManager + { + public: + static LogManager *instance() + { + static LogManager inst; + return &inst; } - - Logger *logger(const QString &name) { - static Logger dummy; - Q_UNUSED(name); - return &dummy; + + Logger *logger(const QString &name) + { + static Logger dummy; + Q_UNUSED(name); + return &dummy; } - + void setDefaultLogger(Logger *logger) { Q_UNUSED(logger); } -}; + }; -// Minimal PropertyConfigurator stub -class PropertyConfigurator -{ -public: - static bool doConfigure(const QString &configFile) { - Q_UNUSED(configFile); - return false; + // Minimal PropertyConfigurator stub + class PropertyConfigurator + { + public: + static bool doConfigure(const QString &configFile) + { + Q_UNUSED(configFile); + return false; } -}; + }; -// Minimal LoggerRepository stub -class LoggerRepository -{ -public: + // Minimal LoggerRepository stub + class LoggerRepository + { + public: inline void setThreshold(int level) { Q_UNUSED(level); } -}; + }; -// Minimal ConfiguratorHelper stub -namespace Helpers { - class ConfiguratorHelper { + // Minimal ConfiguratorHelper stub + namespace Helpers + { + class ConfiguratorHelper + { public: - static ConfiguratorHelper *instance() { - static ConfiguratorHelper inst; - return &inst; - } + static ConfiguratorHelper *instance() + { + static ConfiguratorHelper inst; + return &inst; + } }; - - class Properties { + + class Properties + { public: - Properties() {} - inline void setProperty(const QString &key, const QString &value) { - Q_UNUSED(key); Q_UNUSED(value); - } + Properties() {} + inline void setProperty(const QString &key, const QString &value) + { + Q_UNUSED(key); + Q_UNUSED(value); + } }; - - class Factory { + + class Factory + { public: - static Factory *instance() { - static Factory inst; - return &inst; - } - inline void registerAppender(const QString &name, void *creator) { - Q_UNUSED(name); Q_UNUSED(creator); - } + static Factory *instance() + { + static Factory inst; + return &inst; + } + inline void registerAppender(const QString &name, void *creator) + { + Q_UNUSED(name); + Q_UNUSED(creator); + } }; -} + } } // namespace Log4Qt -#endif // LOG4QT_STUB_H \ No newline at end of file +#endif // LOG4QT_STUB_H diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/test_ngllogger.cpp b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/test_ngllogger.cpp old mode 100755 new mode 100644 index e203ff7ec..30857a24f --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/test_ngllogger.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/test_ngllogger.cpp @@ -8,26 +8,26 @@ int main(int argc, char **argv) NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); - NGL::INGLLogger &l = NGL::NGLLoggerBootstrap::getNGLRootLogger(). getNGLLogger( "Gui" ); + NGL::INGLLogger &l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui"); STARTUP_LOG(l); SHUTDOWN_LOG(l); - NOTICE_LOG(l) << "Gui - NOTICE"; - TRACE_LOG(l) << "Gui - TRACE"; - DEBUG_LOG(l) << "Gui - DEBUG"; - INFO_LOG(l) << "Gui - INFO"; + NOTICE_LOG(l) << "Gui - NOTICE"; + TRACE_LOG(l) << "Gui - TRACE"; + DEBUG_LOG(l) << "Gui - DEBUG"; + INFO_LOG(l) << "Gui - INFO"; WARNING_LOG(l) << "Gui - WARNING"; - ERROR_LOG(l) << "Gui - ERROR"; - FATAL_LOG(l) << "Gui - FATAL"; + ERROR_LOG(l) << "Gui - ERROR"; + FATAL_LOG(l) << "Gui - FATAL"; - NGL::INGLLogger &l2 = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger( "Gui.AES" ); - NOTICE_LOG(l2) << "Gui.AES - NOTICE"; - TRACE_LOG(l2) << "Gui.AES - TRACE"; - DEBUG_LOG(l2) << "Gui.AES - DEBUG"; - INFO_LOG(l2) << "Gui.AES - INFO"; + NGL::INGLLogger &l2 = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui.AES"); + NOTICE_LOG(l2) << "Gui.AES - NOTICE"; + TRACE_LOG(l2) << "Gui.AES - TRACE"; + DEBUG_LOG(l2) << "Gui.AES - DEBUG"; + INFO_LOG(l2) << "Gui.AES - INFO"; WARNING_LOG(l2) << "Gui.AES - WARNING"; - ERROR_LOG(l2) << "Gui.AES - ERROR"; - FATAL_LOG(l2) << "Gui.AES - FATAL"; + ERROR_LOG(l2) << "Gui.AES - ERROR"; + FATAL_LOG(l2) << "Gui.AES - FATAL"; SHUTDOWN_LOG(l2) return 0; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.cpp old mode 100755 new mode 100644 index 96e0cfb60..cdae0e830 --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.cpp @@ -1,7 +1,6 @@ - #include "qtlocalpeer.h" #include #include @@ -11,7 +10,7 @@ #if defined(Q_OS_WIN) #include #include -typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); +typedef BOOL(WINAPI *PProcessIdToSessionId)(DWORD, DWORD *); static PProcessIdToSessionId pProcessIdToSessionId = 0; #endif #if defined(Q_OS_UNIX) @@ -20,7 +19,8 @@ static PProcessIdToSessionId pProcessIdToSessionId = 0; #include #endif -namespace QtLP_Private { +namespace QtLP_Private +{ #include "qtlockedfile.cpp" #if defined(Q_OS_WIN) #include "qtlockedfile_win.cpp" @@ -29,142 +29,147 @@ namespace QtLP_Private { #endif } -const char* QtLocalPeer::ack = "ack"; +const char *QtLocalPeer::ack = "ack"; -QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) - : QObject(parent), id(appId) +QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId) + : QObject(parent) + , id(appId) { - QString prefix = id; - if (id.isEmpty()) { - id = QCoreApplication::applicationFilePath(); + QString prefix = id; + if (id.isEmpty()) + { + id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) - id = id.toLower(); + id = id.toLower(); #endif - prefix = id.section(QLatin1Char('/'), -1); - } - // QRegExp is removed in Qt6; use QRegularExpression - prefix.remove(QRegularExpression(QLatin1String("[^a-zA-Z]"))); - prefix.truncate(6); + prefix = id.section(QLatin1Char('/'), -1); + } + // QRegExp is removed in Qt6; use QRegularExpression + prefix.remove(QRegularExpression(QLatin1String("[^a-zA-Z]"))); + prefix.truncate(6); - QByteArray idc = id.toUtf8(); - // Use QByteArrayView overload to avoid deprecated qChecksum overload - quint16 idNum = qChecksum(QByteArrayView(idc)); - socketName = QLatin1String("qtsingleapp-") + prefix - + QLatin1Char('-') + QString::number(idNum, 16); + QByteArray idc = id.toUtf8(); + // Use QByteArrayView overload to avoid deprecated qChecksum overload + quint16 idNum = qChecksum(QByteArrayView(idc)); + socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) - if (!pProcessIdToSessionId) { - QLibrary lib(QLatin1String("kernel32")); - pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); - } - if (pProcessIdToSessionId) { - DWORD sessionId = 0; - pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - socketName += QLatin1Char('-') + QString::number(sessionId, 16); - } + if (!pProcessIdToSessionId) + { + QLibrary lib(QLatin1String("kernel32")); + pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); + } + if (pProcessIdToSessionId) + { + DWORD sessionId = 0; + pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + socketName += QLatin1Char('-') + QString::number(sessionId, 16); + } #else - socketName += QLatin1Char('-') + QString::number(::getuid(), 16); + socketName += QLatin1Char('-') + QString::number(::getuid(), 16); #endif - server = new QLocalServer(this); - QString lockName = QDir(QDir::tempPath()).absolutePath() - + QLatin1Char('/') + socketName - + QLatin1String("-lockfile"); - lockFile.setFileName(lockName); - lockFile.open(QIODevice::ReadWrite); + server = new QLocalServer(this); + QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile"); + lockFile.setFileName(lockName); + lockFile.open(QIODevice::ReadWrite); } - bool QtLocalPeer::isClient() { - if (lockFile.isLocked()) - return false; - - if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) - return true; - - bool res = server->listen(socketName); -#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) - - if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { - QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); - res = server->listen(socketName); - } -#endif - if (!res) - qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); - QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection); + if (lockFile.isLocked()) return false; + + if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) + return true; + + bool res = server->listen(socketName); +#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4, 5, 0)) + + if (!res && server->serverError() == QAbstractSocket::AddressInUseError) + { + QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName); + res = server->listen(socketName); + } +#endif + if (!res) + qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); + QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection); + return false; } bool QtLocalPeer::sendMessage(const QString &message, int timeout) { - if (!isClient()) - return false; + if (!isClient()) + return false; - QLocalSocket socket; - bool connOk = false; - for(int i = 0; i < 2; i++) { - - socket.connectToServer(socketName); - connOk = socket.waitForConnected(timeout/2); - if (connOk || i) - break; - int ms = 250; + QLocalSocket socket; + bool connOk = false; + for (int i = 0; i < 2; i++) + { + + socket.connectToServer(socketName); + connOk = socket.waitForConnected(timeout / 2); + if (connOk || i) + break; + int ms = 250; #if defined(Q_OS_WIN) - Sleep(DWORD(ms)); + Sleep(DWORD(ms)); #else - struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; - nanosleep(&ts, nullptr); + struct timespec ts = {ms / 1000, (ms % 1000) * 1000 * 1000}; + nanosleep(&ts, nullptr); #endif - } - if (!connOk) - return false; + } + if (!connOk) + return false; - QByteArray uMsg(message.toUtf8()); - QDataStream ds(&socket); - ds.writeBytes(uMsg.constData(), uMsg.size()); - bool res = socket.waitForBytesWritten(timeout); - if (res) { - res &= socket.waitForReadyRead(timeout); - if (res) - res &= (socket.read(qstrlen(ack)) == ack); - } - return res; + QByteArray uMsg(message.toUtf8()); + QDataStream ds(&socket); + ds.writeBytes(uMsg.constData(), uMsg.size()); + bool res = socket.waitForBytesWritten(timeout); + if (res) + { + res &= socket.waitForReadyRead(timeout); + if (res) + res &= (socket.read(qstrlen(ack)) == ack); + } + return res; } void QtLocalPeer::receiveConnection() { - QLocalSocket* socket = server->nextPendingConnection(); - if (!socket) - return; + QLocalSocket *socket = server->nextPendingConnection(); + if (!socket) + return; - while (socket->bytesAvailable() < (int)sizeof(quint32)) - socket->waitForReadyRead(); - QDataStream ds(socket); - QByteArray uMsg; - quint32 remaining; - ds >> remaining; - uMsg.resize(remaining); - int got = 0; - char* uMsgBuf = uMsg.data(); - do { - got = ds.readRawData(uMsgBuf, remaining); - remaining -= got; - uMsgBuf += got; - } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); - if (got < 0) { - qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); - delete socket; - return; - } - QString message(QString::fromUtf8(uMsg)); - socket->write(ack, qstrlen(ack)); - socket->waitForBytesWritten(1000); - socket->waitForDisconnected(1000); + while (socket->bytesAvailable() < (int)sizeof(quint32)) + socket->waitForReadyRead(); + QDataStream ds(socket); + QByteArray uMsg; + quint32 remaining; + ds >> remaining; + uMsg.resize(remaining); + int got = 0; + char *uMsgBuf = uMsg.data(); + do + { + got = ds.readRawData(uMsgBuf, remaining); + remaining -= got; + uMsgBuf += got; + } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); + if (got < 0) + { + qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; - emit messageReceived(message); + return; + } + QString message(QString::fromUtf8(uMsg)); + socket->write(ack, qstrlen(ack)); + socket->waitForBytesWritten(1000); + socket->waitForDisconnected(1000); + delete socket; + emit messageReceived(message); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.h b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.h old mode 100755 new mode 100644 index 544952ff8..afe79955c --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlocalpeer.h @@ -12,29 +12,28 @@ class QtLocalPeer : public QObject { - Q_OBJECT + Q_OBJECT public: - QtLocalPeer(QObject *parent = nullptr, const QString &appId = QString()); - bool isClient(); - bool sendMessage(const QString &message, int timeout); - QString applicationId() const - { return id; } + QtLocalPeer(QObject *parent = nullptr, const QString &appId = QString()); + bool isClient(); + bool sendMessage(const QString &message, int timeout); + QString applicationId() const { return id; } Q_SIGNALS: - void messageReceived(const QString &message); + void messageReceived(const QString &message); protected Q_SLOTS: - void receiveConnection(); + void receiveConnection(); protected: - QString id; - QString socketName; - QLocalServer* server; - QtLP_Private::QtLockedFile lockFile; + QString id; + QString socketName; + QLocalServer *server; + QtLP_Private::QtLockedFile lockFile; private: - static const char* ack; + static const char *ack; }; -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.cpp old mode 100755 new mode 100644 index 00aebffe5..fc5cabbb8 --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.cpp @@ -4,65 +4,46 @@ #include "qtlockedfile.h" - - - - - - - QtLockedFile::QtLockedFile() : QFile() { #ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; + wmutex = 0; + rmutex = 0; #endif - m_lock_mode = NoLock; + m_lock_mode = NoLock; } - QtLockedFile::QtLockedFile(const QString &name) : QFile(name) { #ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; + wmutex = 0; + rmutex = 0; #endif - m_lock_mode = NoLock; + m_lock_mode = NoLock; } - bool QtLockedFile::open(OpenMode mode) { - if (mode & QIODevice::Truncate) { - qWarning("QtLockedFile::open(): Truncate mode not allowed."); - return false; - } - return QFile::open(mode); + if (mode & QIODevice::Truncate) + { + qWarning("QtLockedFile::open(): Truncate mode not allowed."); + return false; + } + return QFile::open(mode); } - bool QtLockedFile::isLocked() const { - return m_lock_mode != NoLock; + return m_lock_mode != NoLock; } - QtLockedFile::LockMode QtLockedFile::lockMode() const { - return m_lock_mode; + return m_lock_mode; } - - - - - - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.h b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.h old mode 100755 new mode 100644 index 14c95420d..8304e5d19 --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile.h @@ -10,27 +10,33 @@ #endif #if defined(Q_OS_WIN) -# if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) -# define QT_QTLOCKEDFILE_EXPORT -# elif defined(QT_QTLOCKEDFILE_IMPORT) -# if defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# endif -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) -# elif defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) -# endif +#if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) +#define QT_QTLOCKEDFILE_EXPORT +#elif defined(QT_QTLOCKEDFILE_IMPORT) +#if defined(QT_QTLOCKEDFILE_EXPORT) +#undef QT_QTLOCKEDFILE_EXPORT +#endif +#define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) +#elif defined(QT_QTLOCKEDFILE_EXPORT) +#undef QT_QTLOCKEDFILE_EXPORT +#define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) +#endif #else -# define QT_QTLOCKEDFILE_EXPORT +#define QT_QTLOCKEDFILE_EXPORT #endif -namespace QtLP_Private { - -class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile +namespace QtLP_Private { -public: - enum LockMode { NoLock = 0, ReadLock, WriteLock }; + + class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile + { + public: + enum LockMode + { + NoLock = 0, + ReadLock, + WriteLock + }; QtLockedFile(); explicit QtLockedFile(const QString &name); @@ -43,7 +49,7 @@ public: bool isLocked() const; LockMode lockMode() const; -private: + private: #ifdef Q_OS_WIN Qt::HANDLE wmutex; Qt::HANDLE rmutex; @@ -55,6 +61,6 @@ private: #endif LockMode m_lock_mode; -}; + }; } #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_unix.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_unix.cpp old mode 100755 new mode 100644 index f44474730..4a719bf5f --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_unix.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_unix.cpp @@ -10,70 +10,72 @@ bool QtLockedFile::lock(LockMode mode, bool block) { - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } - - if (mode == NoLock) - return unlock(); - - if (mode == m_lock_mode) - return true; + if (!isOpen()) + { + qWarning("QtLockedFile::lock(): file is not opened"); + return false; + } - if (m_lock_mode != NoLock) - unlock(); + if (mode == NoLock) + return unlock(); - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; - int cmd = block ? F_SETLKW : F_SETLK; - int ret = fcntl(handle(), cmd, &fl); - - if (ret == -1) { - if (errno != EINTR && errno != EAGAIN) - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - - m_lock_mode = mode; + if (mode == m_lock_mode) return true; + + if (m_lock_mode != NoLock) + unlock(); + + struct flock fl; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; + int cmd = block ? F_SETLKW : F_SETLK; + int ret = fcntl(handle(), cmd, &fl); + + if (ret == -1) + { + if (errno != EINTR && errno != EAGAIN) + qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); + return false; + } + + + m_lock_mode = mode; + return true; } bool QtLockedFile::unlock() { - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } + if (!isOpen()) + { + qWarning("QtLockedFile::unlock(): file is not opened"); + return false; + } - if (!isLocked()) - return true; - - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = F_UNLCK; - int ret = fcntl(handle(), F_SETLKW, &fl); - - if (ret == -1) { - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - m_lock_mode = NoLock; + if (!isLocked()) return true; + + struct flock fl; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + fl.l_type = F_UNLCK; + int ret = fcntl(handle(), F_SETLKW, &fl); + + if (ret == -1) + { + qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); + return false; + } + + m_lock_mode = NoLock; + return true; } QtLockedFile::~QtLockedFile() { - if (isOpen()) - unlock(); + if (isOpen()) + unlock(); } - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_win.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_win.cpp old mode 100755 new mode 100644 index 2edfcb504..7a865380a --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_win.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtlockedfile_win.cpp @@ -16,160 +16,177 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) { - if (mutexname.isEmpty()) { - QFileInfo fi(*this); - mutexname = QString::fromLatin1(MUTEX_PREFIX) - + fi.absoluteFilePath().toLower(); - } - QString mname(mutexname); - if (idx >= 0) - mname += QString::number(idx); + if (mutexname.isEmpty()) + { + QFileInfo fi(*this); + mutexname = QString::fromLatin1(MUTEX_PREFIX) + fi.absoluteFilePath().toLower(); + } + QString mname(mutexname); + if (idx >= 0) + mname += QString::number(idx); - Qt::HANDLE mutex; - if (doCreate) { - QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); - if (!mutex) { - qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); - return 0; - } + Qt::HANDLE mutex; + if (doCreate) + { + QT_WA({ mutex = CreateMutexW(NULL, FALSE, (TCHAR *)mname.utf16()); }, { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); }); + if (!mutex) + { + qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); + return 0; } - else { - QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); - if (!mutex) { - if (GetLastError() != ERROR_FILE_NOT_FOUND) - qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); - return 0; - } + } + else + { + QT_WA( + { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR *)mname.utf16()); }, + { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); }); + if (!mutex) + { + if (GetLastError() != ERROR_FILE_NOT_FOUND) + qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); + return 0; } - return mutex; + } + return mutex; } bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) { - Q_ASSERT(mutex); - DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); - switch (res) { + Q_ASSERT(mutex); + DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); + switch (res) + { case WAIT_OBJECT_0: case WAIT_ABANDONED: - return true; - break; + return true; + break; case WAIT_TIMEOUT: - break; + break; default: - qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); - } - return false; + qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); + } + return false; } - bool QtLockedFile::lock(LockMode mode, bool block) { - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } + if (!isOpen()) + { + qWarning("QtLockedFile::lock(): file is not opened"); + return false; + } - if (mode == NoLock) - return unlock(); + if (mode == NoLock) + return unlock(); - if (mode == m_lock_mode) - return true; - - if (m_lock_mode != NoLock) - unlock(); - - if (!wmutex && !(wmutex = getMutexHandle(-1, true))) - return false; - - if (!waitMutex(wmutex, block)) - return false; - - if (mode == ReadLock) { - int idx = 0; - for (; idx < MAX_READERS; idx++) { - rmutex = getMutexHandle(idx, false); - if (!rmutex || waitMutex(rmutex, false)) - break; - CloseHandle(rmutex); - } - bool ok = true; - if (idx >= MAX_READERS) { - qWarning("QtLockedFile::lock(): too many readers"); - rmutex = 0; - ok = false; - } - else if (!rmutex) { - rmutex = getMutexHandle(idx, true); - if (!rmutex || !waitMutex(rmutex, false)) - ok = false; - } - if (!ok && rmutex) { - CloseHandle(rmutex); - rmutex = 0; - } - ReleaseMutex(wmutex); - if (!ok) - return false; - } - else { - Q_ASSERT(rmutexes.isEmpty()); - for (int i = 0; i < MAX_READERS; i++) { - Qt::HANDLE mutex = getMutexHandle(i, false); - if (mutex) - rmutexes.append(mutex); - } - if (rmutexes.size()) { - DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), - TRUE, block ? INFINITE : 0); - if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { - if (res != WAIT_TIMEOUT) - qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); - m_lock_mode = WriteLock; - unlock(); - return false; - } - } - } - - m_lock_mode = mode; + if (mode == m_lock_mode) return true; + + if (m_lock_mode != NoLock) + unlock(); + + if (!wmutex && !(wmutex = getMutexHandle(-1, true))) + return false; + + if (!waitMutex(wmutex, block)) + return false; + + if (mode == ReadLock) + { + int idx = 0; + for (; idx < MAX_READERS; idx++) + { + rmutex = getMutexHandle(idx, false); + if (!rmutex || waitMutex(rmutex, false)) + break; + CloseHandle(rmutex); + } + bool ok = true; + if (idx >= MAX_READERS) + { + qWarning("QtLockedFile::lock(): too many readers"); + rmutex = 0; + ok = false; + } + else if (!rmutex) + { + rmutex = getMutexHandle(idx, true); + if (!rmutex || !waitMutex(rmutex, false)) + ok = false; + } + if (!ok && rmutex) + { + CloseHandle(rmutex); + rmutex = 0; + } + ReleaseMutex(wmutex); + if (!ok) + return false; + } + else + { + Q_ASSERT(rmutexes.isEmpty()); + for (int i = 0; i < MAX_READERS; i++) + { + Qt::HANDLE mutex = getMutexHandle(i, false); + if (mutex) + rmutexes.append(mutex); + } + if (rmutexes.size()) + { + DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), TRUE, block ? INFINITE : 0); + if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) + { + if (res != WAIT_TIMEOUT) + qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); + m_lock_mode = WriteLock; + unlock(); + return false; + } + } + } + + m_lock_mode = mode; + return true; } bool QtLockedFile::unlock() { - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } + if (!isOpen()) + { + qWarning("QtLockedFile::unlock(): file is not opened"); + return false; + } - if (!isLocked()) - return true; - - if (m_lock_mode == ReadLock) { - ReleaseMutex(rmutex); - CloseHandle(rmutex); - rmutex = 0; - } - else { - for (Qt::HANDLE mutex : std::as_const(rmutexes)) { - ReleaseMutex(mutex); - CloseHandle(mutex); - } - rmutexes.clear(); - ReleaseMutex(wmutex); - } - - m_lock_mode = QtLockedFile::NoLock; + if (!isLocked()) return true; + + if (m_lock_mode == ReadLock) + { + ReleaseMutex(rmutex); + CloseHandle(rmutex); + rmutex = 0; + } + else + { + for (Qt::HANDLE mutex : std::as_const(rmutexes)) + { + ReleaseMutex(mutex); + CloseHandle(mutex); + } + rmutexes.clear(); + ReleaseMutex(wmutex); + } + + m_lock_mode = QtLockedFile::NoLock; + return true; } QtLockedFile::~QtLockedFile() { - if (isOpen()) - unlock(); - if (wmutex) - CloseHandle(wmutex); + if (isOpen()) + unlock(); + if (wmutex) + CloseHandle(wmutex); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.cpp old mode 100755 new mode 100644 index 295a95247..07417582b --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.cpp @@ -1,7 +1,6 @@ - #include "qtsingleapplication.h" #include "qtlocalpeer.h" @@ -12,10 +11,10 @@ void QtSingleApplication::sysInit(const QString &appId) { #ifdef QT6_GUI_AVAILABLE - actWin = nullptr; + actWin = nullptr; #endif - peer = new QtLocalPeer(this, appId); - connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived); + peer = new QtLocalPeer(this, appId); + connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived); } QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) @@ -26,9 +25,9 @@ QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled #endif { #ifndef QT6_GUI_AVAILABLE - Q_UNUSED(GUIenabled); + Q_UNUSED(GUIenabled); #endif - sysInit(); + sysInit(); } QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) @@ -38,53 +37,46 @@ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char * : QCoreApplication(argc, argv) #endif { - sysInit(appId); + sysInit(appId); } bool QtSingleApplication::isRunning() { - return peer->isClient(); + return peer->isClient(); } bool QtSingleApplication::sendMessage(const QString &message, int timeout) { - return peer->sendMessage(message, timeout); + return peer->sendMessage(message, timeout); } QString QtSingleApplication::id() const { - return peer->applicationId(); + return peer->applicationId(); } #ifdef QT6_GUI_AVAILABLE -void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) +void QtSingleApplication::setActivationWindow(QWidget *aw, bool activateOnMessage) { - actWin = aw; - if (activateOnMessage) - connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); - else - disconnect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); + actWin = aw; + if (activateOnMessage) + connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); + else + disconnect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); } -QWidget* QtSingleApplication::activationWindow() const +QWidget *QtSingleApplication::activationWindow() const { - return actWin; + return actWin; } void QtSingleApplication::activateWindow() { - if (actWin) { - actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); - actWin->raise(); - actWin->activateWindow(); - } + if (actWin) + { + actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); + actWin->raise(); + actWin->activateWindow(); + } } #endif - - - - - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.h old mode 100755 new mode 100644 index 52ecf446c..1b9b15812 --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsingleapplication.h @@ -15,53 +15,56 @@ class QtLocalPeer; #ifndef QTSINGLEAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define QTSINGLEAPPLICATION_EXPORT -# else -# if defined(MAKE_QTSINGLEAPPLICATION_LIB) -# define QTSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define QTSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define QTSINGLEAPPLICATION_EXPORT +#else +#if defined(MAKE_QTSINGLEAPPLICATION_LIB) +#define QTSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define QTSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif class QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QTSINGLEAPPLICATION_BASE { - Q_OBJECT + Q_OBJECT public: - QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); - QtSingleApplication(const QString &appId, int &argc, char **argv); + QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); + QtSingleApplication(const QString &appId, int &argc, char **argv); - bool isRunning(); - QString id() const; + bool isRunning(); + QString id() const; #ifdef QT6_GUI_AVAILABLE - void setActivationWindow(QWidget* aw, bool activateOnMessage = true); - QWidget* activationWindow() const; + void setActivationWindow(QWidget *aw, bool activateOnMessage = true); + QWidget *activationWindow() const; #endif - - void initialize(bool dummy = true) - { isRunning(); Q_UNUSED(dummy) } + + void initialize(bool dummy = true) + { + isRunning(); + Q_UNUSED(dummy) + } public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); + bool sendMessage(const QString &message, int timeout = 5000); #ifdef QT6_GUI_AVAILABLE - void activateWindow(); + void activateWindow(); #endif Q_SIGNALS: - void messageReceived(const QString &message); + void messageReceived(const QString &message); private: - void sysInit(const QString &appId = QString()); - QtLocalPeer *peer; + void sysInit(const QString &appId = QString()); + QtLocalPeer *peer; #ifdef QT6_GUI_AVAILABLE - QWidget *actWin; + QWidget *actWin; #endif }; -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.cpp old mode 100755 new mode 100644 index 5427d7f1f..87be511a6 --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.cpp @@ -1,60 +1,39 @@ - #include "qtsinglecoreapplication.h" #include "qtlocalpeer.h" - - - - - QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv) : QCoreApplication(argc, argv) { - peer = new QtLocalPeer(this); - connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleCoreApplication::messageReceived); + peer = new QtLocalPeer(this); + connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleCoreApplication::messageReceived); } - - QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv) : QCoreApplication(argc, argv) { - peer = new QtLocalPeer(this, appId); - connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleCoreApplication::messageReceived); + peer = new QtLocalPeer(this, appId); + connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleCoreApplication::messageReceived); } - - - bool QtSingleCoreApplication::isRunning() { - return peer->isClient(); + return peer->isClient(); } - - - bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout) { - return peer->sendMessage(message, timeout); + return peer->sendMessage(message, timeout); } - - - QString QtSingleCoreApplication::id() const { - return peer->applicationId(); + return peer->applicationId(); } - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.h old mode 100755 new mode 100644 index 3e35f248f..56937208c --- a/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/QtSingleApplication/qtsinglecoreapplication.h @@ -9,38 +9,38 @@ class QtLocalPeer; #ifndef QTSINGLECOREAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define QTSINGLEAPPLICATION_EXPORT -# else -# if defined(MAKE_QTSINGLECOREAPPLICATION_LIB) -# define QTSINGLECOREAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define QTSINGLECOREAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define QTSINGLEAPPLICATION_EXPORT +#else +#if defined(MAKE_QTSINGLECOREAPPLICATION_LIB) +#define QTSINGLECOREAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define QTSINGLECOREAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif class QTSINGLECOREAPPLICATION_EXPORT QtSingleCoreApplication : public QCoreApplication { - Q_OBJECT + Q_OBJECT public: - QtSingleCoreApplication(int &argc, char **argv); - QtSingleCoreApplication(const QString &appId, int &argc, char **argv); + QtSingleCoreApplication(int &argc, char **argv); + QtSingleCoreApplication(const QString &appId, int &argc, char **argv); - bool isRunning(); - QString id() const; + bool isRunning(); + QString id() const; public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); + bool sendMessage(const QString &message, int timeout = 5000); Q_SIGNALS: - void messageReceived(const QString &message); + void messageReceived(const QString &message); private: - QtLocalPeer* peer; + QtLocalPeer *peer; }; -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IECC2WMS.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IECC2WMS.h old mode 100755 new mode 100644 index 9eb944f47..c6f408475 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IECC2WMS.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IECC2WMS.h @@ -5,16 +5,15 @@ namespace WmsJson { -class IECC2WMS -{ + class IECC2WMS + { -public: - IECC2WMS() = default; - virtual ~IECC2WMS() = default; + public: + IECC2WMS() = default; + virtual ~IECC2WMS() = default; - - virtual void playerChanged(int playerId, int exerciseId) = 0; - virtual void exerciseDataChanged(int exerciseId, int betrZustand) = 0; -}; -} + virtual void playerChanged(int playerId, int exerciseId) = 0; + virtual void exerciseDataChanged(int exerciseId, int betrZustand) = 0; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IWMS2ECC.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IWMS2ECC.h old mode 100755 new mode 100644 index af0ed3b0d..3ebfd994e --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IWMS2ECC.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/IWMS2ECC.h @@ -18,7 +18,7 @@ public: { RegistrationOk = 0, PlayerNotFound = 1, - PlayerDeleted = 2, + PlayerDeleted = 2, AssignmentIncorrect = 3, EquipNoAlreadyAssigned = 4, RegistrationFailed = 5 @@ -34,8 +34,8 @@ public: enum PlayerState { NOT_FOUND = 0, - FOUND = 1, - DELETED = 2 + FOUND = 1, + DELETED = 2 }; enum PlayerAssignState @@ -51,16 +51,16 @@ public: { switch (s) { - case UNDEFINED: - case NOT_ASSIGNED: - case ASSIGNED: - case HANDOUT_EXCON: - case HANDOUT_WMS: - case HANDOUT_EXCON_OVERRULED_WMS: - return static_cast(s); + case UNDEFINED: + case NOT_ASSIGNED: + case ASSIGNED: + case HANDOUT_EXCON: + case HANDOUT_WMS: + case HANDOUT_EXCON_OVERRULED_WMS: + return static_cast(s); } Q_ASSERT(false); - return UNDEFINED; + return UNDEFINED; } struct PlayerInfo @@ -104,15 +104,19 @@ public: int specialType = 0; int minEquipNo = 0; int maxEquipNo = 0; - int taVulnerabilityModelId = 0; + int taVulnerabilityModelId = 0; int taPlayerTypeId = 0; bool deletedInWMS = false; }; using equipTypeMap = QMap; - - virtual RegisterReturnValue registerPlayer(int playerId, int equipNo, const PlayerAssignState &zuordnung, const QString &alias, - const QString &info, int exerciseId) = 0; + + virtual RegisterReturnValue registerPlayer(int playerId, + int equipNo, + const PlayerAssignState &zuordnung, + const QString &alias, + const QString &info, + int exerciseId) = 0; virtual UnregisterReturnValue unregister(int equipNo, int exerciseId) = 0; virtual PlayerInfo getPlayerInfo(int playerId, int exerciseId) = 0; @@ -120,7 +124,7 @@ public: virtual exerciseMap getExercises() const = 0; virtual Exercise getActualExercise() const = 0; - + virtual QMap getEquipRequirements(int exerciseId) const = 0; virtual QMap getAllPlayers(int exerciseId) const = 0; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/json_keys.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/json_keys.h old mode 100755 new mode 100644 index 66125d5c9..aa9a34e90 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/json_keys.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/json_keys.h @@ -8,45 +8,86 @@ namespace WebSocketInterface { -namespace JsonKeys -{ + namespace JsonKeys + { -inline QString EXERCISE_ID() { return QStringLiteral("exerciseId"); } -inline QString DATA_MODIFICATION() { return QStringLiteral("dataModification"); } -inline QString PARTICIPANT_ID() { return QStringLiteral("participantId"); } -inline QString REGISTRATION_RETURN_VALUE() { return QStringLiteral("registrationReturnValue"); } + inline QString EXERCISE_ID() + { + return QStringLiteral("exerciseId"); + } + inline QString DATA_MODIFICATION() + { + return QStringLiteral("dataModification"); + } + inline QString PARTICIPANT_ID() + { + return QStringLiteral("participantId"); + } + inline QString REGISTRATION_RETURN_VALUE() + { + return QStringLiteral("registrationReturnValue"); + } -inline QString EQUIPMENT_TYPES_REQUEST() { return QStringLiteral("equipmentTypesRequest"); } + inline QString EQUIPMENT_TYPES_REQUEST() + { + return QStringLiteral("equipmentTypesRequest"); + } -inline QString EQUIPMENT_TYPES_REPLY() { return QStringLiteral("equipmentTypesReply"); } + inline QString EQUIPMENT_TYPES_REPLY() + { + return QStringLiteral("equipmentTypesReply"); + } -inline QString EXERCISES_REQUEST() { return QStringLiteral("exercisesRequest"); } + inline QString EXERCISES_REQUEST() + { + return QStringLiteral("exercisesRequest"); + } -inline QString EXERCISES_REPLY() { return QStringLiteral("exercisesReply"); } + inline QString EXERCISES_REPLY() + { + return QStringLiteral("exercisesReply"); + } -inline QString EXERCISE_UPDATE() { return QStringLiteral("exercisesUpdate"); } + inline QString EXERCISE_UPDATE() + { + return QStringLiteral("exercisesUpdate"); + } -inline QString PARTICIPANTS_REQUEST() { return QStringLiteral("participantsRequest"); } + inline QString PARTICIPANTS_REQUEST() + { + return QStringLiteral("participantsRequest"); + } -inline QString PARTICIPANTS_REPLY() { return QStringLiteral("participantsReply"); } + inline QString PARTICIPANTS_REPLY() + { + return QStringLiteral("participantsReply"); + } -inline QString PARTICIPANTS_UPDATE() { return QStringLiteral("participantsUpdate"); } + inline QString PARTICIPANTS_UPDATE() + { + return QStringLiteral("participantsUpdate"); + } -inline QString PARTICIPANT_REGISTER_IN_EXCON_REQUEST() { return QStringLiteral("participantRegisterInEXCONRequest");} + inline QString PARTICIPANT_REGISTER_IN_EXCON_REQUEST() + { + return QStringLiteral("participantRegisterInEXCONRequest"); + } -inline QString PARTICIPANT_REGISTER_IN_EXCON_REPLY() { return QStringLiteral("participantRegisterInEXCONReply");} + inline QString PARTICIPANT_REGISTER_IN_EXCON_REPLY() + { + return QStringLiteral("participantRegisterInEXCONReply"); + } - -} -} + } +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.cpp old mode 100755 new mode 100644 index 4c8077bc9..6c1a532be --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.cpp @@ -17,8 +17,8 @@ QJsonObject EquipRequirements::toJson() const } QJsonObject retMap; - retMap[QLatin1String("equipMap")] = arr; - retMap[QLatin1String("ok")] = m_ok; + retMap[QLatin1String("equipMap")] = arr; + retMap[QLatin1String("ok")] = m_ok; return retMap; } @@ -32,7 +32,7 @@ EquipRequirements EquipRequirements::fromJson(const QJsonObject &map) { const QJsonObject obj = ele.toObject(); int equipmentTypeId = obj[QLatin1String("key")].toInt(); - int amount = obj[QLatin1String("value")].toInt(); + int amount = obj[QLatin1String("value")].toInt(); eq.m_equipRequire.insert(equipmentTypeId, amount); } @@ -48,8 +48,8 @@ QVariantMap EquipRequirements::toVariantMap() const viMap.insert(QString::number(it.key()), QVariant(it.value())); QVariantMap retMap; - retMap[QLatin1String("equipMap")] = QVariant(viMap); - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("equipMap")] = QVariant(viMap); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.h old mode 100755 new mode 100644 index b7d5ef067..00d68b132 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipRequirements.h @@ -17,7 +17,7 @@ public: QVariantMap toVariantMap() const; static EquipRequirements fromVariantMap(const QVariantMap &map); - + QMap getEquipRequirements() const { return m_equipRequire; } bool getOk() const { return m_ok; } @@ -26,5 +26,5 @@ public: private: QMap m_equipRequire; - bool m_ok = false; + bool m_ok = false; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.cpp old mode 100755 new mode 100644 index d3041e4ab..0e80196a3 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.cpp @@ -8,14 +8,14 @@ QJsonObject EquipmentTypes::toJson(const IWMS2ECC::EquipmentType &et) { QJsonObject obj; - obj[QLatin1String("id")] = et.id; - obj[QLatin1String("name")] = et.name; - obj[QLatin1String("minEquipNo")] = et.minEquipNo; - obj[QLatin1String("maxEquipNo")] = et.maxEquipNo; - obj[QLatin1String("specialType")] = et.specialType; + obj[QLatin1String("id")] = et.id; + obj[QLatin1String("name")] = et.name; + obj[QLatin1String("minEquipNo")] = et.minEquipNo; + obj[QLatin1String("maxEquipNo")] = et.maxEquipNo; + obj[QLatin1String("specialType")] = et.specialType; obj[QLatin1String("taVulnerabilityModelId")] = et.taVulnerabilityModelId; - obj[QLatin1String("taPlayerTypeId")] = et.taPlayerTypeId; - obj[QLatin1String("deletedInWMS")] = et.deletedInWMS; + obj[QLatin1String("taPlayerTypeId")] = et.taPlayerTypeId; + obj[QLatin1String("deletedInWMS")] = et.deletedInWMS; return obj; } @@ -24,14 +24,14 @@ IWMS2ECC::EquipmentType EquipmentTypes::fromJson(const QJsonObject &obj) { IWMS2ECC::EquipmentType et; - et.id = obj[QLatin1String("id")].toInt(); - et.name = obj[QLatin1String("name")].toString(); - et.minEquipNo = obj[QLatin1String("minEquipNo")].toInt(); - et.maxEquipNo = obj[QLatin1String("maxEquipNo")].toInt(); - et.specialType = obj[QLatin1String("specialType")].toInt(); + et.id = obj[QLatin1String("id")].toInt(); + et.name = obj[QLatin1String("name")].toString(); + et.minEquipNo = obj[QLatin1String("minEquipNo")].toInt(); + et.maxEquipNo = obj[QLatin1String("maxEquipNo")].toInt(); + et.specialType = obj[QLatin1String("specialType")].toInt(); et.taVulnerabilityModelId = obj[QLatin1String("taVulnerabilityModelId")].toInt(); - et.taPlayerTypeId = obj[QLatin1String("taPlayerTypeId")].toInt(); - et.deletedInWMS = obj[QLatin1String("deletedInWMS")].toBool(); + et.taPlayerTypeId = obj[QLatin1String("taPlayerTypeId")].toInt(); + et.deletedInWMS = obj[QLatin1String("deletedInWMS")].toBool(); return et; } @@ -43,8 +43,8 @@ QJsonObject EquipmentTypes::toJsonAll() const arr.append(toJson(et)); QJsonObject retMap; - retMap[QLatin1String("etMap")] = arr; - retMap[QLatin1String("ok")] = m_ok; + retMap[QLatin1String("etMap")] = arr; + retMap[QLatin1String("ok")] = m_ok; return retMap; } @@ -70,14 +70,14 @@ QVariantMap EquipmentTypes::toVariantMap() const { QVariantMap vMap; - vMap[QLatin1String("id")] = QVariant(m_equipmentType.id); - vMap[QLatin1String("name")] = m_equipmentType.name; - vMap[QLatin1String("minEquipNo")] = QVariant((int)m_equipmentType.minEquipNo); - vMap[QLatin1String("maxEquipNo")] = QVariant((int)m_equipmentType.maxEquipNo); - vMap[QLatin1String("specialType")] = QVariant(m_equipmentType.specialType); - vMap[QLatin1String("deletedInWMS")] = QVariant(m_equipmentType.deletedInWMS); + vMap[QLatin1String("id")] = QVariant(m_equipmentType.id); + vMap[QLatin1String("name")] = m_equipmentType.name; + vMap[QLatin1String("minEquipNo")] = QVariant((int)m_equipmentType.minEquipNo); + vMap[QLatin1String("maxEquipNo")] = QVariant((int)m_equipmentType.maxEquipNo); + vMap[QLatin1String("specialType")] = QVariant(m_equipmentType.specialType); + vMap[QLatin1String("deletedInWMS")] = QVariant(m_equipmentType.deletedInWMS); - vMap[QLatin1String("ok")] = QVariant(m_ok); + vMap[QLatin1String("ok")] = QVariant(m_ok); return vMap; } @@ -86,12 +86,12 @@ EquipmentTypes EquipmentTypes::fromVariantMap(const QVariantMap &map) { EquipmentTypes ets; - ets.m_equipmentType.id = map[QLatin1String("id")].toInt(); - ets.m_equipmentType.name = map[QLatin1String("name")].toString(); - ets.m_equipmentType.minEquipNo = map[QLatin1String("minEquipNo")].toInt(); - ets.m_equipmentType.maxEquipNo = map[QLatin1String("maxEquipNo")].toInt(); - ets.m_equipmentType.specialType = map[QLatin1String("specialType")].toInt(); - ets.m_equipmentType.deletedInWMS = map[QLatin1String("deletedInWMS")].toBool(); + ets.m_equipmentType.id = map[QLatin1String("id")].toInt(); + ets.m_equipmentType.name = map[QLatin1String("name")].toString(); + ets.m_equipmentType.minEquipNo = map[QLatin1String("minEquipNo")].toInt(); + ets.m_equipmentType.maxEquipNo = map[QLatin1String("maxEquipNo")].toInt(); + ets.m_equipmentType.specialType = map[QLatin1String("specialType")].toInt(); + ets.m_equipmentType.deletedInWMS = map[QLatin1String("deletedInWMS")].toBool(); ets.m_ok = map[QLatin1String("ok")].toBool(); @@ -103,13 +103,13 @@ QVariantMap EquipmentTypes::toVariantMapAll() const QVariantMap vMap; for (IWMS2ECC::equipTypeMap::ConstIterator it = m_equipmentTypes.begin(); it != m_equipmentTypes.end(); ++it) { - m_equipmentType = it.value(); + m_equipmentType = it.value(); vMap.insert(QString::number(it.key()), QVariant(toVariantMap())); } QVariantMap retMap; - retMap[QLatin1String("etMap")] = QVariant(vMap); - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("etMap")] = QVariant(vMap); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.h old mode 100755 new mode 100644 index 7c07bfd64..5e30a3b83 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_equipmenttypes.h @@ -31,7 +31,7 @@ public: void setOk(bool ok) { m_ok = ok; } private: - IWMS2ECC::equipTypeMap m_equipmentTypes; - mutable IWMS2ECC::EquipmentType m_equipmentType; - bool m_ok = false; + IWMS2ECC::equipTypeMap m_equipmentTypes; + mutable IWMS2ECC::EquipmentType m_equipmentType; + bool m_ok = false; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.cpp old mode 100755 new mode 100644 index 3a492c41c..144a6adef --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.cpp @@ -8,128 +8,128 @@ namespace EXCON { -QJsonObject Exercises::toJson(const IWMS2ECC::Exercise &ex) const -{ - QJsonObject obj; - - obj[QLatin1String("id")] = ex.id; - obj[QLatin1String("actExercise")] = ex.actExercise; - obj[QLatin1String("start")] = static_cast(ex.start); - obj[QLatin1String("end")] = static_cast(ex.end); - obj[QLatin1String("name")] = ex.name; - obj[QLatin1String("state")] = ex.stateAsString; - - obj[QLatin1String("ok")] = m_ok; - - return obj; -} - -IWMS2ECC::Exercise Exercises::fromJson(const QJsonObject &obj) -{ - IWMS2ECC::Exercise ex; - - ex.id = obj[QLatin1String("id")].toInt(); - ex.actExercise = obj[QLatin1String("actExercise")].toInt(); - ex.start = static_cast(obj[QLatin1String("start")].toInt()); - ex.end = static_cast(obj[QLatin1String("end")].toInt()); - ex.name = obj[QLatin1String("name")].toString(); - ex.stateAsString = obj[QLatin1String("state")].toString(); - - return ex; -} - -QJsonObject Exercises::toJsonAll() const -{ - QJsonArray arr; - for (const IWMS2ECC::Exercise &ex : m_exercises) - arr.append(toJson(ex)); - - QJsonObject obj; - obj[QLatin1String("exMap")] = arr; - obj[QLatin1String("ok")] = m_ok; - - return obj; -} - -Exercises Exercises::fromJsonAll(const QJsonObject &map) -{ - Exercises ex; - - const QJsonArray arr = map[QLatin1String("exMap")].toArray(); - for (const QJsonValue &val : arr) + QJsonObject Exercises::toJson(const IWMS2ECC::Exercise &ex) const { - const IWMS2ECC::Exercise exinfo = fromJson(val.toObject()); - ex.m_exercises.insert(exinfo.id, exinfo); + QJsonObject obj; + + obj[QLatin1String("id")] = ex.id; + obj[QLatin1String("actExercise")] = ex.actExercise; + obj[QLatin1String("start")] = static_cast(ex.start); + obj[QLatin1String("end")] = static_cast(ex.end); + obj[QLatin1String("name")] = ex.name; + obj[QLatin1String("state")] = ex.stateAsString; + + obj[QLatin1String("ok")] = m_ok; + + return obj; } - ex.m_ok = map[QLatin1String("ok")].toBool(); - - return ex; -} - - -QVariantMap Exercises::toVariantMap() const -{ - QVariantMap vMap; - - vMap[QLatin1String("id")] = QVariant(m_exercise.id); - vMap[QLatin1String("name")] = m_exercise.name; - vMap[QLatin1String("start")] = QVariant(static_cast(m_exercise.start)); - vMap[QLatin1String("end")] = QVariant(static_cast(m_exercise.end)); - vMap[QLatin1String("state")] = m_exercise.stateAsString; - - vMap[QLatin1String("ok")] = QVariant(m_ok); - - return vMap; -} - -Exercises Exercises::fromVariantMap(const QVariantMap &map) -{ - Exercises ex; - - ex.m_exercise.id = map[QLatin1String("id")].toInt(); - ex.m_exercise.name = map[QLatin1String("name")].toString(); - ex.m_exercise.start = map[QLatin1String("start")].toLongLong(); - ex.m_exercise.end = map[QLatin1String("end")].toLongLong(); - ex.m_exercise.stateAsString = map[QLatin1String("state")].toString(); - - ex.m_ok = map[QLatin1String("ok")].toBool(); - - return ex; -} - -QVariantMap Exercises::toVariantMapAll() const -{ - QVariantMap vMap; - for (IWMS2ECC::exerciseMap::ConstIterator it = m_exercises.begin(); it != m_exercises.end(); ++it) + IWMS2ECC::Exercise Exercises::fromJson(const QJsonObject &obj) { - m_exercise = it.value(); - vMap.insert(QString::number(it.key()), QVariant(toVariantMap())); + IWMS2ECC::Exercise ex; + + ex.id = obj[QLatin1String("id")].toInt(); + ex.actExercise = obj[QLatin1String("actExercise")].toInt(); + ex.start = static_cast(obj[QLatin1String("start")].toInt()); + ex.end = static_cast(obj[QLatin1String("end")].toInt()); + ex.name = obj[QLatin1String("name")].toString(); + ex.stateAsString = obj[QLatin1String("state")].toString(); + + return ex; } - QVariantMap retMap; - retMap[QLatin1String("exeMap")] = QVariant(vMap); - retMap[QLatin1String("ok")] = QVariant(m_ok); - - return retMap; -} - -Exercises Exercises::fromVariantMapAll(const QVariantMap &map) -{ - Exercises ex; - - const QVariantMap vMap = map[QLatin1String("exeMap")].toMap(); - for (QVariantMap::ConstIterator it = vMap.begin(); it != vMap.end(); ++it) + QJsonObject Exercises::toJsonAll() const { - - int key = it.key().toInt(); - IWMS2ECC::Exercise e = Exercises::fromVariantMap(it.value().toMap()).m_exercise; - ex.m_exercises.insert(key, e); + QJsonArray arr; + for (const IWMS2ECC::Exercise &ex : m_exercises) + arr.append(toJson(ex)); + + QJsonObject obj; + obj[QLatin1String("exMap")] = arr; + obj[QLatin1String("ok")] = m_ok; + + return obj; } - ex.m_ok = map[QLatin1String("ok")].toBool(); + Exercises Exercises::fromJsonAll(const QJsonObject &map) + { + Exercises ex; + + const QJsonArray arr = map[QLatin1String("exMap")].toArray(); + for (const QJsonValue &val : arr) + { + const IWMS2ECC::Exercise exinfo = fromJson(val.toObject()); + ex.m_exercises.insert(exinfo.id, exinfo); + } + + ex.m_ok = map[QLatin1String("ok")].toBool(); + + return ex; + } + + + QVariantMap Exercises::toVariantMap() const + { + QVariantMap vMap; + + vMap[QLatin1String("id")] = QVariant(m_exercise.id); + vMap[QLatin1String("name")] = m_exercise.name; + vMap[QLatin1String("start")] = QVariant(static_cast(m_exercise.start)); + vMap[QLatin1String("end")] = QVariant(static_cast(m_exercise.end)); + vMap[QLatin1String("state")] = m_exercise.stateAsString; + + vMap[QLatin1String("ok")] = QVariant(m_ok); + + return vMap; + } + + Exercises Exercises::fromVariantMap(const QVariantMap &map) + { + Exercises ex; + + ex.m_exercise.id = map[QLatin1String("id")].toInt(); + ex.m_exercise.name = map[QLatin1String("name")].toString(); + ex.m_exercise.start = map[QLatin1String("start")].toLongLong(); + ex.m_exercise.end = map[QLatin1String("end")].toLongLong(); + ex.m_exercise.stateAsString = map[QLatin1String("state")].toString(); + + ex.m_ok = map[QLatin1String("ok")].toBool(); + + return ex; + } + + QVariantMap Exercises::toVariantMapAll() const + { + QVariantMap vMap; + for (IWMS2ECC::exerciseMap::ConstIterator it = m_exercises.begin(); it != m_exercises.end(); ++it) + { + m_exercise = it.value(); + vMap.insert(QString::number(it.key()), QVariant(toVariantMap())); + } + + QVariantMap retMap; + retMap[QLatin1String("exeMap")] = QVariant(vMap); + retMap[QLatin1String("ok")] = QVariant(m_ok); + + return retMap; + } + + Exercises Exercises::fromVariantMapAll(const QVariantMap &map) + { + Exercises ex; + + const QVariantMap vMap = map[QLatin1String("exeMap")].toMap(); + for (QVariantMap::ConstIterator it = vMap.begin(); it != vMap.end(); ++it) + { + + int key = it.key().toInt(); + IWMS2ECC::Exercise e = Exercises::fromVariantMap(it.value().toMap()).m_exercise; + ex.m_exercises.insert(key, e); + } + + ex.m_ok = map[QLatin1String("ok")].toBool(); + + return ex; + } - return ex; } - -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.h old mode 100755 new mode 100644 index b23b3d6d1..a0b9b14fb --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_exercises.h @@ -11,31 +11,31 @@ namespace EXCON { -class WMS_JSON_DS_EXPORT Exercises : public IBase -{ -public: - QJsonObject toJsonAll() const; - static Exercises fromJsonAll(const QJsonObject &map); - QJsonObject toJson(const IWMS2ECC::Exercise &ex) const; - static IWMS2ECC::Exercise fromJson(const QJsonObject &obj); + class WMS_JSON_DS_EXPORT Exercises : public IBase + { + public: + QJsonObject toJsonAll() const; + static Exercises fromJsonAll(const QJsonObject &map); + QJsonObject toJson(const IWMS2ECC::Exercise &ex) const; + static IWMS2ECC::Exercise fromJson(const QJsonObject &obj); - QVariantMap toVariantMapAll() const; - static Exercises fromVariantMapAll(const QVariantMap &map); - QVariantMap toVariantMap() const; - static Exercises fromVariantMap(const QVariantMap &map); + QVariantMap toVariantMapAll() const; + static Exercises fromVariantMapAll(const QVariantMap &map); + QVariantMap toVariantMap() const; + static Exercises fromVariantMap(const QVariantMap &map); - IWMS2ECC::Exercise getExercise() const { return m_exercise; } - IWMS2ECC::exerciseMap getExercises() const { return m_exercises; } - bool getOk() const { return m_ok; } + IWMS2ECC::Exercise getExercise() const { return m_exercise; } + IWMS2ECC::exerciseMap getExercises() const { return m_exercises; } + bool getOk() const { return m_ok; } - void setExercise(const IWMS2ECC::Exercise &exe) { m_exercise = exe; } - void setExercises(const IWMS2ECC::exerciseMap &exe) { m_exercises = exe; } - void setOk(bool ok) { m_ok = ok; } + void setExercise(const IWMS2ECC::Exercise &exe) { m_exercise = exe; } + void setExercises(const IWMS2ECC::exerciseMap &exe) { m_exercises = exe; } + void setOk(bool ok) { m_ok = ok; } -private: - IWMS2ECC::exerciseMap m_exercises; - mutable IWMS2ECC::Exercise m_exercise; - bool m_ok = false; -}; + private: + IWMS2ECC::exerciseMap m_exercises; + mutable IWMS2ECC::Exercise m_exercise; + bool m_ok = false; + }; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_ibase.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_ibase.h old mode 100755 new mode 100644 index f4866beb4..192a1f310 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_ibase.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_ibase.h @@ -10,6 +10,4 @@ class WMS_JSON_DS_EXPORT IBase public: IBase() = default; virtual ~IBase() = default; - }; - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.cpp old mode 100755 new mode 100644 index dd8432b63..415314932 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.cpp @@ -9,25 +9,25 @@ QJsonObject PlayerInfo::toJson(const IWMS2ECC::PlayerInfo &pi) { QJsonObject obj; - obj[QLatin1String("playerState")] = pi.playerState; - obj[QLatin1String("playerId")] = pi.playerId; - obj[QLatin1String("parentPlayerId")] = pi.parentPlayerId; - obj[QLatin1String("equipNo")] = pi.equipNo; - obj[QLatin1String("assignState")] = pi.assignState; - obj[QLatin1String("exerciseId")] = pi.exerciseId; - obj[QLatin1String("forceId")] = pi.forceId; - obj[QLatin1String("typeId")] = pi.typeId; - obj[QLatin1String("isDeleted")] = pi.isDeleted; - obj[QLatin1String("equipTypeId")] = pi.equipTypeId; - obj[QLatin1String("typeClassId")] = pi.typeClassId; - obj[QLatin1String("symbolColor")] = pi.symbolColor; - obj[QLatin1String("symbolPNG")] = QString::fromLatin1(pi.symbolPNG.toBase64()); - obj[QLatin1String("hierarchy")] = pi.hierarchy; - obj[QLatin1String("designator")] = pi.designator; - obj[QLatin1String("tactIdent")] = pi.tactIdent; - obj[QLatin1String("info")] = pi.info; - obj[QLatin1String("alias")] = pi.alias; - obj[QLatin1String("forceName")] = pi.forceName; + obj[QLatin1String("playerState")] = pi.playerState; + obj[QLatin1String("playerId")] = pi.playerId; + obj[QLatin1String("parentPlayerId")] = pi.parentPlayerId; + obj[QLatin1String("equipNo")] = pi.equipNo; + obj[QLatin1String("assignState")] = pi.assignState; + obj[QLatin1String("exerciseId")] = pi.exerciseId; + obj[QLatin1String("forceId")] = pi.forceId; + obj[QLatin1String("typeId")] = pi.typeId; + obj[QLatin1String("isDeleted")] = pi.isDeleted; + obj[QLatin1String("equipTypeId")] = pi.equipTypeId; + obj[QLatin1String("typeClassId")] = pi.typeClassId; + obj[QLatin1String("symbolColor")] = pi.symbolColor; + obj[QLatin1String("symbolPNG")] = QString::fromLatin1(pi.symbolPNG.toBase64()); + obj[QLatin1String("hierarchy")] = pi.hierarchy; + obj[QLatin1String("designator")] = pi.designator; + obj[QLatin1String("tactIdent")] = pi.tactIdent; + obj[QLatin1String("info")] = pi.info; + obj[QLatin1String("alias")] = pi.alias; + obj[QLatin1String("forceName")] = pi.forceName; return obj; } @@ -36,25 +36,25 @@ IWMS2ECC::PlayerInfo PlayerInfo::fromJson(const QJsonObject &obj) { IWMS2ECC::PlayerInfo pi; - pi.playerState = static_cast(obj[QLatin1String("playerState")].toInt()); - pi.playerId = obj[QLatin1String("playerId")].toInt(); + pi.playerState = static_cast(obj[QLatin1String("playerState")].toInt()); + pi.playerId = obj[QLatin1String("playerId")].toInt(); pi.parentPlayerId = obj[QLatin1String("parentPlayerId")].toInt(); - pi.equipNo = obj[QLatin1String("equipNo")].toInt(); - pi.assignState = static_cast(obj[QLatin1String("assignState")].toInt()); - pi.exerciseId = obj[QLatin1String("exerciseId")].toInt(); - pi.forceId = obj[QLatin1String("forceId")].toInt(); - pi.typeId = obj[QLatin1String("typeId")].toInt(); - pi.isDeleted = obj[QLatin1String("isDeleted")].toBool(); - pi.equipTypeId = obj[QLatin1String("equipTypeId")].toInt(); - pi.typeClassId = obj[QLatin1String("typeClassId")].toInt(); - pi.symbolColor = obj[QLatin1String("symbolColor")].toInt(); - pi.symbolPNG = QByteArray::fromBase64(obj[QLatin1String("symbolPNG")].toString().toLatin1()); - pi.hierarchy = obj[QLatin1String("hierarchy")].toString(); - pi.designator = obj[QLatin1String("designator")].toString(); - pi.tactIdent = obj[QLatin1String("tactIdent")].toString(); - pi.info = obj[QLatin1String("info")].toString(); - pi.alias = obj[QLatin1String("alias")].toString(); - pi.forceName = obj[QLatin1String("forceName")].toString(); + pi.equipNo = obj[QLatin1String("equipNo")].toInt(); + pi.assignState = static_cast(obj[QLatin1String("assignState")].toInt()); + pi.exerciseId = obj[QLatin1String("exerciseId")].toInt(); + pi.forceId = obj[QLatin1String("forceId")].toInt(); + pi.typeId = obj[QLatin1String("typeId")].toInt(); + pi.isDeleted = obj[QLatin1String("isDeleted")].toBool(); + pi.equipTypeId = obj[QLatin1String("equipTypeId")].toInt(); + pi.typeClassId = obj[QLatin1String("typeClassId")].toInt(); + pi.symbolColor = obj[QLatin1String("symbolColor")].toInt(); + pi.symbolPNG = QByteArray::fromBase64(obj[QLatin1String("symbolPNG")].toString().toLatin1()); + pi.hierarchy = obj[QLatin1String("hierarchy")].toString(); + pi.designator = obj[QLatin1String("designator")].toString(); + pi.tactIdent = obj[QLatin1String("tactIdent")].toString(); + pi.info = obj[QLatin1String("info")].toString(); + pi.alias = obj[QLatin1String("alias")].toString(); + pi.forceName = obj[QLatin1String("forceName")].toString(); return pi; } @@ -66,8 +66,8 @@ QJsonObject PlayerInfo::toJsonAll() const arr.append(toJson(pi)); QJsonObject retMap; - retMap[QLatin1String("piMap")] = arr; - retMap[QLatin1String("ok")] = m_ok; + retMap[QLatin1String("piMap")] = arr; + retMap[QLatin1String("ok")] = m_ok; return retMap; } @@ -92,25 +92,25 @@ PlayerInfo PlayerInfo::fromJsonAll(const QJsonObject &map) QVariantMap PlayerInfo::toVariantMap() const { QVariantMap retMap; - retMap[QLatin1String("playerId")] = QVariant(m_playerInfo.playerId); - retMap[QLatin1String("parentPlayerId")] = QVariant(m_playerInfo.parentPlayerId); - retMap[QLatin1String("equipNo")] = QVariant(m_playerInfo.equipNo); - retMap[QLatin1String("equipTypeId")] = QVariant(m_playerInfo.equipTypeId); - retMap[QLatin1String("typeClassId")] = QVariant(m_playerInfo.typeClassId); - retMap[QLatin1String("forceId")] = QVariant(m_playerInfo.forceId); - retMap[QLatin1String("designator")] = m_playerInfo.designator; - retMap[QLatin1String("tactIdent")] = m_playerInfo.tactIdent; - retMap[QLatin1String("hierarchy")] = m_playerInfo.hierarchy; - retMap[QLatin1String("forceName")] = m_playerInfo.forceName; - retMap[QLatin1String("info")] = m_playerInfo.info; - retMap[QLatin1String("alias")] = m_playerInfo.alias; - retMap[QLatin1String("symbolPNG")] = QVariant(m_playerInfo.symbolPNG); - retMap[QLatin1String("symbolColor")] = QVariant(m_playerInfo.symbolColor); + retMap[QLatin1String("playerId")] = QVariant(m_playerInfo.playerId); + retMap[QLatin1String("parentPlayerId")] = QVariant(m_playerInfo.parentPlayerId); + retMap[QLatin1String("equipNo")] = QVariant(m_playerInfo.equipNo); + retMap[QLatin1String("equipTypeId")] = QVariant(m_playerInfo.equipTypeId); + retMap[QLatin1String("typeClassId")] = QVariant(m_playerInfo.typeClassId); + retMap[QLatin1String("forceId")] = QVariant(m_playerInfo.forceId); + retMap[QLatin1String("designator")] = m_playerInfo.designator; + retMap[QLatin1String("tactIdent")] = m_playerInfo.tactIdent; + retMap[QLatin1String("hierarchy")] = m_playerInfo.hierarchy; + retMap[QLatin1String("forceName")] = m_playerInfo.forceName; + retMap[QLatin1String("info")] = m_playerInfo.info; + retMap[QLatin1String("alias")] = m_playerInfo.alias; + retMap[QLatin1String("symbolPNG")] = QVariant(m_playerInfo.symbolPNG); + retMap[QLatin1String("symbolColor")] = QVariant(m_playerInfo.symbolColor); - retMap[QLatin1String("assignState")] = QVariant(m_playerInfo.assignState); - retMap[QLatin1String("playerState")] = QVariant(m_playerInfo.playerState); + retMap[QLatin1String("assignState")] = QVariant(m_playerInfo.assignState); + retMap[QLatin1String("playerState")] = QVariant(m_playerInfo.playerState); - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } @@ -119,24 +119,24 @@ PlayerInfo PlayerInfo::fromVariantMap(const QVariantMap &map) { PlayerInfo pi; - pi.m_playerInfo.playerId = map[QLatin1String("playerId")].toInt(); + pi.m_playerInfo.playerId = map[QLatin1String("playerId")].toInt(); pi.m_playerInfo.parentPlayerId = map[QLatin1String("parentPlayerId")].toInt(); - pi.m_playerInfo.equipNo = map[QLatin1String("equipNo")].toInt(); - pi.m_playerInfo.forceId = map[QLatin1String("forceId")].toInt(); - pi.m_playerInfo.equipTypeId = map[QLatin1String("equipTypeId")].toInt(); - pi.m_playerInfo.typeClassId = map[QLatin1String("typeClassId")].toInt(); - pi.m_playerInfo.designator = map[QLatin1String("designator")].toString(); - pi.m_playerInfo.tactIdent = map[QLatin1String("tactIdent")].toString(); - pi.m_playerInfo.hierarchy = map[QLatin1String("hierarchy")].toString(); - pi.m_playerInfo.forceName = map[QLatin1String("forceName")].toString(); - pi.m_playerInfo.info = map[QLatin1String("info")].toString(); - pi.m_playerInfo.alias = map[QLatin1String("alias")].toString(); - pi.m_playerInfo.symbolPNG = map[QLatin1String("symbolPNG")].toByteArray(); - pi.m_playerInfo.symbolColor = map[QLatin1String("symbolColor")].toInt(); - pi.m_playerInfo.assignState = (IWMS2ECC::PlayerAssignState) map[QLatin1String("assignState")].toInt(); - pi.m_playerInfo.playerState = (IWMS2ECC::PlayerState) map[QLatin1String("playerState")].toInt(); + pi.m_playerInfo.equipNo = map[QLatin1String("equipNo")].toInt(); + pi.m_playerInfo.forceId = map[QLatin1String("forceId")].toInt(); + pi.m_playerInfo.equipTypeId = map[QLatin1String("equipTypeId")].toInt(); + pi.m_playerInfo.typeClassId = map[QLatin1String("typeClassId")].toInt(); + pi.m_playerInfo.designator = map[QLatin1String("designator")].toString(); + pi.m_playerInfo.tactIdent = map[QLatin1String("tactIdent")].toString(); + pi.m_playerInfo.hierarchy = map[QLatin1String("hierarchy")].toString(); + pi.m_playerInfo.forceName = map[QLatin1String("forceName")].toString(); + pi.m_playerInfo.info = map[QLatin1String("info")].toString(); + pi.m_playerInfo.alias = map[QLatin1String("alias")].toString(); + pi.m_playerInfo.symbolPNG = map[QLatin1String("symbolPNG")].toByteArray(); + pi.m_playerInfo.symbolColor = map[QLatin1String("symbolColor")].toInt(); + pi.m_playerInfo.assignState = (IWMS2ECC::PlayerAssignState)map[QLatin1String("assignState")].toInt(); + pi.m_playerInfo.playerState = (IWMS2ECC::PlayerState)map[QLatin1String("playerState")].toInt(); - pi.m_ok = map[QLatin1String("ok")].toBool(); + pi.m_ok = map[QLatin1String("ok")].toBool(); return pi; } @@ -146,13 +146,13 @@ QVariantMap PlayerInfo::toVariantMapAll() const QVariantMap vMap; for (const IWMS2ECC::PlayerInfo &pi : m_allPlayerInfo) { - m_playerInfo = pi; + m_playerInfo = pi; vMap.insert(QString::number(pi.playerId), QVariant(toVariantMap())); } QVariantMap retMap; - retMap[QLatin1String("plMap")] = QVariant(vMap); - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("plMap")] = QVariant(vMap); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } @@ -172,5 +172,3 @@ PlayerInfo PlayerInfo::fromVariantMapAll(const QVariantMap &map) players.m_ok = vMap[QLatin1String("ok")].toBool(); return players; } - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.h old mode 100755 new mode 100644 index 04ac9d794..5a4a79775 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_playerInfo.h @@ -34,7 +34,6 @@ public: private: QMap m_allPlayerInfo; - mutable IWMS2ECC::PlayerInfo m_playerInfo; - bool m_ok = false; + mutable IWMS2ECC::PlayerInfo m_playerInfo; + bool m_ok = false; }; - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.cpp old mode 100755 new mode 100644 index ba8633e98..74b7085b6 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.cpp @@ -8,17 +8,17 @@ QJsonObject Registration::toJson() const { QJsonObject obj; - obj[QLatin1String("playerId")] = m_playerId; + obj[QLatin1String("playerId")] = m_playerId; obj[QLatin1String("assignment")] = m_assignment; obj[QLatin1String("exerciseId")] = m_exerciseId; - obj[QLatin1String("ok")] = m_ok; + obj[QLatin1String("ok")] = m_ok; if (m_bEquipNoIsSet) - obj[QLatin1String("equipNo")] = m_equipNo; + obj[QLatin1String("equipNo")] = m_equipNo; if (m_bAliasIsSet) - obj[QLatin1String("alias")] = m_alias; + obj[QLatin1String("alias")] = m_alias; if (m_bInfoIsSet) - obj[QLatin1String("info")] = m_info; + obj[QLatin1String("info")] = m_info; return obj; } @@ -27,20 +27,20 @@ Registration Registration::fromJson(const QJsonObject &obj) { Registration rg; - rg.m_playerId = obj[QLatin1String("playerId")].toInt(); - rg.m_assignment = IWMS2ECC::int2PlayerAssignState(obj[QLatin1String("assignment")].toInt()); - rg.m_exerciseId = obj[QLatin1String("exerciseId")].toInt(); + rg.m_playerId = obj[QLatin1String("playerId")].toInt(); + rg.m_assignment = IWMS2ECC::int2PlayerAssignState(obj[QLatin1String("assignment")].toInt()); + rg.m_exerciseId = obj[QLatin1String("exerciseId")].toInt(); rg.m_bEquipNoIsSet = obj.contains(QLatin1String("equipNo")); if (rg.m_bEquipNoIsSet) rg.m_equipNo = obj[QLatin1String("equipNo")].toInt(); - rg.m_bAliasIsSet = obj.contains(QLatin1String("alias")); + rg.m_bAliasIsSet = obj.contains(QLatin1String("alias")); if (rg.m_bAliasIsSet) rg.m_alias = obj[QLatin1String("alias")].toString(); - rg.m_bInfoIsSet = obj.contains(QLatin1String("info")); + rg.m_bInfoIsSet = obj.contains(QLatin1String("info")); if (rg.m_bInfoIsSet) - rg.m_info = obj[QLatin1String("info")].toString(); - rg.m_ok = obj[QLatin1String("ok")].toBool(); + rg.m_info = obj[QLatin1String("info")].toString(); + rg.m_ok = obj[QLatin1String("ok")].toBool(); return rg; } @@ -50,18 +50,18 @@ QVariantMap Registration::toVariantMap() const { QVariantMap retMap; - retMap[QLatin1String("playerId")] = QVariant(m_playerId); + retMap[QLatin1String("playerId")] = QVariant(m_playerId); retMap[QLatin1String("assignment")] = QVariant(m_assignment); retMap[QLatin1String("exerciseId")] = QVariant(m_exerciseId); if (m_bEquipNoIsSet) - retMap[QLatin1String("equipNo")] = QVariant(m_equipNo); + retMap[QLatin1String("equipNo")] = QVariant(m_equipNo); if (m_bAliasIsSet) - retMap[QLatin1String("alias")] = m_alias; + retMap[QLatin1String("alias")] = m_alias; if (m_bInfoIsSet) - retMap[QLatin1String("info")] = m_info; + retMap[QLatin1String("info")] = m_info; - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } @@ -70,20 +70,20 @@ Registration Registration::fromVariantMap(const QVariantMap &map) { Registration rg; - rg.m_playerId = map[QLatin1String("playerId")].toInt(); - rg.m_assignment = IWMS2ECC::int2PlayerAssignState(map[QLatin1String("assignment")].toInt()); - rg.m_exerciseId = map[QLatin1String("exerciseId")].toInt(); - rg.m_ok = map[QLatin1String("ok")].toBool(); + rg.m_playerId = map[QLatin1String("playerId")].toInt(); + rg.m_assignment = IWMS2ECC::int2PlayerAssignState(map[QLatin1String("assignment")].toInt()); + rg.m_exerciseId = map[QLatin1String("exerciseId")].toInt(); + rg.m_ok = map[QLatin1String("ok")].toBool(); rg.m_bEquipNoIsSet = map.contains(QLatin1String("equipNo")); if (rg.m_bEquipNoIsSet) - rg.m_equipNo = map[QLatin1String("equipNo")].toInt(); - rg.m_bAliasIsSet = map.contains(QLatin1String("alias")); + rg.m_equipNo = map[QLatin1String("equipNo")].toInt(); + rg.m_bAliasIsSet = map.contains(QLatin1String("alias")); if (rg.m_bAliasIsSet) - rg.m_alias = map[QLatin1String("alias")].toString(); - rg.m_bInfoIsSet = map.contains(QLatin1String("info")); + rg.m_alias = map[QLatin1String("alias")].toString(); + rg.m_bInfoIsSet = map.contains(QLatin1String("info")); if (rg.m_bInfoIsSet) - rg.m_info = map[QLatin1String("info")].toString(); + rg.m_info = map[QLatin1String("info")].toString(); return rg; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.h old mode 100755 new mode 100644 index ec943e4ab..493b21ad0 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_registration.h @@ -19,37 +19,48 @@ public: QVariantMap toVariantMap() const; static Registration fromVariantMap(const QVariantMap &map); - int getPlayerId() const { return m_playerId; } - int getEquipNo() const { return m_equipNo; } + int getPlayerId() const { return m_playerId; } + int getEquipNo() const { return m_equipNo; } int getExerciseId() const { return m_exerciseId; } - QString getAlias() const { return m_alias; } - QString getInfo() const { return m_info; } + QString getAlias() const { return m_alias; } + QString getInfo() const { return m_info; } bool isEquipNoSet() const { return m_bEquipNoIsSet; } - bool isAliasSet() const { return m_bAliasIsSet; } - bool isInfoSet() const { return m_bInfoIsSet; } + bool isAliasSet() const { return m_bAliasIsSet; } + bool isInfoSet() const { return m_bInfoIsSet; } IWMS2ECC::PlayerAssignState getAssignment() const { return m_assignment; } bool getOk() const { return m_ok; } void setPlayerId(int playerId) { m_playerId = playerId; } - void setEquipNo(int equipNo) { m_equipNo = equipNo; m_bEquipNoIsSet = true; } + void setEquipNo(int equipNo) + { + m_equipNo = equipNo; + m_bEquipNoIsSet = true; + } void setAssignment(IWMS2ECC::PlayerAssignState assignment) { m_assignment = assignment; } void setExerciseId(int exerciseId) { m_exerciseId = exerciseId; } - void setAlias(const QString &alias) { m_alias = alias; m_bAliasIsSet = true; } - void setInfo(const QString &info) { m_info = info; m_bInfoIsSet = true; } + void setAlias(const QString &alias) + { + m_alias = alias; + m_bAliasIsSet = true; + } + void setInfo(const QString &info) + { + m_info = info; + m_bInfoIsSet = true; + } void setOk(bool ok) { m_ok = ok; } private: - QString m_alias; - QString m_info; + QString m_alias; + QString m_info; IWMS2ECC::PlayerAssignState m_assignment = IWMS2ECC::UNDEFINED; - int m_playerId = 0; - int m_equipNo = 0; - int m_exerciseId = -1; - bool m_bEquipNoIsSet = false; - bool m_bAliasIsSet = false; - bool m_bInfoIsSet = false; - bool m_ok = false; + int m_playerId = 0; + int m_equipNo = 0; + int m_exerciseId = -1; + bool m_bEquipNoIsSet = false; + bool m_bAliasIsSet = false; + bool m_bInfoIsSet = false; + bool m_ok = false; }; - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.cpp b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.cpp old mode 100755 new mode 100644 index cc3df3944..b9ed900d6 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.cpp @@ -8,9 +8,9 @@ QJsonObject Unregister::toJson() const { QJsonObject obj; - obj[QLatin1String("equipNo")] = m_equipNo; - obj[QLatin1String("exerciseId")] = m_exerciseId; - obj[QLatin1String("ok")] = m_ok; + obj[QLatin1String("equipNo")] = m_equipNo; + obj[QLatin1String("exerciseId")] = m_exerciseId; + obj[QLatin1String("ok")] = m_ok; return obj; } @@ -19,9 +19,9 @@ Unregister Unregister::fromJson(const QJsonObject &obj) { Unregister ur; - ur.m_equipNo = obj[QLatin1String("equipNo")].toInt(); - ur.m_exerciseId = obj[QLatin1String("exerciseId")].toInt(); - ur.m_ok = obj[QLatin1String("ok")].toBool(); + ur.m_equipNo = obj[QLatin1String("equipNo")].toInt(); + ur.m_exerciseId = obj[QLatin1String("exerciseId")].toInt(); + ur.m_ok = obj[QLatin1String("ok")].toBool(); return ur; } @@ -30,9 +30,9 @@ QVariantMap Unregister::toVariantMap() const { QVariantMap retMap; - retMap[QLatin1String("equipNo")] = QVariant(m_equipNo); - retMap[QLatin1String("exerciseId")] = QVariant(m_exerciseId); - retMap[QLatin1String("ok")] = QVariant(m_ok); + retMap[QLatin1String("equipNo")] = QVariant(m_equipNo); + retMap[QLatin1String("exerciseId")] = QVariant(m_exerciseId); + retMap[QLatin1String("ok")] = QVariant(m_ok); return retMap; } @@ -41,10 +41,9 @@ Unregister Unregister::fromVariantMap(const QVariantMap &map) { Unregister ur; - ur.m_equipNo = map[QLatin1String("equipNo")].toInt(); - ur.m_exerciseId = map[QLatin1String("exerciseId")].toInt(); - ur.m_ok = map[QLatin1String("ok")].toBool(); + ur.m_equipNo = map[QLatin1String("equipNo")].toInt(); + ur.m_exerciseId = map[QLatin1String("exerciseId")].toInt(); + ur.m_ok = map[QLatin1String("ok")].toBool(); return ur; } - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.h b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.h old mode 100755 new mode 100644 index 51cfdd63b..6f69a2e66 --- a/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/WMS_Interface/wms_ecc_unregister.h @@ -26,7 +26,7 @@ public: void setOk(bool ok) { m_ok = ok; } private: - int m_equipNo = 0; - int m_exerciseId = -1; - bool m_ok = false; + int m_equipNo = 0; + int m_exerciseId = -1; + bool m_ok = false; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.cpp old mode 100755 new mode 100644 index 5fbb4d19d..e70aae3e7 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.cpp @@ -3,8 +3,8 @@ #include "ngl_signal_handler.inc" NGLApplication::NGLApplication(int &argc, char **argv) - : QApplication(argc, argv) -{ + : QApplication(argc, argv) +{ signal(SIGTERM, &signalHandler); #ifdef Q_OS_WIN installNativeEventFilter(new MyEventFilter); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.h old mode 100755 new mode 100644 index bdfaaf2f0..24daa2bcc --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglapplication.h @@ -6,23 +6,25 @@ #include "nglloggerhandler.h" #ifndef NGLAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLAPPLICATION_EXPORT -# else -# ifdef MAKE_NGLAPPLICATION_LIB -# define NGLAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define NGLAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLAPPLICATION_EXPORT +#else +#ifdef MAKE_NGLAPPLICATION_LIB +#define NGLAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define NGLAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; } -class NGLAPPLICATION_EXPORT NGLApplication : public QApplication, public NGL::LoggerHandler +class NGLAPPLICATION_EXPORT NGLApplication + : public QApplication + , public NGL::LoggerHandler { Q_OBJECT @@ -33,4 +35,4 @@ protected: bool notify(QObject *o, QEvent *e) override; }; -#define nglApp static_cast(NGLApplication::instance()) +#define nglApp static_cast(NGLApplication::instance()) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.cpp old mode 100755 new mode 100644 index 411d1b882..9043a670d --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.cpp @@ -2,8 +2,8 @@ #include "ngl_signal_handler.inc" NGLCoreApplication::NGLCoreApplication(int &argc, char **argv) - : QCoreApplication(argc, argv) -{ + : QCoreApplication(argc, argv) +{ signal(SIGTERM, &signalHandler); #ifdef Q_OS_WIN installNativeEventFilter(new MyEventFilter); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.h old mode 100755 new mode 100644 index 181f11c3b..fb588ccfa --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglcoreapplication.h @@ -4,23 +4,25 @@ #include "nglloggerhandler.h" #ifndef NGLCOREAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLCOREAPPLICATION_EXPORT -# else -# ifdef MAKE_NGLCOREAPPLICATION_LIB -# define NGLCOREAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define NGLCOREAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLCOREAPPLICATION_EXPORT +#else +#ifdef MAKE_NGLCOREAPPLICATION_LIB +#define NGLCOREAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define NGLCOREAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; } -class NGLCOREAPPLICATION_EXPORT NGLCoreApplication : public QCoreApplication, public NGL::LoggerHandler +class NGLCOREAPPLICATION_EXPORT NGLCoreApplication + : public QCoreApplication + , public NGL::LoggerHandler { Q_OBJECT diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.cpp old mode 100755 new mode 100644 index f0cb20a42..c50a20978 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.cpp @@ -2,8 +2,8 @@ #include "ngl_signal_handler.inc" NGLGuiApplication::NGLGuiApplication(int &argc, char **argv) - : QGuiApplication(argc, argv) -{ + : QGuiApplication(argc, argv) +{ signal(SIGTERM, &signalHandler); #ifdef Q_OS_WIN installNativeEventFilter(new MyEventFilter); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.h old mode 100755 new mode 100644 index 92a5e63b8..395ae0e34 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglguiapplication.h @@ -4,23 +4,25 @@ #include "nglloggerhandler.h" #ifndef NGLGUIAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLGUIAPPLICATION_EXPORT -# else -# ifdef MAKE_NGLGUIAPPLICATION_LIB -# define NGLGUIAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define NGLGUIAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLGUIAPPLICATION_EXPORT +#else +#ifdef MAKE_NGLGUIAPPLICATION_LIB +#define NGLGUIAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define NGLGUIAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; } -class NGLGUIAPPLICATION_EXPORT NGLGuiApplication : public QGuiApplication, public NGL::LoggerHandler +class NGLGUIAPPLICATION_EXPORT NGLGuiApplication + : public QGuiApplication + , public NGL::LoggerHandler { Q_OBJECT @@ -28,4 +30,4 @@ public: NGLGuiApplication(int &argc, char **argv); }; -#define nglGuiApp static_cast(NGLGuiApplication::instance()) +#define nglGuiApp static_cast(NGLGuiApplication::instance()) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.cpp old mode 100755 new mode 100644 index e02a8e337..da6a2960a --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.cpp @@ -7,72 +7,72 @@ namespace NGL { -static QByteArray username() -{ + static QByteArray username() + { #ifdef Q_OS_WIN - return qgetenv("USERNAME"); + return qgetenv("USERNAME"); #else - return qgetenv("USER"); + return qgetenv("USER"); #endif + } + + static void setEnvVars() + { + const QString logPath = NGL::Settings::logPath(); + qputenv("LOG4QT_LOGDIR", logPath.toLocal8Bit()); + qputenv("LOG4QT_USER", username()); + } + + void LoggerHandler::createLogger(const QByteArray &baseName, const char *configFileName, bool quiet) + { + setEnvVars(); + m_baseLoggerName = baseName; + + const QString bnStr(QString::fromLatin1(baseName.toLower())); + const QString logPath = NGL::Settings::logPath(); + m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr; + m_loggerFilenamePrefix = QLatin1String(".log"); + + const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix; + NGL::NGLLoggerBootstrap::createNGLRootLogger(QString::fromLatin1(configFileName), false, logOutputName, quiet); + + qInstallMessageHandler(&qtMsgHandler); + } + + void LoggerHandler::createLogger(const QByteArray &baseName, int exerciseId, int additionalId, bool quiet) + { + setEnvVars(); + + const QString bnStr(QString::fromLatin1(baseName.toLower())); + const QString configFileName = QLatin1String("log4cxx_") + bnStr + QLatin1String(".props"); + const QString logPath = NGL::Settings::logPath(); + m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr; + if (exerciseId > 0) + m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(exerciseId); + if (additionalId > 0) + m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(additionalId); + + m_loggerFilenamePrefix = QLatin1String(".log"); + m_baseLoggerName = baseName + QByteArray(".main"); + + const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix; + NGL::NGLLoggerBootstrap::createNGLRootLogger(configFileName, false, logOutputName, quiet); + qInstallMessageHandler(&qtMsgHandler); + } + + NGL::INGLLogger &LoggerHandler::baseLogger() const + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(m_baseLoggerName.data()); + } + + NGL::INGLLogger &LoggerHandler::logger(const char *loggerName) const + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + + LoggerHandler *LoggerHandler::getLoggerHandler() + { + return dynamic_cast(QCoreApplication::instance()); + } + } - -static void setEnvVars() -{ - const QString logPath = NGL::Settings::logPath(); - qputenv("LOG4QT_LOGDIR", logPath.toLocal8Bit()); - qputenv("LOG4QT_USER", username()); -} - -void LoggerHandler::createLogger(const QByteArray &baseName, const char *configFileName, bool quiet) -{ - setEnvVars(); - m_baseLoggerName = baseName; - - const QString bnStr(QString::fromLatin1(baseName.toLower())); - const QString logPath = NGL::Settings::logPath(); - m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr; - m_loggerFilenamePrefix = QLatin1String(".log"); - - const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix; - NGL::NGLLoggerBootstrap::createNGLRootLogger(QString::fromLatin1(configFileName), false, logOutputName, quiet); - - qInstallMessageHandler(&qtMsgHandler); -} - -void LoggerHandler::createLogger(const QByteArray &baseName, int exerciseId, int additionalId, bool quiet) -{ - setEnvVars(); - - const QString bnStr(QString::fromLatin1(baseName.toLower())); - const QString configFileName = QLatin1String("log4cxx_") + bnStr + QLatin1String(".props"); - const QString logPath = NGL::Settings::logPath(); - m_loggerFilenamePostfix = logPath + QLatin1Char('/') + QString::fromLocal8Bit(username()) + QLatin1Char('_') + bnStr; - if (exerciseId > 0) - m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(exerciseId); - if (additionalId > 0) - m_loggerFilenamePostfix += QLatin1Char('_') + QString::number(additionalId); - - m_loggerFilenamePrefix = QLatin1String(".log"); - m_baseLoggerName = baseName + QByteArray(".main"); - - const QString logOutputName = m_loggerFilenamePostfix + m_loggerFilenamePrefix; - NGL::NGLLoggerBootstrap::createNGLRootLogger(configFileName, false, logOutputName, quiet); - qInstallMessageHandler(&qtMsgHandler); -} - -NGL::INGLLogger &LoggerHandler::baseLogger() const -{ - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(m_baseLoggerName.data()); -} - -NGL::INGLLogger &LoggerHandler::logger(const char *loggerName) const -{ - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); -} - -LoggerHandler *LoggerHandler::getLoggerHandler() -{ - return dynamic_cast(QCoreApplication::instance()); -} - -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.h old mode 100755 new mode 100644 index fd92a8ebf..45c618854 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglloggerhandler.h @@ -6,62 +6,52 @@ #include #ifndef LOGGERHANDLER_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LOGGERHANDLER_EXPORT -# else -# if defined(MAKE_NGLCOREAPPLICATION_LIB) || defined(MAKE_NGLGUIAPPLICATION_LIB) || defined(MAKE_NGLAPPLICATION_LIB) || defined(MAKE_NGLSINGLECOREAPPLICATION_LIB) || defined(MAKE_NGLSINGLEAPPLICATION_LIB) -# define LOGGERHANDLER_EXPORT Q_DECL_EXPORT -# else -# define LOGGERHANDLER_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LOGGERHANDLER_EXPORT +#else +#if defined(MAKE_NGLCOREAPPLICATION_LIB) || defined(MAKE_NGLGUIAPPLICATION_LIB) || defined(MAKE_NGLAPPLICATION_LIB) || defined(MAKE_NGLSINGLECOREAPPLICATION_LIB) || \ + defined(MAKE_NGLSINGLEAPPLICATION_LIB) +#define LOGGERHANDLER_EXPORT Q_DECL_EXPORT +#else +#define LOGGERHANDLER_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; -class LOGGERHANDLER_EXPORT LoggerHandler -{ -public: - LoggerHandler() = default; - ~LoggerHandler() = default; + class LOGGERHANDLER_EXPORT LoggerHandler + { + public: + LoggerHandler() = default; + ~LoggerHandler() = default; - - void createLogger(const QByteArray &baseName, - const char *configFileName, - bool quiet = false); + void createLogger(const QByteArray &baseName, const char *configFileName, bool quiet = false); - - void createLogger(const QByteArray &baseName, - int exerciseId = 0, - int additionalId = 0, - bool quiet = false); + void createLogger(const QByteArray &baseName, int exerciseId = 0, int additionalId = 0, bool quiet = false); - - NGL::INGLLogger &baseLogger() const; + NGL::INGLLogger &baseLogger() const; - - NGL::INGLLogger &logger(const char *loggerName) const; + NGL::INGLLogger &logger(const char *loggerName) const; - - QString loggerNamePostfix() const { return m_loggerFilenamePostfix; } + QString loggerNamePostfix() const { return m_loggerFilenamePostfix; } - - QString loggerNamePrefix() const { return m_loggerFilenamePrefix; } + QString loggerNamePrefix() const { return m_loggerFilenamePrefix; } - - static LoggerHandler *getLoggerHandler(); -private: - QByteArray m_baseLoggerName; - QString m_loggerFilenamePostfix; - QString m_loggerFilenamePrefix; -}; -} + static LoggerHandler *getLoggerHandler(); + + private: + QByteArray m_baseLoggerName; + QString m_loggerFilenamePostfix; + QString m_loggerFilenamePrefix; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.cpp old mode 100755 new mode 100644 index 99ecc2482..357c3c35d --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.cpp @@ -7,9 +7,9 @@ NGLSingleApplication::NGLSingleApplication(int &argc, char **argv) - : QtSingleApplication(argc, argv) + : QtSingleApplication(argc, argv) { - + signal(SIGTERM, &signalHandler); #ifdef Q_OS_WIN installNativeEventFilter(new MyEventFilter); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.h old mode 100755 new mode 100644 index 1f83cd5ed..2066ba9ea --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsingleapplication.h @@ -5,23 +5,25 @@ #include "nglloggerhandler.h" #ifndef NGLSINGLEAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLSINGLEAPPLICATION_EXPORT -# else -# ifdef MAKE_NGLSINGLEAPPLICATION_LIB -# define NGLSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define NGLSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLSINGLEAPPLICATION_EXPORT +#else +#ifdef MAKE_NGLSINGLEAPPLICATION_LIB +#define NGLSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define NGLSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; } -class NGLSINGLEAPPLICATION_EXPORT NGLSingleApplication : public QtSingleApplication, public NGL::LoggerHandler +class NGLSINGLEAPPLICATION_EXPORT NGLSingleApplication + : public QtSingleApplication + , public NGL::LoggerHandler { Q_OBJECT @@ -32,4 +34,4 @@ protected: bool notify(QObject *o, QEvent *e) override; }; -#define nglApp static_cast(NGLSingleApplication::instance()) +#define nglApp static_cast(NGLSingleApplication::instance()) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.cpp old mode 100755 new mode 100644 index 9530bd3d3..4d5613452 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.cpp @@ -2,8 +2,8 @@ #include "ngl_signal_handler.inc" NGLSingleCoreApplication::NGLSingleCoreApplication(int &argc, char **argv) - : QtSingleCoreApplication(argc, argv) -{ + : QtSingleCoreApplication(argc, argv) +{ signal(SIGTERM, &signalHandler); #ifdef Q_OS_WIN installNativeEventFilter(new MyEventFilter); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.h b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.h old mode 100755 new mode 100644 index 491237374..7cbbbee6d --- a/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglapplication/nglsinglecoreapplication.h @@ -4,23 +4,25 @@ #include "nglloggerhandler.h" #ifndef NGLSINGLECOREAPPLICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLSINGLECOREAPPLICATION_EXPORT -# else -# ifdef MAKE_NGLSINGLECOREAPPLICATION_LIB -# define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_EXPORT -# else -# define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLSINGLECOREAPPLICATION_EXPORT +#else +#ifdef MAKE_NGLSINGLECOREAPPLICATION_LIB +#define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_EXPORT +#else +#define NGLSINGLECOREAPPLICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif namespace NGL { -class INGLLogger; + class INGLLogger; } -class NGLSINGLECOREAPPLICATION_EXPORT NGLSingleCoreApplication : public QtSingleCoreApplication, public NGL::LoggerHandler +class NGLSINGLECOREAPPLICATION_EXPORT NGLSingleCoreApplication + : public QtSingleCoreApplication + , public NGL::LoggerHandler { Q_OBJECT diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp index 6e30157a7..604978f62 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp @@ -10,336 +10,344 @@ class BZip2IODevice::Private { - public: - Private(BZip2IODevice* parent_, QIODevice* dev, int bs) - : parent(parent_), device(dev), iCurPos(0), iMaxBufSize(1024 * 1024), blocksize(bs), initialized(false), - decomressStreamEnd(false) - { - buffer.resize(iMaxBufSize); - } +public: + Private(BZip2IODevice *parent_, QIODevice *dev, int bs) + : parent(parent_) + , device(dev) + , iCurPos(0) + , iMaxBufSize(1024 * 1024) + , blocksize(bs) + , initialized(false) + , decomressStreamEnd(false) + { + buffer.resize(iMaxBufSize); + } - bool initializeCompress(); - qint64 doCompress(const char* in, qint64 iMaxLen); - bool finishCompress(); - bool initializeDecompress(); - qint64 doDecompress(char* out, qint64 iMaxLen); - bool finishDecompress(); - static QString bzipError2String(int errCode); + bool initializeCompress(); + qint64 doCompress(const char *in, qint64 iMaxLen); + bool finishCompress(); + bool initializeDecompress(); + qint64 doDecompress(char *out, qint64 iMaxLen); + bool finishDecompress(); + static QString bzipError2String(int errCode); - QAtomicInt aborted{0}; - BZip2IODevice* parent; - QIODevice* device; - unsigned int iCurPos; - unsigned int iMaxBufSize; - unsigned int blocksize; - bool initialized; - bool decomressStreamEnd; - QByteArray buffer; - bz_stream stream; + QAtomicInt aborted{0}; + BZip2IODevice *parent; + QIODevice *device; + unsigned int iCurPos; + unsigned int iMaxBufSize; + unsigned int blocksize; + bool initialized; + bool decomressStreamEnd; + QByteArray buffer; + bz_stream stream; }; bool BZip2IODevice::Private::initializeCompress() { - if (initialized) - return true; - memset(&stream, 0, sizeof(stream)); - int blockSize = (blocksize > 0 && blocksize < 10) ? blocksize : 10; - int ret = BZ2_bzCompressInit(&stream, blockSize, 0, 0); - if (ret != BZ_OK) - { - parent->setErrorString(QStringLiteral("Error initializing bzip2 %1").arg(bzipError2String(ret))); - initialized = false; - } - else - initialized = true; + if (initialized) + return true; + memset(&stream, 0, sizeof(stream)); + int blockSize = (blocksize > 0 && blocksize < 10) ? blocksize : 10; + int ret = BZ2_bzCompressInit(&stream, blockSize, 0, 0); + if (ret != BZ_OK) + { + parent->setErrorString(QStringLiteral("Error initializing bzip2 %1").arg(bzipError2String(ret))); + initialized = false; + } + else + initialized = true; - return initialized; + return initialized; } -qint64 BZip2IODevice::Private::doCompress(const char* in, qint64 iMaxLen) +qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen) { - if (!initialized) + if (!initialized) + { + if (parent->errorString().isEmpty()) + parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); + finishCompress(); + return -1; + } + if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + { + finishCompress(); + parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); + return -1; + } + + stream.next_in = const_cast(in); + stream.avail_in = iMaxLen; + + do + { + if (aborted) + return 0; + + stream.next_out = buffer.data(); + stream.avail_out = buffer.size(); + + const int ret = BZ2_bzCompress(&stream, BZ_RUN); + if (ret != BZ_RUN_OK) { - if (parent->errorString().isEmpty()) - parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); - finishCompress(); - return -1; + finishCompress(); + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + return -1; } - if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + int iBytesToWrite = buffer.size() - stream.avail_out; + if (iBytesToWrite) { + if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) + { finishCompress(); - parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); + parent->setErrorString(QLatin1String("Error writing to QIODevice")); return -1; + } } + } while (stream.avail_in != 0); - stream.next_in = const_cast(in); - stream.avail_in = iMaxLen; - - do - { - if (aborted) - return 0; - - stream.next_out = buffer.data(); - stream.avail_out = buffer.size(); - - const int ret = BZ2_bzCompress(&stream, BZ_RUN); - if (ret != BZ_RUN_OK) - { - finishCompress(); - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - return -1; - } - int iBytesToWrite = buffer.size() - stream.avail_out; - if (iBytesToWrite) - { - if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) - { - finishCompress(); - parent->setErrorString(QLatin1String("Error writing to QIODevice")); - return -1; - } - } - } while (stream.avail_in != 0); - - return stream.next_in - in; + return stream.next_in - in; } bool BZip2IODevice::Private::finishCompress() { - if (!initialized || aborted) - return true; - - int ret = -1; - - do - { - stream.next_out = buffer.data(); - stream.avail_out = buffer.size(); - ret = BZ2_bzCompress(&stream, BZ_FINISH); - if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) - { - finishCompress(); - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - return false; - } - int iBytesToWrite = buffer.size() - stream.avail_out; - if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) - { - finishCompress(); - parent->setErrorString(QLatin1String("Error writing to QIODevice")); - return false; - } - } while (ret != BZ_STREAM_END); - BZ2_bzCompressEnd(&stream); - - initialized = false; + if (!initialized || aborted) return true; + + int ret = -1; + + do + { + stream.next_out = buffer.data(); + stream.avail_out = buffer.size(); + ret = BZ2_bzCompress(&stream, BZ_FINISH); + if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) + { + finishCompress(); + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + return false; + } + int iBytesToWrite = buffer.size() - stream.avail_out; + if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) + { + finishCompress(); + parent->setErrorString(QLatin1String("Error writing to QIODevice")); + return false; + } + } while (ret != BZ_STREAM_END); + BZ2_bzCompressEnd(&stream); + + initialized = false; + return true; } bool BZip2IODevice::Private::initializeDecompress() { - if (initialized) - return true; - memset(&stream, 0, sizeof(stream)); - int ret = BZ2_bzDecompressInit(&stream, 0, 0); - if (ret != BZ_OK) - { - parent->setErrorString(QStringLiteral("Error initializing bzip2: %1").arg(bzipError2String(ret))); - initialized = false; - } - else - initialized = true; - decomressStreamEnd = false; - return initialized; + if (initialized) + return true; + memset(&stream, 0, sizeof(stream)); + int ret = BZ2_bzDecompressInit(&stream, 0, 0); + if (ret != BZ_OK) + { + parent->setErrorString(QStringLiteral("Error initializing bzip2: %1").arg(bzipError2String(ret))); + initialized = false; + } + else + initialized = true; + decomressStreamEnd = false; + return initialized; } -qint64 BZip2IODevice::Private::doDecompress(char* out, qint64 iMaxLen) +qint64 BZip2IODevice::Private::doDecompress(char *out, qint64 iMaxLen) { - int ret = -1; - if (!initialized) - { - if (parent->errorString().isEmpty()) - parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); - finishDecompress(); - return -1; - } - if (decomressStreamEnd) - return 0; + int ret = -1; + if (!initialized) + { + if (parent->errorString().isEmpty()) + parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); + finishDecompress(); + return -1; + } + if (decomressStreamEnd) + return 0; - if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + { + finishCompress(); + parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); + return -1; + } + + stream.next_out = out; + stream.avail_out = iMaxLen; + + do + { + if (ret != BZ_STREAM_END && stream.avail_in == 0) { - finishCompress(); - parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); + qint64 iReadCnt = device->read(buffer.data(), buffer.size()); + if (iReadCnt <= 0) return -1; + stream.next_in = buffer.data(); + stream.avail_in = iReadCnt; } - stream.next_out = out; - stream.avail_out = iMaxLen; - - do + ret = BZ2_bzDecompress(&stream); + if (ret != BZ_OK && ret != BZ_STREAM_END) { - if (ret != BZ_STREAM_END && stream.avail_in == 0) - { - qint64 iReadCnt = device->read(buffer.data(), buffer.size()); - if (iReadCnt <= 0) - return -1; - stream.next_in = buffer.data(); - stream.avail_in = iReadCnt; - } - - ret = BZ2_bzDecompress(&stream); - if (ret != BZ_OK && ret != BZ_STREAM_END) - { - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - finishDecompress(); - return -1; - } - } while (stream.avail_out != 0 && ret != BZ_STREAM_END); - decomressStreamEnd = (ret == BZ_STREAM_END); - return stream.next_out - out; + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + finishDecompress(); + return -1; + } + } while (stream.avail_out != 0 && ret != BZ_STREAM_END); + decomressStreamEnd = (ret == BZ_STREAM_END); + return stream.next_out - out; } bool BZip2IODevice::Private::finishDecompress() { - if (!initialized) - return true; - BZ2_bzDecompressEnd(&stream); - - initialized = false; + if (!initialized) return true; + BZ2_bzDecompressEnd(&stream); + + initialized = false; + return true; } QString BZip2IODevice::Private::bzipError2String(int errCode) { - switch (errCode) - { - case BZ_SEQUENCE_ERROR: - return QLatin1String("Sequence error"); - case BZ_PARAM_ERROR: - return QLatin1String("Parameter not correct"); - case BZ_MEM_ERROR: - return QLatin1String("Memory allocation error"); - case BZ_DATA_ERROR: - return QLatin1String("Invalid input data"); - case BZ_DATA_ERROR_MAGIC: - return QLatin1String("Not a bzip2 file"); - case BZ_IO_ERROR: - return QLatin1String("I/O error"); - case BZ_UNEXPECTED_EOF: - return QLatin1String("Unexpected end of file"); - case BZ_OUTBUFF_FULL: - return QLatin1String("Output buffer full"); - case BZ_CONFIG_ERROR: - return QLatin1String("Wrong config parameter"); - }; - return QString::number(errCode); + switch (errCode) + { + case BZ_SEQUENCE_ERROR: + return QLatin1String("Sequence error"); + case BZ_PARAM_ERROR: + return QLatin1String("Parameter not correct"); + case BZ_MEM_ERROR: + return QLatin1String("Memory allocation error"); + case BZ_DATA_ERROR: + return QLatin1String("Invalid input data"); + case BZ_DATA_ERROR_MAGIC: + return QLatin1String("Not a bzip2 file"); + case BZ_IO_ERROR: + return QLatin1String("I/O error"); + case BZ_UNEXPECTED_EOF: + return QLatin1String("Unexpected end of file"); + case BZ_OUTBUFF_FULL: + return QLatin1String("Output buffer full"); + case BZ_CONFIG_ERROR: + return QLatin1String("Wrong config parameter"); + }; + return QString::number(errCode); } -BZip2IODevice::BZip2IODevice(QIODevice* dev, int blocksize) : d(new Private(this, dev, blocksize)) {} +BZip2IODevice::BZip2IODevice(QIODevice *dev, int blocksize) + : d(new Private(this, dev, blocksize)) +{ +} BZip2IODevice::~BZip2IODevice() { - close(); - delete d; + close(); + delete d; } void BZip2IODevice::setBufferSize(unsigned int size) { - d->iMaxBufSize = size > 1024 ? size : 1024; - d->buffer.resize(d->iMaxBufSize); + d->iMaxBufSize = size > 1024 ? size : 1024; + d->buffer.resize(d->iMaxBufSize); } void BZip2IODevice::setBlockSize(unsigned int size) { - if (isOpen()) - return; - d->blocksize = size; + if (isOpen()) + return; + d->blocksize = size; } bool BZip2IODevice::isSequential() const { - return true; + return true; } bool BZip2IODevice::open(OpenMode mode) { - if ((mode & QIODevice::ReadWrite) == 0) + if ((mode & QIODevice::ReadWrite) == 0) + { + setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(static_cast(mode))); + return false; + } + if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) + { + setErrorString(QLatin1String("Can't read and write simultaniously")); + return false; + } + if ((mode & QIODevice::ReadOnly) == QIODevice::ReadOnly) + { + if (!d->device) { - setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(static_cast(mode))); - return false; + setErrorString(QLatin1String("No QIODevice for reading available")); + return false; } - if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) + if ((d->device->openMode() & QIODevice::ReadOnly) == 0) { - setErrorString(QLatin1String("Can't read and write simultaniously")); - return false; + setErrorString(QLatin1String("QIODevice not opened for reading")); + return false; } - if ((mode & QIODevice::ReadOnly) == QIODevice::ReadOnly) + if (!d->initializeDecompress()) + return false; + } + else + { + if (!d->device) { - if (!d->device) - { - setErrorString(QLatin1String("No QIODevice for reading available")); - return false; - } - if ((d->device->openMode() & QIODevice::ReadOnly) == 0) - { - setErrorString(QLatin1String("QIODevice not opened for reading")); - return false; - } - if (!d->initializeDecompress()) - return false; + setErrorString(QLatin1String("No QIODevice for writing available")); + return false; } - else + if ((d->device->openMode() & QIODevice::WriteOnly) == 0) { - if (!d->device) - { - setErrorString(QLatin1String("No QIODevice for writing available")); - return false; - } - if ((d->device->openMode() & QIODevice::WriteOnly) == 0) - { - setErrorString(QLatin1String("QIODevice not opened for writing")); - return false; - } - if (!d->initializeCompress()) - return false; + setErrorString(QLatin1String("QIODevice not opened for writing")); + return false; } - setErrorString(QString()); - setOpenMode(mode); - return QIODevice::open(mode); + if (!d->initializeCompress()) + return false; + } + setErrorString(QString()); + setOpenMode(mode); + return QIODevice::open(mode); } void BZip2IODevice::abort() { - d->aborted = 1; + d->aborted = 1; } void BZip2IODevice::close() { - if (!isOpen()) - return; - if ((openMode() & QIODevice::ReadOnly) == QIODevice::ReadOnly) - d->finishDecompress(); - else - d->finishCompress(); - QIODevice::close(); + if (!isOpen()) + return; + if ((openMode() & QIODevice::ReadOnly) == QIODevice::ReadOnly) + d->finishDecompress(); + else + d->finishCompress(); + QIODevice::close(); } bool BZip2IODevice::atEnd() const { - if (!d->device) - return true; - return d->device->atEnd() && d->decomressStreamEnd && QIODevice::atEnd(); + if (!d->device) + return true; + return d->device->atEnd() && d->decomressStreamEnd && QIODevice::atEnd(); } -qint64 BZip2IODevice::readData(char* data, qint64 maxSize) +qint64 BZip2IODevice::readData(char *data, qint64 maxSize) { - return d->doDecompress(data, maxSize); + return d->doDecompress(data, maxSize); } -qint64 BZip2IODevice::writeData(const char* data, qint64 maxSize) +qint64 BZip2IODevice::writeData(const char *data, qint64 maxSize) { - return d->doCompress(data, maxSize); + return d->doCompress(data, maxSize); } #else diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.h b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.h old mode 100755 new mode 100644 index ca79226f0..d7d4152a5 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.h @@ -1,8 +1,6 @@ - - #ifndef BZIP2IODEVICE_H #define BZIP2IODEVICE_H @@ -14,26 +12,24 @@ class BZip2IODevice : public QIODevice { public: - - - BZip2IODevice(QIODevice *dev, int blocksize = 5); virtual ~BZip2IODevice(); void abort(); - void setBufferSize(unsigned int size); - void setBlockSize(unsigned int size); + void setBufferSize(unsigned int size); + void setBlockSize(unsigned int size); + - virtual bool isSequential() const; virtual bool open(OpenMode mode); virtual void close(); virtual bool atEnd() const; + protected: virtual qint64 readData(char *data, qint64 maxSize); virtual qint64 writeData(const char *data, qint64 maxSize); -private: +private: class Private; friend class Private; Private *const d; @@ -44,19 +40,38 @@ private: class BZip2IODevice : public QIODevice { public: - BZip2IODevice(QIODevice *dev, int blocksize = 5) { Q_UNUSED(dev) Q_UNUSED(blocksize) } + BZip2IODevice(QIODevice *dev, int blocksize = 5) + { + Q_UNUSED(dev) + Q_UNUSED(blocksize) + } virtual ~BZip2IODevice() {} void abort() {} void setBufferSize(unsigned int size) { Q_UNUSED(size) } void setBlockSize(unsigned int size) { Q_UNUSED(size) } virtual bool isSequential() const { return true; } - virtual bool open(OpenMode mode) { Q_UNUSED(mode) return false; } + virtual bool open(OpenMode mode) + { + Q_UNUSED(mode) + return false; + } virtual void close() {} virtual bool atEnd() const { return true; } + protected: - virtual qint64 readData(char *data, qint64 maxSize) { Q_UNUSED(data) Q_UNUSED(maxSize) return -1; } - virtual qint64 writeData(const char *data, qint64 maxSize) { Q_UNUSED(data) Q_UNUSED(maxSize) return -1; } + virtual qint64 readData(char *data, qint64 maxSize) + { + Q_UNUSED(data) + Q_UNUSED(maxSize) + return -1; + } + virtual qint64 writeData(const char *data, qint64 maxSize) + { + Q_UNUSED(data) + Q_UNUSED(maxSize) + return -1; + } }; #endif -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp index 1abdf77f3..4ceab8ca7 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp @@ -21,22 +21,22 @@ namespace NGL { -Compress::Compress(QObject* parent) - : QObject(parent) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("nglcompress")) - , m_u2_memFiles() - , m_aborted(0) -{ + Compress::Compress(QObject *parent) + : QObject(parent) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("nglcompress")) + , m_u2_memFiles() + , m_aborted(0) + { DEBUG_LOG(m_logger) << "c_tor"; - QTimer* t = new QTimer(this); + QTimer *t = new QTimer(this); t->setInterval(1000); connect(t, &QTimer::timeout, this, []() { qWarning() << "still alive ..."; }); t->start(); -} + } -Compress::~Compress() -{ + Compress::~Compress() + { qWarning() << "## COMPRESS DTOR!!!!"; DEBUG_LOG(m_logger) << "~"; @@ -44,10 +44,10 @@ Compress::~Compress() abort(); m_future.waitForFinished(); DEBUG_LOG(m_logger) << "~ finished"; -} + } -void Compress::abort() -{ + void Compress::abort() + { DEBUG_LOG(m_logger) << "ABORT"; m_aborted = 1; @@ -55,29 +55,31 @@ void Compress::abort() if (m_currentTarFilter != nullptr) { - DEBUG_LOG(m_logger) << "aborting tar"; - m_currentTarFilter->abort(); + DEBUG_LOG(m_logger) << "aborting tar"; + m_currentTarFilter->abort(); } if (m_currentBzipDevice != nullptr) { - DEBUG_LOG(m_logger) << "aborting bzip"; - m_currentBzipDevice->abort(); + DEBUG_LOG(m_logger) << "aborting bzip"; + m_currentBzipDevice->abort(); } -} + } -void Compress::compress(QIODevice* out, const QString& filesRootDir, const QVector& files, - const QVector& memFiles, const QString& destRootDir) -{ + void Compress::compress(QIODevice *out, + const QString &filesRootDir, + const QVector &files, + const QVector &memFiles, + const QString &destRootDir) + { DEBUG_LOG(m_logger) << "compress #2"; reset(); - setupFutureWatcher(QtConcurrent::run([this, out, filesRootDir, files, memFiles, destRootDir]() { - return this->_compress(out, filesRootDir, files, memFiles, destRootDir); - })); -} + setupFutureWatcher( + QtConcurrent::run([this, out, filesRootDir, files, memFiles, destRootDir]() { return this->_compress(out, filesRootDir, files, memFiles, destRootDir); })); + } -void Compress::compress(QIODevice* out, const QString& sourceDir, const QString& destRootDir) -{ + void Compress::compress(QIODevice *out, const QString &sourceDir, const QString &destRootDir) + { DEBUG_LOG(m_logger) << "compress #1 source dir: " << sourceDir << ", destRootDir: " << destRootDir; reset(); @@ -85,40 +87,44 @@ void Compress::compress(QIODevice* out, const QString& sourceDir, const QString& int len = sourceDir.length(); if (!sourceDir.endsWith(QLatin1Char('/'))) - len += 1; - for (auto& fi : inFiles) + len += 1; + for (auto &fi : inFiles) { - fi.inputFileName = fi.inputFileName.mid(len); - fi.bAbsInputPath = false; - DEBUG_LOG(m_logger) << "fi: ifm = " << fi.inputFileName << ", abs = " << fi.bAbsInputPath; + fi.inputFileName = fi.inputFileName.mid(len); + fi.bAbsInputPath = false; + DEBUG_LOG(m_logger) << "fi: ifm = " << fi.inputFileName << ", abs = " << fi.bAbsInputPath; } DEBUG_LOG(m_logger) << "FI list size: " << inFiles.count(); compress(out, sourceDir, inFiles, {}, destRootDir); -} + } -bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const QVector& files, - const QVector& memFiles, const QString& _destRootDir) -{ - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); + bool Compress::_compress(QIODevice *output, + const QString &filesRootDir, + const QVector &files, + const QVector &memFiles, + const QString &_destRootDir) + { + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, + [this](int *) + { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); (void)invalidatePointersOnScopeLeave; if (!output || !output->isWritable()) { - m_lastError = tr("Device is not writeable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - ; + m_lastError = tr("Device is not writeable"); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + ; - return false; + return false; } - const QString destRootDir = - _destRootDir.endsWith(QLatin1Char('/')) ? _destRootDir : _destRootDir + QLatin1Char('/'); + const QString destRootDir = _destRootDir.endsWith(QLatin1Char('/')) ? _destRootDir : _destRootDir + QLatin1Char('/'); const qint64 maxCount = files.count() + memFiles.count(); qint64 count = 0; @@ -130,32 +136,31 @@ bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const Q if (!bzip2.open(QIODevice::WriteOnly)) { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = bzip2.errorString(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; + return false; } qint64 bytesTotal = 0; - for (const FileInformations& file : std::as_const(files)) + for (const FileInformations &file : std::as_const(files)) { - if (m_aborted) - return false; + if (m_aborted) + return false; - const QString in = - file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; - const QFileInfo fi(in); + const QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; + const QFileInfo fi(in); - bytesTotal += fi.size(); + bytesTotal += fi.size(); } qint64 currentFileSize = 0; QString currentFileName; - auto readCallback = [this, &maxCount, &count, ¤tFileSize, ¤tFileName, &bytesTotal](const qint64 iSize) { - DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count - << ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName - << ", iSize = " << iSize; - emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal); + auto readCallback = [this, &maxCount, &count, ¤tFileSize, ¤tFileName, &bytesTotal](const qint64 iSize) + { + DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count << ", currentFileSize = " << currentFileSize + << ", currentFileName = " << currentFileName << ", iSize = " << iSize; + emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal); }; TarFilter tf(&bzip2, readCallback); @@ -164,96 +169,94 @@ bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const Q QString curPath; DEBUG_LOG(m_logger) << "prepairing tar filter"; - for (const QString& path : paths) + for (const QString &path : paths) { - DEBUG_LOG(m_logger) << "path = " << path; - if (m_aborted) - return false; + DEBUG_LOG(m_logger) << "path = " << path; + if (m_aborted) + return false; - if (curPath.isEmpty()) - curPath = path + QLatin1Char('/'); - else - curPath += path + QLatin1Char('/'); + if (curPath.isEmpty()) + curPath = path + QLatin1Char('/'); + else + curPath += path + QLatin1Char('/'); - DEBUG_LOG(m_logger) << "curPath = " << curPath << ", filesRootDir.isEmpty() = " << filesRootDir.isEmpty(); + DEBUG_LOG(m_logger) << "curPath = " << curPath << ", filesRootDir.isEmpty() = " << filesRootDir.isEmpty(); - if (filesRootDir.isEmpty()) + if (filesRootDir.isEmpty()) + { + if (!tf.addData(curPath, QByteArray(), true)) { - if (!tf.addData(curPath, QByteArray(), true)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } + return false; } - else + } + else + { + if (!tf.addFile(filesRootDir, curPath)) { - if (!tf.addFile(filesRootDir, curPath)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } + return false; } + } } m_c_sizeInfo.realSize = 0; - for (const FileInformations& file : std::as_const(files)) + for (const FileInformations &file : std::as_const(files)) { - DEBUG_LOG(m_logger) << "file = " << file.inputFileName; - emit compressInfo(maxCount, ++count, file.inputFileName); + DEBUG_LOG(m_logger) << "file = " << file.inputFileName; + emit compressInfo(maxCount, ++count, file.inputFileName); - if (m_aborted) - return false; + if (m_aborted) + return false; - QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; - QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName); + QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; + QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName); - DEBUG_LOG(m_logger) << "in = " << in << ", out = " << out; + DEBUG_LOG(m_logger) << "in = " << in << ", out = " << out; - QFileInfo fi(in); + QFileInfo fi(in); - currentFileName = fi.fileName(); - currentFileSize = fi.size(); - m_c_sizeInfo.realSize += currentFileSize; + currentFileName = fi.fileName(); + currentFileSize = fi.size(); + m_c_sizeInfo.realSize += currentFileSize; - DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize - << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; + DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; - if (!tf.addFile(in, out)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + if (!tf.addFile(in, out)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } + return false; + } } - for (const FileInformations& file : std::as_const(memFiles)) + for (const FileInformations &file : std::as_const(memFiles)) { - DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName; - emit compressInfo(maxCount, ++count, file.inputFileName); + DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName; + emit compressInfo(maxCount, ++count, file.inputFileName); - if (m_aborted) - return false; + if (m_aborted) + return false; - currentFileName = file.inputFileName; - currentFileSize = file.fileData.size(); - m_c_sizeInfo.compressedSize += currentFileSize; + currentFileName = file.inputFileName; + currentFileSize = file.fileData.size(); + m_c_sizeInfo.compressedSize += currentFileSize; - DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName - << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" - << m_c_sizeInfo.realSize; + DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" + << m_c_sizeInfo.realSize; - if (!tf.addData(file.inputFileName, file.fileData)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + if (!tf.addData(file.inputFileName, file.fileData)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } + return false; + } } DEBUG_LOG(m_logger) << "writing eos"; @@ -270,42 +273,44 @@ bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const Q DEBUG_LOG(m_logger) << "DONE!"; return true; -} + } -void Compress::uncompress(QIODevice* in, const QString& outDir) -{ + void Compress::uncompress(QIODevice *in, const QString &outDir) + { DEBUG_LOG(m_logger) << "uncompress #1"; reset(); setupFutureWatcher(QtConcurrent::run([this, in, outDir]() { return this->_uncompressDirectory(in, outDir); })); -} + } -bool Compress::_uncompressDirectory(QIODevice* input, const QString& outDir) -{ + bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir) + { DEBUG_LOG(m_logger) << "_uncompressDirectory"; - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, + [this](int *) + { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); (void)invalidatePointersOnScopeLeave; if (!input || !input->isReadable()) { - m_lastError = tr("Device is not readable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = tr("Device is not readable"); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; + return false; } BZip2IODevice bzip2(input, 9); m_currentBzipDevice = &bzip2; if (!bzip2.open(QIODevice::ReadOnly)) { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = bzip2.errorString(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; + return false; } TarFilter tf(&bzip2); @@ -317,92 +322,94 @@ bool Compress::_uncompressDirectory(QIODevice* input, const QString& outDir) while (tf.getData(tfi)) { - DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; - emit uncompressInfo(input->size(), input->pos(), tfi.fileName); - if (m_aborted) - return false; + DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; + emit uncompressInfo(input->size(), input->pos(), tfi.fileName); + if (m_aborted) + return false; - QString path = outDir + QLatin1Char('/') + tfi.fileName; - DEBUG_LOG(m_logger) << "path = " << path; - if (tfi.fileType == TarFilter::directory) + QString path = outDir + QLatin1Char('/') + tfi.fileName; + DEBUG_LOG(m_logger) << "path = " << path; + if (tfi.fileType == TarFilter::directory) + { + DEBUG_LOG(m_logger) << "tfi.fileType == TarFilter::directory"; + if (!dir.exists(path) && !dir.mkpath(path)) { - DEBUG_LOG(m_logger) << "tfi.fileType == TarFilter::directory"; - if (!dir.exists(path) && !dir.mkpath(path)) - { - m_lastError = tr("Error creating directory %1").arg(outDir); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = tr("Error creating directory %1").arg(outDir); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } + return false; } - else + } + else + { + + QString pathName = QFileInfo(path).absolutePath(); + if (!dir.exists(pathName) && !dir.mkpath(pathName)) { + m_lastError = tr("Error creating directory %1").arg(pathName); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - QString pathName = QFileInfo(path).absolutePath(); - if (!dir.exists(pathName) && !dir.mkpath(pathName)) - { - m_lastError = tr("Error creating directory %1").arg(pathName); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - QFile f(path); - if (!f.open(QIODevice::WriteOnly)) - { - m_lastError = tr("Error opening %1 for writing (%2)").arg(path, f.errorString()); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - if (!tf.getData(&f)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } + return false; } + QFile f(path); + if (!f.open(QIODevice::WriteOnly)) + { + m_lastError = tr("Error opening %1 for writing (%2)").arg(path, f.errorString()); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + if (!tf.getData(&f)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } } DEBUG_LOG(m_logger) << "uncompress done!"; m_success = true; return true; -} + } -void Compress::uncompress(QIODevice* in) -{ + void Compress::uncompress(QIODevice *in) + { DEBUG_LOG(m_logger) << "uncompress #2!"; reset(); setupFutureWatcher(QtConcurrent::run([this, in]() { return this->_uncompressBuffer(in); })); -} + } -bool Compress::_uncompressBuffer(QIODevice* input) -{ + bool Compress::_uncompressBuffer(QIODevice *input) + { DEBUG_LOG(m_logger) << "uncompressBuffer"; - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, + [this](int *) + { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); (void)invalidatePointersOnScopeLeave; if (!input->isReadable()) { - m_lastError = tr("Device is not readable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = tr("Device is not readable"); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; + return false; } BZip2IODevice bzip2(input, 9); m_currentBzipDevice = &bzip2; if (!bzip2.open(QIODevice::ReadOnly)) { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + m_lastError = bzip2.errorString(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; + return false; } TarFilter tf(&bzip2); @@ -410,71 +417,71 @@ bool Compress::_uncompressBuffer(QIODevice* input) TarFilter::FileInformations tfi; while (tf.getData(tfi)) { - DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; - emit uncompressInfo(input->size(), input->pos(), tfi.fileName); - if (m_aborted) - return false; + DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; + emit uncompressInfo(input->size(), input->pos(), tfi.fileName); + if (m_aborted) + return false; - FileInformations fi; - fi.outputFileName = tfi.fileName; + FileInformations fi; + fi.outputFileName = tfi.fileName; - DEBUG_LOG(m_logger) << "fi.outputFileName = " << fi.outputFileName; + DEBUG_LOG(m_logger) << "fi.outputFileName = " << fi.outputFileName; - if (tfi.fileType == TarFilter::directory) + if (tfi.fileType == TarFilter::directory) + { + fi.outputFileName += QLatin1Char('/'); + DEBUG_LOG(m_logger) << "> fi.outputFileName = " << fi.outputFileName; + } + else + { + DEBUG_LOG(m_logger) << "stuff"; + + QBuffer buf(&fi.fileData); + if (!buf.open(QIODevice::WriteOnly)) { - fi.outputFileName += QLatin1Char('/'); - DEBUG_LOG(m_logger) << "> fi.outputFileName = " << fi.outputFileName; + m_lastError = tr("Error opening buffer for writing (%1)").arg(buf.errorString()); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; } - else + if (!tf.getData(&buf)) { - DEBUG_LOG(m_logger) << "stuff"; + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - QBuffer buf(&fi.fileData); - if (!buf.open(QIODevice::WriteOnly)) - { - m_lastError = tr("Error opening buffer for writing (%1)").arg(buf.errorString()); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - if (!tf.getData(&buf)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } + return false; } + } - fi.bAbsInputPath = fi.outputFileName.startsWith(QLatin1Char('/')); - DEBUG_LOG(m_logger) << "added fi.bAbsInputPath = " << fi.bAbsInputPath; - m_u2_memFiles += fi; + fi.bAbsInputPath = fi.outputFileName.startsWith(QLatin1Char('/')); + DEBUG_LOG(m_logger) << "added fi.bAbsInputPath = " << fi.bAbsInputPath; + m_u2_memFiles += fi; } m_success = true; return true; -} + } -bool Compress::success() const -{ + bool Compress::success() const + { ERROR_LOG(m_logger) << "success? " << (m_future.isFinished() && !m_future.isCanceled() && m_success); ERROR_LOG(m_logger) << "success details: " - << "success m_future.isFinished() = " << (m_future.isFinished()) - << " !m_future.isCanceled() = " << !m_future.isCanceled() << " m_success = " << m_success; + << "success m_future.isFinished() = " << (m_future.isFinished()) << " !m_future.isCanceled() = " << !m_future.isCanceled() + << " m_success = " << m_success; return (m_future.isFinished() && !m_future.isCanceled() && m_success); -} + } -bool Compress::waitForFinished() -{ + bool Compress::waitForFinished() + { DEBUG_LOG(m_logger) << "waitForFinished..."; m_future.waitForFinished(); DEBUG_LOG(m_logger) << "waitForFinished... done!"; return success(); -} + } -QVector Compress::directoryFileList(const QString& dir, bool recursive) -{ + QVector Compress::directoryFileList(const QString &dir, bool recursive) + { DEBUG_LOG(m_logger) << "directoryFileList"; QVector sl_absolute; @@ -482,28 +489,28 @@ QVector Compress::directoryFileList(const QString& d if (d.exists()) { - DEBUG_LOG(m_logger) << "exists"; - const auto entries = d.entryList(QDir::Files); - sl_absolute.reserve(sl_absolute.size() + entries.size()); - for (const QString& entry : entries) - sl_absolute << FileInformations(QFileInfo(d, entry).absoluteFilePath(), true); + DEBUG_LOG(m_logger) << "exists"; + const auto entries = d.entryList(QDir::Files); + sl_absolute.reserve(sl_absolute.size() + entries.size()); + for (const QString &entry : entries) + sl_absolute << FileInformations(QFileInfo(d, entry).absoluteFilePath(), true); } if (recursive) { - DEBUG_LOG(m_logger) << "recursive"; - const auto entries = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot); - sl_absolute.reserve(sl_absolute.size() + entries.size()); - for (const QString& s : entries) - sl_absolute << directoryFileList(dir + QLatin1Char('/') + s, true); + DEBUG_LOG(m_logger) << "recursive"; + const auto entries = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot); + sl_absolute.reserve(sl_absolute.size() + entries.size()); + for (const QString &s : entries) + sl_absolute << directoryFileList(dir + QLatin1Char('/') + s, true); } DEBUG_LOG(m_logger) << "done"; return sl_absolute; -} + } -void Compress::reset() -{ + void Compress::reset() + { DEBUG_LOG(m_logger) << "reset"; m_u2_memFiles.clear(); @@ -513,19 +520,18 @@ void Compress::reset() m_c_sizeInfo.compressedSize = 0; m_success = false; -} + } -void Compress::setupFutureWatcher(const QFuture& future) -{ + void Compress::setupFutureWatcher(const QFuture &future) + { DEBUG_LOG(m_logger) << "setupFutureWatcher"; m_future = future; - QFutureWatcher* fw = new QFutureWatcher(this); + QFutureWatcher *fw = new QFutureWatcher(this); QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; }); QObject::connect(fw, &QFutureWatcher::finished, this, &Compress::finished); QObject::connect(fw, &QFutureWatcher::finished, fw, &QObject::deleteLater); - QObject::connect(fw, &QFutureWatcher::finished, fw, - [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; }); + QObject::connect(fw, &QFutureWatcher::finished, fw, [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; }); fw->setFuture(m_future); -} + } } // namespace NGL diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.h b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.h old mode 100755 new mode 100644 index c2a021592..ccf60e068 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.h @@ -19,122 +19,112 @@ class BZip2IODevice; namespace NGL { -class NGLCOMPRESSION_EXPORT Compress : public QObject -{ - Q_OBJECT -public: - struct FileInformations + class NGLCOMPRESSION_EXPORT Compress : public QObject { - QString inputFileName; - QString outputFileName; - QByteArray fileData; - bool bAbsInputPath = true; - FileInformations() = default; + Q_OBJECT + public: + struct FileInformations + { + QString inputFileName; + QString outputFileName; + QByteArray fileData; + bool bAbsInputPath = true; + FileInformations() = default; - FileInformations(const QString &name, bool isAbsolute) - : inputFileName(name) - , bAbsInputPath(isAbsolute) - {} + FileInformations(const QString &name, bool isAbsolute) + : inputFileName(name) + , bAbsInputPath(isAbsolute) + { + } + }; + + + struct FileSizeInfo + { + qint64 realSize = 0; + qint64 compressedSize = 0; + }; + + + explicit Compress(QObject *parent = nullptr); + + ~Compress(); + + + QVector getMemFiles() const { return m_u2_memFiles; } + + + FileSizeInfo getFileSizeInfo() const { return m_c_sizeInfo; } + + + bool success() const; + + + void compress(QIODevice *out, + const QString &sourceRootDir, + const QVector &files, + const QVector &memFiles, + const QString &destRootDir); + + + void compress(QIODevice *out, const QString &sourceDir, const QString &destRootDir); + + + void uncompress(QIODevice *in, const QString &outDir); + + + void uncompress(QIODevice *in); + + + QString lastError() const { return m_lastError; } + + + bool waitForFinished(); + + public Q_SLOTS: + void abort(); + + Q_SIGNALS: + + + void uncompressInfo(qint64 totalSize, qint64 curPos, const QString &curName); + + + void compressInfo(qint64 totalFiles, qint64 curFile, const QString &curName); + void compressInfoEx(qint64 totalFiles, qint64 curFile, qint64 totalSize, qint64 curPos, const QString &curName, const qint64 bytesTotal); + + + void error(const QString &errorString); + + + void finished(); + + private: + NGL::INGLLogger &m_logger; + bool _compress(QIODevice *output, + const QString &filesRootDir, + const QVector &files, + const QVector &memFiles, + const QString &_destRootDir); + bool _uncompressDirectory(QIODevice *input, const QString &outDir); + bool _uncompressBuffer(QIODevice *input); + + void reset(); + void setupFutureWatcher(const QFuture &future); + + QVector directoryFileList(const QString &dir, bool recursive = false); + + FileSizeInfo m_c_sizeInfo; + QVector m_u2_memFiles; + + QString m_lastError; + QAtomicInt m_aborted; + + TarFilter *m_currentTarFilter{nullptr}; + BZip2IODevice *m_currentBzipDevice{nullptr}; + + QFuture m_future; + bool m_success{false}; }; - - - struct FileSizeInfo - { - qint64 realSize = 0; - qint64 compressedSize = 0; - }; - - - - explicit Compress(QObject *parent = nullptr); - - ~Compress(); - - - - QVector getMemFiles() const { return m_u2_memFiles; } - - - FileSizeInfo getFileSizeInfo() const { return m_c_sizeInfo; } - - - bool success() const; - - - - void compress(QIODevice *out, - const QString &sourceRootDir, - const QVector &files, - const QVector &memFiles, - const QString &destRootDir); - - - - void compress(QIODevice *out, - const QString &sourceDir, - const QString &destRootDir); - - - void uncompress(QIODevice *in, - const QString &outDir); - - - void uncompress(QIODevice *in); - - - QString lastError() const { return m_lastError; } - - - - bool waitForFinished(); - -public Q_SLOTS: - void abort(); - -Q_SIGNALS: - - - void uncompressInfo(qint64 totalSize, qint64 curPos, const QString &curName); - - - void compressInfo(qint64 totalFiles, qint64 curFile, const QString &curName); - void compressInfoEx(qint64 totalFiles, qint64 curFile, qint64 totalSize, qint64 curPos, const QString &curName, const qint64 bytesTotal); - - - - void error(const QString &errorString); - - - - void finished(); -private: - -NGL::INGLLogger &m_logger; - bool _compress(QIODevice *output, - const QString &filesRootDir, - const QVector &files, - const QVector &memFiles, - const QString &_destRootDir); - bool _uncompressDirectory(QIODevice *input, const QString &outDir); - bool _uncompressBuffer(QIODevice *input); - - void reset(); - void setupFutureWatcher(const QFuture &future); - - QVector directoryFileList(const QString &dir, bool recursive = false); - - FileSizeInfo m_c_sizeInfo; - QVector m_u2_memFiles; - - QString m_lastError; - QAtomicInt m_aborted; - - TarFilter *m_currentTarFilter { nullptr }; - BZip2IODevice *m_currentBzipDevice { nullptr }; - - QFuture m_future; - bool m_success { false }; -}; } Q_DECLARE_TYPEINFO(NGL::Compress::FileInformations, Q_MOVABLE_TYPE); - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_export.h b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_export.h old mode 100755 new mode 100644 index 731a1c242..ce10a7055 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_export.h @@ -5,13 +5,13 @@ #include #ifndef NGLCOMPRESSION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLCOMPRESSION_EXPORT -# else -# if defined(MAKE_NGLCOMPRESSION_LIB) -# define NGLCOMPRESSION_EXPORT Q_DECL_EXPORT -# else -# define NGLCOMPRESSION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLCOMPRESSION_EXPORT +#else +#if defined(MAKE_NGLCOMPRESSION_LIB) +#define NGLCOMPRESSION_EXPORT Q_DECL_EXPORT +#else +#define NGLCOMPRESSION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.cpp old mode 100755 new mode 100644 index 216229781..7c91b2bbb --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.cpp @@ -1,8 +1,6 @@ - - #include #include #include @@ -21,20 +19,15 @@ #endif - - - - - - class TarFilter::Private { public: Private(QIODevice *dev) - : device(dev) - , iBufSize(1024 * 1024) - , nextChunkSize(-1) - {} + : device(dev) + , iBufSize(1024 * 1024) + , nextChunkSize(-1) + { + } struct tar_posix_header { @@ -54,21 +47,21 @@ public: char devmajor[8]; char devminor[8]; char prefix[155]; - char unused[12]; + char unused[12]; }; - bool fi2tph(const FileInformations &infos); - bool addHeader(const FileInformations &infos); + bool fi2tph(const FileInformations &infos); + bool addHeader(const FileInformations &infos); - bool tph2fi(FileInformations &infos); - bool getHeader(FileInformations &infos); + bool tph2fi(FileInformations &infos); + bool getHeader(FileInformations &infos); bool checkDevice(QIODevice *in, QIODevice *out); bool copyData(QIODevice *in, QIODevice *out, qint64 iSize); - QIODevice *device; - QString lastError; + QIODevice *device; + QString lastError; unsigned int iBufSize; - qint64 nextChunkSize; - QAtomicInt aborted { 0 }; + qint64 nextChunkSize; + QAtomicInt aborted{0}; std::function readCallback; }; @@ -83,23 +76,23 @@ bool TarFilter::Private::fi2tph(const FileInformations &infos) fn = fn.mid(1); long unsigned int fileSize = infos.fileType == directory ? 0 : infos.fileSize; - long unsigned int mtime = infos.mtime != -1 ? infos.mtime : time(nullptr); + long unsigned int mtime = infos.mtime != -1 ? infos.mtime : time(nullptr); tar_posix_header hdr; memset(&hdr, 0, sizeof(hdr)); QByteArray fn_part1 = fn.left(sizeof(hdr.name)); - memcpy(hdr.name, fn_part1.constData(), fn_part1.size()); - sprintf(hdr.mode, "%07x", 0x0fff & infos.mode); - sprintf(hdr.uid, "%07o", infos.uid); - sprintf(hdr.gid, "%07o", infos.gid); - sprintf(hdr.size, "%011lo", fileSize); - sprintf(hdr.mtime, "%011lo", mtime); - memset(hdr.chksum, ' ', sizeof(hdr.chksum)); + memcpy(hdr.name, fn_part1.constData(), fn_part1.size()); + sprintf(hdr.mode, "%07x", 0x0fff & infos.mode); + sprintf(hdr.uid, "%07o", infos.uid); + sprintf(hdr.gid, "%07o", infos.gid); + sprintf(hdr.size, "%011lo", fileSize); + sprintf(hdr.mtime, "%011lo", mtime); + memset(hdr.chksum, ' ', sizeof(hdr.chksum)); hdr.typeflag = infos.fileType; - - memcpy(hdr.magic, "ustar ",sizeof(hdr.magic) + sizeof(hdr.version)); + + memcpy(hdr.magic, "ustar ", sizeof(hdr.magic) + sizeof(hdr.version)); #ifdef Q_OS_WIN - - + + #else { QByteArray unameBa = infos.uname.toUtf8(); @@ -108,9 +101,7 @@ bool TarFilter::Private::fi2tph(const FileInformations &infos) qstrncpy(hdr.gname, gnameBa.constData(), sizeof(hdr.gname)); } #endif - - - + unsigned int checksum = 0; const unsigned char *ptr = reinterpret_cast(&hdr); @@ -133,7 +124,7 @@ bool TarFilter::Private::fi2tph(const FileInformations &infos) bool TarFilter::Private::addHeader(const FileInformations &infos) { - + QByteArray fn = infos.fileName.toUtf8(); #ifdef Q_OS_WIN @@ -152,10 +143,10 @@ bool TarFilter::Private::addHeader(const FileInformations &infos) FileInformations longlink; longlink.fileName = QLatin1String("././@LongLink"); longlink.fileType = gnu_longname; - longlink.fileSize = strlen(fn.constData()) + 1; - longlink.mtime = 0; - longlink.uid = 0; - longlink.gid = 0; + longlink.fileSize = strlen(fn.constData()) + 1; + longlink.mtime = 0; + longlink.uid = 0; + longlink.gid = 0; #ifndef Q_OS_WIN struct passwd *p = getpwuid(longlink.uid); if (p) @@ -195,8 +186,7 @@ bool TarFilter::Private::tph2fi(FileInformations &infos) lastError = QStringLiteral("Error reading from QIODevice! needed: %1, got: %2").arg(sizeof(hdr)).arg(iBytesRead); return false; } - } - while (memcmp(hdr.magic, "\0\0\0\0\0\0", sizeof(hdr.magic)) == 0); + } while (memcmp(hdr.magic, "\0\0\0\0\0\0", sizeof(hdr.magic)) == 0); if (memcmp(hdr.magic, "ustar ", sizeof(hdr.magic))) { lastError = QLatin1String("The archive is not supported"); @@ -214,17 +204,17 @@ bool TarFilter::Private::tph2fi(FileInformations &infos) return false; } - QByteArray ba(hdr.name, sizeof(hdr.name)); + QByteArray ba(hdr.name, sizeof(hdr.name)); ba.resize(qstrlen(ba.constData())); infos.fileName = QString::fromUtf8(ba.constData()); - infos.fileSize = QByteArray(hdr.size, sizeof(hdr.size)).toUInt(nullptr, 8); - infos.mode = static_cast(QByteArray(hdr.mode, sizeof(hdr.mode)).toUInt(nullptr, 16)); - infos.uid = QByteArray(hdr.uid, sizeof(hdr.uid)).toUInt(nullptr, 8); - infos.gid = QByteArray(hdr.gid, sizeof(hdr.gid)).toUInt(nullptr, 8); - infos.mtime = QByteArray(hdr.mtime, sizeof(hdr.mtime)).toUInt(nullptr, 8); + infos.fileSize = QByteArray(hdr.size, sizeof(hdr.size)).toUInt(nullptr, 8); + infos.mode = static_cast(QByteArray(hdr.mode, sizeof(hdr.mode)).toUInt(nullptr, 16)); + infos.uid = QByteArray(hdr.uid, sizeof(hdr.uid)).toUInt(nullptr, 8); + infos.gid = QByteArray(hdr.gid, sizeof(hdr.gid)).toUInt(nullptr, 8); + infos.mtime = QByteArray(hdr.mtime, sizeof(hdr.mtime)).toUInt(nullptr, 8); infos.fileType = (FileType)hdr.typeflag; - infos.uname = QString::fromUtf8(QByteArray(hdr.uname, sizeof(hdr.uname)).constData()); - infos.gname = QString::fromUtf8(QByteArray(hdr.gname, sizeof(hdr.gname)).constData()); + infos.uname = QString::fromUtf8(QByteArray(hdr.uname, sizeof(hdr.uname)).constData()); + infos.gname = QString::fromUtf8(QByteArray(hdr.gname, sizeof(hdr.gname)).constData()); return true; } @@ -235,14 +225,14 @@ bool TarFilter::Private::getHeader(FileInformations &infos) return false; switch (infos.fileType) { - case regular: - case regular2: - case directory: - case gnu_longname: - break; - default: - lastError = QStringLiteral("Unsupported fileType %1").arg(infos.fileType); - return false; + case regular: + case regular2: + case directory: + case gnu_longname: + break; + default: + lastError = QStringLiteral("Unsupported fileType %1").arg(infos.fileType); + return false; } if (infos.fileType == gnu_longname) { @@ -254,7 +244,7 @@ bool TarFilter::Private::getHeader(FileInformations &infos) } if (!tph2fi(infos)) return false; - const int len = qstrlen(fn.constData()); + const int len = qstrlen(fn.constData()); infos.fileName = QString::fromUtf8(fn.constData(), len); } @@ -294,12 +284,14 @@ bool TarFilter::Private::copyData(QIODevice *in, QIODevice *out, qint64 iSize) while (iSize > 0) { - if (aborted) return false; + if (aborted) + return false; const qint64 iBytesToRead = iSize > iBufSize ? iBufSize : iSize; const QByteArray ba = in->read(iBytesToRead); - if (aborted) return false; + if (aborted) + return false; if (ba.size() == 0) { @@ -321,10 +313,8 @@ bool TarFilter::Private::copyData(QIODevice *in, QIODevice *out, qint64 iSize) } - - TarFilter::TarFilter(QIODevice *dev, const std::function &readCallback) - : d(new Private(dev)) + : d(new Private(dev)) { d->readCallback = readCallback; } @@ -371,17 +361,17 @@ bool TarFilter::addFile(const QString &filename, const QString &filenameInArchiv FileInformations fInfos; fInfos.fileName = (filenameInArchive.isEmpty() ? filename : filenameInArchive); fInfos.fileSize = fi.isDir() ? 0 : fi.size(); - fInfos.mode = fi.permissions() & 0x0fff; + fInfos.mode = fi.permissions() & 0x0fff; #ifdef Q_OS_WIN - fInfos.uid = 1000; - fInfos.gid = 100; + fInfos.uid = 1000; + fInfos.gid = 100; #else - fInfos.uid = fi.ownerId(); - fInfos.gid = fi.groupId(); - fInfos.uname = fi.owner(); - fInfos.gname = fi.group(); + fInfos.uid = fi.ownerId(); + fInfos.gid = fi.groupId(); + fInfos.uname = fi.owner(); + fInfos.gname = fi.group(); #endif - fInfos.mtime = fi.lastModified().toSecsSinceEpoch(); + fInfos.mtime = fi.lastModified().toSecsSinceEpoch(); fInfos.fileType = fi.isDir() ? directory : regular; if (fi.isDir()) @@ -397,23 +387,25 @@ bool TarFilter::addFile(const QString &filename, const QString &filenameInArchiv return false; } - if (d->aborted) return false; + if (d->aborted) + return false; return addData(fInfos, &f); } bool TarFilter::addData(const QString &filename, const QByteArray &data, bool bIsDir) { - if (d->aborted) return false; + if (d->aborted) + return false; FileInformations fi; fi.fileName = filename; - fi.fileSize = bIsDir ? 0 : data.size(); - fi.mode = static_cast(bIsDir ? 0x0755 : 0x0644); + fi.fileSize = bIsDir ? 0 : data.size(); + fi.mode = static_cast(bIsDir ? 0x0755 : 0x0644); fi.fileType = bIsDir ? directory : regular; #ifndef Q_OS_WIN - fi.uid = getuid(); - fi.gid = getgid(); + fi.uid = getuid(); + fi.gid = getgid(); char name[256]; struct passwd *p_ptr = nullptr; struct passwd p; @@ -438,7 +430,8 @@ bool TarFilter::addData(const QString &filename, const QByteArray &data, bool bI bool TarFilter::addData(const FileInformations &fi, QIODevice *in) { - if (d->aborted) return false; + if (d->aborted) + return false; if (!d->checkDevice(in, d->device)) return false; @@ -464,7 +457,7 @@ bool TarFilter::addData(const FileInformations &fi, QIODevice *in) bool TarFilter::writeEOS() { - + const int size = sizeof(TarFilter::Private::tar_posix_header) * 2; QByteArray ba(size, '\0'); return (d->device->write(ba) == size); @@ -472,7 +465,8 @@ bool TarFilter::writeEOS() bool TarFilter::getData(FileInformations &fi) { - if (d->aborted) return false; + if (d->aborted) + return false; d->nextChunkSize = -1; if (!d->getHeader(fi)) @@ -483,7 +477,8 @@ bool TarFilter::getData(FileInformations &fi) bool TarFilter::getData(QIODevice *out) { - if (d->aborted) return false; + if (d->aborted) + return false; if (!d->checkDevice(d->device, out)) return false; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.h b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.h old mode 100755 new mode 100644 index e1477c895..e99c4edc2 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_tarfilter.h @@ -1,8 +1,6 @@ - - #ifndef TARFILTER_H #define TARFILTER_H @@ -14,7 +12,6 @@ class QIODevice; class QByteArray; - class TarFilter { public: @@ -22,53 +19,52 @@ public: enum FileType { - regular = '0', - regular2 = '\0', - link = '1', - reserved = '2', - charType = '3', - block = '4', + regular = '0', + regular2 = '\0', + link = '1', + reserved = '2', + charType = '3', + block = '4', directory = '5', - fifo = '6', + fifo = '6', reserved2 = '7', - gnu_longLink = 'K', - gnu_longname = 'L', + gnu_longLink = 'K', + gnu_longname = 'L', }; struct FileInformations { - QString fileName; - qint64 fileSize = 0; - int uid = 1000; - int gid = 100; - QString uname; - QString gname; - time_t mtime = -1; - FileType fileType = regular; + QString fileName; + qint64 fileSize = 0; + int uid = 1000; + int gid = 100; + QString uname; + QString gname; + time_t mtime = -1; + FileType fileType = regular; QFile::Permissions mode = QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::ReadOther; }; - - + TarFilter(QIODevice *dev, const std::function &readCallback = nullptr); ~TarFilter(); void abort(); - void setBufferSize(unsigned int size); - bool error() const; - QString lastError() const; + void setBufferSize(unsigned int size); + bool error() const; + QString lastError() const; + - bool addData(const FileInformations &fi, QIODevice *in); - + bool addFile(const QString &filename, const QString &filenameInArchive = QString()); bool addData(const QString &filename, const QByteArray &data = QByteArray(), bool bIsDir = false); - + bool writeEOS(); - + bool getData(FileInformations &fi, QIODevice *out); - - bool getData(FileInformations &fi); + + bool getData(FileInformations &fi); bool getData(QIODevice *out); bool getData(FileInformations &fi, QByteArray &data); @@ -77,4 +73,4 @@ private: Private *const d; }; -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.cpp old mode 100755 new mode 100644 index a8d454da5..c7b559683 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.cpp @@ -12,7 +12,6 @@ #include - void nglcomp_test::initTestCase() { m_tempDirIn.setAutoRemove(true); @@ -22,23 +21,18 @@ void nglcomp_test::initTestCase() QVERIFY(m_tf.open()); m_tf.setAutoRemove(true); - m_fileContent[QLatin1String("1.txt")] = "111111111111111111111111"; - m_fileContent[QLatin1String("sub1/s1.txt")] = "222222222222222222222222"; + m_fileContent[QLatin1String("1.txt")] = "111111111111111111111111"; + m_fileContent[QLatin1String("sub1/s1.txt")] = "222222222222222222222222"; m_fileContent[QLatin1String("sub1/sub11/s11.txt")] = "333333333333333333333333"; m_fileContent[QLatin1String("sub1/sub12/s12.txt")] = "444444444444444444444444"; - m_fileContent[QLatin1String("sub2/2.txt")] = "555555555555555555555555"; + m_fileContent[QLatin1String("sub2/2.txt")] = "555555555555555555555555"; } void nglcomp_test::testCompressFile() { QDir dir; - const auto directories = { - QLatin1String("sub1"), - QLatin1String("sub1/sub11"), - QLatin1String("sub1/sub12"), - QLatin1String("sub2") - }; + const auto directories = {QLatin1String("sub1"), QLatin1String("sub1/sub11"), QLatin1String("sub1/sub12"), QLatin1String("sub2")}; for (const QLatin1String &directory : directories) QVERIFY(dir.mkdir(subPathIn(directory))); @@ -113,7 +107,6 @@ void nglcomp_test::cleanupTestCase() } - void nglcomp_test::writeTestFile(const QString &fn, const QByteArray &content) const { QFile f(subPathIn(fn)); @@ -140,35 +133,10 @@ QString nglcomp_test::subPathOut(const QString &p) const } - - - - - - - - - - - - - - - - - - - - - - - - - int main(int argc, char *argv[]) { NGLCoreApplication app(argc, argv); - + app.createLogger("nglcomp_test", "log4cxx_nglcomp_test.props"); nglcomp_test tc; return QTest::qExec(&tc, argc, argv); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.h b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.h old mode 100755 new mode 100644 index 0d55d1e94..65da6ee59 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_test.h @@ -22,11 +22,13 @@ private Q_SLOTS: void testUncompressFile(); void testUncompressMemory(); void cleanupTestCase(); + private: void writeTestFile(const QString &fn, const QByteArray &content) const; void checkContent(const QString &fn, const QByteArray &content) const; QString subPathIn(const QString &p) const; QString subPathOut(const QString &p) const; + private: QHash m_fileContent; QByteArray m_ba; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/db_service_handler.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/db_service_handler.h old mode 100755 new mode 100644 index aaf856359..2dd5d0986 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/db_service_handler.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/db_service_handler.h @@ -8,51 +8,50 @@ class QSqlDatabase; namespace NGLDB { -template -class DbServiceHandler -{ -public: - DbServiceHandler() = default; - ~DbServiceHandler() = default; - - - bool init(int exerciseId, NGL::Settings *settings) + template class DbServiceHandler { - if (m_dbInterface) - return true; + public: + DbServiceHandler() = default; + ~DbServiceHandler() = default; - m_dbInterface = DB::create(exerciseId); - if (!m_dbInterface->init(m_dbInterface->dbUser(), - settings->databasePassword(m_dbInterface->dbUser()), - settings->databaseDriver(), - settings->databaseHostname(), - settings->databaseName())) + bool init(int exerciseId, NGL::Settings *settings) { - m_dbInterface = nullptr; - return false; - } - return true; - } + if (m_dbInterface) + return true; - bool init(int exerciseId, const QSqlDatabase &db) - { - if (m_dbInterface) + m_dbInterface = DB::create(exerciseId); + + if (!m_dbInterface->init(m_dbInterface->dbUser(), + settings->databasePassword(m_dbInterface->dbUser()), + settings->databaseDriver(), + settings->databaseHostname(), + settings->databaseName())) + { + m_dbInterface = nullptr; + return false; + } return true; - - m_dbInterface = DB::create(exerciseId); - - if (!m_dbInterface->init(db)) - { - m_dbInterface = nullptr; - return false; } - return true; - } - std::shared_ptr db() const { return m_dbInterface; } + bool init(int exerciseId, const QSqlDatabase &db) + { + if (m_dbInterface) + return true; -private: - std::shared_ptr m_dbInterface; -}; -} + m_dbInterface = DB::create(exerciseId); + + if (!m_dbInterface->init(db)) + { + m_dbInterface = nullptr; + return false; + } + return true; + } + + std::shared_ptr db() const { return m_dbInterface; } + + private: + std::shared_ptr m_dbInterface; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbcommon.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbcommon.h old mode 100755 new mode 100644 index 4724915c0..039599985 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbcommon.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbcommon.h @@ -7,35 +7,31 @@ #include - namespace DBCommon { -enum class eDatabaseSchema -{ - Exercise -}; + enum class eDatabaseSchema + { + Exercise + }; + inline QString getExerciseSchemaName(int exerciseId) + { + return QLatin1String("ex_") + QString::number(exerciseId); + } -inline QString getExerciseSchemaName(int exerciseId) -{ - return QLatin1String("ex_") + QString::number(exerciseId); -} + inline QString getTableName(const QString &tableName, const QString &schemaName) + { + if (schemaName.isEmpty()) + return tableName; + return schemaName + QLatin1Char('.') + tableName; + } -inline QString getTableName(const QString &tableName, const QString &schemaName) -{ - if (schemaName.isEmpty()) - return tableName; - return schemaName + QLatin1Char('.') + tableName; -} - - - -inline QString getExerciseTableName(const QString &tableName, int exerciseId) -{ - return getTableName(tableName, getExerciseSchemaName(exerciseId)); -} + inline QString getExerciseTableName(const QString &tableName, int exerciseId) + { + return getTableName(tableName, getExerciseSchemaName(exerciseId)); + } } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.cpp old mode 100755 new mode 100644 index bbe3f45f1..7b046241e --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.cpp @@ -11,58 +11,55 @@ namespace DBConnection { -QSqlDatabase open(NGL::INGLLogger &logger, - const QString &dbUser, - const QString &dbPasswd, - const QString &dbDriver, - const QString &dbHost, - const QString &dbName, - const QString &schemaName, - const QString &connectionName) -{ - - - - DEBUG_LOG(logger) << "host: " << dbHost << " database: " << dbName; - QString realConnectionName(connectionName); - if (connectionName.isEmpty()) + QSqlDatabase open(NGL::INGLLogger &logger, + const QString &dbUser, + const QString &dbPasswd, + const QString &dbDriver, + const QString &dbHost, + const QString &dbName, + const QString &schemaName, + const QString &connectionName) { - realConnectionName = dbHost + QLatin1Char('_') + dbName; + + + DEBUG_LOG(logger) << "host: " << dbHost << " database: " << dbName; + QString realConnectionName(connectionName); + if (connectionName.isEmpty()) + { + realConnectionName = dbHost + QLatin1Char('_') + dbName; + if (!schemaName.isEmpty()) + realConnectionName += QLatin1Char('_') + schemaName; + } + + auto dbConnection = QSqlDatabase::addDatabase(dbDriver, realConnectionName); + dbConnection.setHostName(dbHost); + dbConnection.setDatabaseName(dbName); + dbConnection.setUserName(dbUser); + dbConnection.setPassword(dbPasswd); + + if (!dbConnection.open()) + { + const QString err = dbConnection.lastError().nativeErrorCode(); + FATAL_LOG(logger) << "Error opening database " << dbHost << ":" << dbName << " as user " << dbUser; + FATAL_LOG(logger) << dbConnection.lastError().driverText() << " " << dbConnection.lastError().databaseText() << " " << err; + return dbConnection; + } + + DEBUG_LOG(logger) << "Database Initialisation successful -> DB: " << dbName << ", con: " << realConnectionName; + if (!schemaName.isEmpty()) - realConnectionName += QLatin1Char('_') + schemaName; - } + { + const QString stmt = QLatin1String("SET SEARCH_PATH TO ") + schemaName + QLatin1String(", PUBLIC"); - auto dbConnection = QSqlDatabase::addDatabase(dbDriver, realConnectionName); - dbConnection.setHostName(dbHost); - dbConnection.setDatabaseName(dbName); - dbConnection.setUserName(dbUser); - dbConnection.setPassword(dbPasswd); + NSqlQuery q(dbConnection); + if (!q.exec(stmt)) + { + ERROR_LOG(logger) << "Set SEARCH_PATH to " << schemaName << " failed!"; + dbConnection.close(); + } + } - if (!dbConnection.open()) - { - const QString err = dbConnection.lastError().nativeErrorCode(); - FATAL_LOG(logger) << "Error opening database " << dbHost - << ":" << dbName << " as user " << dbUser; - FATAL_LOG(logger) << dbConnection.lastError().driverText() << " " - << dbConnection.lastError().databaseText() << " " << err; return dbConnection; } - DEBUG_LOG(logger) << "Database Initialisation successful -> DB: " << dbName << ", con: " << realConnectionName; - - if (!schemaName.isEmpty()) - { - const QString stmt = QLatin1String("SET SEARCH_PATH TO ") + schemaName + QLatin1String(", PUBLIC"); - - NSqlQuery q(dbConnection); - if (!q.exec(stmt)) - { - ERROR_LOG(logger) << "Set SEARCH_PATH to " << schemaName << " failed!"; - dbConnection.close(); - } - } - - return dbConnection; } - -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.h old mode 100755 new mode 100644 index d3435cefc..73c8ae333 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbconnection.h @@ -8,17 +8,17 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } namespace DBConnection { -NGLDB_EXPORT QSqlDatabase open(NGL::INGLLogger &logger, - const QString &dbUser, - const QString &dbPasswd, - const QString &dbDriver, - const QString &dbHost, - const QString &dbName, - const QString &schemaName = QString(), - const QString &connectionName = QString()); -} + NGLDB_EXPORT QSqlDatabase open(NGL::INGLLogger &logger, + const QString &dbUser, + const QString &dbPasswd, + const QString &dbDriver, + const QString &dbHost, + const QString &dbName, + const QString &schemaName = QString(), + const QString &connectionName = QString()); +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.cpp old mode 100755 new mode 100644 index 472e6727c..e2b16ab74 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.cpp @@ -8,9 +8,9 @@ thread_local int s_refCounter = 0; DBTransaction::DBTransaction(const QSqlDatabase &db) - : m_db(db) - , m_bCommitted(true) - , mLogger(NGLDB::getLogger("DBTransaction")) + : m_db(db) + , m_bCommitted(true) + , mLogger(NGLDB::getLogger("DBTransaction")) { ++s_refCounter; if (s_refCounter == 1) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.h old mode 100755 new mode 100644 index 645377c3e..67b498c48 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/dbtransaction.h @@ -8,31 +8,27 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } class NGLDB_EXPORT DBTransaction { public: - - explicit DBTransaction(const QSqlDatabase &db); - ~DBTransaction(); - bool begin(); - + bool commit(); - + bool rollback(); - + bool state() const; @@ -44,5 +40,3 @@ private: bool m_lastState; NGL::INGLLogger &mLogger; }; - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_export.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_export.h old mode 100755 new mode 100644 index 568874e25..930144fe2 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_export.h @@ -5,13 +5,13 @@ #include #ifndef NGLDB_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLDB_EXPORT -# else -# if defined(MAKE_NGLDB_LIB) -# define NGLDB_EXPORT Q_DECL_EXPORT -# else -# define NGLDB_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLDB_EXPORT +#else +#if defined(MAKE_NGLDB_LIB) +#define NGLDB_EXPORT Q_DECL_EXPORT +#else +#define NGLDB_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.cpp old mode 100755 new mode 100644 index 0c59a952a..9cde55ae9 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.cpp @@ -13,10 +13,11 @@ NGLDB::LOGGER_T NGLDB::getLogger(const char *name) loggerName.append(ns, sizeof(ns) - 1); loggerName.append(name, len); - try { - return NGL::NGLLoggerBootstrap::getNGLRootLogger(). - getNGLLogger( loggerName ); - } catch ( const std::exception &ex ) + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception &ex) { fprintf(stderr, "Error retrieving logger: %s", ex.what()); abort(); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.h old mode 100755 new mode 100644 index 78e7f48e0..f9bb3e42b --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/ngldb_logger.h @@ -12,8 +12,8 @@ #endif #ifdef NGLDB_ENABLE_TRACE -#define DB_TRACE { TRACE_LOG(mLogger) << DB_TRACE_FUNCTION } -#define DB_TRACE2(x) { TRACE_LOG(mLogger) << DB_TRACE_FUNCTION << x } +#define DB_TRACE {TRACE_LOG(mLogger) << DB_TRACE_FUNCTION} +#define DB_TRACE2(x) {TRACE_LOG(mLogger) << DB_TRACE_FUNCTION << x} #else #define DB_TRACE #define DB_TRACE2(x) @@ -21,11 +21,11 @@ namespace NGLDB { -typedef NGL::INGLLogger &LOGGER_T; + typedef NGL::INGLLogger &LOGGER_T; -LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) -{ - return getLogger(loggerName.toUtf8().constData()); + LOGGER_T getLogger(const char *name); + inline LOGGER_T getLogger(const QString &loggerName) + { + return getLogger(loggerName.toUtf8().constData()); + } } -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.cpp old mode 100755 new mode 100644 index 206daaa74..ec483dd24 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.cpp @@ -20,42 +20,40 @@ static QString getSqlErrorString(const QSqlError &error) { - return error.driverText() + QLatin1Char(' ') + - error.databaseText() + QLatin1Char(' ') + - error.nativeErrorCode(); + return error.driverText() + QLatin1Char(' ') + error.databaseText() + QLatin1Char(' ') + error.nativeErrorCode(); } NSqlQuery::NSqlQuery(const QSqlDatabase &db) - : QSqlQuery(db) - , m_db(db) - , mLogger(NGLDB::getLogger("NSqlQuery")) + : QSqlQuery(db) + , m_db(db) + , mLogger(NGLDB::getLogger("NSqlQuery")) { DB_TRACE setForwardOnly(true); } NSqlQuery::NSqlQuery(const QSqlDatabase &db, NGL::INGLLogger &logger) - : QSqlQuery(db) - , m_db(db) - , mLogger(logger) + : QSqlQuery(db) + , m_db(db) + , mLogger(logger) { DB_TRACE setForwardOnly(true); } NSqlQuery::NSqlQuery(const QString &query, const QSqlDatabase &db) - : QSqlQuery(query, db) - , m_db(db) - , mLogger(NGLDB::getLogger("NSqlQuery")) + : QSqlQuery(query, db) + , m_db(db) + , mLogger(NGLDB::getLogger("NSqlQuery")) { DB_TRACE setForwardOnly(true); } NSqlQuery::NSqlQuery(const QString &query, const QSqlDatabase &db, NGL::INGLLogger &logger) - : QSqlQuery(query, db) - , m_db(db) - , mLogger(logger) + : QSqlQuery(query, db) + , m_db(db) + , mLogger(logger) { DB_TRACE setForwardOnly(true); @@ -143,12 +141,12 @@ bool NSqlQuery::exec(bool bEmitMessageOnError) if (mLogger.isDebugEnabled()) { const QMap &boundValuesMap = boundValues(); - for (auto it=boundValuesMap.begin(); it != boundValuesMap.end(); ++it) + for (auto it = boundValuesMap.begin(); it != boundValuesMap.end(); ++it) { - if ( it.value().canConvert()) - DEBUG_LOG(mLogger) << "key='" << it.key() << "' value='" << it.value().toString() << "'"; + if (it.value().canConvert()) + DEBUG_LOG(mLogger) << "key='" << it.key() << "' value='" << it.value().toString() << "'"; else - DEBUG_LOG(mLogger) << "key='" << it.key() << "' value cant Convert to string'"; + DEBUG_LOG(mLogger) << "key='" << it.key() << "' value cant Convert to string'"; } } if (QSqlQuery::exec()) @@ -257,7 +255,7 @@ QString NSqlQuery::sqlstate() #ifdef PostgreSQL_FOUND if (resultHandle.isValid() && (qstrcmp(resultHandle.typeName(), "PGresult*") == 0)) { - const PGresult *pgresHandle = *static_cast(resultHandle.data()); + const PGresult *pgresHandle = *static_cast(resultHandle.data()); if (pgresHandle != nullptr) { @@ -265,7 +263,7 @@ QString NSqlQuery::sqlstate() } } #endif - + return QStringLiteral("58000"); } @@ -383,7 +381,7 @@ QVariant NSqlQuery::value(int index) const return QSqlQuery::value(index); } -NSqlQuery &NSqlQuery::operator= (const NSqlQuery &other) +NSqlQuery &NSqlQuery::operator=(const NSqlQuery &other) { DB_TRACE // Use move assignment to avoid deprecated copy-assignment of QSqlQuery. diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.h old mode 100755 new mode 100644 index 3677c5306..dae542e87 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/nsqlquery.h @@ -10,205 +10,160 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } class QDateTime; class QJsonValue; - class NGLDB_EXPORT NSqlQuery final : public QSqlQuery { public: - - explicit NSqlQuery(const QSqlDatabase &db); explicit NSqlQuery(const QSqlDatabase &db, NGL::INGLLogger &logger); explicit NSqlQuery(const QString &query, const QSqlDatabase &db); explicit NSqlQuery(const QString &query, const QSqlDatabase &db, NGL::INGLLogger &logger); - NSqlQuery(const NSqlQuery &other) = default; - ~NSqlQuery() = default; - void addBindValue(const QVariant &val, QSql::ParamType paramType = QSql::In); - int at() const; - void bindValue(const QString &placeholder, const QVariant &val, QSql::ParamType paramType = QSql::In); - void bindValue(int pos, const QVariant &val, QSql::ParamType paramType = QSql::In); - QVariant boundValue(const QString &placeholder) const; - QVariant boundValue(int pos) const; - QMap boundValues() const; - void clear(); - const QSqlDriver *driver() const; - bool exec(const QString &query, bool bEmitMessageOnError = true); - bool exec(bool bEmitMessageOnError = true); - bool execAndFetch(); - bool execAndFetch(const QString &query); - bool execBatch(BatchExecutionMode mode = ValuesAsRows); - QString executedQuery() const; - void finish(); - bool first(); - bool isActive() const; - bool isForwardOnly() const; - bool isNull(int field) const; - bool isSelect() const; - bool isValid() const; - bool last(); - QSqlError lastError() const; QString sqlstate(); - + QVariant lastInsertId(); - QString lastQuery() const; - bool next(); - bool nextResult(); - int numRowsAffected() const; - QSql::NumericalPrecisionPolicy numericalPrecisionPolicy() const; - bool prepare(const QString &query); - bool previous(); - QSqlRecord record() const; - const QSqlResult *result() const; - bool seek(int index, bool relative = false); - void setForwardOnly(bool forward); - void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy); - int size() const; - QVariant value(int index) const; - - NSqlQuery &operator= (const NSqlQuery &other); + NSqlQuery &operator=(const NSqlQuery &other); bool export2CSV(const QString &filename); - static QVariant qDateTimeToQVariant(const QDateTime &dt); - + static QDateTime qVariantToQDateTime(const QVariant &var); - + static QString qVariantToJsonString(const QVariant &value); - + static QString jsonValueToJsonString(const QJsonValue &value); static inline QString fixupEmptyJsonString(const QString &str) { return str.isEmpty() ? QLatin1String("{}") : str; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.cpp old mode 100755 new mode 100644 index 8cd8a1e71..a11ea8449 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.cpp @@ -7,14 +7,14 @@ SqlQueryJanitor::SqlQueryJanitor(NSqlQuery *query) - : m_query(query) + : m_query(query) { Q_ASSERT(m_query); Q_ASSERT(!m_query->isActive()); } SqlQueryJanitor::SqlQueryJanitor(const std::unique_ptr &query) - : SqlQueryJanitor(query.get()) + : SqlQueryJanitor(query.get()) { } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.h b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.h old mode 100755 new mode 100644 index 22ed21484..6d225706f --- a/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngldb/sql_query_janitor.h @@ -9,7 +9,6 @@ class NSqlQuery; - class NGLDB_EXPORT SqlQueryJanitor { public: @@ -18,5 +17,5 @@ public: ~SqlQueryJanitor(); private: - NSqlQuery *m_query; + NSqlQuery *m_query; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.cpp old mode 100755 new mode 100644 index 129991c4c..54a520b13 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.cpp @@ -12,164 +12,164 @@ namespace NGL { -namespace Connections -{ -enum class eHostConfig -{ - public_local, - localhost, - server, - server_avs -}; -struct configStruct -{ - eHostConfig host; - unsigned short port; - QString name; -}; - -static QMap *s_config = nullptr; -static QSettings *s_settings = nullptr; -static unsigned short s_portOffset = 9000; -static QString *s_serverHostname = nullptr; - -static void cleanupSettings() -{ - delete s_settings; - s_settings = nullptr; - delete s_serverHostname; - s_serverHostname = nullptr; - delete s_config; - s_config = nullptr; -} - -static void insertConfig(eConnection conn, eHostConfig host, unsigned short port, const char *name) -{ - if (!s_config) - s_config = new QMap(); - configStruct s; - s.host = host; - s.port = port; - s.name = QString::fromLatin1(name); - s_config->insert(conn, s); -} - -static void initConfig() -{ - if (s_config && !s_config->isEmpty()) - return; - - insertConfig(eConnection::AVS_WORKSTATION, eHostConfig::localhost, 6370, "AVS_WORKSTATION"); - insertConfig(eConnection::AVS_WORKSTATION_VD, eHostConfig::localhost, 6380, "AVS_WORKSTATION_VD"); - insertConfig(eConnection::AVS_ROOT, eHostConfig::server_avs, 6350, "AVS_ROOT"); - insertConfig(eConnection::AVS_FM, eHostConfig::server_avs, 6360, "AVS_FM"); - insertConfig(eConnection::AVS_MOTION_RECORDER, eHostConfig::server_avs, 6390, "AVS_MOTION_RECORDER"); - insertConfig(eConnection::AVS_AVA, eHostConfig::server_avs, 6391, "AVS_AVA"); - - insertConfig(eConnection::PWS_WEBSOCKET, eHostConfig::server, 5701, "PWS_WEBSOCKET"); - insertConfig(eConnection::SCM_WEBSOCKET, eHostConfig::server, 7300, "SCM_WEBSOCKET"); - insertConfig(eConnection::ISM_WEBSOCKET, eHostConfig::server, 2080, "ISM_WEBSOCKET"); - insertConfig(eConnection::FLM_THP_SERVER, eHostConfig::server, 2090, "FLM_THP_SERVER"); - insertConfig(eConnection::FLM_PDF_SERVER, eHostConfig::server, 3000, "FLM_PDF_SERVER"); - - insertConfig(eConnection::LVS, eHostConfig::server, 94, "LVS"); - insertConfig(eConnection::ZWLVSV, eHostConfig::server, 95, "ZWLVSV"); - insertConfig(eConnection::ZWLVWCS, eHostConfig::server, 97, "ZWLVWCS"); - insertConfig(eConnection::ZWLVWMS, eHostConfig::server, 98, "ZWLVWMS"); - insertConfig(eConnection::ZSLV, eHostConfig::server, 99, "ZSLV"); -} - -void setIniFile(const QString &iniFileName) -{ - if (!s_settings) - qAddPostRoutine(cleanupSettings); - delete s_settings; - s_settings = new QSettings(iniFileName, QSettings::IniFormat); -} - -QString iniFile() -{ - return s_settings ? s_settings->fileName() : QString(); -} - -unsigned short portOffset() -{ - return s_portOffset; -} - -void setPortOffset(unsigned short portOffset) -{ - s_portOffset = portOffset; -} - -unsigned short port(eConnection connection) -{ - initConfig(); - unsigned short port = s_config->value(connection).port; - - if (s_settings) + namespace Connections { - bool bOk; - QString key = s_config->value(connection).name + QLatin1String("/port"); - unsigned short port2 = s_settings->value(key, port).toString().toUShort(&bOk); - if (bOk) - port = port2; - } - if (port < 100) - return portOffset() + port; - return port; -} + enum class eHostConfig + { + public_local, + localhost, + server, + server_avs + }; + struct configStruct + { + eHostConfig host; + unsigned short port; + QString name; + }; -QString hostName(eConnection connection) -{ - initConfig(); + static QMap *s_config = nullptr; + static QSettings *s_settings = nullptr; + static unsigned short s_portOffset = 9000; + static QString *s_serverHostname = nullptr; - QString host; - switch (s_config->value(connection).host) - { - case eHostConfig::public_local: - host = QString::fromLocal8Bit(qgetenv("HOST")); - break; - case eHostConfig::localhost: - host = QLatin1String("127.0.0.1"); - break; - case eHostConfig::server: - if (s_serverHostname) - host = *s_serverHostname; - if (host.isEmpty()) - host = QLatin1String("EXCTDS01"); - break; - case eHostConfig::server_avs: - host = QStringLiteral("EXCAVS01"); - break; - } - if (s_settings) - { - QString key = s_config->value(connection).name + QLatin1String("/host"); - QString host2 = s_settings->value(key, host).toString(); - if (!host2.isEmpty()) - host = host2; - } - return host; -} + static void cleanupSettings() + { + delete s_settings; + s_settings = nullptr; + delete s_serverHostname; + s_serverHostname = nullptr; + delete s_config; + s_config = nullptr; + } -void setServerHostname(const QString &serverHostName) -{ - if (!s_serverHostname) - s_serverHostname = new QString(serverHostName); - else - *s_serverHostname = serverHostName; -} + static void insertConfig(eConnection conn, eHostConfig host, unsigned short port, const char *name) + { + if (!s_config) + s_config = new QMap(); + configStruct s; + s.host = host; + s.port = port; + s.name = QString::fromLatin1(name); + s_config->insert(conn, s); + } -QString connectionName(eConnection connection) -{ - if (s_config) - { - auto it = s_config->constFind(connection); - if (it != s_config->constEnd()) - return it.value().name; + static void initConfig() + { + if (s_config && !s_config->isEmpty()) + return; + + insertConfig(eConnection::AVS_WORKSTATION, eHostConfig::localhost, 6370, "AVS_WORKSTATION"); + insertConfig(eConnection::AVS_WORKSTATION_VD, eHostConfig::localhost, 6380, "AVS_WORKSTATION_VD"); + insertConfig(eConnection::AVS_ROOT, eHostConfig::server_avs, 6350, "AVS_ROOT"); + insertConfig(eConnection::AVS_FM, eHostConfig::server_avs, 6360, "AVS_FM"); + insertConfig(eConnection::AVS_MOTION_RECORDER, eHostConfig::server_avs, 6390, "AVS_MOTION_RECORDER"); + insertConfig(eConnection::AVS_AVA, eHostConfig::server_avs, 6391, "AVS_AVA"); + + insertConfig(eConnection::PWS_WEBSOCKET, eHostConfig::server, 5701, "PWS_WEBSOCKET"); + insertConfig(eConnection::SCM_WEBSOCKET, eHostConfig::server, 7300, "SCM_WEBSOCKET"); + insertConfig(eConnection::ISM_WEBSOCKET, eHostConfig::server, 2080, "ISM_WEBSOCKET"); + insertConfig(eConnection::FLM_THP_SERVER, eHostConfig::server, 2090, "FLM_THP_SERVER"); + insertConfig(eConnection::FLM_PDF_SERVER, eHostConfig::server, 3000, "FLM_PDF_SERVER"); + + insertConfig(eConnection::LVS, eHostConfig::server, 94, "LVS"); + insertConfig(eConnection::ZWLVSV, eHostConfig::server, 95, "ZWLVSV"); + insertConfig(eConnection::ZWLVWCS, eHostConfig::server, 97, "ZWLVWCS"); + insertConfig(eConnection::ZWLVWMS, eHostConfig::server, 98, "ZWLVWMS"); + insertConfig(eConnection::ZSLV, eHostConfig::server, 99, "ZSLV"); + } + + void setIniFile(const QString &iniFileName) + { + if (!s_settings) + qAddPostRoutine(cleanupSettings); + delete s_settings; + s_settings = new QSettings(iniFileName, QSettings::IniFormat); + } + + QString iniFile() + { + return s_settings ? s_settings->fileName() : QString(); + } + + unsigned short portOffset() + { + return s_portOffset; + } + + void setPortOffset(unsigned short portOffset) + { + s_portOffset = portOffset; + } + + unsigned short port(eConnection connection) + { + initConfig(); + unsigned short port = s_config->value(connection).port; + + if (s_settings) + { + bool bOk; + QString key = s_config->value(connection).name + QLatin1String("/port"); + unsigned short port2 = s_settings->value(key, port).toString().toUShort(&bOk); + if (bOk) + port = port2; + } + if (port < 100) + return portOffset() + port; + return port; + } + + QString hostName(eConnection connection) + { + initConfig(); + + QString host; + switch (s_config->value(connection).host) + { + case eHostConfig::public_local: + host = QString::fromLocal8Bit(qgetenv("HOST")); + break; + case eHostConfig::localhost: + host = QLatin1String("127.0.0.1"); + break; + case eHostConfig::server: + if (s_serverHostname) + host = *s_serverHostname; + if (host.isEmpty()) + host = QLatin1String("EXCTDS01"); + break; + case eHostConfig::server_avs: + host = QStringLiteral("EXCAVS01"); + break; + } + if (s_settings) + { + QString key = s_config->value(connection).name + QLatin1String("/host"); + QString host2 = s_settings->value(key, host).toString(); + if (!host2.isEmpty()) + host = host2; + } + return host; + } + + void setServerHostname(const QString &serverHostName) + { + if (!s_serverHostname) + s_serverHostname = new QString(serverHostName); + else + *s_serverHostname = serverHostName; + } + + QString connectionName(eConnection connection) + { + if (s_config) + { + auto it = s_config->constFind(connection); + if (it != s_config->constEnd()) + return it.value().name; + } + return QString::number((int)connection); + } } - return QString::number((int)connection); } -} -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.h b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.h old mode 100755 new mode 100644 index 0f8a0a01c..345adabb8 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_connections.h @@ -9,51 +9,49 @@ namespace NGL { -namespace Connections -{ + namespace Connections + { -enum class eConnection -{ - UNKNOWN = 0, - AVS_WORKSTATION, - AVS_WORKSTATION_VD, - AVS_ROOT, - AVS_FM, - AVS_MOTION_RECORDER, - AVS_AVA, - ZWLVSV, - ZSLV, - ZWLVWCS, - ZWLVWMS, - PWS_WEBSOCKET, - SCM_WEBSOCKET, - ISM_WEBSOCKET, - FLM_THP_SERVER, - FLM_PDF_SERVER, - LVS , -}; + enum class eConnection + { + UNKNOWN = 0, + AVS_WORKSTATION, + AVS_WORKSTATION_VD, + AVS_ROOT, + AVS_FM, + AVS_MOTION_RECORDER, + AVS_AVA, + ZWLVSV, + ZSLV, + ZWLVWCS, + ZWLVWMS, + PWS_WEBSOCKET, + SCM_WEBSOCKET, + ISM_WEBSOCKET, + FLM_THP_SERVER, + FLM_PDF_SERVER, + LVS, + }; - -NGLSETTINGS_EXPORT void setIniFile(const QString &iniFileName); + NGLSETTINGS_EXPORT void setIniFile(const QString &iniFileName); -NGLSETTINGS_EXPORT QString iniFile(); + NGLSETTINGS_EXPORT QString iniFile(); - -NGLSETTINGS_EXPORT unsigned short portOffset(); -void setPortOffset(unsigned short portOffset); + NGLSETTINGS_EXPORT unsigned short portOffset(); + void setPortOffset(unsigned short portOffset); -NGLSETTINGS_EXPORT unsigned short port(eConnection connection); + NGLSETTINGS_EXPORT unsigned short port(eConnection connection); -NGLSETTINGS_EXPORT QString hostName(eConnection connection); -void setServerHostname(const QString &serverHostName); + NGLSETTINGS_EXPORT QString hostName(eConnection connection); + void setServerHostname(const QString &serverHostName); -NGLSETTINGS_EXPORT QString connectionName(eConnection connection); -} -} + NGLSETTINGS_EXPORT QString connectionName(eConnection connection); + } +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_export.h b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_export.h old mode 100755 new mode 100644 index e241cd015..fb8ab0136 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_export.h @@ -5,13 +5,13 @@ #include #ifndef NGLSETTINGS_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLSETTINGS_EXPORT -# else -# ifdef MAKE_NGLSETTINGS_LIB -# define NGLSETTINGS_EXPORT Q_DECL_EXPORT -# else -# define NGLSETTINGS_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLSETTINGS_EXPORT +#else +#ifdef MAKE_NGLSETTINGS_LIB +#define NGLSETTINGS_EXPORT Q_DECL_EXPORT +#else +#define NGLSETTINGS_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.cpp old mode 100755 new mode 100644 index 7493b455d..38bbbffb9 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.cpp @@ -16,20 +16,21 @@ namespace NGL QSettings *Settings::s_globalSettings = nullptr; Settings::Settings(const QString &iniFile_) - : m_settings(nullptr) + : m_settings(nullptr) { QString iniFile = iniFile_; - if(iniFile == QLatin1String("gfs_ws.ini")) { + if (iniFile == QLatin1String("gfs_ws.ini")) + { const QByteArray defUser = qgetenv("USER"); - if( defUser == "ctc_aar" || defUser == "ctc_rbf" ) { + if (defUser == "ctc_aar" || defUser == "ctc_rbf") + { QByteArray home = qgetenv("HOME"); - if(!home.isEmpty()) { - QString fn = QString::fromLocal8Bit(home) + - QLatin1String("/gfs_") + - QString::fromLocal8Bit(defUser.mid(4)) + - QLatin1String(".ini"); + if (!home.isEmpty()) + { + QString fn = QString::fromLocal8Bit(home) + QLatin1String("/gfs_") + QString::fromLocal8Bit(defUser.mid(4)) + QLatin1String(".ini"); QFileInfo fi(fn); - if(fi.exists() && fi.isFile() && fi.isReadable()) { + if (fi.exists() && fi.isFile() && fi.isReadable()) + { iniFile = fn; } } @@ -39,8 +40,9 @@ namespace NGL initializeGlobalSettings(); initPre(); - if(!iniFile.isEmpty()) { - if(QFileInfo(iniFile).isAbsolute()) + if (!iniFile.isEmpty()) + { + if (QFileInfo(iniFile).isAbsolute()) m_settings = new QSettings(iniFile, QSettings::IniFormat); else m_settings = new QSettings(basePath() + iniFile, QSettings::IniFormat); @@ -52,7 +54,7 @@ namespace NGL } Settings::Settings(const QString &organization, const QString &application) - : m_settings(new QSettings(organization, application)) + : m_settings(new QSettings(organization, application)) { initPre(); initPost(); @@ -71,8 +73,8 @@ namespace NGL if (!s_globalSettings) { QString globalSettingsFile = NGL::findProjectConfigFile(); - - + + if (!globalSettingsFile.isEmpty()) s_globalSettings = new QSettings(globalSettingsFile, QSettings::IniFormat); } @@ -141,7 +143,7 @@ namespace NGL { initializeGlobalSettings(); - return s_globalSettings->value(globalSectionName()+ QLatin1String("/DatabaseName"), QLatin1String("lts_ets_pro")).toString(); + return s_globalSettings->value(globalSectionName() + QLatin1String("/DatabaseName"), QLatin1String("lts_ets_pro")).toString(); } QString Settings::databaseHostname() @@ -209,23 +211,24 @@ namespace NGL QString Settings::fixupPath(const QString &_path) const { QString path = QDir::fromNativeSeparators(_path); - if(!QDir::isAbsolutePath(path)) + if (!QDir::isAbsolutePath(path)) path = basePath() + path; path = QDir::cleanPath(path); - if(!path.endsWith(QLatin1Char('/'))) + if (!path.endsWith(QLatin1Char('/'))) path += QLatin1Char('/'); return path; } QString Settings::getDirectory(const QByteArray &_dir, const QString &defPrefix, bool bPathLowercase) { - if(m_paths[_dir].isEmpty()) { + if (m_paths[_dir].isEmpty()) + { const QString lowerDir = QString::fromLatin1(_dir.toLower()); const QString dir = bPathLowercase ? lowerDir : QString::fromLatin1(_dir); QString def = defPrefix + QLatin1Char('/') + dir + QLatin1Char('/'); m_paths[_dir] = fixupPath(m_settings->value(QLatin1String("paths/") + lowerDir, def).toString()); QDir d(m_paths[_dir]); - if(!d.exists()) + if (!d.exists()) d.mkpath(d.absolutePath()); } return m_paths[_dir]; @@ -235,18 +238,18 @@ namespace NGL { #ifdef WIN32 QString path = QString::fromLocal8Bit(qgetenv("GFS_PATH")); - if(path.isEmpty()) + if (path.isEmpty()) path = QCoreApplication::applicationDirPath(); m_paths["GFS_PATH"] = fixupPath(path); #else QByteArray path = qgetenv("GFS_PATH"); - if(path.isEmpty()) + if (path.isEmpty()) path = qgetenv("HOME"); m_paths["GFS_PATH"] = fixupPath(QString::fromLocal8Bit(path)); #endif QByteArray tmppath = qgetenv("TMP_PATH"); - if(tmppath.isEmpty()) + if (tmppath.isEmpty()) tmppath = qgetenv("TMP"); if (tmppath.isEmpty()) tmppath = QDir::tempPath().toLocal8Bit(); @@ -317,4 +320,4 @@ namespace NGL #endif } -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.h b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.h old mode 100755 new mode 100644 index 14a9122c1..47b8f33ec --- a/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglsettings/nglsettings_settings.h @@ -8,135 +8,115 @@ class QSettings; -namespace NGL { - +namespace NGL +{ - class NGLSETTINGS_EXPORT Settings { - public: - - explicit Settings(const QString &iniFile); + class NGLSETTINGS_EXPORT Settings + { + public: + explicit Settings(const QString &iniFile); - - explicit Settings(const QString &organization, const QString &application); - - Settings(const Settings&) = delete; - Settings &operator=(const Settings&) = delete; + explicit Settings(const QString &organization, const QString &application); - + Settings(const Settings &) = delete; + Settings &operator=(const Settings &) = delete; - virtual ~Settings(); - - static void initializeGlobalSettings(); + virtual ~Settings(); - - QString basePath() const; - - QString tempPath() const; - - QString printPath(); - - QString logoProject(); - - QString bitmapPath(); - - - QString zsks_rxPath(); - - QString zsks_txPath(); + static void initializeGlobalSettings(); - - - static QString databaseName(); - - static QString databaseHostname(); - - QString databaseUser(); - - QString databasePassword(const QString &databaseUser = QString()); - - QString databaseDriver(); - - - QString aarServerPath(int exerciseId); - bool isDatabaseConnectionLocal(); + QString basePath() const; - - int avsKeepAliveTimeout(); - QString avsServerHost(); - quint16 avsServerPortAVE(); + QString tempPath() const; - - QSettings *settings(); - - const QSettings *settings() const; + QString printPath(); - - int getInteger(const QString &key, int defVal) const; + QString logoProject(); - - int getInteger(const QString &group, const QString &key, int defVal) const - { - return getInteger(group + QLatin1Char('/') + key, defVal); - } + QString bitmapPath(); - - float getFloat(const QString &key, float defVal) const; - - float getFloat(const QString &group, const QString &key, float defVal) const - { - return getFloat(group + QLatin1Char('/') + key, defVal); - } + QString zsks_rxPath(); - - double getDouble(const QString &key, double defVal) const; + QString zsks_txPath(); - - double getDouble(const QString &group, const QString &key, double defVal) const - { - return getDouble(group + QLatin1Char('/') + key, defVal); - } - - bool getBoolean(const QString &key, bool defVal) const; + static QString databaseName(); - - bool getBoolean(const QString &group, const QString &key, bool defVal) const - { - return getBoolean(group + QLatin1Char('/') + key, defVal); - } + static QString databaseHostname(); - - QString getString(const QString &key, const QString &defVal) const; + QString databaseUser(); - - QString getString(const QString &group, const QString &key, const QString &defVal) const - { - return getString(group + QLatin1Char('/') + key, defVal); - } + QString databasePassword(const QString &databaseUser = QString()); - static unsigned short portOffset(); - static unsigned short domainId(); - static QString serverHostname(); - static QString logPath(); - static QString globalSectionName(); + QString databaseDriver(); - private: - - QString fixupPath(const QString &path) const; - - QString getDirectory(const QByteArray &dir, const QString &defPrefix, bool bPathLowercase = false); - private: - void initPre(); - void initPost(); - QSettings *m_settings; - static QSettings *s_globalSettings; - QHash m_paths; + QString aarServerPath(int exerciseId); + bool isDatabaseConnectionLocal(); + + + int avsKeepAliveTimeout(); + QString avsServerHost(); + quint16 avsServerPortAVE(); + + + QSettings *settings(); + + const QSettings *settings() const; + + + int getInteger(const QString &key, int defVal) const; + + + int getInteger(const QString &group, const QString &key, int defVal) const { return getInteger(group + QLatin1Char('/') + key, defVal); } + + + float getFloat(const QString &key, float defVal) const; + + + float getFloat(const QString &group, const QString &key, float defVal) const { return getFloat(group + QLatin1Char('/') + key, defVal); } + + + double getDouble(const QString &key, double defVal) const; + + + double getDouble(const QString &group, const QString &key, double defVal) const { return getDouble(group + QLatin1Char('/') + key, defVal); } + + + bool getBoolean(const QString &key, bool defVal) const; + + + bool getBoolean(const QString &group, const QString &key, bool defVal) const { return getBoolean(group + QLatin1Char('/') + key, defVal); } + + + QString getString(const QString &key, const QString &defVal) const; + + + QString getString(const QString &group, const QString &key, const QString &defVal) const { return getString(group + QLatin1Char('/') + key, defVal); } + + static unsigned short portOffset(); + static unsigned short domainId(); + static QString serverHostname(); + static QString logPath(); + static QString globalSectionName(); + + private: + QString fixupPath(const QString &path) const; + + + QString getDirectory(const QByteArray &dir, const QString &defPrefix, bool bPathLowercase = false); + + private: + void initPre(); + void initPost(); + QSettings *m_settings; + static QSettings *s_globalSettings; + QHash m_paths; }; -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_bitset.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_bitset.h old mode 100755 new mode 100644 index fe6ed2fb3..6ef0d6c05 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_bitset.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_bitset.h @@ -3,33 +3,33 @@ #pragma once -namespace NGL { - template - class BitSet { +namespace NGL +{ + template class BitSet + { public: BitSet(T bitset = T()) - : mBitSet(bitset) - , mSize(sizeof(T)*8) - {} + : mBitSet(bitset) + , mSize(sizeof(T) * 8) + { + } BitSet(const BitSet &other) - : mBitSet(other.mBitSet) - , mSize(other.mSize) - {} + : mBitSet(other.mBitSet) + , mSize(other.mSize) + { + } BitSet &operator=(const BitSet &other) { - if(this == &other) + if (this == &other) return *this; mBitSet = other.mBitSet; mSize = other.mSize; return *this; } - bool operator==(const BitSet &other) const - { - return (mBitSet == other.mBitSet && mSize == other.mSize); - } + bool operator==(const BitSet &other) const { return (mBitSet == other.mBitSet && mSize == other.mSize); } bool setBit(unsigned int bitNum) { - if(bitNum >= mSize) + if (bitNum >= mSize) return false; mBitSet |= getBit(bitNum); return true; @@ -37,55 +37,46 @@ namespace NGL { bool clearBit(unsigned int bitNum) { - if(bitNum >= mSize) + if (bitNum >= mSize) return false; mBitSet &= ~(getBit(bitNum)); return true; } - + bool at(unsigned int bitNum) const { - if(bitNum >= sizeof(T) * 8) + if (bitNum >= sizeof(T) * 8) return false; T compVal = getBit(bitNum); return ((mBitSet & compVal) == compVal); } - - bool operator[] (unsigned int bitNum) const - { - return at(bitNum); - } - - size_t size() const - { - return mSize; - } - + + bool operator[](unsigned int bitNum) const { return at(bitNum); } + + size_t size() const { return mSize; } + bool resize(size_t newSize) { - if(newSize >= sizeof(T) * 8) + if (newSize >= sizeof(T) * 8) return false; - for(unsigned int i = mSize; i < newSize; ++i) + for (unsigned int i = mSize; i < newSize; ++i) clearBit(i); mSize = newSize; return true; } - - void clear() - { - fill(false); - } - + + void clear() { fill(false); } + void fill(bool bBitsSet) { - if(bBitsSet) + if (bBitsSet) mBitSet = ~T(); else mBitSet = T(); } - + T operator()() const { return mBitSet; } - + protected: static T getBit(unsigned int bitNum_) { @@ -97,4 +88,4 @@ namespace NGL { T mBitSet; size_t mSize; }; -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.cpp old mode 100755 new mode 100644 index e58059807..783f7bad8 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.cpp @@ -4,88 +4,88 @@ namespace NGL { -QByteArray quoteForTelnet(const QVector &sl) -{ - QVector tmp; - tmp.reserve(sl.size()); - for (const QString &s : sl) - tmp += s.toUtf8(); - return quoteForTelnet(tmp); -} - -QByteArray quoteForTelnet(const QVector &sl) -{ - QByteArray cmd; - for (QByteArray s : sl) + QByteArray quoteForTelnet(const QVector &sl) { - s.replace('\"', "\\\""); - if (s.contains(' ')) - s = '"' + s + '"'; - if (s.isEmpty()) - s = "\"\""; - cmd += s + ' '; + QVector tmp; + tmp.reserve(sl.size()); + for (const QString &s : sl) + tmp += s.toUtf8(); + return quoteForTelnet(tmp); } - cmd += '\n'; - return cmd; -} - -QVector parseFromTelnet(const QByteArray &ba, const int iStart) -{ - QVector ret; - const char *p = ba.constData() + iStart; - const int iLen = ba.length(); - const char *p_end = ba.constData() + iLen; - if (iLen <= iStart) - return ret; - char quoteEndChar = '"'; - - while (p < p_end && *p) + QByteArray quoteForTelnet(const QVector &sl) { - while (isspace(*p)) - ++p; - if (*p && p < p_end) + QByteArray cmd; + for (QByteArray s : sl) { - bool escaped = false; - bool bQuoted = (*p == '\"') || (*p == '{'); - if (bQuoted) - { - quoteEndChar = (*p == '\"') ? '\"' : '}'; + s.replace('\"', "\\\""); + if (s.contains(' ')) + s = '"' + s + '"'; + if (s.isEmpty()) + s = "\"\""; + cmd += s + ' '; + } + cmd += '\n'; + return cmd; + } + + + QVector parseFromTelnet(const QByteArray &ba, const int iStart) + { + QVector ret; + const char *p = ba.constData() + iStart; + const int iLen = ba.length(); + const char *p_end = ba.constData() + iLen; + if (iLen <= iStart) + return ret; + char quoteEndChar = '"'; + + while (p < p_end && *p) + { + while (isspace(*p)) ++p; - } - const char *start = p; - while (true) + if (*p && p < p_end) { - while (p < p_end && *p != (bQuoted ? quoteEndChar : ' ')) - ++p; + bool escaped = false; + bool bQuoted = (*p == '\"') || (*p == '{'); if (bQuoted) { - - if (* (p - 1) == '\\') - { - ++p; - escaped = true; - continue; - } + quoteEndChar = (*p == '\"') ? '\"' : '}'; + ++p; } - QByteArray result = QByteArray(start, p - start).trimmed(); - if (escaped) + const char *start = p; + while (true) { - if (quoteEndChar == '}') + while (p < p_end && *p != (bQuoted ? quoteEndChar : ' ')) + ++p; + if (bQuoted) { - result = result.replace("\\{", "{"); - result = result.replace("\\}", "}"); + + if (*(p - 1) == '\\') + { + ++p; + escaped = true; + continue; + } } - else - result = result.replace("\\\"", "\""); + QByteArray result = QByteArray(start, p - start).trimmed(); + if (escaped) + { + if (quoteEndChar == '}') + { + result = result.replace("\\{", "{"); + result = result.replace("\\}", "}"); + } + else + result = result.replace("\\\"", "\""); + } + ret += result; + ++p; + break; } - ret += result; - ++p; - break; } } + return ret; } - return ret; -} -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.h old mode 100755 new mode 100644 index da6bd2961..c212f4ead --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_convert.h @@ -11,13 +11,9 @@ namespace NGL { -NGLTOOLS_EXPORT QByteArray quoteForTelnet(const QVector &sl); -NGLTOOLS_EXPORT QByteArray quoteForTelnet(const QVector &sl); + NGLTOOLS_EXPORT QByteArray quoteForTelnet(const QVector &sl); + NGLTOOLS_EXPORT QByteArray quoteForTelnet(const QVector &sl); -NGLTOOLS_EXPORT QVector parseFromTelnet(const QByteArray &ba, const int iStart = 0); + NGLTOOLS_EXPORT QVector parseFromTelnet(const QByteArray &ba, const int iStart = 0); } - - - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.cpp old mode 100755 new mode 100644 index 47697e039..1003054cd --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.cpp @@ -7,367 +7,362 @@ namespace DTG { -static char s_timezone = 'Z'; -static char s_userDefinedTimezone = s_timezone; -static char s_exerciseDefaultTimezone = s_timezone; -int timezone2Hours(char tz, bool *bOk) -{ - if (!isTimezoneValid(tz)) + static char s_timezone = 'Z'; + static char s_userDefinedTimezone = s_timezone; + static char s_exerciseDefaultTimezone = s_timezone; + int timezone2Hours(char tz, bool *bOk) { + if (!isTimezoneValid(tz)) + { + if (bOk) + *bOk = false; + return 0; + } if (bOk) - *bOk = false; + *bOk = true; + if (tz < 'J') + return tz - 'A' + 1; + if (tz < 'N') + return tz - 'A'; + if (tz < 'Z') + return 'Z' - tz - 13; + return 0; } - if (bOk) - *bOk = true; - if (tz < 'J') - return tz - 'A' + 1; - if (tz < 'N') - return tz - 'A'; - if (tz < 'Z') - return 'Z' - tz - 13; - return 0; -} - -int timezone2Secs(char tz, bool *bOk) -{ - return 3600 * timezone2Hours(tz, bOk) ; -} - - -bool setTimezone(char tz, bool bUserDefinedZone) -{ - if (!isTimezoneValid(tz)) + int timezone2Secs(char tz, bool *bOk) { - - if (!(tz == 0 && bUserDefinedZone)) - return false; + return 3600 * timezone2Hours(tz, bOk); } - if (bUserDefinedZone) - s_userDefinedTimezone = tz; - else - s_exerciseDefaultTimezone = tz; - - s_timezone = s_userDefinedTimezone != 0 ? s_userDefinedTimezone : s_exerciseDefaultTimezone; - return true; -} - -char timezone() -{ - return s_timezone; -} -char timezoneUserDefined() -{ - return s_userDefinedTimezone; -} -char timezoneExerciseDefault() -{ - return s_exerciseDefaultTimezone; -} - -bool isTimezoneValid(char tz) -{ - tz = toupper(tz); - return !(tz < 'A' || tz == 'J' || tz > 'Z'); -} - -static DateTimeType s_dateTimeType = DDMMYYYY_Z_HHMMSS; -static DisplayFormat s_defaultDisplayFormat = Long; - - -void setDateTimeType(DateTimeType dtType) -{ - s_dateTimeType = dtType; -} - -DateTimeType dateTimeType() -{ - return s_dateTimeType; -} - -void setDefaultDisplayFormat(DisplayFormat dtFormat) -{ - s_defaultDisplayFormat = dtFormat; -} - -DisplayFormat defaultDisplayFormat() -{ - return s_defaultDisplayFormat; -} - -QString toString(const QDateTime &dt, DisplayFormat format, DateTimeType type) -{ - if (format == Default) - format = s_defaultDisplayFormat; - static const QDateTime dtNull = QDateTime::fromSecsSinceEpoch(0); - if (!dt.isValid() || dt == dtNull) - return QString(); - - const QDateTime dateTime = dt.toUTC().addSecs(timezone2Hours(s_timezone) * 3600); - QString ret; - - switch (type) + bool setTimezone(char tz, bool bUserDefinedZone) { - case DTG: - { - - - - QString str1; - - if (format == Long) - str1 = dateTime.toString(QLatin1String("dd hhmmss")); - else if (format == TurboLong) - str1 = dateTime.toString(QLatin1String("dd hhmmss.z")); - else + if (!isTimezoneValid(tz)) { - ret = dateTime.toString(QLatin1String("ddhhmm")) + QLatin1Char(s_timezone); + + if (!(tz == 0 && bUserDefinedZone)) + return false; + } + if (bUserDefinedZone) + s_userDefinedTimezone = tz; + else + s_exerciseDefaultTimezone = tz; + + s_timezone = s_userDefinedTimezone != 0 ? s_userDefinedTimezone : s_exerciseDefaultTimezone; + return true; + } + + char timezone() + { + return s_timezone; + } + char timezoneUserDefined() + { + return s_userDefinedTimezone; + } + char timezoneExerciseDefault() + { + return s_exerciseDefaultTimezone; + } + + bool isTimezoneValid(char tz) + { + tz = toupper(tz); + return !(tz < 'A' || tz == 'J' || tz > 'Z'); + } + + + static DateTimeType s_dateTimeType = DDMMYYYY_Z_HHMMSS; + static DisplayFormat s_defaultDisplayFormat = Long; + + + void setDateTimeType(DateTimeType dtType) + { + s_dateTimeType = dtType; + } + + DateTimeType dateTimeType() + { + return s_dateTimeType; + } + + void setDefaultDisplayFormat(DisplayFormat dtFormat) + { + s_defaultDisplayFormat = dtFormat; + } + + DisplayFormat defaultDisplayFormat() + { + return s_defaultDisplayFormat; + } + + QString toString(const QDateTime &dt, DisplayFormat format, DateTimeType type) + { + if (format == Default) + format = s_defaultDisplayFormat; + static const QDateTime dtNull = QDateTime::fromSecsSinceEpoch(0); + if (!dt.isValid() || dt == dtNull) + return QString(); + + const QDateTime dateTime = dt.toUTC().addSecs(timezone2Hours(s_timezone) * 3600); + QString ret; + + switch (type) + { + case DTG: + { + + + QString str1; + + if (format == Long) + str1 = dateTime.toString(QLatin1String("dd hhmmss")); + else if (format == TurboLong) + str1 = dateTime.toString(QLatin1String("dd hhmmss.z")); + else + { + ret = dateTime.toString(QLatin1String("ddhhmm")) + QLatin1Char(s_timezone); + break; + } + + + const int month = dateTime.date().month() - 1; + const int year = dateTime.date().year() - 2000; + ret = QStringLiteral("%1 %2 %3 %4").arg(str1).arg(QLatin1Char(s_timezone)).arg(months().at(month)).arg(year, 2, 10, QLatin1Char('0')); + } break; + case DDMMYYYY_HHMMSS_Z: + { + if (format == Long) + ret = dateTime.toString(QLatin1String("dd.MM.yyyy HH:mm:ss")) + QLatin1Char(s_timezone); + else + ret = dateTime.toString(QLatin1String("dd.MM HH:mm")) + QLatin1Char(s_timezone); + } + break; + case DDMMYYYY_Z_HHMMSS: + if (format == Long) + ret = dateTime.toString(QLatin1String("dd.MM.yyyy ")) + QLatin1Char(s_timezone) + dateTime.toString(QLatin1String(" HH:mm:ss")); + else + ret = dateTime.toString(QLatin1String("dd.MM ")) + QLatin1Char(s_timezone) + dateTime.toString(QLatin1String(" HH:mm")); + break; } - const int month = dateTime.date().month() - 1; - const int year = dateTime.date().year() - 2000; - ret = QStringLiteral("%1 %2 %3 %4") - .arg(str1) - .arg(QLatin1Char(s_timezone)) - .arg(months().at(month)) - .arg(year, 2, 10, QLatin1Char('0')); + return ret; } - break; - case DDMMYYYY_HHMMSS_Z: - { - if (format == Long) - ret = dateTime.toString(QLatin1String("dd.MM.yyyy HH:mm:ss")) + QLatin1Char(s_timezone); - else - ret = dateTime.toString(QLatin1String("dd.MM HH:mm")) + QLatin1Char(s_timezone); + QString toStringMSec(qint64 msecSinceEpoch, DisplayFormat format) + { + if (msecSinceEpoch <= 0) + return QString(); + return toString(QDateTime::fromMSecsSinceEpoch(msecSinceEpoch), format); } - break; - case DDMMYYYY_Z_HHMMSS: - if (format == Long) - ret = dateTime.toString(QLatin1String("dd.MM.yyyy ")) - + QLatin1Char(s_timezone) - + dateTime.toString(QLatin1String(" HH:mm:ss")); - else - ret = dateTime.toString(QLatin1String("dd.MM ")) - + QLatin1Char(s_timezone) - + dateTime.toString(QLatin1String(" HH:mm")); - break; - } - return ret; -} - -QString toStringMSec(qint64 msecSinceEpoch, DisplayFormat format) -{ - if (msecSinceEpoch <= 0) - return QString(); - return toString(QDateTime::fromMSecsSinceEpoch(msecSinceEpoch), format); -} - - -static bool check24(const QChar *input, int *output) -{ - const int i1 = input[0].unicode() - '0'; - const int i2 = input[1].unicode() - '0'; - if (i1 > 2) - return false; - if (i1 == 2 && i2 > 5) - return false; - if (output) - *output = i1 * 10 + i2; - return true; -} - -static bool check31(const QChar *input, int *output = nullptr) -{ - const int i1 = input[0].unicode() - '0'; - const int i2 = input[1].unicode() - '0'; - if (i1 > 3) - return false; - if (i1 == 3 && i2 > 1) - return false; - if (output) - *output = i1 * 10 + i2; - return true; -} - -static bool check60(const QChar *input, int *output) -{ - const int i1 = input[0].unicode() - '0'; - const int i2 = input[1].unicode() - '0'; - if (i1 > 5) - return false; - if (output) - *output = i1 * 10 + i2; - return true; -} - -static DTGValidation validate18(const QString &input, QDateTime &dt) -{ - int hh, mm, ss; - - for (int i = 0; i < 2; ++i) + static bool check24(const QChar *input, int *output) { - if (!input[i].isDigit()) - return Invalid; + const int i1 = input[0].unicode() - '0'; + const int i2 = input[1].unicode() - '0'; + if (i1 > 2) + return false; + if (i1 == 2 && i2 > 5) + return false; + if (output) + *output = i1 * 10 + i2; + return true; } - if (!check31(&input.data() [0])) - return Invalid; - if (input[2] != QLatin1Char(' ')) - return Invalid; - - if (input.length() == 7) + static bool check31(const QChar *input, int *output = nullptr) { - for (int i = 3; i < 7; ++i) + const int i1 = input[0].unicode() - '0'; + const int i2 = input[1].unicode() - '0'; + if (i1 > 3) + return false; + if (i1 == 3 && i2 > 1) + return false; + if (output) + *output = i1 * 10 + i2; + return true; + } + + static bool check60(const QChar *input, int *output) + { + const int i1 = input[0].unicode() - '0'; + const int i2 = input[1].unicode() - '0'; + if (i1 > 5) + return false; + if (output) + *output = i1 * 10 + i2; + return true; + } + + static DTGValidation validate18(const QString &input, QDateTime &dt) + { + int hh, mm, ss; + + for (int i = 0; i < 2; ++i) { if (!input[i].isDigit()) return Invalid; } - return Intermediate; - } - for (int i = 3; i < 9; ++i) - { - if (!input[i].isDigit()) + if (!check31(&input.data()[0])) return Invalid; - } - if (!check24(&input.data() [3], &hh)) - return Invalid; - if (!check60(&input.data() [5], &mm)) - return Invalid; - if (!check60(&input.data() [7], &ss)) - return Invalid; - if (input[9] != QLatin1Char(' ')) - return Invalid; - - const QChar c = input[10]; - if (c < QLatin1Char('A') || c > QLatin1Char('Z')) - return Invalid; - if (c == QLatin1Char('J')) - { - - return Invalid; - } - - const QString mon = input.mid(12, 3); - int month = months().indexOf(mon); - if (month < 0) - { - - return Invalid; - } - - for (int i = 16; i < 18; ++i) - { - if (!input[i].isDigit()) + if (input[2] != QLatin1Char(' ')) return Invalid; - } - - const int day = input.left(2).toInt(); - const int year = input.mid(16, 2).toInt() + 2000; - dt = QDateTime(QDate(year, month + 1, day), QTime(hh, mm, ss), QTimeZone::utc()); - if (!dt.isValid()) - { - - return Invalid; - } - dt = dt.addSecs(-timezone2Hours(c.toLatin1()) * 3600); - - - return Acceptable; -} - -static DTGValidation validate7(const QString &input, QDateTime &dt) -{ - int hh, mm; - - for (int i = 0; i < 6; ++i) - { - if (!input[i].isDigit()) + if (input.length() == 7) + { + for (int i = 3; i < 7; ++i) + { + if (!input[i].isDigit()) + return Invalid; + } + return Intermediate; + } + for (int i = 3; i < 9; ++i) + { + if (!input[i].isDigit()) + return Invalid; + } + if (!check24(&input.data()[3], &hh)) + return Invalid; + if (!check60(&input.data()[5], &mm)) + return Invalid; + if (!check60(&input.data()[7], &ss)) return Invalid; - } - if (!check31(&input.data() [0])) - return Invalid; - if (!check24(&input.data() [2], &hh)) - return Invalid; - if (!check60(&input.data() [4], &mm)) - return Invalid; - - const QChar c = input[6]; - if (c < QLatin1Char('A') || c > QLatin1Char('Z')) - return Invalid; - if (c == QLatin1Char('J')) + if (input[9] != QLatin1Char(' ')) + return Invalid; + + const QChar c = input[10]; + if (c < QLatin1Char('A') || c > QLatin1Char('Z')) + return Invalid; + if (c == QLatin1Char('J')) + { + + return Invalid; + } + + const QString mon = input.mid(12, 3); + int month = months().indexOf(mon); + if (month < 0) + { + + return Invalid; + } + + for (int i = 16; i < 18; ++i) + { + if (!input[i].isDigit()) + return Invalid; + } + + + const int day = input.left(2).toInt(); + const int year = input.mid(16, 2).toInt() + 2000; + dt = QDateTime(QDate(year, month + 1, day), QTime(hh, mm, ss), QTimeZone::utc()); + if (!dt.isValid()) + { + + return Invalid; + } + dt = dt.addSecs(-timezone2Hours(c.toLatin1()) * 3600); + + + return Acceptable; + } + + static DTGValidation validate7(const QString &input, QDateTime &dt) { - - return Invalid; + int hh, mm; + + for (int i = 0; i < 6; ++i) + { + if (!input[i].isDigit()) + return Invalid; + } + if (!check31(&input.data()[0])) + return Invalid; + if (!check24(&input.data()[2], &hh)) + return Invalid; + if (!check60(&input.data()[4], &mm)) + return Invalid; + + + const QChar c = input[6]; + if (c < QLatin1Char('A') || c > QLatin1Char('Z')) + return Invalid; + if (c == QLatin1Char('J')) + { + + return Invalid; + } + + + const int day = input.left(2).toInt(); + const QDate curDate = QDate::currentDate(); + dt = QDateTime(QDate(curDate.year(), curDate.month(), day), QTime(hh, mm), QTimeZone::utc()); + if (!dt.isValid()) + { + + return Invalid; + } + dt = dt.addSecs(-timezone2Hours(c.toLatin1()) * 3600); + + + return Acceptable; } - - const int day = input.left(2).toInt(); - const QDate curDate = QDate::currentDate(); - dt = QDateTime(QDate(curDate.year(), curDate.month(), day), QTime(hh, mm), QTimeZone::utc()); - if (!dt.isValid()) + QDateTime fromDTGString(const QString &str, bool *bOk) { - + if (bOk) + *bOk = false; + + QDateTime dt; + if (str.length() == 7) + { + DTGValidation state = validate7(str, dt); + if (state == Acceptable && bOk) + *bOk = true; + } + else if (str.length() == 18) + { + DTGValidation state = validate18(str, dt); + if (state == Acceptable && bOk) + *bOk = true; + } + return dt; + } + + DTGValidation validateString(const QString &str, QDateTime &dt) + { + const int len = str.length(); + if (len == 7 || len == 18) + { + + if (len == 18 || (str[2] == QLatin1Char(' '))) + return validate18(str, dt); + return validate7(str, dt); + } return Invalid; } - dt = dt.addSecs(-timezone2Hours(c.toLatin1()) * 3600); - - return Acceptable; + QStringList months() + { + return {QLatin1String("jan"), + QLatin1String("feb"), + QLatin1String("mar"), + QLatin1String("apr"), + QLatin1String("may"), + QLatin1String("jun"), + QLatin1String("jul"), + QLatin1String("aug"), + QLatin1String("sep"), + QLatin1String("oct"), + QLatin1String("nov"), + QLatin1String("dec")}; + } + } - -QDateTime fromDTGString(const QString &str, bool *bOk) -{ - if (bOk) - *bOk = false; - - QDateTime dt; - if (str.length() == 7) - { - DTGValidation state = validate7(str, dt); - if (state == Acceptable && bOk) - *bOk = true; - } - else if (str.length() == 18) - { - DTGValidation state = validate18(str, dt); - if (state == Acceptable && bOk) - *bOk = true; - } - return dt; -} - -DTGValidation validateString(const QString &str, QDateTime &dt) -{ - const int len = str.length(); - if (len == 7 || len == 18) - { - - if (len == 18 || (str[2] == QLatin1Char(' '))) - return validate18(str, dt); - return validate7(str, dt); - } - return Invalid; -} - -QStringList months() -{ - return { - QLatin1String("jan"), QLatin1String("feb"), QLatin1String("mar"), - QLatin1String("apr"), QLatin1String("may"), QLatin1String("jun"), - QLatin1String("jul"), QLatin1String("aug"), QLatin1String("sep"), - QLatin1String("oct"), QLatin1String("nov"), QLatin1String("dec") - }; -} - -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.h old mode 100755 new mode 100644 index cc4b0b6d6..1a093795b --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_dtg.h @@ -10,78 +10,70 @@ namespace DTG { - -enum DateTimeType -{ - DTG = 1, - DDMMYYYY_HHMMSS_Z = 2, - DDMMYYYY_Z_HHMMSS = 4 -}; + enum DateTimeType + { + DTG = 1, + DDMMYYYY_HHMMSS_Z = 2, + DDMMYYYY_Z_HHMMSS = 4 + }; + enum DisplayFormat + { + Short, + Long, + TurboLong, + Default + }; + + enum DTGValidation + { + Invalid, + Intermediate, + Acceptable + }; -enum DisplayFormat -{ - Short, - Long, - TurboLong, - Default -}; - -enum DTGValidation -{ - Invalid, - Intermediate, - Acceptable -}; + NGLTOOLS_EXPORT void setDateTimeType(DateTimeType dtType); - -NGLTOOLS_EXPORT void setDateTimeType(DateTimeType dtType); + NGLTOOLS_EXPORT DateTimeType dateTimeType(); -NGLTOOLS_EXPORT DateTimeType dateTimeType(); + NGLTOOLS_EXPORT void setDefaultDisplayFormat(DisplayFormat dtFormat); - -NGLTOOLS_EXPORT void setDefaultDisplayFormat(DisplayFormat dtFormat); + NGLTOOLS_EXPORT DisplayFormat defaultDisplayFormat(); -NGLTOOLS_EXPORT DisplayFormat defaultDisplayFormat(); + NGLTOOLS_EXPORT QString toString(const QDateTime &dt, DisplayFormat format = Default, DateTimeType = dateTimeType()); - -NGLTOOLS_EXPORT QString toString(const QDateTime &dt, DisplayFormat format = Default, DateTimeType = dateTimeType()); + NGLTOOLS_EXPORT QString toStringMSec(qint64 msecSinceEpoch, DisplayFormat format = Default); -NGLTOOLS_EXPORT QString toStringMSec(qint64 msecSinceEpoch, DisplayFormat format = Default); + NGLTOOLS_EXPORT QDateTime fromDTGString(const QString &str, bool *bOk = nullptr); - -NGLTOOLS_EXPORT QDateTime fromDTGString(const QString &str, bool *bOk = nullptr); + NGLTOOLS_EXPORT DTGValidation validateString(const QString &str, QDateTime &dt); -NGLTOOLS_EXPORT DTGValidation validateString(const QString &str, QDateTime &dt); + NGLTOOLS_EXPORT bool setTimezone(char tz, bool bUserDefinedZone); + NGLTOOLS_EXPORT char timezone(); + NGLTOOLS_EXPORT char timezoneUserDefined(); + NGLTOOLS_EXPORT char timezoneExerciseDefault(); -NGLTOOLS_EXPORT bool setTimezone(char tz, bool bUserDefinedZone); + NGLTOOLS_EXPORT bool isTimezoneValid(char tz); -NGLTOOLS_EXPORT char timezone(); -NGLTOOLS_EXPORT char timezoneUserDefined(); -NGLTOOLS_EXPORT char timezoneExerciseDefault(); - -NGLTOOLS_EXPORT bool isTimezoneValid(char tz); + NGLTOOLS_EXPORT int timezone2Hours(char tz, bool *bOk = nullptr); -NGLTOOLS_EXPORT int timezone2Hours(char tz, bool *bOk = nullptr); + NGLTOOLS_EXPORT int timezone2Secs(char tz, bool *bOk = nullptr); -NGLTOOLS_EXPORT int timezone2Secs(char tz, bool *bOk = nullptr); + NGLTOOLS_EXPORT QStringList months(); - -NGLTOOLS_EXPORT QStringList months(); - -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_export.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_export.h old mode 100755 new mode 100644 index b05ee3c2c..9c61638e1 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_export.h @@ -3,17 +3,17 @@ #pragma once #ifndef NGLTOOLS_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLTOOLS_EXPORT -# else -# ifdef WIN32 -# ifdef MAKE_NGLTOOLS_LIB -# define NGLTOOLS_EXPORT __declspec(dllexport) -# else -# define NGLTOOLS_EXPORT __declspec(dllimport) -# endif -# else -# define NGLTOOLS_EXPORT __attribute__((visibility("default"))) -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLTOOLS_EXPORT +#else +#ifdef WIN32 +#ifdef MAKE_NGLTOOLS_LIB +#define NGLTOOLS_EXPORT __declspec(dllexport) +#else +#define NGLTOOLS_EXPORT __declspec(dllimport) +#endif +#else +#define NGLTOOLS_EXPORT __attribute__((visibility("default"))) +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.cpp old mode 100755 new mode 100644 index dd868bf9b..fd03e091b --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.cpp @@ -11,280 +11,274 @@ namespace NGL { -bool removeDirContentsRecursively(const QString &d, bool bAlsoDeleteBaseDir) -{ - - QDir dir(d); - if (!dir.exists()) - return false; - - bool success = true; - const QFileInfoList list = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries); - for (const QFileInfo &fi : list) + bool removeDirContentsRecursively(const QString &d, bool bAlsoDeleteBaseDir) { - bool ret = false; - if (fi.isDir()) + + QDir dir(d); + if (!dir.exists()) + return false; + + bool success = true; + const QFileInfoList list = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries); + for (const QFileInfo &fi : list) { - ret = removeDirContentsRecursively(fi.absoluteFilePath()); - if (!ret) + bool ret = false; + if (fi.isDir()) { - - } - else - { - ret = dir.rmdir(fi.absoluteFilePath()); + ret = removeDirContentsRecursively(fi.absoluteFilePath()); if (!ret) { - + } + else + { + ret = dir.rmdir(fi.absoluteFilePath()); + if (!ret) + { + } } } - - } - else if (fi.isFile() || fi.isSymLink()) - { - ret = dir.remove(fi.fileName()); - if (!ret) + else if (fi.isFile() || fi.isSymLink()) { - + ret = dir.remove(fi.fileName()); + if (!ret) + { + } } + success &= ret; } - success &= ret; + if (bAlsoDeleteBaseDir) + success &= dir.rmpath(d); + return success; } - if (bAlsoDeleteBaseDir) - success &= dir.rmpath(d); - return success; -} -bool copyDirContentsToDir(const QString &source, const QString &destination, bool sourceIsRelative) -{ - QString srcPath(source); - - if (sourceIsRelative) + bool copyDirContentsToDir(const QString &source, const QString &destination, bool sourceIsRelative) { - QVector pathsToSearch = directories(FileType::ConfigFile); - pathsToSearch.append(directories(FileType::ProjectConfigFile)); - for (const QString &basePath : std::as_const(pathsToSearch)) + QString srcPath(source); + + if (sourceIsRelative) { - QString absolutePath = basePath + QLatin1Char('/') + source; - if (QDir(absolutePath).exists()) + QVector pathsToSearch = directories(FileType::ConfigFile); + pathsToSearch.append(directories(FileType::ProjectConfigFile)); + for (const QString &basePath : std::as_const(pathsToSearch)) { - srcPath = absolutePath; - break; + QString absolutePath = basePath + QLatin1Char('/') + source; + if (QDir(absolutePath).exists()) + { + srcPath = absolutePath; + break; + } } + if (srcPath.isEmpty()) + return false; } - if (srcPath.isEmpty()) - return false; - } - QDir srcDir(srcPath); - QDir dstDir(destination); + QDir srcDir(srcPath); + QDir dstDir(destination); - if (!dstDir.exists()) - { - bool succ = dstDir.mkdir(destination); - if (!succ) - return false; - } - - const QFileInfoList dirList = srcDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot); - for (const QFileInfo &fi : dirList) - { - if (!dstDir.exists()) { - bool succ = dstDir.mkdir(fi.fileName()); + bool succ = dstDir.mkdir(destination); if (!succ) return false; } - bool succ = copyDirContentsToDir(fi.filePath(), dstDir.absolutePath() + QLatin1Char('/') + fi.fileName()); - if (!succ) - return false; + + const QFileInfoList dirList = srcDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot); + for (const QFileInfo &fi : dirList) + { + + if (!dstDir.exists()) + { + bool succ = dstDir.mkdir(fi.fileName()); + if (!succ) + return false; + } + bool succ = copyDirContentsToDir(fi.filePath(), dstDir.absolutePath() + QLatin1Char('/') + fi.fileName()); + if (!succ) + return false; + } + + const QFileInfoList fileList = srcDir.entryInfoList(QDir::Files | QDir::Hidden); + for (const QFileInfo &fi : fileList) + { + QString targetFileName = dstDir.absolutePath() + QLatin1Char('/') + fi.fileName(); + QFile targetFile(targetFileName); + if (targetFile.exists()) + targetFile.remove(); + bool succ = QFile::copy(fi.absoluteFilePath(), targetFileName); + if (!succ) + return false; + } + return true; } - const QFileInfoList fileList = srcDir.entryInfoList(QDir::Files | QDir::Hidden); - for (const QFileInfo &fi : fileList) + qint64 getDirectorySize(const QString &dir) { - QString targetFileName = dstDir.absolutePath() + QLatin1Char('/') + fi.fileName(); - QFile targetFile(targetFileName); - if (targetFile.exists()) - targetFile.remove(); - bool succ = QFile::copy(fi.absoluteFilePath(), targetFileName); - if (!succ) - return false; + QDir d(dir); + qint64 ret = QFileInfo(dir).size(); + + const QFileInfoList dirList = d.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot); + const QFileInfoList fileList = d.entryInfoList(QDir::Files | QDir::Hidden); + + for (const QFileInfo &fi : dirList) + ret += getDirectorySize(fi.absoluteFilePath()); + + for (const QFileInfo &fi : fileList) + ret += fi.size(); + + return ret; } - return true; -} -qint64 getDirectorySize(const QString &dir) -{ - QDir d(dir); - qint64 ret = QFileInfo(dir).size(); - - const QFileInfoList dirList = d.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot); - const QFileInfoList fileList = d.entryInfoList(QDir::Files | QDir::Hidden); - - for (const QFileInfo &fi : dirList) - ret += getDirectorySize(fi.absoluteFilePath()); - - for (const QFileInfo &fi : fileList) - ret += fi.size(); - - return ret; -} - -bool isAppInBuildBasePath() -{ - bool ret = false; + bool isAppInBuildBasePath() + { + bool ret = false; #ifdef BUILD_BASE_PATH - const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); - if (!bbp.isEmpty()) - ret = QCoreApplication::applicationDirPath().startsWith(bbp); + const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); + if (!bbp.isEmpty()) + ret = QCoreApplication::applicationDirPath().startsWith(bbp); #endif - return ret; -} + return ret; + } -QString projectConfigFileName() -{ - return QLatin1String("lts-cc.conf"); -} + QString projectConfigFileName() + { + return QLatin1String("lts-cc.conf"); + } -QString findProjectConfigFile() -{ - return findFile(FileType::ProjectConfigFile, projectConfigFileName()); -} + QString findProjectConfigFile() + { + return findFile(FileType::ProjectConfigFile, projectConfigFileName()); + } -static QString searchFileInDir(const QString &path, const QString &filename, bool bRecursive) -{ - if (QFile::exists(path + QLatin1Char('/') + filename)) - return path + QLatin1Char('/') + filename; + static QString searchFileInDir(const QString &path, const QString &filename, bool bRecursive) + { + if (QFile::exists(path + QLatin1Char('/') + filename)) + return path + QLatin1Char('/') + filename; - if (!bRecursive) + if (!bRecursive) + return QString(); + + const QDir d(path); + const QStringList entryList = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); + for (const QString &entry : entryList) + { + const QString foundPath = searchFileInDir(path + QLatin1Char('/') + entry, filename, bRecursive); + if (!foundPath.isEmpty()) + return foundPath; + } return QString(); - - const QDir d(path); - const QStringList entryList = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); - for (const QString &entry : entryList) - { - const QString foundPath = searchFileInDir(path + QLatin1Char('/') + entry, filename, bRecursive); - if (!foundPath.isEmpty()) - return foundPath; } - return QString(); -} -QString findFile(FileType fileType, const QString &filename) -{ - const QFileInfo fi(filename); - if (fi.isAbsolute()) - return fi.exists() ? filename : QString(); - const bool bRecursive = (fileType == FileType::ConfigFile); - const QVector pathsToSearch = directories(fileType); - for (const QString &path : pathsToSearch) + QString findFile(FileType fileType, const QString &filename) { - const QString foundPath = searchFileInDir(path, filename, bRecursive); - if (!foundPath.isEmpty()) - return foundPath; - } - return QString(); -} - -QVector directories(FileType fileType) -{ - QVector pathsToSearch; - switch (fileType) - { - case FileType::ProjectConfigFile: - { -#ifdef BUILD_BASE_PATH - const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); - if (!bbp.isEmpty()) + const QFileInfo fi(filename); + if (fi.isAbsolute()) + return fi.exists() ? filename : QString(); + const bool bRecursive = (fileType == FileType::ConfigFile); + const QVector pathsToSearch = directories(fileType); + for (const QString &path : pathsToSearch) { - - - - if (QCoreApplication::applicationDirPath().startsWith(bbp)) - pathsToSearch += bbp; + const QString foundPath = searchFileInDir(path, filename, bRecursive); + if (!foundPath.isEmpty()) + return foundPath; } + return QString(); + } + + QVector directories(FileType fileType) + { + QVector pathsToSearch; + switch (fileType) + { + case FileType::ProjectConfigFile: + { +#ifdef BUILD_BASE_PATH + const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); + if (!bbp.isEmpty()) + { + + + if (QCoreApplication::applicationDirPath().startsWith(bbp)) + pathsToSearch += bbp; + } #endif - pathsToSearch += QDir::homePath(); + pathsToSearch += QDir::homePath(); #ifdef Q_OS_UNIX - pathsToSearch += QLatin1String("/etc"); + pathsToSearch += QLatin1String("/etc"); #else - pathsToSearch += QStringLiteral("C:/Rheinmetall/Lts/"); - pathsToSearch += QCoreApplication::applicationDirPath(); + pathsToSearch += QStringLiteral("C:/Rheinmetall/Lts/"); + pathsToSearch += QCoreApplication::applicationDirPath(); #endif - break; - } - case FileType::ConfigFile: - { + break; + } + case FileType::ConfigFile: + { #ifdef BUILD_BASE_PATH - const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); - if (!bbp.isEmpty()) - { - - - - if (QCoreApplication::applicationDirPath().startsWith(bbp)) - pathsToSearch += bbp + QLatin1String("/share/Lts"); - } + const QString bbp(QString::fromLocal8Bit(BUILD_BASE_PATH)); + if (!bbp.isEmpty()) + { + + + if (QCoreApplication::applicationDirPath().startsWith(bbp)) + pathsToSearch += bbp + QLatin1String("/share/Lts"); + } #endif - pathsToSearch += QCoreApplication::applicationDirPath() + QLatin1String("/share/Lts"); - pathsToSearch += QCoreApplication::applicationDirPath() + QLatin1String("/../share/Lts"); - pathsToSearch += QDir::homePath() + QLatin1String("/share/Lts"); + pathsToSearch += QCoreApplication::applicationDirPath() + QLatin1String("/share/Lts"); + pathsToSearch += QCoreApplication::applicationDirPath() + QLatin1String("/../share/Lts"); + pathsToSearch += QDir::homePath() + QLatin1String("/share/Lts"); #ifdef INSTALL_PREFIX - pathsToSearch += QString::fromLocal8Bit(INSTALL_PREFIX) + QLatin1String("/share/Lts"); + pathsToSearch += QString::fromLocal8Bit(INSTALL_PREFIX) + QLatin1String("/share/Lts"); #endif - break; + break; + } + } + return pathsToSearch; } - } - return pathsToSearch; -} -QString findServiceXmlFile(const QString &serviceShortName) -{ - return findFile(FileType::ConfigFile, serviceShortName + QLatin1String(".xml")); -} - -QString directory(FileType fileType, const QString &subdir) -{ - const QVector pathsToSearch = directories(fileType); - QFileInfo fi; - for (const QString &path : pathsToSearch) + QString findServiceXmlFile(const QString &serviceShortName) { - fi.setFile(path + QLatin1Char('/') + subdir); - if (fi.isDir() && fi.exists() && fi.isReadable()) - return fi.absoluteFilePath() + QLatin1Char('/'); + return findFile(FileType::ConfigFile, serviceShortName + QLatin1String(".xml")); } - return QString(); -} -QString postgresExecutablePath(const QString &psqlProgram, QString &errStr) -{ - errStr.clear(); + QString directory(FileType fileType, const QString &subdir) + { + const QVector pathsToSearch = directories(fileType); + QFileInfo fi; + for (const QString &path : pathsToSearch) + { + fi.setFile(path + QLatin1Char('/') + subdir); + if (fi.isDir() && fi.exists() && fi.isReadable()) + return fi.absoluteFilePath() + QLatin1Char('/'); + } + return QString(); + } + + QString postgresExecutablePath(const QString &psqlProgram, QString &errStr) + { + errStr.clear(); #ifdef Q_OS_LINUX - return QStringLiteral("/usr/bin/") + psqlProgram; + return QStringLiteral("/usr/bin/") + psqlProgram; #else - static QString s_postgresBinariesPath; - if (s_postgresBinariesPath.isEmpty()) - { - QSettings s(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\PostgreSQL\\Installations"), QSettings::NativeFormat); - const QStringList installations = s.childGroups(); - if (installations.isEmpty()) + static QString s_postgresBinariesPath; + if (s_postgresBinariesPath.isEmpty()) { - errStr = QStringLiteral("Could not find a valid PostgreSQL windows installation..."); - return psqlProgram; + QSettings s(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\PostgreSQL\\Installations"), QSettings::NativeFormat); + const QStringList installations = s.childGroups(); + if (installations.isEmpty()) + { + errStr = QStringLiteral("Could not find a valid PostgreSQL windows installation..."); + return psqlProgram; + } + if (installations.size() > 1) + errStr = QStringLiteral("More than one PostgreSQL windows installation found - using the first one: %1").arg(installations.first()); + s.beginGroup(installations.first()); + const QString baseDir = s.value(QStringLiteral("Base Directory")).toString(); + if (baseDir.isEmpty() || !QDir(baseDir).exists()) + { + errStr = QStringLiteral("Could not find a valid PostgreSQL windows installation... - Base Directory is empty or does not exist (%1)").arg(baseDir); + return psqlProgram; + } + s_postgresBinariesPath = baseDir + QStringLiteral("/bin/"); } - if (installations.size() > 1) - errStr = QStringLiteral("More than one PostgreSQL windows installation found - using the first one: %1").arg(installations.first()); - s.beginGroup(installations.first()); - const QString baseDir = s.value(QStringLiteral("Base Directory")).toString(); - if (baseDir.isEmpty() || !QDir(baseDir).exists()) - { - errStr = QStringLiteral("Could not find a valid PostgreSQL windows installation... - Base Directory is empty or does not exist (%1)").arg(baseDir); - return psqlProgram; - } - s_postgresBinariesPath = baseDir + QStringLiteral("/bin/"); - } - return s_postgresBinariesPath + psqlProgram + QStringLiteral(".exe"); + return s_postgresBinariesPath + psqlProgram + QStringLiteral(".exe"); #endif + } } -} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.h old mode 100755 new mode 100644 index 6d59f67c8..6d626efaf --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_filesystem.h @@ -10,10 +10,10 @@ namespace NGL { - NGLTOOLS_EXPORT bool removeDirContentsRecursively(const QString &d, bool bAlsoDeleteBaseDir = false); - NGLTOOLS_EXPORT bool copyDirContentsToDir(const QString &source, const QString &destination, bool sourceIsRelative = false); + NGLTOOLS_EXPORT bool removeDirContentsRecursively(const QString &d, bool bAlsoDeleteBaseDir = false); + NGLTOOLS_EXPORT bool copyDirContentsToDir(const QString &source, const QString &destination, bool sourceIsRelative = false); NGLTOOLS_EXPORT qint64 getDirectorySize(const QString &dir); - + enum class FileType { @@ -25,14 +25,14 @@ namespace NGL NGLTOOLS_EXPORT QString projectConfigFileName(); NGLTOOLS_EXPORT QString findProjectConfigFile(); NGLTOOLS_EXPORT QString findFile(FileType fileType, const QString &filename); - + NGLTOOLS_EXPORT QString findServiceXmlFile(const QString &serviceShortName); - + NGLTOOLS_EXPORT QVector directories(FileType fileType); - + NGLTOOLS_EXPORT QString directory(FileType fileType, const QString &subdir); - + NGLTOOLS_EXPORT QString postgresExecutablePath(const QString &psqlProgram, QString &errStr); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.cpp old mode 100755 new mode 100644 index 937348497..27376408e --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.cpp @@ -13,7 +13,7 @@ void NGLHelpEvent::sendHelpEvent(const QString &helpContext) QEvent::Type NGLHelpEvent::helpEventId() { - if(sHelpEventId < 0) + if (sHelpEventId < 0) sHelpEventId = (QEvent::Type)(QEvent::registerEventType()); return sHelpEventId; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.h old mode 100755 new mode 100644 index e408fb52a..00f570430 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/ngltools_helpevent.h @@ -7,24 +7,21 @@ #include "ngltools_export.h" - class NGLTOOLS_EXPORT NGLHelpEvent : public QEvent { protected: - - explicit NGLHelpEvent(const QString &helpContext) - : QEvent(helpEventId()) - , mHelpContext(helpContext) - {} -public: - + : QEvent(helpEventId()) + , mHelpContext(helpContext) + { + } +public: QString helpContext() const { return mHelpContext; } - + static void sendHelpEvent(const QString &helpContext); - + static QEvent::Type helpEventId(); diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/tests/NGLToolsQtSmokeTest.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/tests/NGLToolsQtSmokeTest.cpp index 921b4eae7..34a352b30 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltools/tests/NGLToolsQtSmokeTest.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltools/tests/NGLToolsQtSmokeTest.cpp @@ -6,18 +6,18 @@ class NGLToolsQtSmokeTest : public QObject { - Q_OBJECT + Q_OBJECT private slots: - void testDTG() - { - QDateTime now = QDateTime::currentDateTimeUtc(); - QString s = DTG::toString(now, DTG::Default, DTG::DTG); - QVERIFY(!s.isEmpty()); - bool ok = false; - QDateTime parsed = DTG::fromDTGString(s, &ok); - QVERIFY(ok); - QVERIFY(parsed.isValid()); - } + void testDTG() + { + QDateTime now = QDateTime::currentDateTimeUtc(); + QString s = DTG::toString(now, DTG::Default, DTG::DTG); + QVERIFY(!s.isEmpty()); + bool ok = false; + QDateTime parsed = DTG::fromDTGString(s, &ok); + QVERIFY(ok); + QVERIFY(parsed.isValid()); + } }; QTEST_MAIN(NGLToolsQtSmokeTest) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.cpp b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.cpp old mode 100755 new mode 100644 index 1aa865720..a6cb5290a --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.cpp @@ -19,212 +19,201 @@ namespace NGL { -struct TranslationData -{ - QByteArray isoCode; - QString qmPrefix; - QTranslator qtTranslator; - QTranslator kdReportsTranslator; - QTranslator ltsTranslator; - Translator dynamicTranslator; + struct TranslationData + { + QByteArray isoCode; + QString qmPrefix; + QTranslator qtTranslator; + QTranslator kdReportsTranslator; + QTranslator ltsTranslator; + Translator dynamicTranslator; - TranslationData() - { - QCoreApplication::installTranslator(&qtTranslator); - QCoreApplication::installTranslator(&kdReportsTranslator); - QCoreApplication::installTranslator(<sTranslator); - QCoreApplication::installTranslator(&dynamicTranslator); - } - ~TranslationData() - { - if (qApp) + TranslationData() { - QCoreApplication::removeTranslator(&qtTranslator); - QCoreApplication::removeTranslator(&kdReportsTranslator); - QCoreApplication::removeTranslator(<sTranslator); - QCoreApplication::removeTranslator(&dynamicTranslator); + QCoreApplication::installTranslator(&qtTranslator); + QCoreApplication::installTranslator(&kdReportsTranslator); + QCoreApplication::installTranslator(<sTranslator); + QCoreApplication::installTranslator(&dynamicTranslator); } + ~TranslationData() + { + if (qApp) + { + QCoreApplication::removeTranslator(&qtTranslator); + QCoreApplication::removeTranslator(&kdReportsTranslator); + QCoreApplication::removeTranslator(<sTranslator); + QCoreApplication::removeTranslator(&dynamicTranslator); + } + } + }; + + Q_GLOBAL_STATIC(TranslationData, s_translationData) + + + Translator::Translator(QObject *parent) + : QTranslator(parent) + { } -}; - -Q_GLOBAL_STATIC(TranslationData, s_translationData) -Translator::Translator(QObject *parent) - : QTranslator(parent) -{} + void Translator::setTranslationCatalog(const TranslationCatalog &catalog) + { + m_catalog = catalog; + m_md5Sum.clear(); + isoCodeChanged(s_translationData()->isoCode); + } + bool Translator::setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed) + { + if (m_md5Sum == md5Sum) + return true; -void Translator::setTranslationCatalog(const TranslationCatalog &catalog) -{ - m_catalog = catalog; - m_md5Sum.clear(); - isoCodeChanged(s_translationData()->isoCode); -} + // Use fromJson; fromBinaryData is not available in this Qt build + const QByteArray jsonRaw = bCompressed ? qUncompress(jsonData) : jsonData; + const QJsonObject jObj = QJsonDocument::fromJson(jsonRaw).object(); + const QString translationKey(QStringLiteral("translations")); + if (jObj.empty() || !jObj.contains(translationKey) || !jObj.value(translationKey).isArray()) + return false; -bool Translator::setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed) -{ - if (m_md5Sum == md5Sum) - return true; + const QJsonArray arr = jObj[translationKey].toArray(); + + m_catalog.clear(); + m_catalog.reserve(arr.size()); + TranslationEntry te; + for (const QJsonValue &element : arr) + { + const QJsonObject obj = element.toObject(); + + te.isoCode = obj.value(QStringLiteral("isoCode")).toString().toUtf8(); + te.context = obj.value(QStringLiteral("context")).toString().toUtf8(); + te.key = obj.value(QStringLiteral("key")).toString().toUtf8(); + te.disambiguation = obj.value(QStringLiteral("disambiguation")).toString().toUtf8(); + te.translation = obj.value(QStringLiteral("translation")).toString(); + + m_catalog += te; + } + + m_md5Sum = md5Sum; + isoCodeChanged(s_translationData()->isoCode); - // Use fromJson; fromBinaryData is not available in this Qt build - const QByteArray jsonRaw = bCompressed ? qUncompress(jsonData) : jsonData; - const QJsonObject jObj = QJsonDocument::fromJson(jsonRaw).object(); - const QString translationKey(QStringLiteral("translations")); - if (jObj.empty() || - !jObj.contains(translationKey) || - !jObj.value(translationKey).isArray()) return false; - - const QJsonArray arr = jObj[translationKey].toArray(); - - m_catalog.clear(); - m_catalog.reserve(arr.size()); - TranslationEntry te; - for (const QJsonValue &element : arr) - { - const QJsonObject obj = element.toObject(); - - te.isoCode = obj.value(QStringLiteral("isoCode")).toString().toUtf8(); - te.context = obj.value(QStringLiteral("context")).toString().toUtf8(); - te.key = obj.value(QStringLiteral("key")).toString().toUtf8(); - te.disambiguation = obj.value(QStringLiteral("disambiguation")).toString().toUtf8(); - te.translation = obj.value(QStringLiteral("translation")).toString(); - - m_catalog += te; } - m_md5Sum = md5Sum; - isoCodeChanged(s_translationData()->isoCode); - return false; -} - - - -QString Translator::translate(const char *context, - const char *sourceText, - const char *disambiguation, - int n) const -{ - - if (n != -1) - return QString(); - - const auto itCtx = m_translationLookup.find(QByteArray::fromRawData(context, strlen(context))); - if (itCtx == m_translationLookup.end()) - return QString(); - const auto itKey = itCtx.value().find(QByteArray::fromRawData(sourceText, strlen(sourceText))); - if (itKey == itCtx.value().end()) - return QString(); - const auto itDis = itKey.value().find(disambiguation ? QByteArray::fromRawData(disambiguation, strlen(disambiguation)) : QByteArray()); - if (itDis == itKey.value().end()) - return QString(); - return itDis.value(); -} - - -void Translator::isoCodeChanged(const QByteArray &isoCode) -{ - m_translationLookup.clear(); - for (const TranslationEntry &te : std::as_const(m_catalog)) + QString Translator::translate(const char *context, const char *sourceText, const char *disambiguation, int n) const { - if (te.isoCode != isoCode) - continue; - m_translationLookup[te.context][te.key][te.disambiguation] = te.translation; + + if (n != -1) + return QString(); + + const auto itCtx = m_translationLookup.find(QByteArray::fromRawData(context, strlen(context))); + if (itCtx == m_translationLookup.end()) + return QString(); + const auto itKey = itCtx.value().find(QByteArray::fromRawData(sourceText, strlen(sourceText))); + if (itKey == itCtx.value().end()) + return QString(); + const auto itDis = itKey.value().find(disambiguation ? QByteArray::fromRawData(disambiguation, strlen(disambiguation)) : QByteArray()); + if (itDis == itKey.value().end()) + return QString(); + return itDis.value(); } -} - - -void setTranslationCatalog(const TranslationCatalog &catalog) -{ - s_translationData()->dynamicTranslator.setTranslationCatalog(catalog); -} - - -bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed) -{ - return s_translationData()->dynamicTranslator.setTranslationDataJson(jsonData, md5Sum, bCompressed); -} - - -bool setTranslationLocale(const QByteArray &isoCode, const QString &qmPrefix) -{ - - if (s_translationData()->isoCode == isoCode && - s_translationData()->qmPrefix == qmPrefix) - return true; - - s_translationData()->isoCode = isoCode; - s_translationData()->qmPrefix = qmPrefix; - - const QString relTranslationPath = QLatin1Char('/') + QString::fromLatin1(isoCode) + QLatin1Char('/'); - const QStringList possiblePaths = { QCoreApplication::applicationDirPath() + QStringLiteral("/translations/"), - QCoreApplication::applicationDirPath() + QStringLiteral("/../translations/"), - QDir::homePath() + QStringLiteral("/translations/") - }; - const QString qm(QStringLiteral(".qm")); - - QString ltsQmPath; - for (const QString &path : possiblePaths) + void Translator::isoCodeChanged(const QByteArray &isoCode) { - const QString absPath = path + relTranslationPath; - if (!QDir(absPath).exists()) - continue; - if (QTranslator().load(qmPrefix + qm, absPath)) + m_translationLookup.clear(); + for (const TranslationEntry &te : std::as_const(m_catalog)) { - ltsQmPath = absPath + qmPrefix + qm; - break; + if (te.isoCode != isoCode) + continue; + m_translationLookup[te.context][te.key][te.disambiguation] = te.translation; } } - - QString kdReportsQmPath; - const QString kdReportsPrefix(QStringLiteral("kdreports")); - for (const QString &path : possiblePaths) + + void setTranslationCatalog(const TranslationCatalog &catalog) { - const QString absPath = path + relTranslationPath; - if (!QDir(absPath).exists()) - continue; - if (QTranslator().load(kdReportsPrefix + qm, absPath)) + s_translationData()->dynamicTranslator.setTranslationCatalog(catalog); + } + + + bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed) + { + return s_translationData()->dynamicTranslator.setTranslationDataJson(jsonData, md5Sum, bCompressed); + } + + + bool setTranslationLocale(const QByteArray &isoCode, const QString &qmPrefix) + { + + if (s_translationData()->isoCode == isoCode && s_translationData()->qmPrefix == qmPrefix) + return true; + + s_translationData()->isoCode = isoCode; + s_translationData()->qmPrefix = qmPrefix; + + const QString relTranslationPath = QLatin1Char('/') + QString::fromLatin1(isoCode) + QLatin1Char('/'); + const QStringList possiblePaths = {QCoreApplication::applicationDirPath() + QStringLiteral("/translations/"), + QCoreApplication::applicationDirPath() + QStringLiteral("/../translations/"), + QDir::homePath() + QStringLiteral("/translations/")}; + const QString qm(QStringLiteral(".qm")); + + QString ltsQmPath; + for (const QString &path : possiblePaths) { - kdReportsQmPath = absPath + kdReportsPrefix + qm; - break; + const QString absPath = path + relTranslationPath; + if (!QDir(absPath).exists()) + continue; + if (QTranslator().load(qmPrefix + qm, absPath)) + { + ltsQmPath = absPath + qmPrefix + qm; + break; + } } - } - - QStringList isoCodeList(QString::fromLatin1(isoCode).split(QLatin1Char('_'))); - if (isoCodeList.count() == 2) - { - if (!s_translationData->qtTranslator.load(QLatin1String("qt_") + isoCodeList.at(0), - QLibraryInfo::path(QLibraryInfo::TranslationsPath))) + + QString kdReportsQmPath; + const QString kdReportsPrefix(QStringLiteral("kdreports")); + for (const QString &path : possiblePaths) { - qWarning("qtTranslator.load failed for %s", qPrintable(isoCodeList.at(0))); + const QString absPath = path + relTranslationPath; + if (!QDir(absPath).exists()) + continue; + if (QTranslator().load(kdReportsPrefix + qm, absPath)) + { + kdReportsQmPath = absPath + kdReportsPrefix + qm; + break; + } } + + + QStringList isoCodeList(QString::fromLatin1(isoCode).split(QLatin1Char('_'))); + if (isoCodeList.count() == 2) + { + if (!s_translationData->qtTranslator.load(QLatin1String("qt_") + isoCodeList.at(0), QLibraryInfo::path(QLibraryInfo::TranslationsPath))) + { + qWarning("qtTranslator.load failed for %s", qPrintable(isoCodeList.at(0))); + } + } + else + { + + qWarning() << "translation iso code not compatible with qt translations"; + } + + if (!s_translationData->kdReportsTranslator.load(kdReportsQmPath)) + qWarning("kdReportsTranslator.load failed: %s", qPrintable(kdReportsQmPath)); + if (!s_translationData->ltsTranslator.load(ltsQmPath)) + qWarning("ltsTranslator.load failed: %s", qPrintable(ltsQmPath)); + s_translationData->dynamicTranslator.isoCodeChanged(isoCode); + + return !s_translationData->ltsTranslator.isEmpty(); } - else + + + QByteArray translationLocale() { - - qWarning() << "translation iso code not compatible with qt translations"; + return s_translationData()->isoCode; } - if (!s_translationData->kdReportsTranslator.load(kdReportsQmPath)) - qWarning("kdReportsTranslator.load failed: %s", qPrintable(kdReportsQmPath)); - if (!s_translationData->ltsTranslator.load(ltsQmPath)) - qWarning("ltsTranslator.load failed: %s", qPrintable(ltsQmPath)); - s_translationData->dynamicTranslator.isoCodeChanged(isoCode); - - return !s_translationData->ltsTranslator.isEmpty(); } - - -QByteArray translationLocale() -{ - return s_translationData()->isoCode; -} - -} - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.h old mode 100755 new mode 100644 index c5d365a83..498073e45 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator.h @@ -11,30 +11,26 @@ namespace NGL { -struct TranslationEntry -{ - QByteArray isoCode; - QByteArray context; - QByteArray key; - QByteArray disambiguation; - QString translation; -}; -using TranslationCatalog = QVector; + struct TranslationEntry + { + QByteArray isoCode; + QByteArray context; + QByteArray key; + QByteArray disambiguation; + QString translation; + }; + using TranslationCatalog = QVector; - -NGLTRANSLATOR_EXPORT void setTranslationCatalog(const TranslationCatalog &catalog); + NGLTRANSLATOR_EXPORT void setTranslationCatalog(const TranslationCatalog &catalog); - -NGLTRANSLATOR_EXPORT bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed); + NGLTRANSLATOR_EXPORT bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed); - -NGLTRANSLATOR_EXPORT bool setTranslationLocale(const QByteArray &isoCode, const QString &qmPrefix = QStringLiteral("tds")); + NGLTRANSLATOR_EXPORT bool setTranslationLocale(const QByteArray &isoCode, const QString &qmPrefix = QStringLiteral("tds")); + NGLTRANSLATOR_EXPORT QByteArray translationLocale(); -NGLTRANSLATOR_EXPORT QByteArray translationLocale(); - -} +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_export.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_export.h old mode 100755 new mode 100644 index 505aa294f..0f52a8d4e --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_export.h @@ -3,17 +3,17 @@ #pragma once #ifndef NGLTRANSLATOR_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLTRANSLATOR_EXPORT -# else -# ifdef WIN32 -# ifdef MAKE_NGLTRANSLATOR_LIB -# define NGLTRANSLATOR_EXPORT __declspec(dllexport) -# else -# define NGLTRANSLATOR_EXPORT __declspec(dllimport) -# endif -# else -# define NGLTRANSLATOR_EXPORT __attribute__((visibility("default"))) -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLTRANSLATOR_EXPORT +#else +#ifdef WIN32 +#ifdef MAKE_NGLTRANSLATOR_LIB +#define NGLTRANSLATOR_EXPORT __declspec(dllexport) +#else +#define NGLTRANSLATOR_EXPORT __declspec(dllimport) +#endif +#else +#define NGLTRANSLATOR_EXPORT __attribute__((visibility("default"))) +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_p.h b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_p.h old mode 100755 new mode 100644 index c3bc11238..9e678b072 --- a/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_p.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/ngltranslator/ngltranslator_p.h @@ -9,26 +9,23 @@ namespace NGL { -class Translator final : public QTranslator -{ - Q_OBJECT -public: - explicit Translator(QObject *parent = nullptr); + class Translator final : public QTranslator + { + Q_OBJECT + public: + explicit Translator(QObject *parent = nullptr); - QString translate(const char *context, - const char *sourceText, - const char *disambiguation = nullptr, - int n = -1) const override; + QString translate(const char *context, const char *sourceText, const char *disambiguation = nullptr, int n = -1) const override; - void setTranslationCatalog(const TranslationCatalog &catalog); - bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed); - - void isoCodeChanged(const QByteArray &isoCode); -private: - - QHash>> m_translationLookup; - TranslationCatalog m_catalog; - QByteArray m_md5Sum; -}; + void setTranslationCatalog(const TranslationCatalog &catalog); + bool setTranslationDataJson(const QByteArray &jsonData, const QByteArray &md5Sum, bool bCompressed); + + void isoCodeChanged(const QByteArray &isoCode); + + private: + QHash>> m_translationLookup; + TranslationCatalog m_catalog; + QByteArray m_md5Sum; + }; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.cpp old mode 100755 new mode 100644 index 7e48d4921..13db969cc --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.cpp @@ -15,8 +15,8 @@ #include "ngldialogbuttonbox.h" NGLDialog::NGLDialog(QWidget *parent, Qt::WindowFlags f) - : QDialog(parent, f) - , m_bReadOnly(false) + : QDialog(parent, f) + , m_bReadOnly(false) { setWindowIcon(QIcon(QLatin1String(":icons/16x16/rde_16x16.png"))); } @@ -30,9 +30,7 @@ void NGLDialog::showEvent(QShowEvent *e) { NGLDialogButtonBox *bb = findChild(); if (bb) - connect(bb, &NGLDialogButtonBox::onHelp, - this, &NGLDialog::onInvokeHelp, - Qt::UniqueConnection); + connect(bb, &NGLDialogButtonBox::onHelp, this, &NGLDialog::onInvokeHelp, Qt::UniqueConnection); QDialog::showEvent(e); } @@ -40,9 +38,7 @@ void NGLDialog::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_F1) onInvokeHelp(); - if (e->key() == Qt::Key_P && - e->modifiers().testFlag(Qt::ControlModifier) && - e->modifiers().testFlag(Qt::AltModifier)) + if (e->key() == Qt::Key_P && e->modifiers().testFlag(Qt::ControlModifier) && e->modifiers().testFlag(Qt::AltModifier)) printWidget(); QDialog::keyPressEvent(e); @@ -133,13 +129,13 @@ QString NGLDialog::windowTitle() const void NGLDialog::setDialogReadOnly(bool bReadOnly, const QString &reason) { - m_bReadOnly = bReadOnly; + m_bReadOnly = bReadOnly; if (bReadOnly && !reason.isEmpty()) m_readOnlyReason = reason; else m_readOnlyReason.clear(); - setWindowTitle(windowTitle()); + setWindowTitle(windowTitle()); } bool NGLDialog::isDialogReadOnly() const diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.h old mode 100755 new mode 100644 index 556cbaaa6..d97184a7e --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialog.h @@ -16,47 +16,42 @@ public: void setHelpContext(const QString &helpContext); - static void centerWidget(QWidget *widgetToCenter); - static void printWidget(QWidget *widgetToPrint); - void setWindowTitle(const QString &title); - QString windowTitle() const; - void setDialogReadOnly(bool bReadOnly, const QString &reason = QString()); - bool isDialogReadOnly() const; Q_SIGNALS: - + void invokeHelp(const QString &helpContext); + protected: virtual void showEvent(QShowEvent *e); virtual void keyPressEvent(QKeyEvent *e); void centerWidget(); void printWidget(); protected Q_SLOTS: - + void onInvokeHelp(); private: - QString m_helpContext; - bool m_bReadOnly; - QString m_readOnlyReason; - QString m_realWindowTitle; + QString m_helpContext; + bool m_bReadOnly; + QString m_readOnlyReason; + QString m_realWindowTitle; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.cpp old mode 100755 new mode 100644 index 9d714e6a9..69d9b3b1b --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.cpp @@ -5,31 +5,29 @@ #include NGLDialogButtonBox::NGLDialogButtonBox(QWidget *parent) - : NGLDialogButtonBox(Qt::Horizontal, parent) -{} + : NGLDialogButtonBox(Qt::Horizontal, parent) +{ +} -NGLDialogButtonBox::NGLDialogButtonBox(Qt::Orientation orientation, - QWidget *parent) - : QWidget(parent) - , m_orientation(orientation) - , m_buttons(NGLStandardButton::NoButton) - , m_line(nullptr) - , m_bSpacer2ContextAction(nullptr) - , m_bLineVisible(true) +NGLDialogButtonBox::NGLDialogButtonBox(Qt::Orientation orientation, QWidget *parent) + : QWidget(parent) + , m_orientation(orientation) + , m_buttons(NGLStandardButton::NoButton) + , m_line(nullptr) + , m_bSpacer2ContextAction(nullptr) + , m_bLineVisible(true) { setFocusPolicy(Qt::StrongFocus); init(); } -NGLDialogButtonBox::NGLDialogButtonBox(NGLStandardButton::StandardButtons buttons, - Qt::Orientation orientation, - QWidget *parent) - : QWidget(parent) - , m_orientation(orientation) - , m_buttons(buttons) - , m_line(nullptr) - , m_bSpacer2ContextAction(nullptr) - , m_bLineVisible(true) +NGLDialogButtonBox::NGLDialogButtonBox(NGLStandardButton::StandardButtons buttons, Qt::Orientation orientation, QWidget *parent) + : QWidget(parent) + , m_orientation(orientation) + , m_buttons(buttons) + , m_line(nullptr) + , m_bSpacer2ContextAction(nullptr) + , m_bLineVisible(true) { setFocusPolicy(Qt::StrongFocus); setStandardButtons(m_buttons); @@ -81,7 +79,7 @@ void NGLDialogButtonBox::setStandardButtons(NGLStandardButton::StandardButtons b button->setAutoDefault(true); } } - i = (NGLStandardButton::StandardButton)((int) i << 1); + i = (NGLStandardButton::StandardButton)((int)i << 1); } init(); @@ -118,7 +116,7 @@ NGLStandardButton *NGLDialogButtonBox::button(NGLStandardButton::StandardButton if (it.value()->type() == button) return it.value(); } - return new NGLStandardButton(nullptr); + return new NGLStandardButton(nullptr); } void NGLDialogButtonBox::removeFromActionList(NGLStandardButton::StandardButton button) @@ -192,7 +190,8 @@ static void addSpacer2(QLayout *l, Qt::Orientation orientation) void NGLDialogButtonBox::init() { delete layout(); - delete m_line; m_line = nullptr; + delete m_line; + m_line = nullptr; if (m_bSpacer2ContextAction) { removeAction(m_bSpacer2ContextAction); @@ -212,7 +211,7 @@ void NGLDialogButtonBox::init() lMain = new QHBoxLayout; l = new QVBoxLayout; } - lMain->setContentsMargins(0,0,0,0); + lMain->setContentsMargins(0, 0, 0, 0); if (m_bLineVisible) { m_line = new QFrame(this); @@ -225,7 +224,7 @@ void NGLDialogButtonBox::init() l->setContentsMargins(0, 0, 0, 0); setLayout(lMain); - const auto actions = findChildren(); + const auto actions = findChildren(); for (auto a : actions) a->disconnect(a, &QAction::triggered, this, &NGLDialogButtonBox::buttonClicked); @@ -246,7 +245,7 @@ void NGLDialogButtonBox::init() bSpacer1Added = true; if (bLowestPrioButton) { - + QSpacerItem *item = new QSpacerItem(7, 7, QSizePolicy::Fixed, QSizePolicy::Fixed); l->addItem(item); } @@ -256,10 +255,10 @@ void NGLDialogButtonBox::init() bSpacer2Added = true; addSpacer2(l, m_orientation); } - + if (prio >= 30 && prio < 100) { - + const QList actions = button->actions(); for (QAction *a : actions) removeAction(a); @@ -276,26 +275,23 @@ void NGLDialogButtonBox::init() } } l->addWidget(button); - + if (button->type() == NGLStandardButton::Library) { QAction *ex = button->findChild(QLatin1String("actionExport")); if (ex) { - connect(ex, &QAction::triggered, - this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); + connect(ex, &QAction::triggered, this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); } QAction *im = button->findChild(QLatin1String("actionImport")); if (im) { - connect(im, &QAction::triggered, - this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); + connect(im, &QAction::triggered, this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); } } else { - connect(button, &NGLStandardButton::clicked, - this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); + connect(button, &NGLStandardButton::clicked, this, &NGLDialogButtonBox::buttonClicked, Qt::UniqueConnection); } } if (!bSpacer2Added) @@ -315,10 +311,10 @@ void NGLDialogButtonBox::init() void NGLDialogButtonBox::buttonClicked() { - NGLStandardButton *b = qobject_cast (sender()); + NGLStandardButton *b = qobject_cast(sender()); if (!b) { - QAction *a = qobject_cast (sender()); + QAction *a = qobject_cast(sender()); if (!a) return; if (a->objectName() == QLatin1String("actionExport")) @@ -335,80 +331,80 @@ void NGLDialogButtonBox::buttonClicked() } switch (b->type()) { - case NGLStandardButton::Ok: - emit onOk(); - break; - case NGLStandardButton::Send: - emit onSend(); - break; - case NGLStandardButton::New: - emit onNew(); - break; - case NGLStandardButton::Delete: - emit onDelete(); - break; - case NGLStandardButton::Save: - emit onSave(); - break; - case NGLStandardButton::Open: - emit onOpen(); - break; - case NGLStandardButton::Yes: - emit onYes(); - break; - case NGLStandardButton::No: - emit onNo(); - break; - case NGLStandardButton::Close: - emit onClose(); - break; - case NGLStandardButton::Cancel: - emit onCancel(); - break; - case NGLStandardButton::Help: - emit onHelp(); - break; - case NGLStandardButton::Apply: - emit onApply(); - break; - case NGLStandardButton::Reset: - emit onReset(); - break; - case NGLStandardButton::Print: - emit onPrint(); - break; - case NGLStandardButton::Modify: - emit onModify(); - break; - case NGLStandardButton::Add: - emit onAdd(); - break; - case NGLStandardButton::Remove: - emit onRemove(); - break; - case NGLStandardButton::Edit: - emit onEdit(); - break; - case NGLStandardButton::Download: - emit onDownload(); - break; - case NGLStandardButton::Library: - break; - case NGLStandardButton::Show: - emit onShow(); - break; - case NGLStandardButton::ZoomIn: - emit onZoomIn(); - break; - case NGLStandardButton::ZoomOut: - emit onZoomOut(); - break; - case NGLStandardButton::Hide: - emit onHide(); - break; - default: - emit clicked(b); - break; + case NGLStandardButton::Ok: + emit onOk(); + break; + case NGLStandardButton::Send: + emit onSend(); + break; + case NGLStandardButton::New: + emit onNew(); + break; + case NGLStandardButton::Delete: + emit onDelete(); + break; + case NGLStandardButton::Save: + emit onSave(); + break; + case NGLStandardButton::Open: + emit onOpen(); + break; + case NGLStandardButton::Yes: + emit onYes(); + break; + case NGLStandardButton::No: + emit onNo(); + break; + case NGLStandardButton::Close: + emit onClose(); + break; + case NGLStandardButton::Cancel: + emit onCancel(); + break; + case NGLStandardButton::Help: + emit onHelp(); + break; + case NGLStandardButton::Apply: + emit onApply(); + break; + case NGLStandardButton::Reset: + emit onReset(); + break; + case NGLStandardButton::Print: + emit onPrint(); + break; + case NGLStandardButton::Modify: + emit onModify(); + break; + case NGLStandardButton::Add: + emit onAdd(); + break; + case NGLStandardButton::Remove: + emit onRemove(); + break; + case NGLStandardButton::Edit: + emit onEdit(); + break; + case NGLStandardButton::Download: + emit onDownload(); + break; + case NGLStandardButton::Library: + break; + case NGLStandardButton::Show: + emit onShow(); + break; + case NGLStandardButton::ZoomIn: + emit onZoomIn(); + break; + case NGLStandardButton::ZoomOut: + emit onZoomOut(); + break; + case NGLStandardButton::Hide: + emit onHide(); + break; + default: + emit clicked(b); + break; } } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.h old mode 100755 new mode 100644 index 74a3adf1c..0f98cd2ae --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngldialogbuttonbox.h @@ -17,155 +17,138 @@ class NGLWIDGETS_EXPORT NGLDialogButtonBox : public QWidget Q_PROPERTY(bool m_bLineVisible READ lineVisible WRITE setLineVisible) public: - - explicit NGLDialogButtonBox(QWidget *parent = nullptr); - + explicit NGLDialogButtonBox(Qt::Orientation orientation, QWidget *parent = nullptr); - + NGLDialogButtonBox(NGLStandardButton::StandardButtons buttons, Qt::Orientation orientation = Qt::Horizontal, QWidget *parent = nullptr); - Qt::Orientation orientation() const; - + void setOrientation(Qt::Orientation orientation); - NGLStandardButton::StandardButtons standardButtons() const; - + void setStandardButtons(NGLStandardButton::StandardButtons buttons); - void addButton(NGLStandardButton *button); - + NGLStandardButton *addButton(NGLStandardButton::StandardButton button); - NGLStandardButton *button(NGLStandardButton::StandardButton button); - void removeFromActionList(NGLStandardButton::StandardButton button); - bool setEnabled(NGLStandardButton::StandardButton button, bool enable); - bool isEnabled(NGLStandardButton::StandardButton button); - bool lineVisible() const; - void setLineVisible(bool bVisible); - bool setVisible(NGLStandardButton::StandardButton button, bool visible); - void setVisible(bool visible) { QWidget::setVisible(visible); } - void enableExport(bool ena); - void enableImport(bool ena); public Q_SLOTS: - + void layoutPriorityChanged(); Q_SIGNALS: - + void clicked(NGLStandardButton *button); - + void onOk(); - + void onSend(); - + void onNew(); - + void onDelete(); - + void onSave(); - + void onOpen(); - + void onYes(); - + void onNo(); - + void onClose(); - + void onCancel(); - + void onHelp(); - + void onApply(); - + void onReset(); - + void onPrint(); - + void onModify(); - + void onAdd(); - + void onRemove(); - + void onEdit(); - + void onDownload(); - void onLibraryImport(); - void onLibraryExport(); void onShow(); void onZoomIn(); void onZoomOut(); - + void onHide(); @@ -185,5 +168,3 @@ protected: QAction *m_bSpacer2ContextAction; bool m_bLineVisible; }; - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.cpp old mode 100755 new mode 100644 index 98d6e5263..2eb7ca484 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.cpp @@ -12,21 +12,28 @@ #include NGLMainWindow::NGLMainWindow(QWidget *parent) - : QMainWindow(parent) - , m_helpProcess(nullptr) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) - , m_versionView(nullptr) - , m_menuBar(new QMenuBar(this)) + : QMainWindow(parent) + , m_helpProcess(nullptr) + , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) + , m_versionView(nullptr) + , m_menuBar(new QMenuBar(this)) { m_menu[QLatin1String("File")] = m_menuBar->addMenu(tr("File")); m_fileActionBefore = m_menu[QLatin1String("File")]->addSeparator(); - m_menu[QLatin1String("File")]->addAction(QIcon(QLatin1String(":/icons/16x16/application-exit.png")), tr("Quit"), QKeySequence(tr("Ctrl+q")), this, &NGLMainWindow::onExit); + m_menu[QLatin1String("File")]->addAction(QIcon(QLatin1String(":/icons/16x16/application-exit.png")), + tr("Quit"), + QKeySequence(tr("Ctrl+q")), + this, + &NGLMainWindow::onExit); m_menu[QLatin1String("Help")] = m_menuBar->addMenu(tr("Help")); - m_menu[QLatin1String("Help")]->addAction(QIcon(QLatin1String(":/icons/16x16/help-contents.png")), tr("Help"), QKeySequence(tr("F1")), this, &NGLMainWindow::onHelpIndex); + m_menu[QLatin1String("Help")]->addAction(QIcon(QLatin1String(":/icons/16x16/help-contents.png")), + tr("Help"), + QKeySequence(tr("F1")), + this, + &NGLMainWindow::onHelpIndex); m_menu[QLatin1String("Help")]->addSeparator(); - m_menu[QLatin1String("Help")]->addAction(QIcon(QLatin1String(":/icons/16x16/help-about.png")), - tr("About"), this, &NGLMainWindow::onHelpAbout); + m_menu[QLatin1String("Help")]->addAction(QIcon(QLatin1String(":/icons/16x16/help-about.png")), tr("About"), this, &NGLMainWindow::onHelpAbout); setWindowIcon(QIcon(QLatin1String(":icons/16x16/rde_16x16.png"))); setMenuBar(m_menuBar); @@ -34,7 +41,7 @@ NGLMainWindow::NGLMainWindow(QWidget *parent) void NGLMainWindow::onExit() { - + close(); } @@ -45,8 +52,8 @@ void NGLMainWindow::onHelpIndex() void NGLMainWindow::onInvokeHelp(const QString &helpContext) { - - DEBUG_LOG(m_logger) << "onInvokeHelp " << helpContext ; + + DEBUG_LOG(m_logger) << "onInvokeHelp " << helpContext; if (!m_helpProcess) { @@ -58,22 +65,17 @@ void NGLMainWindow::onInvokeHelp(const QString &helpContext) m_helpProcess->setProcessEnvironment(env); QStringList args; QString fn = QString::fromLatin1(NGL::translationLocale()) + QLatin1String(".qhc"); - args << QLatin1String("-collectionFile") - << QCoreApplication::applicationDirPath() + QLatin1String("/../help/scms/") + fn - << QLatin1String("-enableRemoteControl"); - DEBUG_LOG(m_logger) << "Attempting to invoke help at URL: " << args.join(QLatin1String(" ")) ; + args << QLatin1String("-collectionFile") << QCoreApplication::applicationDirPath() + QLatin1String("/../help/scms/") + fn << QLatin1String("-enableRemoteControl"); + DEBUG_LOG(m_logger) << "Attempting to invoke help at URL: " << args.join(QLatin1String(" ")); m_helpProcess->start(QLibraryInfo::path(QLibraryInfo::BinariesPath) + QLatin1String("/assistant"), args); if (!m_helpProcess->waitForStarted()) { - ERROR_LOG(m_logger) << "Could not start help browser (error: " - << m_helpProcess->error() - << " )" ; + ERROR_LOG(m_logger) << "Could not start help browser (error: " << m_helpProcess->error() << " )"; delete m_helpProcess; m_helpProcess = nullptr; return; } - connect(m_helpProcess, QOverload::of(&QProcess::finished), - this, &NGLMainWindow::onHelpFinished); + connect(m_helpProcess, QOverload::of(&QProcess::finished), this, &NGLMainWindow::onHelpFinished); } QTextStream str(m_helpProcess); @@ -85,9 +87,7 @@ void NGLMainWindow::onHelpFinished(int exitCode, QProcess::ExitStatus exitStatus { if (exitStatus != QProcess::NormalExit) { - WARNING_LOG(m_logger) << "help browser exited with status " - << exitStatus << " code " - << exitCode << "!" ; + WARNING_LOG(m_logger) << "help browser exited with status " << exitStatus << " code " << exitCode << "!"; } delete m_helpProcess; m_helpProcess = nullptr; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.h old mode 100755 new mode 100644 index 21b5b3239..9b0591018 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglmainwindow.h @@ -10,7 +10,7 @@ namespace NGL { -class INGLLogger; + class INGLLogger; } class NGLWIDGETS_EXPORT NGLMainWindow : public QMainWindow @@ -29,18 +29,16 @@ public slots: void onHelpFinished(int exitCode, QProcess::ExitStatus exitStatus); private: - QProcess *m_helpProcess; + QProcess *m_helpProcess; protected: NGL::INGLLogger &m_logger; - QWidget *m_versionView; - QMenuBar *m_menuBar; - QMap m_menu; - QAction *m_fileActionBefore; + QWidget *m_versionView; + QMenuBar *m_menuBar; + QMap m_menu; + QAction *m_fileActionBefore; protected slots: void onVersionViewDeleted(); void onExit(); - }; - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.cpp old mode 100755 new mode 100644 index 5f805079b..f817430f8 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.cpp @@ -16,393 +16,387 @@ namespace NGL { -PDFDocument::PDFDocument(QWidget *parent) - : QWidget(parent) - , m_doc(nullptr) - , m_currentPage(0) - , m_maxCachedPages(20) - , m_scaleFactor(1.0) - , m_widthFactor(1.0) + PDFDocument::PDFDocument(QWidget *parent) + : QWidget(parent) + , m_doc(nullptr) + , m_currentPage(0) + , m_maxCachedPages(20) + , m_scaleFactor(1.0) + , m_widthFactor(1.0) #ifdef HAVE_POPPLER_QT6 - , m_rotation(Poppler::Page::Rotate0) + , m_rotation(Poppler::Page::Rotate0) #endif -{ - QVBoxLayout *lay = new QVBoxLayout(this); - lay->setContentsMargins(0,0,0,0); - lay->setSpacing(0); - - m_pdfLabel = new QWidget(this); - m_pdfLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - QVBoxLayout *l = new QVBoxLayout(m_pdfLabel); - const int innerMargin = 6; - l->setContentsMargins(innerMargin, innerMargin, innerMargin, innerMargin); - l->setSpacing(innerMargin); - l->setSizeConstraint(QLayout::SetFixedSize); - - m_scrollArea = new QScrollArea(this); - m_scrollArea->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); - - m_scrollArea->setWidgetResizable(true); - m_scrollArea->setWidget(m_pdfLabel); - - lay->addWidget(m_scrollArea); -} - -PDFDocument::~PDFDocument() -{ -#ifdef HAVE_POPPLER_QT6 - qDeleteAll(m_pages); - m_pages.clear(); -#endif - m_doc.reset(); -} - -bool PDFDocument::showPDF(const QUrl &url) -{ - return showPDF(url.toLocalFile()); -} - -bool PDFDocument::showPDF(const QString &path) -{ - if (path.isEmpty()) - return false; - - if (path == m_currentPath) { - m_scaleFactor = 0; - m_widthFactor = 1; - setZoomFactor(1.0); + QVBoxLayout *lay = new QVBoxLayout(this); + lay->setContentsMargins(0, 0, 0, 0); + lay->setSpacing(0); + + m_pdfLabel = new QWidget(this); + m_pdfLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + QVBoxLayout *l = new QVBoxLayout(m_pdfLabel); + const int innerMargin = 6; + l->setContentsMargins(innerMargin, innerMargin, innerMargin, innerMargin); + l->setSpacing(innerMargin); + l->setSizeConstraint(QLayout::SetFixedSize); + + m_scrollArea = new QScrollArea(this); + m_scrollArea->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + + m_scrollArea->setWidgetResizable(true); + m_scrollArea->setWidget(m_pdfLabel); + + lay->addWidget(m_scrollArea); + } + + PDFDocument::~PDFDocument() + { #ifdef HAVE_POPPLER_QT6 - setRotation(Poppler::Page::Rotate0); + qDeleteAll(m_pages); + m_pages.clear(); +#endif + m_doc.reset(); + } + + bool PDFDocument::showPDF(const QUrl &url) + { + return showPDF(url.toLocalFile()); + } + + bool PDFDocument::showPDF(const QString &path) + { + if (path.isEmpty()) + return false; + + if (path == m_currentPath) + { + m_scaleFactor = 0; + m_widthFactor = 1; + setZoomFactor(1.0); +#ifdef HAVE_POPPLER_QT6 + setRotation(Poppler::Page::Rotate0); +#endif + return true; + } + +#ifdef HAVE_POPPLER_QT6 + m_doc = Poppler::Document::load(path); + if (!m_doc) + return false; + m_currentPath = path; + + return showPDFInternal(); +#else + Q_UNUSED(path); + return false; +#endif + } + + bool PDFDocument::showPDF(const QByteArray &pdf) + { + m_currentPath.clear(); + +#ifdef HAVE_POPPLER_QT6 + m_doc = Poppler::Document::loadFromData(pdf); + if (!m_doc) + return false; + + return showPDFInternal(); +#else + Q_UNUSED(pdf); + return false; +#endif + } + + bool PDFDocument::showPDFInternal() + { +#ifdef HAVE_POPPLER_QT6 + disconnect(m_scrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, &PDFDocument::onVSliderValueChanged); + + m_doc->setRenderHint(Poppler::Document::Antialiasing); + m_doc->setRenderHint(Poppler::Document::TextAntialiasing); + m_doc->setRenderHint(Poppler::Document::TextHinting); + m_doc->setRenderHint(Poppler::Document::TextSlightHinting); + + m_scrollArea->horizontalScrollBar()->setSliderPosition(0); + m_scrollArea->verticalScrollBar()->setSliderPosition(0); + + m_renderedPages.clear(); + qDeleteAll(m_pages); + m_pages.clear(); + m_ranges.clear(); + + QVBoxLayout *l = qobject_cast(m_pdfLabel->layout()); + const int cnt = m_doc->numPages(); + m_pages.reserve(cnt); + for (int i = 0; i < cnt; ++i) + { + PDFPage *p = new PDFPage(m_pdfLabel); + p->setZoomFactor(m_scaleFactor); + p->setRotation(m_rotation); + auto pagePtr = m_doc->page(i); + // transfer ownership of Poppler::Page to PDFPage; PDFPage will delete it + p->setPopplerPage(pagePtr.release()); + connect(p, &PDFPage::pageRendered, this, &PDFDocument::onPageRendered); +#ifdef HAVE_POPPLER_QT6 + connect(p, &PDFPage::externalLinkClicked, this, &PDFDocument::linkClicked); + connect(p, &PDFPage::linkClicked, this, &PDFDocument::onLinkClicked); +#endif + m_pages += p; + + l->addWidget(p); + } + rebuildRanges(); + + m_currentPage = std::min(m_currentPage, static_cast(m_ranges.count() - 1)); + + ensureCurPageVisible(); + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); + connect(m_scrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, &PDFDocument::onVSliderValueChanged); #endif return true; } -#ifdef HAVE_POPPLER_QT6 - m_doc = Poppler::Document::load(path); - if (!m_doc) - return false; - m_currentPath = path; - - return showPDFInternal(); -#else - Q_UNUSED(path); - return false; -#endif -} - -bool PDFDocument::showPDF(const QByteArray &pdf) -{ - m_currentPath.clear(); - -#ifdef HAVE_POPPLER_QT6 - m_doc = Poppler::Document::loadFromData(pdf); - if (!m_doc) - return false; - - return showPDFInternal(); -#else - Q_UNUSED(pdf); - return false; -#endif -} - -bool PDFDocument::showPDFInternal() -{ -#ifdef HAVE_POPPLER_QT6 - disconnect(m_scrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, &PDFDocument::onVSliderValueChanged); - - m_doc->setRenderHint(Poppler::Document::Antialiasing); - m_doc->setRenderHint(Poppler::Document::TextAntialiasing); - m_doc->setRenderHint(Poppler::Document::TextHinting); - m_doc->setRenderHint(Poppler::Document::TextSlightHinting); - - m_scrollArea->horizontalScrollBar()->setSliderPosition(0); - m_scrollArea->verticalScrollBar()->setSliderPosition(0); - - m_renderedPages.clear(); - qDeleteAll(m_pages); - m_pages.clear(); - m_ranges.clear(); - - QVBoxLayout *l = qobject_cast (m_pdfLabel->layout()); - const int cnt = m_doc->numPages(); - m_pages.reserve(cnt); - for (int i = 0; i < cnt; ++i) + void PDFDocument::resizePdfToWidth() { - PDFPage *p = new PDFPage(m_pdfLabel); - p->setZoomFactor(m_scaleFactor); - p->setRotation(m_rotation); - auto pagePtr = m_doc->page(i); - // transfer ownership of Poppler::Page to PDFPage; PDFPage will delete it - p->setPopplerPage(pagePtr.release()); - connect(p, &PDFPage::pageRendered, - this, &PDFDocument::onPageRendered); -#ifdef HAVE_POPPLER_QT6 - connect(p, &PDFPage::externalLinkClicked, - this, &PDFDocument::linkClicked); - connect(p, &PDFPage::linkClicked, - this, &PDFDocument::onLinkClicked); -#endif - m_pages += p; + double scale = m_scaleFactor; - l->addWidget(p); + m_widthFactor = double(m_pdfLabel->size().width()) / size().width() * 1.03; + + m_scaleFactor = 0; + setZoomFactor(scale); } - rebuildRanges(); - m_currentPage = std::min(m_currentPage, static_cast(m_ranges.count() - 1)); - - ensureCurPageVisible(); - emit currentPageChanged(m_currentPage + 1, m_ranges.count()); - connect(m_scrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, &PDFDocument::onVSliderValueChanged); -#endif - return true; -} - -void PDFDocument::resizePdfToWidth() -{ - double scale = m_scaleFactor; - - m_widthFactor = double(m_pdfLabel->size().width()) / size().width() * 1.03; - - m_scaleFactor = 0; - setZoomFactor(scale); -} - -int PDFDocument::curPage() const -{ - return m_currentPage + 1; -} - -int PDFDocument::numPages() const -{ - // Return 0 when no document is loaded to satisfy tests that expect a non-negative page count -#ifdef HAVE_POPPLER_QT6 - return m_doc ? m_doc->numPages() : 0; -#else - return 0; -#endif -} - -void PDFDocument::setZoomFactor(double zoom) -{ - if (qFuzzyCompare(m_scaleFactor, zoom)) - return; - m_scaleFactor = zoom; - -#ifdef HAVE_POPPLER_QT6 - for (PDFPage *p : std::as_const(m_pages)) - p->setZoomFactor(m_scaleFactor / m_widthFactor); - - rebuildRanges(); -#endif -} - -void PDFDocument::setRotation(Poppler::Page::Rotation rot) -{ -#ifdef HAVE_POPPLER_QT6 - if (m_rotation == rot) - return; - m_rotation = rot; - if (m_pages.isEmpty()) - return; - - for (PDFPage *p : std::as_const(m_pages)) - p->setRotation(m_rotation); - - rebuildRanges(); - emit currentPageChanged(m_currentPage+1, m_ranges.count()); - emit rotationChanged(m_rotation); -#else - Q_UNUSED(rot); -#endif -} - -bool PDFDocument::setPage(int page) -{ - page--; - if (m_currentPage == page) + int PDFDocument::curPage() const { + return m_currentPage + 1; + } + + int PDFDocument::numPages() const + { + // Return 0 when no document is loaded to satisfy tests that expect a non-negative page count +#ifdef HAVE_POPPLER_QT6 + return m_doc ? m_doc->numPages() : 0; +#else + return 0; +#endif + } + + void PDFDocument::setZoomFactor(double zoom) + { + if (qFuzzyCompare(m_scaleFactor, zoom)) + return; + m_scaleFactor = zoom; + +#ifdef HAVE_POPPLER_QT6 + for (PDFPage *p : std::as_const(m_pages)) + p->setZoomFactor(m_scaleFactor / m_widthFactor); + + rebuildRanges(); +#endif + } + + void PDFDocument::setRotation(Poppler::Page::Rotation rot) + { +#ifdef HAVE_POPPLER_QT6 + if (m_rotation == rot) + return; + m_rotation = rot; + if (m_pages.isEmpty()) + return; + + for (PDFPage *p : std::as_const(m_pages)) + p->setRotation(m_rotation); + + rebuildRanges(); + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); + emit rotationChanged(m_rotation); +#else + Q_UNUSED(rot); +#endif + } + + bool PDFDocument::setPage(int page) + { + page--; + if (m_currentPage == page) + { + ensureCurPageVisible(); + return true; + } +#ifdef HAVE_POPPLER_QT6 + if (m_pages.isEmpty()) + { + m_currentPage = page; + return true; + } + if (page < 0 || numPages() < 0 || page >= m_doc->numPages()) + return false; + + m_currentPage = page; + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); ensureCurPageVisible(); return true; +#else + Q_UNUSED(page); + return false; +#endif } -#ifdef HAVE_POPPLER_QT6 - if (m_pages.isEmpty()) + + bool PDFDocument::nextPage() { - m_currentPage = page; +#ifdef HAVE_POPPLER_QT6 + if (m_doc == nullptr || m_currentPage >= m_doc->numPages() - 1) + return false; + m_currentPage++; + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); + ensureCurPageVisible(); return true; +#else + return false; +#endif } - if (page < 0 || numPages() < 0 || page >= m_doc->numPages()) - return false; - - m_currentPage = page; - emit currentPageChanged(m_currentPage + 1, m_ranges.count()); - ensureCurPageVisible(); - return true; -#else - Q_UNUSED(page); - return false; -#endif -} -bool PDFDocument::nextPage() -{ -#ifdef HAVE_POPPLER_QT6 - if (m_doc == nullptr || m_currentPage >= m_doc->numPages() - 1) - return false; - m_currentPage++; - emit currentPageChanged(m_currentPage + 1, m_ranges.count()); - ensureCurPageVisible(); - return true; -#else - return false; -#endif -} - -bool PDFDocument::previousPage() -{ -#ifdef HAVE_POPPLER_QT6 - if (m_doc == nullptr || m_currentPage < 1) - return false; - m_currentPage--; - emit currentPageChanged(m_currentPage + 1, m_ranges.count()); - ensureCurPageVisible(); - return true; -#else - return false; -#endif -} - -void PDFDocument::onVSliderValueChanged(int y) -{ - - y += m_scrollArea->height() / 2; - int curPage = m_ranges.count() - 1; - for (int i = 0; i < m_ranges.count(); ++i) + bool PDFDocument::previousPage() { - if (m_ranges.at(i) > y) +#ifdef HAVE_POPPLER_QT6 + if (m_doc == nullptr || m_currentPage < 1) + return false; + m_currentPage--; + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); + ensureCurPageVisible(); + return true; +#else + return false; +#endif + } + + void PDFDocument::onVSliderValueChanged(int y) + { + + y += m_scrollArea->height() / 2; + int curPage = m_ranges.count() - 1; + for (int i = 0; i < m_ranges.count(); ++i) { - curPage = i - 1; - break; + if (m_ranges.at(i) > y) + { + curPage = i - 1; + break; + } + } + if (curPage != m_currentPage && curPage >= 0) + { + m_currentPage = curPage; + emit currentPageChanged(m_currentPage + 1, m_ranges.count()); } } - if (curPage != m_currentPage && curPage >= 0) + + void PDFDocument::onPageRendered() { - m_currentPage = curPage; +#ifdef HAVE_POPPLER_QT6 + PDFPage *p = qobject_cast(sender()); + if (m_renderedPages.contains(p)) + return; + + while (m_renderedPages.count() > m_maxCachedPages - 1) + { + p = m_renderedPages.takeFirst(); + if (p) + p->clearPixmap(); + } + m_renderedPages.push_back(p); +#else +#endif + } + + void PDFDocument::onLinkClicked(const Poppler::LinkDestination &dest) + { +#ifdef HAVE_POPPLER_QT6 + PDFPage *p = qobject_cast(sender()); + if (!p) + return; + m_currentPage = dest.pageNumber() - 1; emit currentPageChanged(m_currentPage + 1, m_ranges.count()); + ensureCurPageVisible(qRound(dest.right() * p->width()), qRound(dest.top() * p->height())); +#else + Q_UNUSED(dest); +#endif } -} -void PDFDocument::onPageRendered() -{ -#ifdef HAVE_POPPLER_QT6 - PDFPage *p = qobject_cast (sender()); - if (m_renderedPages.contains(p)) - return; - - while (m_renderedPages.count() > m_maxCachedPages - 1) + QVector PDFDocument::getPrintableImages(int resolution) const { - p = m_renderedPages.takeFirst(); - if (p) - p->clearPixmap(); +#ifdef HAVE_POPPLER_QT6 + QVector imageList; + imageList.reserve(m_pages.size()); + for (const PDFPage *p : m_pages) + imageList.append(p->getPrintableImage(resolution)); + return imageList; +#else + Q_UNUSED(resolution); + return QVector(); +#endif } - m_renderedPages.push_back(p); -#else -#endif -} -void PDFDocument::onLinkClicked(const Poppler::LinkDestination &dest) -{ + QImage PDFDocument::getPrintableImage(int pageNum, int resolution) const + { #ifdef HAVE_POPPLER_QT6 - PDFPage *p = qobject_cast(sender()); - if (!p) - return; - m_currentPage = dest.pageNumber() - 1; - emit currentPageChanged(m_currentPage + 1, m_ranges.count()); - ensureCurPageVisible(qRound(dest.right() * p->width()), - qRound(dest.top() * p->height())); + if (pageNum < 0 || pageNum >= m_pages.size()) + return QImage(); + return m_pages[pageNum]->getPrintableImage(resolution); #else - Q_UNUSED(dest); -#endif -} - -QVector PDFDocument::getPrintableImages(int resolution) const -{ -#ifdef HAVE_POPPLER_QT6 - QVector imageList; - imageList.reserve(m_pages.size()); - for (const PDFPage *p : m_pages) - imageList.append(p->getPrintableImage(resolution)); - return imageList; -#else - Q_UNUSED(resolution); - return QVector(); -#endif -} - -QImage PDFDocument::getPrintableImage(int pageNum, int resolution) const -{ -#ifdef HAVE_POPPLER_QT6 - if (pageNum < 0 || pageNum >= m_pages.size()) + Q_UNUSED(pageNum); + Q_UNUSED(resolution); return QImage(); - return m_pages[pageNum]->getPrintableImage(resolution); -#else - Q_UNUSED(pageNum); - Q_UNUSED(resolution); - return QImage(); #endif -} - -void PDFDocument::ensureCurPageVisible(int xOfs, int yOfs) -{ -#ifdef HAVE_POPPLER_QT6 - if (m_currentPage >= m_ranges.size() || m_currentPage < 0) - return; - - - - if (m_scrollArea->verticalScrollBar()->maximum() == 0) - { - QTimer::singleShot(50, this, [this, xOfs, yOfs]() { ensureCurPageVisible(xOfs, yOfs); }); - return; } - - - - int y = m_ranges.at(m_currentPage) + yOfs; - - y -= m_pdfLabel->layout()->spacing() * 2; - int x = m_scrollArea->horizontalScrollBar()->value() + xOfs; - - - m_scrollArea->ensureVisible(x, y, 0, 0); - y += m_scrollArea->height(); - - m_scrollArea->ensureVisible(x, y, 0, 0); -#else - Q_UNUSED(xOfs); - Q_UNUSED(yOfs); -#endif -} - -void PDFDocument::rebuildRanges() -{ -#ifdef HAVE_POPPLER_QT6 - QVBoxLayout *l = qobject_cast (m_pdfLabel->layout()); - m_ranges.clear(); - int height = l->contentsMargins().top(); - for (PDFPage *p : std::as_const(m_pages)) + void PDFDocument::ensureCurPageVisible(int xOfs, int yOfs) { - m_ranges += height; - height += p->height(); - height += l->spacing(); - } - m_pdfLabel->resize(m_pdfLabel->sizeHint()); - m_pdfLabel->setMinimumSize(m_pdfLabel->sizeHint()); -#else - // Stub implementation when Poppler not available -#endif -} +#ifdef HAVE_POPPLER_QT6 + if (m_currentPage >= m_ranges.size() || m_currentPage < 0) + return; -} + + if (m_scrollArea->verticalScrollBar()->maximum() == 0) + { + QTimer::singleShot(50, this, [this, xOfs, yOfs]() { ensureCurPageVisible(xOfs, yOfs); }); + return; + } + + + int y = m_ranges.at(m_currentPage) + yOfs; + + y -= m_pdfLabel->layout()->spacing() * 2; + + int x = m_scrollArea->horizontalScrollBar()->value() + xOfs; + + + m_scrollArea->ensureVisible(x, y, 0, 0); + y += m_scrollArea->height(); + + m_scrollArea->ensureVisible(x, y, 0, 0); +#else + Q_UNUSED(xOfs); + Q_UNUSED(yOfs); +#endif + } + + void PDFDocument::rebuildRanges() + { +#ifdef HAVE_POPPLER_QT6 + QVBoxLayout *l = qobject_cast(m_pdfLabel->layout()); + m_ranges.clear(); + int height = l->contentsMargins().top(); + for (PDFPage *p : std::as_const(m_pages)) + { + m_ranges += height; + height += p->height(); + height += l->spacing(); + } + m_pdfLabel->resize(m_pdfLabel->sizeHint()); + m_pdfLabel->setMinimumSize(m_pdfLabel->sizeHint()); +#else + // Stub implementation when Poppler not available +#endif + } + +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.h old mode 100755 new mode 100644 index df69bae34..7e9a51ef5 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfdocument.h @@ -13,8 +13,8 @@ #ifdef HAVE_POPPLER_QT6 namespace Poppler { -class Document; -class LinkDestination; + class Document; + class LinkDestination; } #endif class QUrl; @@ -22,102 +22,96 @@ class QScrollArea; namespace NGL { #ifdef HAVE_POPPLER_QT6 -class PDFPage; + class PDFPage; #endif -class NGLWIDGETS_EXPORT PDFDocument : public QWidget -{ - Q_OBJECT -public: - + class NGLWIDGETS_EXPORT PDFDocument : public QWidget + { + Q_OBJECT + public: + explicit PDFDocument(QWidget *parent = nullptr); - explicit PDFDocument(QWidget *parent = nullptr); - - virtual ~PDFDocument(); + virtual ~PDFDocument(); - - int curPage() const; - + int curPage() const; - int numPages() const; -public Q_SLOTS: - + int numPages() const; - bool showPDF(const QString &path); + public Q_SLOTS: - - bool showPDF(const QUrl &url); + bool showPDF(const QString &path); - - bool showPDF(const QByteArray &pdf); + bool showPDF(const QUrl &url); - - void setZoomFactor(double zoom); + bool showPDF(const QByteArray &pdf); + + + void setZoomFactor(double zoom); #ifdef HAVE_POPPLER_QT6 - void setRotation(Poppler::Page::Rotation rot); + void setRotation(Poppler::Page::Rotation rot); #endif - bool setPage(int page); - + bool setPage(int page); - bool nextPage(); - - bool previousPage(); + bool nextPage(); - void resizePdfToWidth(); -public: + bool previousPage(); + + void resizePdfToWidth(); + + public: #ifdef HAVE_POPPLER_QT6 - Poppler::Page::Rotation getRotation() const { return m_rotation; } + Poppler::Page::Rotation getRotation() const { return m_rotation; } #endif - QVector getPrintableImages(int resolution = 300) const; - + QVector getPrintableImages(int resolution = 300) const; - QImage getPrintableImage(int pageNum, int resolution = 300) const; -Q_SIGNALS: - - void currentPageChanged(int cur, int max); + QImage getPrintableImage(int pageNum, int resolution = 300) const; + + Q_SIGNALS: + + void currentPageChanged(int cur, int max); #ifdef HAVE_POPPLER_QT6 - void rotationChanged(Poppler::Page::Rotation rot); - void linkClicked(const QString &url); + void rotationChanged(Poppler::Page::Rotation rot); + void linkClicked(const QString &url); -protected Q_SLOTS: - void onLinkClicked(const Poppler::LinkDestination &dest); + protected Q_SLOTS: + void onLinkClicked(const Poppler::LinkDestination &dest); #endif - void onVSliderValueChanged(int y); - void onPageRendered(); + void onVSliderValueChanged(int y); + void onPageRendered(); -protected: - bool showPDFInternal(); - void ensureCurPageVisible(int xOfs = 0, int yOfs = 0); - void rebuildRanges(); + protected: + bool showPDFInternal(); + void ensureCurPageVisible(int xOfs = 0, int yOfs = 0); + void rebuildRanges(); #ifdef HAVE_POPPLER_QT6 - std::unique_ptr m_doc; + std::unique_ptr m_doc; #endif - int m_currentPage; - int m_maxCachedPages; - double m_scaleFactor; - double m_widthFactor; - QString m_currentPath; + int m_currentPage; + int m_maxCachedPages; + double m_scaleFactor; + double m_widthFactor; + QString m_currentPath; - QWidget *m_pdfLabel; - QScrollArea *m_scrollArea; + QWidget *m_pdfLabel; + QScrollArea *m_scrollArea; #ifdef HAVE_POPPLER_QT6 - QVector m_pages; - QVector m_ranges; - QVector > m_renderedPages; - Poppler::Page::Rotation m_rotation; + QVector m_pages; + QVector m_ranges; + QVector> m_renderedPages; + Poppler::Page::Rotation m_rotation; #endif -}; -} + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.cpp old mode 100755 new mode 100644 index 0b081d048..c485ccf2f --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.cpp @@ -11,207 +11,205 @@ namespace NGL { -template -static inline T getRotatedSize(const T &in, Poppler::Page::Rotation rot) -{ - switch (rot) + template static inline T getRotatedSize(const T &in, Poppler::Page::Rotation rot) { - case Poppler::Page::Rotate0: - case Poppler::Page::Rotate180: - return in; - case Poppler::Page::Rotate90: - case Poppler::Page::Rotate270: - return in.transposed(); - } - Q_ASSERT(false); - return in; -} - -PDFPage::PDFPage(QWidget *parent) - : QWidget(parent) - , m_page(nullptr) - , m_rotation(Poppler::Page::Rotate0) - , m_scaleFactor(1.0) -{ - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setMouseTracking(true); -} - -PDFPage::~PDFPage() -{ - delete m_page; -} - -void PDFPage::setPopplerPage(Poppler::Page *page) -{ - if (m_page == page) - return; - delete m_page; - m_page = page; - m_links.clear(); - m_linkRects.clear(); - if (!m_page) - return; - - // Poppler::Page::links() returns std::vector> in Poppler Qt6 - auto links = m_page->links(); - for (auto &linkUp : links) - { - Poppler::Link *link = linkUp.get(); - if (!link) - continue; - if (link->linkType() == Poppler::Link::Browse || - link->linkType() == Poppler::Link::Goto) - m_links.emplace_back(std::move(linkUp)); - else - std::cerr << "linktype: " << link->linkType() << std::endl; - } - - rebuildInternalData(); -} - -void PDFPage::setZoomFactor(double zoom) -{ - if (qFuzzyCompare(m_scaleFactor, zoom)) - return; - m_scaleFactor = zoom; - rebuildInternalData(); -} - -void PDFPage::setRotation(Poppler::Page::Rotation rot) -{ - if (m_rotation == rot) - return; - m_rotation = rot; - rebuildInternalData(); -} - -void PDFPage::clearPixmap() -{ - m_pdfPixmap = QPixmap(); -} - -QImage PDFPage::getPrintableImage(int resolution) const -{ - if (!m_page) - return QImage(); - - - Poppler::Page::Rotation rot = Poppler::Page::Rotate0; - - if (m_page->orientation() == Poppler::Page::Landscape) - rot = Poppler::Page::Rotate270; - else if (m_page->orientation() == Poppler::Page::Seascape) - rot = Poppler::Page::Rotate90; - else if (m_page->orientation() == Poppler::Page::UpsideDown) - rot = Poppler::Page::Rotate180; - Q_UNUSED(rot) - - - return m_page->renderToImage(resolution, resolution, -1, -1, -1, -1, m_rotation); -} - -QSize PDFPage::sizeHint() const -{ - if (!m_page) - return QSize(); - return getRotatedSize(m_page->pageSize(), m_rotation); -} - -void PDFPage::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event) - if (!m_page) - return; - if (m_pdfPixmap.isNull()) - { - const QImage img = m_page->renderToImage(m_scaleFactor * 72, m_scaleFactor * 72, -1, -1, -1, -1, m_rotation); - m_pdfPixmap = QPixmap::fromImage(img); - emit pageRendered(); - } - QPainter p(this); - p.drawPixmap(0, 0, m_pdfPixmap); - p.end(); -} - -void PDFPage::mouseMoveEvent(QMouseEvent *event) -{ - const QPointF pos = event->position(); - for (const auto &linkRect : std::as_const(m_linkRects)) - { - if (linkRect.contains(pos)) + switch (rot) { - setCursor(Qt::PointingHandCursor); - return; + case Poppler::Page::Rotate0: + case Poppler::Page::Rotate180: + return in; + case Poppler::Page::Rotate90: + case Poppler::Page::Rotate270: + return in.transposed(); } + Q_ASSERT(false); + return in; } - setCursor(Qt::ArrowCursor); - QWidget::mouseMoveEvent(event); -} -void PDFPage::mouseReleaseEvent(QMouseEvent *event) -{ - const QPointF pos = event->position(); - for (int i = 0; i < m_linkRects.size(); ++i) + PDFPage::PDFPage(QWidget *parent) + : QWidget(parent) + , m_page(nullptr) + , m_rotation(Poppler::Page::Rotate0) + , m_scaleFactor(1.0) { - if (m_linkRects.at(i).contains(pos)) + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setMouseTracking(true); + } + + PDFPage::~PDFPage() + { + delete m_page; + } + + void PDFPage::setPopplerPage(Poppler::Page *page) + { + if (m_page == page) + return; + delete m_page; + m_page = page; + m_links.clear(); + m_linkRects.clear(); + if (!m_page) + return; + + // Poppler::Page::links() returns std::vector> in Poppler Qt6 + auto links = m_page->links(); + for (auto &linkUp : links) { - const Poppler::Link *link = m_links.at(i).get(); + Poppler::Link *link = linkUp.get(); if (!link) continue; - if (link->linkType() == Poppler::Link::Browse) + if (link->linkType() == Poppler::Link::Browse || link->linkType() == Poppler::Link::Goto) + m_links.emplace_back(std::move(linkUp)); + else + std::cerr << "linktype: " << link->linkType() << std::endl; + } + + rebuildInternalData(); + } + + void PDFPage::setZoomFactor(double zoom) + { + if (qFuzzyCompare(m_scaleFactor, zoom)) + return; + m_scaleFactor = zoom; + rebuildInternalData(); + } + + void PDFPage::setRotation(Poppler::Page::Rotation rot) + { + if (m_rotation == rot) + return; + m_rotation = rot; + rebuildInternalData(); + } + + void PDFPage::clearPixmap() + { + m_pdfPixmap = QPixmap(); + } + + QImage PDFPage::getPrintableImage(int resolution) const + { + if (!m_page) + return QImage(); + + + Poppler::Page::Rotation rot = Poppler::Page::Rotate0; + + if (m_page->orientation() == Poppler::Page::Landscape) + rot = Poppler::Page::Rotate270; + else if (m_page->orientation() == Poppler::Page::Seascape) + rot = Poppler::Page::Rotate90; + else if (m_page->orientation() == Poppler::Page::UpsideDown) + rot = Poppler::Page::Rotate180; + Q_UNUSED(rot) + + + return m_page->renderToImage(resolution, resolution, -1, -1, -1, -1, m_rotation); + } + + QSize PDFPage::sizeHint() const + { + if (!m_page) + return QSize(); + return getRotatedSize(m_page->pageSize(), m_rotation); + } + + void PDFPage::paintEvent(QPaintEvent *event) + { + Q_UNUSED(event) + if (!m_page) + return; + if (m_pdfPixmap.isNull()) + { + const QImage img = m_page->renderToImage(m_scaleFactor * 72, m_scaleFactor * 72, -1, -1, -1, -1, m_rotation); + m_pdfPixmap = QPixmap::fromImage(img); + emit pageRendered(); + } + QPainter p(this); + p.drawPixmap(0, 0, m_pdfPixmap); + p.end(); + } + + void PDFPage::mouseMoveEvent(QMouseEvent *event) + { + const QPointF pos = event->position(); + for (const auto &linkRect : std::as_const(m_linkRects)) + { + if (linkRect.contains(pos)) { - const Poppler::LinkBrowse *linkBrowse = static_cast(link); - emit externalLinkClicked(linkBrowse->url()); - return; - } - else if (link->linkType() == Poppler::Link::Goto) - { - const Poppler::LinkGoto *linkGoto = static_cast(link); - if (linkGoto->isExternal()) - { - const QUrl url = QUrl::fromLocalFile(linkGoto->fileName()); - emit externalLinkClicked(url.toString()); - return; - } - emit linkClicked(linkGoto->destination()); + setCursor(Qt::PointingHandCursor); return; } } + setCursor(Qt::ArrowCursor); + QWidget::mouseMoveEvent(event); } - QWidget::mouseReleaseEvent(event); -} -void PDFPage::rebuildInternalData() -{ - clearPixmap(); - - if (!m_page) - return; - - const QSizeF s(rotatedPageSize()); - const int w = qRound(s.width() * m_scaleFactor); - const int h = qRound(s.height() * m_scaleFactor); - setMinimumSize(w, h); - resize(sizeHint()); - - - m_linkRects.clear(); - m_linkRects.reserve(static_cast(m_links.size())); - for (const auto &linkUp : m_links) + void PDFPage::mouseReleaseEvent(QMouseEvent *event) { - const Poppler::Link *link = linkUp.get(); - if (!link) - continue; - const QRectF r = link->linkArea(); - m_linkRects += QRectF(r.x() * w, r.y() * h, r.width() * w, r.height() * h); + const QPointF pos = event->position(); + for (int i = 0; i < m_linkRects.size(); ++i) + { + if (m_linkRects.at(i).contains(pos)) + { + const Poppler::Link *link = m_links.at(i).get(); + if (!link) + continue; + if (link->linkType() == Poppler::Link::Browse) + { + const Poppler::LinkBrowse *linkBrowse = static_cast(link); + emit externalLinkClicked(linkBrowse->url()); + return; + } + else if (link->linkType() == Poppler::Link::Goto) + { + const Poppler::LinkGoto *linkGoto = static_cast(link); + if (linkGoto->isExternal()) + { + const QUrl url = QUrl::fromLocalFile(linkGoto->fileName()); + emit externalLinkClicked(url.toString()); + return; + } + emit linkClicked(linkGoto->destination()); + return; + } + } + } + QWidget::mouseReleaseEvent(event); + } + + void PDFPage::rebuildInternalData() + { + clearPixmap(); + + if (!m_page) + return; + + const QSizeF s(rotatedPageSize()); + const int w = qRound(s.width() * m_scaleFactor); + const int h = qRound(s.height() * m_scaleFactor); + setMinimumSize(w, h); + resize(sizeHint()); + + + m_linkRects.clear(); + m_linkRects.reserve(static_cast(m_links.size())); + for (const auto &linkUp : m_links) + { + const Poppler::Link *link = linkUp.get(); + if (!link) + continue; + const QRectF r = link->linkArea(); + m_linkRects += QRectF(r.x() * w, r.y() * h, r.width() * w, r.height() * h); + } + } + + QSizeF PDFPage::rotatedPageSize() const + { + return m_page ? getRotatedSize(m_page->pageSizeF(), m_rotation) : QSizeF(); } } -QSizeF PDFPage::rotatedPageSize() const -{ - return m_page ? getRotatedSize(m_page->pageSizeF(), m_rotation) : QSizeF(); -} -} - -#endif // HAVE_POPPLER_QT6 +#endif // HAVE_POPPLER_QT6 diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.h old mode 100755 new mode 100644 index 115377fe4..4151a5df6 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfpage.h @@ -12,9 +12,9 @@ #ifdef HAVE_POPPLER_QT6 namespace Poppler { -class Page; -class Link; -class LinkDestination; + class Page; + class Link; + class LinkDestination; } #endif @@ -22,44 +22,46 @@ namespace NGL { -class PDFPage final : public QWidget -{ - Q_OBJECT -public: - explicit PDFPage(QWidget *parent = nullptr); - virtual ~PDFPage(); + class PDFPage final : public QWidget + { + Q_OBJECT + public: + explicit PDFPage(QWidget *parent = nullptr); + virtual ~PDFPage(); #ifdef HAVE_POPPLER_QT6 - void setPopplerPage(Poppler::Page *page); - void setRotation(Poppler::Page::Rotation rot); - QImage getPrintableImage(int resolution = 300) const; -Q_SIGNALS: - void linkClicked(const Poppler::LinkDestination &dest); + void setPopplerPage(Poppler::Page *page); + void setRotation(Poppler::Page::Rotation rot); + QImage getPrintableImage(int resolution = 300) const; + Q_SIGNALS: + void linkClicked(const Poppler::LinkDestination &dest); #endif -public: - void setZoomFactor(double zoom); - void clearPixmap(); - QSize sizeHint() const override; -Q_SIGNALS: - void pageRendered(); - - void externalLinkClicked(const QString &url); - -protected: - void paintEvent(QPaintEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; -private: - void rebuildInternalData(); - QSizeF rotatedPageSize() const; -protected: + public: + void setZoomFactor(double zoom); + void clearPixmap(); + QSize sizeHint() const override; + Q_SIGNALS: + void pageRendered(); + + void externalLinkClicked(const QString &url); + + protected: + void paintEvent(QPaintEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + + private: + void rebuildInternalData(); + QSizeF rotatedPageSize() const; + + protected: #ifdef HAVE_POPPLER_QT6 - Poppler::Page *m_page; - std::vector> m_links; - QList< QRectF > m_linkRects; - Poppler::Page::Rotation m_rotation; + Poppler::Page *m_page; + std::vector> m_links; + QList m_linkRects; + Poppler::Page::Rotation m_rotation; #endif - double m_scaleFactor; - QPixmap m_pdfPixmap; -}; -} + double m_scaleFactor; + QPixmap m_pdfPixmap; + }; +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.cpp old mode 100755 new mode 100644 index be7a12bde..f7d764cda --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.cpp @@ -10,162 +10,162 @@ static const double s_minZoom = 1.0; namespace NGL { -PDFWidget::PDFWidget(QWidget *parent) - : QWidget(parent) - , m_zoomFactor(1.0) - , ui(std::make_unique()) -{ - ui->setupUi(this); - ui->zoomFull->setVisible(false); - ui->zoom100->setVisible(false); - ui->pageLabel->setAutoFillBackground(true); + PDFWidget::PDFWidget(QWidget *parent) + : QWidget(parent) + , m_zoomFactor(1.0) + , ui(std::make_unique()) + { + ui->setupUi(this); + ui->zoomFull->setVisible(false); + ui->zoom100->setVisible(false); + ui->pageLabel->setAutoFillBackground(true); - connect(ui->previousPage, &QToolButton::clicked, ui->pdfDocument, &PDFDocument::previousPage); - connect(ui->nextPage, &QToolButton::clicked, ui->pdfDocument, &PDFDocument::nextPage); + connect(ui->previousPage, &QToolButton::clicked, ui->pdfDocument, &PDFDocument::previousPage); + connect(ui->nextPage, &QToolButton::clicked, ui->pdfDocument, &PDFDocument::nextPage); #ifdef HAVE_POPPLER_QT6 - connect(ui->zoom100, &QToolButton::clicked, this, &PDFWidget::onZoomDefault); - connect(ui->zoomMinus, &QToolButton::clicked, this, &PDFWidget::onZoomMinus); - connect(ui->zoomPlus, &QToolButton::clicked, this, &PDFWidget::onZoomPlus); - connect(ui->zoomFull, &QToolButton::clicked, this, &PDFWidget::onZoomFull); - connect(ui->rotateDoc, &QToolButton::clicked, this, &PDFWidget::rotate); - connect(ui->pdfDocument, &PDFDocument::rotationChanged, this, &PDFWidget::rotationChanged); + connect(ui->zoom100, &QToolButton::clicked, this, &PDFWidget::onZoomDefault); + connect(ui->zoomMinus, &QToolButton::clicked, this, &PDFWidget::onZoomMinus); + connect(ui->zoomPlus, &QToolButton::clicked, this, &PDFWidget::onZoomPlus); + connect(ui->zoomFull, &QToolButton::clicked, this, &PDFWidget::onZoomFull); + connect(ui->rotateDoc, &QToolButton::clicked, this, &PDFWidget::rotate); + connect(ui->pdfDocument, &PDFDocument::rotationChanged, this, &PDFWidget::rotationChanged); #endif - connect(ui->pdfDocument, &PDFDocument::currentPageChanged, this, &PDFWidget::pageChanged); -} + connect(ui->pdfDocument, &PDFDocument::currentPageChanged, this, &PDFWidget::pageChanged); + } -PDFWidget::~PDFWidget() -{ - // unique_ptr destructor runs here where Ui::pdfWidget is a complete type -} + PDFWidget::~PDFWidget() + { + // unique_ptr destructor runs here where Ui::pdfWidget is a complete type + } -bool PDFWidget::showPDF(const QUrl &pdf) -{ - return ui->pdfDocument->showPDF(pdf); -} + bool PDFWidget::showPDF(const QUrl &pdf) + { + return ui->pdfDocument->showPDF(pdf); + } -bool PDFWidget::showPDF(const QByteArray &pdf) -{ - return ui->pdfDocument->showPDF(pdf); -} + bool PDFWidget::showPDF(const QByteArray &pdf) + { + return ui->pdfDocument->showPDF(pdf); + } -void PDFWidget::setZoomFactor(double newZoomFactor) -{ - m_zoomFactor = newZoomFactor; - ui->pdfDocument->setZoomFactor(newZoomFactor); -} + void PDFWidget::setZoomFactor(double newZoomFactor) + { + m_zoomFactor = newZoomFactor; + ui->pdfDocument->setZoomFactor(newZoomFactor); + } #ifdef HAVE_POPPLER_QT6 -void PDFWidget::setRotation(Poppler::Page::Rotation rot) -{ - ui->pdfDocument->setRotation(rot); -} + void PDFWidget::setRotation(Poppler::Page::Rotation rot) + { + ui->pdfDocument->setRotation(rot); + } #endif -bool PDFWidget::setPage(int newPage) -{ - return ui->pdfDocument->setPage(newPage); -} + bool PDFWidget::setPage(int newPage) + { + return ui->pdfDocument->setPage(newPage); + } -int PDFWidget::numPages() const -{ - return ui->pdfDocument->numPages(); -} + int PDFWidget::numPages() const + { + return ui->pdfDocument->numPages(); + } -int PDFWidget::curPage() const -{ - return ui->pdfDocument->curPage(); -} + int PDFWidget::curPage() const + { + return ui->pdfDocument->curPage(); + } -QVector PDFWidget::getPrintableImages(int resolution) const -{ + QVector PDFWidget::getPrintableImages(int resolution) const + { #ifdef HAVE_POPPLER_QT6 - return ui->pdfDocument->getPrintableImages(resolution); + return ui->pdfDocument->getPrintableImages(resolution); #else - Q_UNUSED(resolution); - return QVector(); + Q_UNUSED(resolution); + return QVector(); #endif -} - -void PDFWidget::resizePdfToWidth() -{ -#ifdef HAVE_POPPLER_QT6 - ui->pdfDocument->resizePdfToWidth(); -#endif -} - -void PDFWidget::pageChanged(int cur, int max) -{ - if (cur < 1) - { - ui->pdfDocument->setPage(1); - return; } - ui->pageLabel->setText(tr("Page %1 of %2").arg(cur).arg(max)); - ui->nextPage->setEnabled(cur < max); - ui->previousPage->setEnabled(cur > 1); -} -void PDFWidget::rotate() -{ -#ifdef HAVE_POPPLER_QT6 - Poppler::Page::Rotation rot0 = ui->pdfDocument->getRotation(); - Poppler::Page::Rotation rot1 = rot0; - switch (rot0) + void PDFWidget::resizePdfToWidth() { - case Poppler::Page::Rotate0: - rot1 = Poppler::Page::Rotate90; - break; - case Poppler::Page::Rotate90: - rot1 = Poppler::Page::Rotate180; - break; - case Poppler::Page::Rotate180: - rot1 = Poppler::Page::Rotate270; - break; - case Poppler::Page::Rotate270: - rot1 = Poppler::Page::Rotate0; - break; +#ifdef HAVE_POPPLER_QT6 + ui->pdfDocument->resizePdfToWidth(); +#endif } - ui->pdfDocument->setRotation(rot1); -#endif -} -void PDFWidget::onZoomDefault() -{ + void PDFWidget::pageChanged(int cur, int max) + { + if (cur < 1) + { + ui->pdfDocument->setPage(1); + return; + } + ui->pageLabel->setText(tr("Page %1 of %2").arg(cur).arg(max)); + ui->nextPage->setEnabled(cur < max); + ui->previousPage->setEnabled(cur > 1); + } + + void PDFWidget::rotate() + { #ifdef HAVE_POPPLER_QT6 - ui->pdfDocument->setZoomFactor(1.0); - m_zoomFactor = 1.0; + Poppler::Page::Rotation rot0 = ui->pdfDocument->getRotation(); + Poppler::Page::Rotation rot1 = rot0; + switch (rot0) + { + case Poppler::Page::Rotate0: + rot1 = Poppler::Page::Rotate90; + break; + case Poppler::Page::Rotate90: + rot1 = Poppler::Page::Rotate180; + break; + case Poppler::Page::Rotate180: + rot1 = Poppler::Page::Rotate270; + break; + case Poppler::Page::Rotate270: + rot1 = Poppler::Page::Rotate0; + break; + } + ui->pdfDocument->setRotation(rot1); #endif -} -void PDFWidget::onZoomFull() -{ + } + + void PDFWidget::onZoomDefault() + { #ifdef HAVE_POPPLER_QT6 - ui->pdfDocument->resizePdfToWidth(); - m_zoomFactor = 1.0; + ui->pdfDocument->setZoomFactor(1.0); + m_zoomFactor = 1.0; #endif -} - - -void PDFWidget::onZoomMinus() -{ + } + void PDFWidget::onZoomFull() + { #ifdef HAVE_POPPLER_QT6 - if (m_zoomFactor > s_minZoom) - m_zoomFactor -= 0.20; - if (m_zoomFactor < s_minZoom) - m_zoomFactor = s_minZoom; - ui->pdfDocument->setZoomFactor(m_zoomFactor); + ui->pdfDocument->resizePdfToWidth(); + m_zoomFactor = 1.0; #endif -} + } -void PDFWidget::onZoomPlus() -{ + + void PDFWidget::onZoomMinus() + { #ifdef HAVE_POPPLER_QT6 - if (m_zoomFactor < s_maxZoom) - m_zoomFactor += 0.20; - if(m_zoomFactor > s_maxZoom) - m_zoomFactor = s_maxZoom; - ui->pdfDocument->setZoomFactor(m_zoomFactor); + if (m_zoomFactor > s_minZoom) + m_zoomFactor -= 0.20; + if (m_zoomFactor < s_minZoom) + m_zoomFactor = s_minZoom; + ui->pdfDocument->setZoomFactor(m_zoomFactor); #endif -} + } -} + void PDFWidget::onZoomPlus() + { +#ifdef HAVE_POPPLER_QT6 + if (m_zoomFactor < s_maxZoom) + m_zoomFactor += 0.20; + if (m_zoomFactor > s_maxZoom) + m_zoomFactor = s_maxZoom; + ui->pdfDocument->setZoomFactor(m_zoomFactor); +#endif + } + +} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.h old mode 100755 new mode 100644 index 49524b36d..77459f0c8 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglpdfwidget.h @@ -13,48 +13,48 @@ class QUrl; namespace Ui { -class pdfWidget; + class pdfWidget; } namespace NGL { -class NGLWIDGETS_EXPORT PDFWidget : public QWidget -{ - Q_OBJECT -public: - explicit PDFWidget(QWidget *parent = nullptr); - ~PDFWidget(); + class NGLWIDGETS_EXPORT PDFWidget : public QWidget + { + Q_OBJECT + public: + explicit PDFWidget(QWidget *parent = nullptr); + ~PDFWidget(); - bool showPDF(const QUrl &pdf); - bool showPDF(const QByteArray &pdf); - void setZoomFactor(double newZoomFactor); + bool showPDF(const QUrl &pdf); + bool showPDF(const QByteArray &pdf); + void setZoomFactor(double newZoomFactor); #ifdef HAVE_POPPLER_QT6 - void setRotation(Poppler::Page::Rotation rot); + void setRotation(Poppler::Page::Rotation rot); #endif - bool setPage(int newPage); + bool setPage(int newPage); #ifdef HAVE_POPPLER_QT6 - QVector getPrintableImages(int resolution = 300) const; - void resizePdfToWidth(); + QVector getPrintableImages(int resolution = 300) const; + void resizePdfToWidth(); #endif - int numPages() const; - int curPage() const; + int numPages() const; + int curPage() const; -Q_SIGNALS: - void currentPageChanged(int cur, int max); + Q_SIGNALS: + void currentPageChanged(int cur, int max); #ifdef HAVE_POPPLER_QT6 - void rotationChanged(Poppler::Page::Rotation newRotation); + void rotationChanged(Poppler::Page::Rotation newRotation); #endif -protected Q_SLOTS: - void pageChanged(int cur, int max); + protected Q_SLOTS: + void pageChanged(int cur, int max); #ifdef HAVE_POPPLER_QT6 - void rotate(); - void onZoomDefault(); - void onZoomFull(); - void onZoomMinus(); - void onZoomPlus(); + void rotate(); + void onZoomDefault(); + void onZoomFull(); + void onZoomMinus(); + void onZoomPlus(); #endif -protected: - double m_zoomFactor{1.0}; - std::unique_ptr ui; -}; + protected: + double m_zoomFactor{1.0}; + std::unique_ptr ui; + }; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.cpp old mode 100755 new mode 100644 index fae392ac5..d94fbb311 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.cpp @@ -7,13 +7,14 @@ #include NGLStandardButton::NGLStandardButton(QWidget *parent) - : NGLStandardButton(NoButton, parent) -{} + : NGLStandardButton(NoButton, parent) +{ +} NGLStandardButton::NGLStandardButton(StandardButton type, QWidget *parent) - : QPushButton(parent) - , m_type(type) - , m_layoutPriority(-1) + : QPushButton(parent) + , m_type(type) + , m_layoutPriority(-1) { init(); } @@ -40,164 +41,162 @@ void NGLStandardButton::setType(StandardButton t) const char *objectName = nullptr; switch (t) { - case Ok: - iconName = ":icons/png/ok.png"; - text = tr("&Ok"); - objectName = "btnOk"; - break; - case Send: - iconName = ":icons/svg/messages.svg"; - text = tr("&Send"); - key = QKeySequence(Qt::CTRL | Qt::Key_Return); - objectName = "btnSend"; - break; - case New: - iconName = ":icons/png/messages_new.png"; - text = tr("&New"); - key = QKeySequence::New; - objectName = "btnNew"; - break; - case Delete: - iconName = ":icons/png/deleteall.png"; - text = tr("&Delete"); - key = QKeySequence::Delete; - objectName = "btnDelete"; - break; - case Save: - iconName = ":icons/png/save.png"; - text = tr("Sa&ve"); - key = QKeySequence::Save; - objectName = "btnSave"; - break; - case Open: - iconName = ":icons/png/address_book.png"; - text = tr("&Open"); - key = QKeySequence::Open; - objectName = "btnOpen"; - break; - case Yes: - iconName = ":icons/png/ok.png"; - text = tr("&Yes"); - objectName = "btnYes"; - break; - case No: - iconName = ":icons/png/delete.png"; - text = tr("&No"); - objectName = "btnNo"; - break; - case Close: - iconName = ":icons/png/delete_exercise.png"; - text = tr("&Close"); - objectName = "btnClose"; - break; - case Cancel: - iconName = ":icons/png/delete_exercise.png"; - text = tr("&Cancel"); - objectName = "btnCancel"; - break; - case Help: - iconName = ":icons/svg/ueb_index.svg"; - text = QString(); - actionText = tr("Help"); - setMaximumWidth(sizeHint().height()); - key = QKeySequence::HelpContents; - objectName = "btnHelp"; - break; - case Apply: - iconName = ":icons/png/ok.png"; - text = tr("&Apply"); - objectName = "btnApply"; - break; - case Reset: - iconName = ":icons/png/undo_act.png"; - text = tr("Re&set"); - objectName = "btnReset"; - break; - case Print: - iconName = ":icons/png/printer.png"; - text = QString(); - actionText = tr("Print"); - setMaximumWidth(sizeHint().height()); - key = QKeySequence::Print; - objectName = "btnPrint"; - break; - case Add: - iconName = ":icons/png/add.png"; - text = tr("A&dd"); - objectName = "btnAdd"; - break; - case Remove: - iconName = ":icons/png/remove.png"; - text = tr("Re&move"); - objectName = "btnRemove"; - break; - case Edit: - iconName = ":icons/png/rename_exercise.png"; - text = tr("&Edit"); - objectName = "btnEdit"; - break; - case Modify: - iconName = ":icons/png/ok.png"; - text = tr("Modify"); - objectName = "btnModify"; - break; - case Hide: - iconName = ":icons/png/ok.png"; - text = tr("Hide"); - objectName = "btnHide"; - break; - case Download: - iconName = ":icons/png/download.png"; - text = tr("Download"); - objectName = "btnDownload"; - break; - case Library: - { - iconName = ":icons/png/address_book.png"; - text.clear(); - setMaximumWidth(minimumSizeHint().width() * 4 / 5); - QMenu *menu = new QMenu(this); - setMenu(menu); + case Ok: + iconName = ":icons/png/ok.png"; + text = tr("&Ok"); + objectName = "btnOk"; + break; + case Send: + iconName = ":icons/svg/messages.svg"; + text = tr("&Send"); + key = QKeySequence(Qt::CTRL | Qt::Key_Return); + objectName = "btnSend"; + break; + case New: + iconName = ":icons/png/messages_new.png"; + text = tr("&New"); + key = QKeySequence::New; + objectName = "btnNew"; + break; + case Delete: + iconName = ":icons/png/deleteall.png"; + text = tr("&Delete"); + key = QKeySequence::Delete; + objectName = "btnDelete"; + break; + case Save: + iconName = ":icons/png/save.png"; + text = tr("Sa&ve"); + key = QKeySequence::Save; + objectName = "btnSave"; + break; + case Open: + iconName = ":icons/png/address_book.png"; + text = tr("&Open"); + key = QKeySequence::Open; + objectName = "btnOpen"; + break; + case Yes: + iconName = ":icons/png/ok.png"; + text = tr("&Yes"); + objectName = "btnYes"; + break; + case No: + iconName = ":icons/png/delete.png"; + text = tr("&No"); + objectName = "btnNo"; + break; + case Close: + iconName = ":icons/png/delete_exercise.png"; + text = tr("&Close"); + objectName = "btnClose"; + break; + case Cancel: + iconName = ":icons/png/delete_exercise.png"; + text = tr("&Cancel"); + objectName = "btnCancel"; + break; + case Help: + iconName = ":icons/svg/ueb_index.svg"; + text = QString(); + actionText = tr("Help"); + setMaximumWidth(sizeHint().height()); + key = QKeySequence::HelpContents; + objectName = "btnHelp"; + break; + case Apply: + iconName = ":icons/png/ok.png"; + text = tr("&Apply"); + objectName = "btnApply"; + break; + case Reset: + iconName = ":icons/png/undo_act.png"; + text = tr("Re&set"); + objectName = "btnReset"; + break; + case Print: + iconName = ":icons/png/printer.png"; + text = QString(); + actionText = tr("Print"); + setMaximumWidth(sizeHint().height()); + key = QKeySequence::Print; + objectName = "btnPrint"; + break; + case Add: + iconName = ":icons/png/add.png"; + text = tr("A&dd"); + objectName = "btnAdd"; + break; + case Remove: + iconName = ":icons/png/remove.png"; + text = tr("Re&move"); + objectName = "btnRemove"; + break; + case Edit: + iconName = ":icons/png/rename_exercise.png"; + text = tr("&Edit"); + objectName = "btnEdit"; + break; + case Modify: + iconName = ":icons/png/ok.png"; + text = tr("Modify"); + objectName = "btnModify"; + break; + case Hide: + iconName = ":icons/png/ok.png"; + text = tr("Hide"); + objectName = "btnHide"; + break; + case Download: + iconName = ":icons/png/download.png"; + text = tr("Download"); + objectName = "btnDownload"; + break; + case Library: + { + iconName = ":icons/png/address_book.png"; + text.clear(); + setMaximumWidth(minimumSizeHint().width() * 4 / 5); + QMenu *menu = new QMenu(this); + setMenu(menu); - QAction *actionImport = menu->addAction(QIcon(QLatin1String(":icons/svg/import_docs.svg")), tr("Import from library")); - actionImport->setObjectName(QLatin1String("actionImport")); - connect(actionImport, &QAction::triggered, - this, QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); - m_actionList += actionImport; + QAction *actionImport = menu->addAction(QIcon(QLatin1String(":icons/svg/import_docs.svg")), tr("Import from library")); + actionImport->setObjectName(QLatin1String("actionImport")); + connect(actionImport, &QAction::triggered, this, QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); + m_actionList += actionImport; - QAction *actionExport = menu->addAction(QIcon(QLatin1String(":icons/svg/export_docs.svg")), tr("Export to library")); - actionExport->setObjectName(QLatin1String("actionExport")); - connect(actionExport, &QAction::triggered, - this, QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); - m_actionList += actionExport; + QAction *actionExport = menu->addAction(QIcon(QLatin1String(":icons/svg/export_docs.svg")), tr("Export to library")); + actionExport->setObjectName(QLatin1String("actionExport")); + connect(actionExport, &QAction::triggered, this, QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); + m_actionList += actionExport; - objectName = "btnLibrary"; - break; - } - case Show: - { - iconName = ":icons/png/preview.png"; - text = tr("Show"); - objectName = "btnShow"; - break; - } - case ZoomIn: - { - iconName = ":icons/png/zoom_in.png"; - text.clear(); - objectName = "btnZoomIn"; - break; - } - case ZoomOut: - { - iconName = ":icons/png/zoom_out.png"; - text.clear(); - objectName = "btnZoomOut"; - break; - } - default: - text = QLatin1String("ButtonText"); - break; + objectName = "btnLibrary"; + break; + } + case Show: + { + iconName = ":icons/png/preview.png"; + text = tr("Show"); + objectName = "btnShow"; + break; + } + case ZoomIn: + { + iconName = ":icons/png/zoom_in.png"; + text.clear(); + objectName = "btnZoomIn"; + break; + } + case ZoomOut: + { + iconName = ":icons/png/zoom_out.png"; + text.clear(); + objectName = "btnZoomOut"; + break; + } + default: + text = QLatin1String("ButtonText"); + break; }; if (!m_defaultText.isEmpty()) text = tr(m_defaultText.constData()); @@ -222,8 +221,7 @@ void NGLStandardButton::setType(StandardButton t) action->setEnabled(isEnabled()); action->setToolTip(toolTip()); action->setWhatsThis(whatsThis()); - connect(action, &QAction::triggered, this, - QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); + connect(action, &QAction::triggered, this, QOverload::of(&QAbstractButton::clicked), Qt::QueuedConnection); m_actionList += action; } } @@ -235,62 +233,62 @@ void NGLStandardButton::setLayoutPriority(qint32 priority) qint32 NGLStandardButton::layoutPriority() const { - + if (m_layoutPriority >= 0) return m_layoutPriority; switch (m_type) { - case Close: - return 10; - case Cancel: - return 11; - case Apply: - return 13; - case Ok: - return 15; - case No: - return 31; - case Yes: - return 32; - case ZoomIn: - return 36; - case ZoomOut: - return 37; - case Show: - return 38; - case Download: - return 44; - case Save: - return 45; - case Open: - return 47; - case Reset: - return 50; - case Send: - return 50; - case Modify: - return 51; - case Hide: - return 52; - case Delete: - return 55; - case Remove: - return 56; - case New: - return 60; - case Add: - return 61; - case Edit: - return 63; - case Library: - return 105; - case Print: - return 110; - case Help: - return 120; - default: - break; + case Close: + return 10; + case Cancel: + return 11; + case Apply: + return 13; + case Ok: + return 15; + case No: + return 31; + case Yes: + return 32; + case ZoomIn: + return 36; + case ZoomOut: + return 37; + case Show: + return 38; + case Download: + return 44; + case Save: + return 45; + case Open: + return 47; + case Reset: + return 50; + case Send: + return 50; + case Modify: + return 51; + case Hide: + return 52; + case Delete: + return 55; + case Remove: + return 56; + case New: + return 60; + case Add: + return 61; + case Edit: + return 63; + case Library: + return 105; + case Print: + return 110; + case Help: + return 120; + default: + break; }; return 50; } @@ -299,18 +297,18 @@ void NGLStandardButton::changeEvent(QEvent *e) { switch (e->type()) { - case QEvent::LanguageChange: - setType(m_type); - break; - case QEvent::EnabledChange: - { - QAction *a = findChild(); - if (a) - a->setEnabled(isEnabled()); - break; - } - default: - break; + case QEvent::LanguageChange: + setType(m_type); + break; + case QEvent::EnabledChange: + { + QAction *a = findChild(); + if (a) + a->setEnabled(isEnabled()); + break; + } + default: + break; } QPushButton::changeEvent(e); } @@ -333,4 +331,3 @@ void NGLStandardButton::setDefaultToolTip(const char *toolTip) if (!m_defaultToolTip.isEmpty()) setToolTip(tr(m_defaultToolTip.constData())); } - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.h old mode 100755 new mode 100644 index 2b6e31fcd..2a6c17857 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglstandardbutton.h @@ -7,8 +7,6 @@ #include "nglwidgets_export.h" - - class NGLWIDGETS_EXPORT NGLStandardButton : public QPushButton { Q_OBJECT @@ -16,76 +14,67 @@ class NGLWIDGETS_EXPORT NGLStandardButton : public QPushButton Q_PROPERTY(qint32 layoutPriority READ layoutPriority WRITE setLayoutPriority) public: - - enum StandardButton { - NoButton = 0x00000000, - Ok = 0x00000001, - Save = 0x00000002, - Open = 0x00000004, - Yes = 0x00000008, - No = 0x00000010, - Close = 0x00000020, - Cancel = 0x00000040, - Help = 0x00000080, - Apply = 0x00000100, - Reset = 0x00000200, - Print = 0x00000400, - Add = 0x00000800, - Remove = 0x00002000, - Edit = 0x00008000, - Send = 0x00010000, - New = 0x00020000, - Delete = 0x00040000, - Download = 0x00080000, - Library = 0x00100000, - Show = 0x00200000, - ZoomIn = 0x00400000, - ZoomOut = 0x00800000, - Modify = 0x01000000, - Hide = 0x02000000, + NoButton = 0x00000000, + Ok = 0x00000001, + Save = 0x00000002, + Open = 0x00000004, + Yes = 0x00000008, + No = 0x00000010, + Close = 0x00000020, + Cancel = 0x00000040, + Help = 0x00000080, + Apply = 0x00000100, + Reset = 0x00000200, + Print = 0x00000400, + Add = 0x00000800, + Remove = 0x00002000, + Edit = 0x00008000, + Send = 0x00010000, + New = 0x00020000, + Delete = 0x00040000, + Download = 0x00080000, + Library = 0x00100000, + Show = 0x00200000, + ZoomIn = 0x00400000, + ZoomOut = 0x00800000, + Modify = 0x01000000, + Hide = 0x02000000, #ifndef Q_MOC_RUN - FirstButton = Ok, - LastButton = Hide + FirstButton = Ok, + LastButton = Hide #endif }; Q_ENUM(StandardButton) Q_DECLARE_FLAGS(StandardButtons, StandardButton) Q_FLAG(StandardButtons) - explicit NGLStandardButton(QWidget *parent = nullptr); - + explicit NGLStandardButton(StandardButton type, QWidget *parent = nullptr); - StandardButton type() const; - + void setType(StandardButton t); - void setLayoutPriority(qint32 priority); - virtual qint32 layoutPriority() const; - QList actions() const; - void setDefaultText(const char *text); - void setDefaultToolTip(const char *toolTip); @@ -97,9 +86,8 @@ protected: QList m_actionList; virtual void changeEvent(QEvent *e); + private: void init(); }; Q_DECLARE_OPERATORS_FOR_FLAGS(NGLStandardButton::StandardButtons) - - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.cpp old mode 100755 new mode 100644 index 89018080f..b716a6d5f --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.cpp @@ -10,14 +10,12 @@ NGLTreeItem::~NGLTreeItem() } - NGLTreeItem::NGLTreeItem(const NGLTreeItem &orig) { set(orig); } - NGLTreeItem &NGLTreeItem::operator=(const NGLTreeItem &orig) { set(orig); @@ -25,7 +23,6 @@ NGLTreeItem &NGLTreeItem::operator=(const NGLTreeItem &orig) } - void NGLTreeItem::set(const NGLTreeItem &orig) { m_parentItem = orig.m_parentItem; @@ -57,7 +54,6 @@ void NGLTreeItem::appendChild(NGLTreeItem *item) } - NGLTreeItem *NGLTreeItem::takeChild(int row) { return validRow(row) ? m_childItems.takeAt(row) : nullptr; @@ -91,8 +87,7 @@ bool NGLTreeItem::removeChild(const NGLTreeItem *child) bool NGLTreeItem::removeChildren(int row, int count) { int lastRow = row + count - 1; - if (validRow(row) && - (lastRow >= 0) && (lastRow < childCount())) + if (validRow(row) && (lastRow >= 0) && (lastRow < childCount())) { while (lastRow >= row) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.h old mode 100755 new mode 100644 index e427aaa8c..58819da96 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreeitem.h @@ -10,32 +10,24 @@ #include "nglwidgets_export.h" - - - class NGLWIDGETS_EXPORT NGLTreeItem { public: - - NGLTreeItem(const QVariant &data, const QIcon &icon = QIcon()) - : m_data(data) - , m_icon(icon) - {} + : m_data(data) + , m_icon(icon) + { + } - virtual ~NGLTreeItem(); - NGLTreeItem(const NGLTreeItem &orig); - NGLTreeItem &operator=(const NGLTreeItem &orig); - bool insertChild(int row, NGLTreeItem *item); void appendChild(NGLTreeItem *item); @@ -60,7 +52,7 @@ public: virtual QIcon icon() const { return m_icon; } private: - void set(const NGLTreeItem &orig); + void set(const NGLTreeItem &orig); bool validRow(int row) const { return ((row >= 0) && (row < childCount())); } private: diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.cpp old mode 100755 new mode 100644 index 5fb0e9f54..aff656319 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.cpp @@ -13,22 +13,17 @@ #include -NGLTreeModel::NGLTreeModel(QObject *parent, NGLTreeItem *rootItem, - const QStringList &titles) - : QAbstractItemModel(parent) - , m_rootItem(rootItem) - , m_titles(titles) - , m_mimeType(QStringLiteral("NGLTreeModel/dragDrop")) - , m_bMimeDataWithicon(true) +NGLTreeModel::NGLTreeModel(QObject *parent, NGLTreeItem *rootItem, const QStringList &titles) + : QAbstractItemModel(parent) + , m_rootItem(rootItem) + , m_titles(titles) + , m_mimeType(QStringLiteral("NGLTreeModel/dragDrop")) + , m_bMimeDataWithicon(true) { - connect(this, &NGLTreeModel::dataChanged, - this, &NGLTreeModel::modelDataChanged); - connect(this, &NGLTreeModel::rowsInserted, - this, &NGLTreeModel::modelDataChanged); - connect(this, &NGLTreeModel::rowsMoved, - this, &NGLTreeModel::modelDataChanged); - connect(this, &NGLTreeModel::rowsRemoved, - this, &NGLTreeModel::modelDataChanged); + connect(this, &NGLTreeModel::dataChanged, this, &NGLTreeModel::modelDataChanged); + connect(this, &NGLTreeModel::rowsInserted, this, &NGLTreeModel::modelDataChanged); + connect(this, &NGLTreeModel::rowsMoved, this, &NGLTreeModel::modelDataChanged); + connect(this, &NGLTreeModel::rowsRemoved, this, &NGLTreeModel::modelDataChanged); } @@ -82,8 +77,7 @@ Qt::ItemFlags NGLTreeModel::flags(const QModelIndex &index) const } -QVariant NGLTreeModel::headerData(int section, Qt::Orientation orientation, - int role) const +QVariant NGLTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { @@ -94,8 +88,7 @@ QVariant NGLTreeModel::headerData(int section, Qt::Orientation orientation, } -QModelIndex NGLTreeModel::index(int row, int column, - const QModelIndex &parent) const +QModelIndex NGLTreeModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) @@ -142,8 +135,7 @@ int NGLTreeModel::rowCount(const QModelIndex &parent) const } -bool NGLTreeModel::setData(const QModelIndex &index, const QVariant &value, - int role) +bool NGLTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(index) Q_UNUSED(value) @@ -168,9 +160,7 @@ void NGLTreeModel::resetModifedFlag(NGLTreeItem *rootItem) } - -bool NGLTreeModel::setItemData(const QModelIndex &index, const QVariant &value, - const QIcon &icon) +bool NGLTreeModel::setItemData(const QModelIndex &index, const QVariant &value, const QIcon &icon) { if (!index.isValid()) return false; @@ -207,15 +197,14 @@ QMimeData *NGLTreeModel::mimeData(const QModelIndexList &indexes) const } -QMimeData *NGLTreeModel::getMimeData(const QModelIndexList &indexes, - const QString &mimeType) const +QMimeData *NGLTreeModel::getMimeData(const QModelIndexList &indexes, const QString &mimeType) const { QMimeData *mimeData = new QMimeData(); QByteArray encodedData; QDataStream stream(&encodedData, QIODevice::WriteOnly); - + stream << m_bMimeDataWithicon; bool dataStreamed = false; @@ -244,40 +233,34 @@ void NGLTreeModel::streamAddChilds(QDataStream &stream, const NGLTreeItem *item) } -bool NGLTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool NGLTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { - qDebug() << "dropMimeData: action = " << action - << ", row = " << row - << ", column = " << column - << ", parent: valid = " << parent.isValid(); + qDebug() << "dropMimeData: action = " << action << ", row = " << row << ", column = " << column << ", parent: valid = " << parent.isValid(); if ((action != Qt::MoveAction) && (action != Qt::CopyAction)) return false; if (!data->hasFormat(m_mimeType)) return false; - + int beginRow; QModelIndex parentR; if (row != -1) { - + parentR = parent; beginRow = row; } else if (parent.isValid()) { - - - parentR = parent; - - beginRow = rowCount(parentR); - + + parentR = parent; + + beginRow = rowCount(parentR); } else { - + parentR = QModelIndex(); beginRow = rowCount(parentR); } @@ -285,11 +268,10 @@ bool NGLTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, } -bool NGLTreeModel::insertMimeData(const QMimeData *data, const QString &mimeType, - QModelIndex parentR, int beginRow) +bool NGLTreeModel::insertMimeData(const QMimeData *data, const QString &mimeType, QModelIndex parentR, int beginRow) { bool bStreamContainsIcons; - + QByteArray encodedData = data->data(mimeType); QDataStream stream(&encodedData, QIODevice::ReadOnly); @@ -315,7 +297,7 @@ bool NGLTreeModel::insertMimeData(const QMimeData *data, const QString &mimeType first = false; rowCache.insert(idParent, parentR); } - else if (idParent == prevIdParent) + else if (idParent == prevIdParent) { parentR = rowCache[idParent]; beginRow++; @@ -339,10 +321,9 @@ bool NGLTreeModel::insertMimeData(const QMimeData *data, const QString &mimeType } -QVector NGLTreeModel::getMimeDataItems(const QMimeData *data, - const QString &mimeType) const +QVector NGLTreeModel::getMimeDataItems(const QMimeData *data, const QString &mimeType) const { - QVector ret; + QVector ret; QByteArray encodedData = data->data(mimeType); QDataStream stream(&encodedData, QIODevice::ReadOnly); @@ -372,16 +353,14 @@ NGLTreeItem *NGLTreeModel::privateData(const QModelIndex &index) const } -bool NGLTreeModel::moveRow(const QModelIndex &sourceParent, int sourceRow, - const QModelIndex &destParent, int destRow) +bool NGLTreeModel::moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destParent, int destRow) { Q_ASSERT(sourceParent.column() == 0 || !sourceParent.isValid()); Q_ASSERT(destParent.column() == 0 || !destParent.isValid()); NGLTreeItem *sourceParentItem = privateData(sourceParent); NGLTreeItem *destParentItem = privateData(destParent); - if ((sourceRow >= 0) && (sourceRow < sourceParentItem->childCount()) && - (destRow >= 0) && (destRow < destParentItem->childCount())) + if ((sourceRow >= 0) && (sourceRow < sourceParentItem->childCount()) && (destRow >= 0) && (destRow < destParentItem->childCount())) { beginRemoveRows(sourceParent, sourceRow, sourceRow); NGLTreeItem *item = sourceParentItem->takeChild(sourceRow); @@ -413,7 +392,7 @@ bool NGLTreeModel::removeRows(int row, int count, const QModelIndex &parent) if (ret) { for (int r = row; r < parentItem->childCount(); ++r) - parentItem->child(r)->setModified(true); + parentItem->child(r)->setModified(true); } endRemoveRows(); return ret; @@ -430,15 +409,12 @@ bool NGLTreeModel::insertRow(int row, const QModelIndex &parent, NGLTreeItem *it if (parent.column() != 0 && parent.isValid()) return false; - - - parentItem->setModified(true); beginInsertRows(parent, row, row); bool ret = parentItem->insertChild(row, item); for (int r = row; r < parentItem->childCount(); ++r) - parentItem->child(r)->setModified(true); + parentItem->child(r)->setModified(true); endInsertRows(); return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.h old mode 100755 new mode 100644 index 6198c09b3..59b354d46 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/ngltreemodel.h @@ -10,75 +10,57 @@ class NGLTreeItem; - - - class NGLWIDGETS_EXPORT NGLTreeModel : public QAbstractItemModel { Q_OBJECT public: - NGLTreeModel(QObject *parent, NGLTreeItem *rootItem, - const QStringList &titles); + NGLTreeModel(QObject *parent, NGLTreeItem *rootItem, const QStringList &titles); virtual ~NGLTreeModel(); void resetModel(); Qt::ItemFlags flags(const QModelIndex &index) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; - QModelIndex index(int row, int column, - const QModelIndex &parent = QModelIndex()) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::EditRole) const override; - bool setData(const QModelIndex &index, const QVariant &value, - int role = Qt::EditRole) override; - QStringList mimeTypes() const override { return { m_mimeType }; } + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + QStringList mimeTypes() const override { return {m_mimeType}; } Qt::DropActions supportedDropActions() const override { return Qt::CopyAction | Qt::MoveAction; } QMimeData *mimeData(const QModelIndexList &indexes) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) override; + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override; - bool removeRows(int row, int count, - const QModelIndex &parent = QModelIndex()) override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; NGLTreeItem *privateData(const QModelIndex &index) const; void setMimeType(const QString &mimeType); - - bool setItemData(const QModelIndex &index, const QMap &roles) override - { - return QAbstractItemModel::setItemData(index, roles); - } + + bool setItemData(const QModelIndex &index, const QMap &roles) override { return QAbstractItemModel::setItemData(index, roles); } protected: - void setMimeDataWithIcon(bool bWithIcon) { m_bMimeDataWithicon = bWithIcon; } - + void resetModifedFlag(NGLTreeItem *rootItem); - bool setItemData(const QModelIndex &index, const QVariant &value, - const QIcon &icon); - QMimeData *getMimeData(const QModelIndexList &indexes, - const QString &mimeType) const; - bool insertMimeData(const QMimeData *data, const QString &mimeType, - QModelIndex parentR, int beginRow); - - QVector getMimeDataItems(const QMimeData *data, - const QString &mimeType) const; + bool setItemData(const QModelIndex &index, const QVariant &value, const QIcon &icon); + QMimeData *getMimeData(const QModelIndexList &indexes, const QString &mimeType) const; + bool insertMimeData(const QMimeData *data, const QString &mimeType, QModelIndex parentR, int beginRow); - bool moveRow(const QModelIndex &sourceParent, int sourceRow, - const QModelIndex &destParent, int destRow); + QVector getMimeDataItems(const QMimeData *data, const QString &mimeType) const; + + bool moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destParent, int destRow); bool insertRow(int row, const QModelIndex &parent, NGLTreeItem *item); void setRootItem(NGLTreeItem *rootItem); NGLTreeItem *getRootItem() const; - + virtual NGLTreeItem *createItem(const QVariant &data, const QIcon &icon) const; void streamAddChilds(QDataStream &stream, const NGLTreeItem *item) const; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglwidgets_export.h b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglwidgets_export.h old mode 100755 new mode 100644 index 2bf6476de..620b52bda --- a/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglwidgets_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglwidgets/nglwidgets_export.h @@ -5,13 +5,13 @@ #include #ifndef NGLWIDGETS_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define NGLWIDGETS_EXPORT -# else -# if defined(MAKE_NGLWIDGETS_LIB) -# define NGLWIDGETS_EXPORT Q_DECL_EXPORT -# else -# define NGLWIDGETS_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define NGLWIDGETS_EXPORT +#else +#if defined(MAKE_NGLWIDGETS_LIB) +#define NGLWIDGETS_EXPORT Q_DECL_EXPORT +#else +#define NGLWIDGETS_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.cpp old mode 100755 new mode 100644 index e54d96221..25d4af491 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.cpp @@ -8,8 +8,9 @@ #include CBI_Help::CBI_Help(unsigned short port) - : CommandInterface(port, "HELP") -{} + : CommandInterface(port, "HELP") +{ +} void CBI_Help::handleCommandInternal(const QVector &) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h index 4c7812498..2ab2eb217 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h @@ -7,10 +7,10 @@ class TCPSERVER_EXPORT CBI_Help : public CommandInterface { - Q_OBJECT - public: - explicit CBI_Help(unsigned short port); + Q_OBJECT +public: + explicit CBI_Help(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.cpp old mode 100755 new mode 100644 index 848983d77..66bb1ca5d --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.cpp @@ -4,8 +4,9 @@ #include "cbi_pingpong.h" CBI_PingPong::CBI_PingPong(unsigned short port) - : CommandInterface(port, "PING") -{} + : CommandInterface(port, "PING") +{ +} void CBI_PingPong::handleCommandInternal(const QVector &args) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h index f8a370368..939cce6c6 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h @@ -7,10 +7,10 @@ class CBI_PingPong : public CommandInterface { - Q_OBJECT - public: - explicit CBI_PingPong(unsigned short port); + Q_OBJECT +public: + explicit CBI_PingPong(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.cpp old mode 100755 new mode 100644 index 475730921..20d42f218 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.cpp @@ -4,8 +4,9 @@ #include "cbi_quit.h" CBI_Quit::CBI_Quit(unsigned short port) - : CommandInterface(port, "QUIT") -{} + : CommandInterface(port, "QUIT") +{ +} void CBI_Quit::handleCommandInternal(const QVector &) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h index 09733a861..38080fc80 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h @@ -7,10 +7,10 @@ class TCPSERVER_EXPORT CBI_Quit : public CommandInterface { - Q_OBJECT - public: - explicit CBI_Quit(unsigned short port); + Q_OBJECT +public: + explicit CBI_Quit(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.cpp old mode 100755 new mode 100644 index 542ab075a..5765d8350 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.cpp @@ -10,8 +10,9 @@ #include CBI_Recvfile::CBI_Recvfile(unsigned short port) - : CommandInterface(port, "RECV_FILE") -{} + : CommandInterface(port, "RECV_FILE") +{ +} void CBI_Recvfile::handleCommandInternal(const QVector &args) { @@ -39,43 +40,42 @@ void CBI_Recvfile::newPlainData() { WorkerBase *wb = workerBase(); QAbstractSocket *in = socket(); - QIODevice *out = m_wbMap[ wb ].first; + QIODevice *out = m_wbMap[wb].first; if (!out) { in->write("ERROR\n"); - + wb->redirectDataHandling(false); return; } - int size = m_wbMap[ wb ].second; + int size = m_wbMap[wb].second; - - QByteArray ba(10, 0); + + QByteArray ba(10, 0); do { qint64 bytesRead = in->read(ba.data(), ba.size() < size ? ba.size() : size); if (bytesRead < 0) { in->write("ERROR\n"); - + m_wbMap.remove(wb); wb->redirectDataHandling(false); return; } size -= bytesRead; out->write(ba.constData(), bytesRead); - } - while (size > 0 && in->bytesAvailable()); + } while (size > 0 && in->bytesAvailable()); + - if (size != 0) { - m_wbMap[ wb ].second = size; + m_wbMap[wb].second = size; return; } out->close(); delete out; - + m_wbMap.remove(wb); wb->redirectDataHandling(false); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h index e7bce7200..ebe1beffa 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h @@ -12,14 +12,14 @@ class QIODevice; class CBI_Recvfile : public CommandInterface { - Q_OBJECT - public: - explicit CBI_Recvfile(unsigned short port); + Q_OBJECT +public: + explicit CBI_Recvfile(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; - void newPlainData() override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; + void newPlainData() override; - protected: - QMap> m_wbMap; +protected: + QMap> m_wbMap; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.cpp old mode 100755 new mode 100644 index 881a20d4b..82da01858 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.cpp @@ -10,8 +10,9 @@ #include CBI_Sendfile::CBI_Sendfile(unsigned short port) - : CommandInterface(port, "SEND_FILE") -{} + : CommandInterface(port, "SEND_FILE") +{ +} void CBI_Sendfile::handleCommandInternal(const QVector &args) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h index bba7295d1..f46412386 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h @@ -7,10 +7,10 @@ class CBI_Sendfile : public CommandInterface { - Q_OBJECT - public: - explicit CBI_Sendfile(unsigned short port); + Q_OBJECT +public: + explicit CBI_Sendfile(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.cpp old mode 100755 new mode 100644 index 4eb4e56c0..5e289ff27 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.cpp @@ -5,10 +5,9 @@ #include "tcpserver.h" CBI_Shutdown::CBI_Shutdown(unsigned short port) - : CommandInterface(port, "SHUTDOWN") + : CommandInterface(port, "SHUTDOWN") { - connect(this, &CBI_Shutdown::shutdownRequest, - TcpServer::instance(port), &TcpServer::shutdownRequest); + connect(this, &CBI_Shutdown::shutdownRequest, TcpServer::instance(port), &TcpServer::shutdownRequest); } void CBI_Shutdown::handleCommandInternal(const QVector &) @@ -22,4 +21,3 @@ QString CBI_Shutdown::help() const { return QLatin1String("SHUTDOWN - shut down the server"); } - diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h index 4d4a12704..889cf53b9 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h @@ -7,16 +7,16 @@ class TCPSERVER_EXPORT CBI_Shutdown : public CommandInterface { - Q_OBJECT - public: - explicit CBI_Shutdown(unsigned short port); + Q_OBJECT +public: + explicit CBI_Shutdown(unsigned short port); - void handleCommandInternal(const QVector& args) override; - QString help() const override; + void handleCommandInternal(const QVector &args) override; + QString help() const override; - Q_SIGNALS: +Q_SIGNALS: - void shutdownRequest(); + void shutdownRequest(); - private: +private: }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.cpp old mode 100755 new mode 100644 index a47c59a85..f8e4be93b --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.cpp @@ -14,15 +14,16 @@ class CommandInterface::Private { public: explicit Private(unsigned short port_, const QByteArray &command_) - : command(command_) - , port(port_) - {} + : command(command_) + , port(port_) + { + } QByteArray m_connString; QByteArray command; - QAbstractSocket *dev = nullptr; - WorkerBase *wb = nullptr; - int writeTimeout = 1000; + QAbstractSocket *dev = nullptr; + WorkerBase *wb = nullptr; + int writeTimeout = 1000; unsigned short port; bool autoWriteEOL = true; bool bWriteError = false; @@ -35,8 +36,9 @@ QByteArray CommandInterface::Private::defaultSuccessMessage("OK"); QByteArray CommandInterface::Private::defaultErrorMessage("ERROR"); CommandInterface::CommandInterface(unsigned short port, const QByteArray &command) - : d(new Private(port, command)) -{} + : d(new Private(port, command)) +{ +} CommandInterface::~CommandInterface() { @@ -55,9 +57,9 @@ void CommandInterface::handleCommand(const QVector &args) d->dev->flush(); if (d->closeConnection) { - + d->dev->disconnectFromHost(); - + d->dev = nullptr; } } @@ -83,10 +85,8 @@ void CommandInterface::writeData(const QByteArray &payload) if (!payload.size()) return; - TCPSERVER_DEBUG("Sending \'" << WorkerBase::formatForDebug(payload).constData() - << "\' (" << payload.size() << " Bytes) to " - << d->m_connString.constData()) - + TCPSERVER_DEBUG("Sending \'" << WorkerBase::formatForDebug(payload).constData() << "\' (" << payload.size() << " Bytes) to " << d->m_connString.constData()) + qint64 bytesToWrite = payload.size(); qint64 bytesWritten = 0; do @@ -94,17 +94,11 @@ void CommandInterface::writeData(const QByteArray &payload) bytesWritten += d->dev->write(&payload.data()[bytesWritten], bytesToWrite - bytesWritten); if (!d->dev->waitForBytesWritten(d->writeTimeout)) { - TCPSERVER_ERROR("waitForBytesWritten returned false for connection " - << d->m_connString.constData() - << " " - << d->dev->error() - << " " - << d->dev->errorString()) + TCPSERVER_ERROR("waitForBytesWritten returned false for connection " << d->m_connString.constData() << " " << d->dev->error() << " " << d->dev->errorString()) d->bWriteError = true; return; } - } - while (bytesToWrite != bytesWritten); + } while (bytesToWrite != bytesWritten); } void CommandInterface::writeData(const QString &payload) @@ -243,8 +237,7 @@ bool CommandInterface::socketIsOpen() const void CommandInterface::conversionError(const QByteArray &arg, const QByteArray &type) { - writeError(QLatin1String("Can not convert ") + QString::fromUtf8(arg) + - QLatin1String(" to ") + QString::fromUtf8(type)); + writeError(QLatin1String("Can not convert ") + QString::fromUtf8(arg) + QLatin1String(" to ") + QString::fromUtf8(type)); } bool CommandInterface::getValue(const QByteArray &arg, bool &value) diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h index 88bd046bb..394abdeb9 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h @@ -14,94 +14,91 @@ class WorkerBase; class TCPSERVER_EXPORT CommandInterface : public QObject { - Q_OBJECT - public: - explicit CommandInterface(unsigned short port, const QByteArray& command = QByteArray()); + Q_OBJECT +public: + explicit CommandInterface(unsigned short port, const QByteArray &command = QByteArray()); - virtual ~CommandInterface(); + virtual ~CommandInterface(); - void handleCommand(const QVector& args); + void handleCommand(const QVector &args); - virtual void newPlainData(); + virtual void newPlainData(); - virtual QString help() const = 0; + virtual QString help() const = 0; - QByteArray command() const; + QByteArray command() const; - void setAutoWriteEOL(bool newAutoWriteEOL); + void setAutoWriteEOL(bool newAutoWriteEOL); - bool autoWriteEOL() const; + bool autoWriteEOL() const; - bool errorOccured() const; + bool errorOccured() const; - static void setDefaultSuccessMessage(const QString& msg); + static void setDefaultSuccessMessage(const QString &msg); - static void setDefaultErrorMessage(const QString& msg); + static void setDefaultErrorMessage(const QString &msg); - template static CommandInterface* factory(unsigned short port) - { - return new T(port); - } + template static CommandInterface *factory(unsigned short port) { return new T(port); } - virtual void aboutToDestroy() {} + virtual void aboutToDestroy() {} - protected: - virtual void handleCommandInternal(const QVector& args) = 0; +protected: + virtual void handleCommandInternal(const QVector &args) = 0; - void setWriteTimeout(int iMS); + void setWriteTimeout(int iMS); - void writeData(const QByteArray& payload); + void writeData(const QByteArray &payload); - void writeData(const char* payload); + void writeData(const char *payload); - void writeData(const QString& payload); + void writeData(const QString &payload); - void writeData(const QStringList& payload); + void writeData(const QStringList &payload); - void writeData(const QList& payload); + void writeData(const QList &payload); - void writeOk(const QString& additionalMsg = QString()); + void writeOk(const QString &additionalMsg = QString()); - void writeError(const QString& additionalMsg = QString()); + void writeError(const QString &additionalMsg = QString()); - void writeEOL(); + void writeEOL(); - QByteArray quote(const QByteArray& payload); + QByteArray quote(const QByteArray &payload); - QAbstractSocket* socket(); + QAbstractSocket *socket(); - void setSocket(QAbstractSocket* socket); + void setSocket(QAbstractSocket *socket); - WorkerBase* workerBase(); + WorkerBase *workerBase(); - void setWorkerBase(WorkerBase* wb); + void setWorkerBase(WorkerBase *wb); - void conversionError(const QByteArray& arg, const QByteArray& type); + void conversionError(const QByteArray &arg, const QByteArray &type); - bool getValue(const QByteArray& arg, bool& value); + bool getValue(const QByteArray &arg, bool &value); - bool getValue(const QByteArray& arg, long& value); + bool getValue(const QByteArray &arg, long &value); - bool getValue(const QByteArray& arg, unsigned long& value); + bool getValue(const QByteArray &arg, unsigned long &value); - bool getValue(const QByteArray& arg, int& value); + bool getValue(const QByteArray &arg, int &value); - bool getValue(const QByteArray& arg, unsigned int& value); + bool getValue(const QByteArray &arg, unsigned int &value); - bool getValue(const QByteArray& arg, float& value); + bool getValue(const QByteArray &arg, float &value); - bool getValue(const QByteArray& arg, double& value); + bool getValue(const QByteArray &arg, double &value); - unsigned short port() const; + unsigned short port() const; - void closeConnection(); + void closeConnection(); - bool socketIsOpen() const; + bool socketIsOpen() const; - private: - friend class WorkerBase; +private: + friend class WorkerBase; - class Private; + class Private; - Private* const d; + Private *const d; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.cpp old mode 100755 new mode 100644 index 2f1b15a99..2523877c8 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.cpp @@ -21,21 +21,22 @@ NGL::INGLLogger &getTcpServerLogger() return *tcpserver_logger_ptr; } -typedef QHash< unsigned short, TcpServer::CommandInterfaceList > CommandFactory; +typedef QHash CommandFactory; class TcpServer::Private { public: explicit Private(unsigned short port_) - : mUserData(nullptr) - , port(port_) - , bUseThreads(false) - {} + : mUserData(nullptr) + , port(port_) + , bUseThreads(false) + { + } ~Private() { const auto copy(workers); for (WorkerInstance *worker : copy) { - + QThread *workerThread = worker->thread(); if (workerThread != qApp->thread()) { @@ -60,8 +61,8 @@ QHash TcpServer::Private::s_servers; CommandFactory TcpServer::Private::s_cbFactory; TcpServer::TcpServer(unsigned short port) - : QTcpServer() - , d(new Private(port)) + : QTcpServer() + , d(new Private(port)) { TCPSERVER_TRACE2("Port: " << port); } @@ -78,7 +79,7 @@ TcpServer *TcpServer::instance(unsigned short port) if (!Private::s_servers.contains(port)) Private::s_servers.insert(port, new TcpServer(port)); - return Private::s_servers[ port ]; + return Private::s_servers[port]; } bool TcpServer::listen(const QHostAddress &address) @@ -108,7 +109,7 @@ unsigned short TcpServer::getListenPort() const return d->port; } -bool TcpServer::registerCommand(unsigned short port, CommandInterface * (*factory)(unsigned short)) +bool TcpServer::registerCommand(unsigned short port, CommandInterface *(*factory)(unsigned short)) { CommandInterfaceList &factoryList = Private::s_cbFactory[port]; if (factoryList.contains(factory)) @@ -121,7 +122,7 @@ bool TcpServer::registerCommand(unsigned short port, CommandInterface * (*factor return true; } -bool TcpServer::unregisterCommand(unsigned short port, CommandInterface * (*factory)(unsigned short)) +bool TcpServer::unregisterCommand(unsigned short port, CommandInterface *(*factory)(unsigned short)) { CommandInterfaceList &factoryList = Private::s_cbFactory[port]; if (!factoryList.contains(factory)) @@ -141,7 +142,7 @@ TcpServer::CommandInterfaceList TcpServer::registeredCommands(unsigned short por void TcpServer::incomingConnection(qintptr socketDescriptor) { - + WorkerInstance *worker = new WorkerInstance(socketDescriptor, d->port); connect(worker, &WorkerInstance::finished, this, &TcpServer::workerFinished); d->workers += worker; @@ -156,7 +157,7 @@ void TcpServer::incomingConnection(qintptr socketDescriptor) workerThread->start(); - + connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); TCPSERVER_DEBUG("Created new WorkerThread " << worker) } @@ -174,7 +175,7 @@ void TcpServer::workerFinished() { if (!d->workers.removeAll(wi)) TCPSERVER_WARN("Got a signal that a worker exited, but could not find it in our list!") - wi->deleteLater(); + wi->deleteLater(); } else { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h index 9e03c9c76..32d6c6a45 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h @@ -11,54 +11,54 @@ class CommandInterface; class TCPSERVER_EXPORT TcpServer : public QTcpServer { - Q_OBJECT - public: - typedef QVector CommandInterfaceList; + Q_OBJECT +public: + typedef QVector CommandInterfaceList; - public: - virtual ~TcpServer(); +public: + virtual ~TcpServer(); - static TcpServer* instance(unsigned short port); + static TcpServer *instance(unsigned short port); - bool listen(const QHostAddress& address = QHostAddress::Any); + bool listen(const QHostAddress &address = QHostAddress::Any); - void setUseWorkerThreads(bool bEnable); + void setUseWorkerThreads(bool bEnable); - bool useWorkerThreads() const; + bool useWorkerThreads() const; - QVector workers() const; + QVector workers() const; - unsigned short getListenPort() const; + unsigned short getListenPort() const; - static bool registerCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); + static bool registerCommand(unsigned short port, CommandInterface *(*factory)(unsigned short)); - static bool unregisterCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); + static bool unregisterCommand(unsigned short port, CommandInterface *(*factory)(unsigned short)); - static CommandInterfaceList registeredCommands(unsigned short port); + static CommandInterfaceList registeredCommands(unsigned short port); - void setUserData(void* userData); + void setUserData(void *userData); - void* userData() const; + void *userData() const; - Q_SIGNALS: +Q_SIGNALS: - void aboutToQuit(unsigned short port); + void aboutToQuit(unsigned short port); - public Q_SLOTS: +public Q_SLOTS: - void shutdownRequest(); + void shutdownRequest(); - void workerFinished(); + void workerFinished(); - protected: - void incomingConnection(qintptr socketDescriptor); +protected: + void incomingConnection(qintptr socketDescriptor); - private: - class Private; +private: + class Private; - Private* const d; + Private *const d; - explicit TcpServer(unsigned short port); + explicit TcpServer(unsigned short port); - bool listen(const QHostAddress& address, quint16 port); + bool listen(const QHostAddress &address, quint16 port); }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_export.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_export.h old mode 100755 new mode 100644 index b652a0baa..050125b64 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_export.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_export.h @@ -11,17 +11,17 @@ #define TCPSERVER_VERSION (((TCPSERVER_VERSION_MAJ) << 16) | ((TCPSERVER_VERSION_MIN) << 8) | (TCPSERVER_VERSION_REL)) #ifndef TCPSERVER_STATIC -# ifdef BUILD_STATIC_LIBRARIES -# define TCPSERVER_EXPORT -# else -# ifdef MAKE_TCPSERVER_LIB -# define TCPSERVER_EXPORT Q_DECL_EXPORT -# else -# define TCPSERVER_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define TCPSERVER_EXPORT #else -# define TCPSERVER_EXPORT __attribute__((visibility("default"))) +#ifdef MAKE_TCPSERVER_LIB +#define TCPSERVER_EXPORT Q_DECL_EXPORT +#else +#define TCPSERVER_EXPORT Q_DECL_IMPORT +#endif +#endif +#else +#define TCPSERVER_EXPORT __attribute__((visibility("default"))) #endif -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_logger.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_logger.h old mode 100755 new mode 100644 index 3c00d9b21..91e893c6d --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_logger.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver_logger.h @@ -14,14 +14,35 @@ NGL::INGLLogger &getTcpServerLogger(); #ifdef TCPSERVER_ENABLE_TRACE -#define TCPSERVER_TRACE { TRACE_LOG(getTcpServerLogger()) << TCPSERVER_TRACE_FUNCTION; } -#define TCPSERVER_TRACE2(x) { TRACE_LOG(getTcpServerLogger()) << TCPSERVER_TRACE_FUNCTION << x; } +#define TCPSERVER_TRACE \ + { \ + TRACE_LOG(getTcpServerLogger()) << TCPSERVER_TRACE_FUNCTION; \ + } +#define TCPSERVER_TRACE2(x) \ + { \ + TRACE_LOG(getTcpServerLogger()) << TCPSERVER_TRACE_FUNCTION << x; \ + } #else #define TCPSERVER_TRACE #define TCPSERVER_TRACE2(x) #endif -#define TCPSERVER_DEBUG(y) { DEBUG_LOG (getTcpServerLogger()) << y; } -#define TCPSERVER_INFO(y) { INFO_LOG (getTcpServerLogger()) << y; } -#define TCPSERVER_WARN(y) { WARNING_LOG (getTcpServerLogger()) << y; } -#define TCPSERVER_ERROR(y) { ERROR_LOG (getTcpServerLogger()) << y; } -#define TCPSERVER_FATAL(y) { FATAL_LOG (getTcpServerLogger()) << y; } +#define TCPSERVER_DEBUG(y) \ + { \ + DEBUG_LOG(getTcpServerLogger()) << y; \ + } +#define TCPSERVER_INFO(y) \ + { \ + INFO_LOG(getTcpServerLogger()) << y; \ + } +#define TCPSERVER_WARN(y) \ + { \ + WARNING_LOG(getTcpServerLogger()) << y; \ + } +#define TCPSERVER_ERROR(y) \ + { \ + ERROR_LOG(getTcpServerLogger()) << y; \ + } +#define TCPSERVER_FATAL(y) \ + { \ + FATAL_LOG(getTcpServerLogger()) << y; \ + } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.cpp b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.cpp old mode 100755 new mode 100644 index f5cec21f9..ec08e5a09 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.cpp @@ -18,12 +18,13 @@ #include WorkerBase::WorkerBase(qintptr sd, unsigned short port) - : m_socketDescriptor(sd) - , m_connection(nullptr) - , m_port(port) - , m_bRedirectIncomingData(false) - , m_bRedirectDataHandler(nullptr) -{} + : m_socketDescriptor(sd) + , m_connection(nullptr) + , m_port(port) + , m_bRedirectIncomingData(false) + , m_bRedirectDataHandler(nullptr) +{ +} QAbstractSocket *WorkerBase::connection() { @@ -37,7 +38,7 @@ const QAbstractSocket *WorkerBase::connection() const void WorkerBase::newDataInternal() { - + if (m_bRedirectIncomingData) { if (m_bRedirectDataHandler) @@ -47,7 +48,7 @@ void WorkerBase::newDataInternal() if (!m_connection || !m_connection->isOpen()) return; - + while (m_connection && m_connection->canReadLine()) { QByteArray ba(2048, '\0'); @@ -58,38 +59,36 @@ void WorkerBase::newDataInternal() qint64 length = m_connection->readLine(ba.data() + iOffset, ba.size()); if (length < 0) { - TCPSERVER_ERROR("Error reading data from " << m_connString.constData() - << qPrintable(m_connection->errorString())) + TCPSERVER_ERROR("Error reading data from " << m_connString.constData() << qPrintable(m_connection->errorString())) return; } bGotEOL = ba.contains('\n'); if (bGotEOL) { - + ba.resize(iOffset + length); } else { - + iOffset = ba.size(); ba.resize(ba.size() * 2); - + memset(ba.data() + iOffset, 0, ba.size() - iOffset); } - } - while (!bGotEOL); + } while (!bGotEOL); + - while (ba.endsWith('\r') || ba.endsWith('\n')) { - ba.data() [ba.size() - 1] = '\0'; + ba.data()[ba.size() - 1] = '\0'; ba.resize(ba.size() - 1); } int idx = ba.indexOf(' '); if (idx == -1) idx = ba.size(); - + QByteArray command = ba.left(idx); if (command.isEmpty()) { @@ -100,27 +99,19 @@ void WorkerBase::newDataInternal() CommandMap::ConstIterator it = m_registeredCommands.constFind(command.toLower()); if (it == m_registeredCommands.constEnd()) { - TCPSERVER_WARN("Got unknown command " << formatForDebug(command).constData() - << " from connection " - << m_connString.constData()) + TCPSERVER_WARN("Got unknown command " << formatForDebug(command).constData() << " from connection " << m_connString.constData()) m_connection->write("UNKNOWN COMMAND "); m_connection->write(command); m_connection->write("\n"); if (!m_connection->waitForBytesWritten(1000)) { - TCPSERVER_WARN("waitForBytesWritten returned false for connection " - << m_connString.constData() - << " " - << m_connection->error() - << " " - << m_connection->errorString()) + TCPSERVER_WARN("waitForBytesWritten returned false for connection " << m_connString.constData() << " " << m_connection->error() << " " + << m_connection->errorString()) } } else { - TCPSERVER_DEBUG("Got command " << formatForDebug(command).constData() - << " from connection " - << m_connString.constData()) + TCPSERVER_DEBUG("Got command " << formatForDebug(command).constData() << " from connection " << m_connString.constData()) CommandInterface *interface = *it; const QVector args = NGL::parseFromTelnet(ba, idx + 1); @@ -130,7 +121,7 @@ void WorkerBase::newDataInternal() TCPSERVER_ERROR("Write error occured on connection " << m_connString.constData()) } } - + if (m_bRedirectIncomingData && m_connection && m_connection->bytesAvailable()) { if (m_bRedirectDataHandler) @@ -144,7 +135,7 @@ void WorkerBase::redirectDataHandling(bool bDoRedirect, CommandInterface *newDat { m_bRedirectIncomingData = bDoRedirect; m_bRedirectDataHandler = newDataHandler; - + if (!bDoRedirect) newDataInternal(); } @@ -223,12 +214,12 @@ void WorkerBase::cleanupCommands() } - WorkerInstance::WorkerInstance(qintptr sd, unsigned short port, QObject *parent) - : QObject(parent) - , WorkerBase(sd, port) - , m_bFinished(false) -{} + : QObject(parent) + , WorkerBase(sd, port) + , m_bFinished(false) +{ +} WorkerInstance::~WorkerInstance() { @@ -251,16 +242,12 @@ void WorkerInstance::doWork() if (!m_connection->setSocketDescriptor(m_socketDescriptor)) { m_connString = formatForDebug(m_connection); - TCPSERVER_ERROR("Connection to " << m_connString.constData() - << " failed - Aborting (" - << m_connection->error() << ")") + TCPSERVER_ERROR("Connection to " << m_connString.constData() << " failed - Aborting (" << m_connection->error() << ")") return; } m_connString = formatForDebug(m_connection); - TCPSERVER_DEBUG("New incoming connection from " - << m_connString.constData() - << " to " << m_connection->localAddress().toString().toUtf8().constData() - << ":" << m_connection->localPort()); + TCPSERVER_DEBUG("New incoming connection from " << m_connString.constData() << " to " << m_connection->localAddress().toString().toUtf8().constData() << ":" + << m_connection->localPort()); connect(m_connection.data(), &QTcpSocket::readyRead, this, &WorkerInstance::newData); connect(m_connection.data(), &QTcpSocket::disconnected, this, &WorkerInstance::connectionDisconnected); } @@ -277,7 +264,7 @@ void WorkerInstance::connectionDisconnected() m_connection->deleteLater(); m_connection = nullptr; m_bFinished = true; - + QThread *workerThread = QThread::currentThread(); if (workerThread != qApp->thread()) { diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h index 090858f79..5bbb88914 100644 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h @@ -14,74 +14,76 @@ class CommandInterface; class TCPSERVER_EXPORT WorkerBase { - public: - typedef QMap CommandMap; +public: + typedef QMap CommandMap; - public: - WorkerBase(qintptr sd, unsigned short port); +public: + WorkerBase(qintptr sd, unsigned short port); - virtual ~WorkerBase() = default; + virtual ~WorkerBase() = default; - QAbstractSocket* connection(); + QAbstractSocket *connection(); - const QAbstractSocket* connection() const; + const QAbstractSocket *connection() const; - void redirectDataHandling(bool bDoRedirect, CommandInterface* newDataHandler = nullptr); + void redirectDataHandling(bool bDoRedirect, CommandInterface *newDataHandler = nullptr); - static QByteArray formatForDebug(const QByteArray& data); + static QByteArray formatForDebug(const QByteArray &data); - static QByteArray formatForDebug(const QAbstractSocket* dev); + static QByteArray formatForDebug(const QAbstractSocket *dev); - CommandMap getCommands() const; + CommandMap getCommands() const; - protected: - void newDataInternal(); +protected: + void newDataInternal(); - int initCommands(unsigned short port); + int initCommands(unsigned short port); - void cleanupCommands(); + void cleanupCommands(); - qintptr m_socketDescriptor; + qintptr m_socketDescriptor; - QPointer m_connection; + QPointer m_connection; - unsigned short m_port; + unsigned short m_port; - QByteArray m_connString; + QByteArray m_connString; - bool m_bRedirectIncomingData; + bool m_bRedirectIncomingData; - CommandInterface* m_bRedirectDataHandler; + CommandInterface *m_bRedirectDataHandler; - CommandMap m_registeredCommands; + CommandMap m_registeredCommands; }; -class WorkerInstance final : public QObject, public WorkerBase +class WorkerInstance final + : public QObject + , public WorkerBase { - Q_OBJECT - public: - WorkerInstance(qintptr sd, unsigned short port, QObject* parent = nullptr); - virtual ~WorkerInstance(); + Q_OBJECT +public: + WorkerInstance(qintptr sd, unsigned short port, QObject *parent = nullptr); + virtual ~WorkerInstance(); - bool isRunning() const; + bool isRunning() const; - bool isFinished() const; + bool isFinished() const; - public Q_SLOTS: +public Q_SLOTS: - void quit(); + void quit(); - void doWork(); + void doWork(); - protected Q_SLOTS: +protected Q_SLOTS: - void newData(); + void newData(); - void connectionDisconnected(); + void connectionDisconnected(); - Q_SIGNALS: - void finished(); +Q_SIGNALS: + void finished(); - private: - bool m_bFinished; +private: + bool m_bFinished; };