Merge story/create-release-two-delivery-25_11_2026 into story/release-2-cleanup

Import the full AP3/AP4/AP9 Qt6 modules (create-two's 16,890-file
qt6-after tree: LtsSession, LtsWidgets, LtsCoordinate, LtsMultiMonitor,
PluginInterfaces, Lts/DDS, DdsView, LogViewer, SqlBrowser, ngl_codegen,
Krypto, etc.) into the Release 2 branch.

Kept from release-2-cleanup:
- new_docker_build_release2.sh (aqtinstall 'cleanup' build driver)
- Release 2 infra (jenkins-ci-rme/, rpmbuild/, Dockerfile, README.md,
  .clang-format, TetraIF/unit-test/)
- the pruned repo root
This commit is contained in:
berrux-dev committed 2026-11-13 13:00:27 +01:00
commit 40b5a09489
15957 files changed
+3221695 -42560

No files matched your search

@@ -7,4 +7,3 @@
ADD_SUBDIRECTORY(CoPrtCnv)
ADD_SUBDIRECTORY(LogView)
ADD_SUBDIRECTORY(PrtCnv)
ADD_SUBDIRECTORY(unit-test)
@@ -35,6 +35,4 @@ NGL_TARGET_INCLUDE_DIRECTORIES(CoPrtCnv
INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../PrtCnv
${CMAKE_CURRENT_BINARY_DIR}/../PrtCnv
)
@@ -1,10 +1,5 @@
/**
* Thin wrapper around json telegram data
* $Id$
* $HeadURL$
* $Author$
* Created by Christian Ehrlicher, SLSE, 2016-04-22
*/
#include "CoPrtCnvCentralTelegram.hpp"
#include <QtCore/QJsonDocument>
@@ -12,76 +7,76 @@
namespace N_CoPrtCnv
{
void CoPrtCnvCentralTelegram::setData(const QByteArray &data)
{
m_data = data;
m_json = QJsonObject();
}
void CoPrtCnvCentralTelegram::setData(const QByteArray &data)
{
m_data = data;
m_json = QJsonObject();
}
QByteArray CoPrtCnvCentralTelegram::data()
{
ensureByteArray();
return m_data;
}
QByteArray CoPrtCnvCentralTelegram::data()
{
ensureByteArray();
return m_data;
}
QJsonObject CoPrtCnvCentralTelegram::json()
{
ensureJson();
return m_json;
}
QJsonObject CoPrtCnvCentralTelegram::json()
{
ensureJson();
return m_json;
}
QJsonObject CoPrtCnvCentralTelegram::jsonData()
{
return json()[QStringLiteral("data")].toObject();
}
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<TrainingAreaBase::TetraIcd::TelegramId>(m_json[QStringLiteral("typeId")].toInt());
TrainingAreaBase::TetraIcd::TelegramId CoPrtCnvCentralTelegram::telegramId()
{
if (m_telegramId != TrainingAreaBase::TetraIcd::UNKNOWN)
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();
}
ensureJson();
m_telegramId = static_cast<TrainingAreaBase::TetraIcd::TelegramId>(m_json[QStringLiteral("typeId")].toInt());
return m_telegramId;
}
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::setCounter(qint32 counter)
{
if (m_json.isEmpty())
m_json = QJsonDocument::fromJson(m_data).object();
m_json[QStringLiteral("counter")] = counter;
m_data.clear();
}
void CoPrtCnvCentralTelegram::ensureJson()
{
if (m_json.isEmpty())
{
if (m_data.isEmpty())
return;
m_json = QJsonDocument::fromJson(m_data).object();
}
}
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::ensureByteArray()
void CoPrtCnvCentralTelegram::ensureJson()
{
if (m_json.isEmpty())
{
if (m_data.isEmpty())
{
if (m_json.isEmpty())
return;
m_data = QJsonDocument(m_json).toJson(QJsonDocument::Compact);
}
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
}
@@ -1,10 +1,5 @@
/**
* Thin wrapper around json telegram data
* $Id$
* $HeadURL$
* $Author$
* Created by Christian Ehrlicher, SLSE, 2016-04-22
*/
#pragma once
@@ -15,37 +10,30 @@
namespace N_CoPrtCnv
{
/**
* The central-telegram, an subclass of XDR_Wrapper_it used for creation of
* telegrams with telegramId. It also contains the deletion of dynamic allocated
* space within central-telegrams.
*/
class COPRTCNV_EXPORT CoPrtCnvCentralTelegram final
{
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();
@@ -54,8 +42,8 @@ namespace N_CoPrtCnv
void setData(const QByteArray &data);
QByteArray data();
QJsonObject json(); // complete json
QJsonObject jsonData(); // json()["data"]
QJsonObject json();
QJsonObject jsonData();
TrainingAreaBase::TetraIcd::TelegramId telegramId();
void setCounter(qint32 counter);
qint32 counter();
@@ -63,7 +51,6 @@ namespace N_CoPrtCnv
private:
void ensureJson();
void ensureByteArray();
private:
QByteArray m_data;
QJsonObject m_json;
@@ -1,16 +1,16 @@
// **************************************************************************
//
// @RDE_HEADER@
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Helper to dump the data in hex
// **************************************************************************
#include "CoPrtCnvHexDumpHelper.hpp"
#include "CoPrtCnvRadioTelegram.hpp"
@@ -18,16 +18,15 @@
#include <QtCore/QByteArray>
#include <NGLLogger/NGLLoggerBootstrap.h>
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)
{
uint16_t telId = sammelTelegram->getPayloadDataUInt32(ANZAHL_POS + SIZE_POS + 2 * i, 2); // add kennung
unsigned int cnt = sammelTelegram->getPayloadDataUInt32(ANZAHL_POS, SIZE_POS);
for (unsigned int i = 0; i < cnt; ++i) {
uint16_t telId = sammelTelegram->getPayloadDataUInt32(ANZAHL_POS + SIZE_POS + 2 * i, 2);
sstream << telId << " ";
}
return sstream.str();
@@ -38,269 +37,94 @@ 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);
@@ -311,34 +135,33 @@ 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<int>(wirkfeldTyp));
}
@@ -350,63 +173,70 @@ 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;
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// @RDE_HEADER@
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Helper to dump the data in hex
// **************************************************************************
#pragma once
#include <QtCore/QString>
@@ -21,9 +21,12 @@
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);
@@ -1,64 +1,52 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <stdint.h>
namespace N_CoPrtCnv
{
/**
* The header used for injection-data
*
* @author alois.wismer
* @version 1.0
* @created 06-Aug-2010 10:27:55
*/
struct CoPrtCnvInjectionHeader
{
/**
* The m_Id1 and m_Id2 are used to detect rubish data.
*/
uint32_t m_Id1;
/**
* The m_Id1 and m_Id2 are used to detect rubish data.
*/
uint32_t m_Id2;
/**
* 0 => unknown
* 1 => central-telegram
* 2 => radio-telegram
* all others: unknown
*/
enum Destination
{
eUnknown = 0,
eCentral = 1,
eRadio = 2
} m_Kind;
/**
* The size of following data
*/
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); }
};
}
@@ -1,34 +1,28 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <stdint.h>
namespace N_CoPrtCnv
{
/**
* @author alois.wismer
* @version 1.0
* @created 12-Mrz-2010 16:07:19
*/
struct CoPrtCnvLogHeader
{
/**
* @author alois.wismer
* @version 1.0
* @created 12-Mrz-2010 16:04:42
*/
enum E_CoPrtCnvProtocol
{
e_DestProtocolCentral = 0,
@@ -40,24 +34,19 @@ namespace N_CoPrtCnv
e_DestReceive = 0x40000000,
e_DestSend = 0xC0000000
};
/**
* length of data, including length of this header
*/
short m_Length = 0;
short m_Version = 0;
int m_Priority = 0;
/**
* We do not use E_CoPrtCnvProtocol here, because we want a size of 4 bytes
*/
int m_Protocol = 0;
/**
* needed for correct alignment when compiling on 64-bit systems
*/
int m_Reserved = 0;
/**
* Upper 4 bytes => seconds
* Lower 4 byte => microseconds
*/
uint64_t m_Time = 0;
};
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -17,56 +17,41 @@
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
{
/**
* 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);
/**
* 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);
/**
* Set the text codec to use for string send to/received from tetra
*/
COPRTCNV_EXPORT void setTetraTextCodec(const char *codecName);
namespace CoPrtCnvTelegramConverter
{
/**
* 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 CoPrtCnvRadioTelegram *convertToRadio(CoPrtCnvCentralTelegram *a_telegram);
COPRTCNV_EXPORT CoPrtCnvRadioTelegram *convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *a_telegram);
COPRTCNV_EXPORT CoPrtCnvCentralTelegram *convertToCentral(const CoPrtCnvRadioTelegram *a_radioTelegram);
COPRTCNV_EXPORT TrainingAreaBase::TetraIcd::TrainingAreaTelegram *convertToTabTele(const CoPrtCnvRadioTelegram *a_radioTelegram);
COPRTCNV_EXPORT void setTetraTextCodec(const char *codecName);
COPRTCNV_EXPORT void setUse2BytesForSingleFireDiameter(bool bUse);
COPRTCNV_EXPORT void setUsePvSan(bool bUse);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,121 +1,116 @@
/**
* Telegram IDs used in ICD52
* $Id$
* $HeadURL$
* $Author$
* Created by hjl, SLSE, 2016-11-14
*/
#pragma once
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
};
@@ -4,21 +4,11 @@
# $Author$
#
ADD_SUBDIRECTORY(Console)
# Create a separate library for logger functionality that can be linked by other targets
NGL_ADD_LIBRARY(LogViewLogger AAR SV STATIC
logger.cpp
logger.h
)
NGL_TARGET_LINK_LIBRARIES(LogViewLogger
NGLLogger
)
SET_TARGET_PROPERTIES(LogViewLogger PROPERTIES POSITION_INDEPENDENT_CODE ON)
SET(my_SRCS
IntegerCalculator.cpp
IntegerCalculator.hpp
logger.cpp
logger.h
LogViewBooleanEdit.cpp
LogViewBooleanEdit.hpp
LogViewDateTimeEdit.cpp
@@ -89,7 +79,6 @@ if(QT6_GUI_AVAILABLE)
NGLLogger
nglapplication
ngltools
LogViewLogger
)
endif()
NGL_INSTALL_TARGET(LogView)
@@ -17,7 +17,8 @@
#include <TrainingAreaBase/training_area_telegrams.h>
static QSet<int> s_eqIds;
template <typename T> bool validEqId(const T &tele)
template <typename T>
bool validEqId(const T &tele)
{
if (!s_eqIds.isEmpty() && !s_eqIds.contains(tele.header.equipmentNumber))
return false;
@@ -38,28 +39,31 @@ int main(int argc, char **argv)
QCoreApplication app(argc, argv);
// Check alle 30 Sekunden
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx_tetra.props", false);
NGL::INGLLogger &logger(NGL::NGLLoggerBootstrap::getNGLRootLogger());
if (app.arguments().count() < 3)
{
ERROR_LOG(logger) << "Usage: " << app.arguments().at(0) << " <logfile> <telId> <equipId>";
ERROR_LOG(logger) << "Usage: " << app.arguments().at(0)
<< " <logfile> <telId> <equipId>";
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();
@@ -68,102 +72,119 @@ 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;
}
//fprintf(stdout, "Counter;EqID;TelID;TelTime;LogTime;Diff\n");
while (true)
{
// read the header of telegram-entry
N_CoPrtCnv::CoPrtCnvLogHeader lh;
if (sizeof(lh) == telegramFile.read((char *)&lh, sizeof(lh)))
{
if (lh.m_Version == 3)
{
// read the telegram itself
qint64 telegramLength = lh.m_Length - sizeof(lh);
QByteArray telegramData(telegramLength, Qt::Uninitialized);
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:
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 QByteArray tBA = formatTime(lh.m_Time);
const char *timeStr = tBA.constData();
switch (telId)
{
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();
case Constraints<CreateFunctionalArea>::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<DeactivateEffectSimulation>::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<PositionReport>::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();
switch (telId)
static uint16_t bci = 0xFFFF;
if (bci != radioTelegram.getBroadcastIndex())
{
case Constraints<CreateFunctionalArea>::id():
if (bci > radioTelegram.getBroadcastIndex() && bci != 0xFFFF)
{
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 reset in %s at %s!\n",
qPrintable(telegramFile.fileName()),
timeStr);
}
case Constraints<DeactivateEffectSimulation>::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<PositionReport>::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;
fprintf(stdout, "BCI: %d\n", radioTelegram.getBroadcastIndex());
bci = radioTelegram.getBroadcastIndex();
}
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;
break;
}
default:
break;
}
}
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "IntegerCalculator.hpp"
#include <sstream>
@@ -19,492 +19,479 @@
namespace N_SST
{
IntegerCalculator::IntegerCalculator()
: m_OperationList({{"*", 6}, {"/", 6}, {"%", 6}, {"+", 5}, {"-", 5}, {"<<", 4}, {">>", 4}})
, m_AdditionalErrorText()
, m_ParanthesisCount(0)
, m_Error(IntegerCalculator::e_Ok)
IntegerCalculator::IntegerCalculator()
: m_OperationList({{"*", 6},{"/", 6},{"%", 6},{"+", 5},{"-", 5},{"<<", 4},{">>", 4}})
, m_AdditionalErrorText()
, m_ParanthesisCount(0)
, m_Error(IntegerCalculator::e_Ok)
{
}
int64_t IntegerCalculator::calc(const std::string& a_calcText, E_Error& a_error, std::string* a_addErrorText)
{
std::string calcText = a_calcText;
for (auto iter = m_OperationList.begin(); iter != m_OperationList.end(); ++iter)
replace(calcText, iter->first, " "+iter->first+" ");
replace(calcText, "(", " ( ");
replace(calcText, ")", " ) ");
m_ParanthesisCount = 0;
m_Error = e_Ok;
m_AdditionalErrorText = "";
size_t pos = 0;
bool dummy;
int64_t value = calc(calcText, pos, dummy, "", 0, "+");
if (m_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)
{
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)
if (m_ParanthesisCount > 0)
{
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;
}
m_Error = e_MissingRightParanthesis;
}
// actions if a failure happens
a_error = m_Error;
if (a_error != e_Ok)
else if (m_ParanthesisCount < 0)
{
value = 0;
if (a_addErrorText)
{
*a_addErrorText = m_AdditionalErrorText;
}
m_Error = e_MissingLeftParanthesis;
}
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<std::string, int64_t>::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<std::string, int64_t>::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())
else if (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);
m_Error = e_UnknownError;
}
}
// 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;
}
a_error = m_Error;
if (a_error != e_Ok)
{
value = 0;
if (a_addErrorText)
{
*a_addErrorText = m_AdditionalErrorText;
}
}
return value;
}
operation = "";
}
else if (')' == calcText[a_pos])
void IntegerCalculator::addVariable(const std::string& a_name, const int64_t a_value)
{
std::map<std::string, int64_t>::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));
}
void IntegerCalculator::removeVariable(const std::string& a_name)
{
std::map<std::string, int64_t>::iterator iter = m_VariableList.find(a_name);
if (iter != m_VariableList.end())
m_VariableList.erase(iter);
}
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);
size_t tmpPos = a_pos;
std::string nextOp = getToken(a_calcText, tmpPos);
if (isOperation(nextOp) && isOperation(a_prevOp) && !isOperationPriorityHigher(nextOp, a_prevOp))
{
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))
operation = "";
}
else if (')' == calcText[a_pos])
{
m_ParanthesisCount--;
a_pos++;
a_IsEndParanthesis = true;
return value1;
}
else if (isDigit(calcText[a_pos]))
{
int64_t value2 = calcSign(convertValue(calcText, a_pos), isNegative);
if (calcWithPriority(calcText, a_pos, value1, operation, value2, a_prevOp)) return value1;
}
else
{
std::string oldOperation = operation;
operation = getToken(calcText, a_pos);
if (!isOperation(operation))
{
int64_t value2 = 0;
if (getVariableValue(operation, value2))
{
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;
}
value2 = calcSign(value2, isNegative);
if (calcWithPriority(calcText, a_pos, value1, oldOperation, value2, a_prevOp)) return value1;
operation = "";
}
else
{
// do we have a sign?
if (oldOperation != "")
m_Error = e_UnknownOperationOrVariable;
m_AdditionalErrorText = operation;
}
}
else
{
if (oldOperation != "")
{
if (operation == "+")
{
if (operation == "+")
{
operation = oldOperation;
}
else if (operation == "-")
{
isNegative = !isNegative;
operation = oldOperation;
}
else
{
m_Error = e_NoOperandBetweenOperators;
m_AdditionalErrorText = oldOperation + " " + operation;
return 0;
}
operation = oldOperation;
}
else if (operation == "-")
{
isNegative = !isNegative;
operation = oldOperation;
}
else
{
m_Error = e_NoOperandBetweenOperators;
m_AdditionalErrorText = oldOperation + " " + operation;
return 0;
}
}
}
}
return value1;
}
return value1;
}
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;
size_t tmpPos = a_pos;
std::string nextOp = getToken(a_calcText, tmpPos);
if (isOperation(a_operation) && isOperation(nextOp) && isOperationPriorityHigher(nextOp, a_operation))
{
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)))
{
return true;
}
a_operation = "";
return false;
}
int64_t IntegerCalculator::calcSign(const int64_t a_value, bool& a_isNegative)
{
if (a_isNegative)
{
a_isNegative = false;
return -a_value;
}
return a_value;
}
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;
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;
}
size_t i;
for (i=startpos; i<valueText.length(); i++)
{
if (!isDigit(valueText[i], isHex, isBin))
{
break;
}
}
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)
{
const std::string binValueAsText = stream.str();
for (const char c : binValueAsText)
{
value = value << 1;
if (c == '1')
value += 1;
}
}
else
{
stream << std::setbase(base);
stream >> value;
}
return value;
}
std::string IntegerCalculator::getToken(const std::string &a_calcText, size_t& a_pos)
{
while (a_pos < a_calcText.length())
{
if (a_calcText[a_pos] == ' ') a_pos++;
else break;
}
// ---------------------------------------------------------------
// 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)
size_t startPos = a_pos;
while (a_pos < a_calcText.length())
{
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))
{
// 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;
if (' ' == a_calcText[a_pos]) break;
a_pos++;
}
return a_calcText.substr(startPos, a_pos-startPos);
}
// ---------------------------------------------------------------
// 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)
bool IntegerCalculator::isOperation(const std::string& a_operation) const
{
std::map<std::string, int>::const_iterator iter = m_OperationList.find(a_operation);
return (iter != m_OperationList.end());
}
int64_t IntegerCalculator::doOperation(const int64_t a_value1, const std::string& a_operation, const int64_t a_value2)
{
if (("+" == a_operation) || a_operation.empty())
{
if (a_isNegative)
{
a_isNegative = false;
return -a_value;
}
return a_value;
return a_value1 + a_value2;
}
// ---------------------------------------------------------------
// 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)
else if ("-" == a_operation)
{
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)
return a_value1 - a_value2;
}
else if ("*" == a_operation)
{
return a_value1 * a_value2;
}
else if ("/" == a_operation)
{
if (0 == a_value2)
{
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;
}
m_Error = e_DivisionByZero;
}
else
{
stream << std::setbase(base);
stream >> value;
return a_value1 / a_value2;
}
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)
else if ("%" == a_operation)
{
// skip spaces at begin
while (a_pos < a_calcText.length())
if (0 == a_value2)
{
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<std::string, int>::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;
m_Error = e_DivisionByZero;
}
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<std::string, int>::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);
return a_value1 % a_value2;
}
}
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;
}
} // namespace N_SST
bool IntegerCalculator::isOperationPriorityHigher(const std::string& a_operation1, const std::string& a_operation2) const
{
return (getPriority(a_operation1) > getPriority(a_operation2));
}
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;
}
return false;
}
bool IntegerCalculator::isDigit(const char a_char, const bool a_isHex, const bool a_isBin)
{
if (a_isHex)
{
return (a_char >= '0' && a_char <= '9') || (a_char >= 'A' && a_char <= 'F') || (a_char >= 'a' && a_char <= 'f');
}
else if (a_isBin)
{
return (a_char >= '0' && a_char <= '1');
}
return (a_char >= '0' && a_char <= '9');
}
int16_t IntegerCalculator::getPriority(const std::string& a_operation) const
{
std::map<std::string, int>::const_iterator iter = m_OperationList.find(a_operation);
if (iter != m_OperationList.end())
return iter->second;
return -1;
}
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);
}
}
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -18,65 +18,39 @@
namespace N_SST
{
/**
* This class calculates algebraic texts with integer values and returns its
* result as a signed value. It handles the operations - +, -, *, /, %, <<, >>. It
* understands the paranthesis and priorities of operations, like * before -. It
* also computes with variables, which names are case-sensitive. The values can be
* decimal, hexadecimal (0x) or binary (0b). The variable-system implemented
* virtual, so you can implement your own variable system (see getVariableValue()).
*
*
* @author alois.wismer
* @version 1.0
* @created 12-Mai-2010 16:26:43
*/
class IntegerCalculator
{
public:
/**
* Describes the error happend while calculation of an expression
*
* @author alois.wismer
* @version 1.0
* @created 17-Mai-2010 16:38:24
*/
enum E_Error
{
/**
* No error happend
*/
e_Ok,
/**
* The divisor is 0
*/
e_DivisionByZero,
/**
* The operation/variable is not known. a_addErrorText will contain the unknown
* operation/variable.
*/
e_UnknownOperationOrVariable,
/**
* Between to operators no variable/operand exists. a_addErrorText contains the 2
* operations.
*/
e_NoOperandBetweenOperators,
/**
* The operand contains invalid characters. a_addErrorText contains the invalid
* operand.
*/
e_InvalidOperand,
/**
* There are more ) than (
*/
e_MissingLeftParanthesis,
/**
* There are more ) than (
*/
e_MissingRightParanthesis,
/**
* Something else went wrong
*/
e_UnknownError
};
@@ -84,173 +58,86 @@ namespace N_SST
IntegerCalculator();
virtual ~IntegerCalculator() = default;
/**
* 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).
*
* @param a_calcText
* @param a_error
* @param a_addErrorText
*/
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.
*
* @param a_name
* @param a_value
*/
void addVariable(const std::string &a_name, const int64_t a_value);
int64_t calc(const std::string& a_calcText, E_Error& a_error, std::string* a_addErrorText = nullptr);
/**
* Removes a case-sensitive variable from the calculator.
*
* @param a_name
*/
void removeVariable(const std::string &a_name);
void addVariable(const std::string& a_name, const int64_t a_value);
void removeVariable(const std::string& a_name);
protected:
/**
* Contains all supported operations
*/
const std::map<std::string, int> m_OperationList;
/**
* Contains all variables
*/
std::map<std::string, int64_t> m_VariableList;
/**
* The additional text for errors
*/
std::string m_AdditionalErrorText;
/**
* The number of open paranthesis
*/
int32_t m_ParanthesisCount;
E_Error m_Error;
/**
* Calculates the expression (recursive)
*
* @param a_calcText
* @param a_pos
* @param a_IsEndParanthesis
* @param a_prevOp
* @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());
/**
* Calculates an operation with respecting the priority of operations. This will
* be done with recursion.
*
* @param a_calcText
* @param a_pos
* @param a_value1
* @param a_operation
* @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);
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());
/**
* 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.
*
* @param a_value
* @param 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
* (0x) or binary (0b).
*
* @param a_valueText
* @param a_pos
*/
int64_t convertValue(const std::string &a_valueText, size_t &a_pos);
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 next token (with space as separator). Heading spaces will be
* ignored.
*
* @param a_calcText
* @param 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;
static int64_t calcSign(const int64_t a_value, bool& a_isNegative);
/**
* Calculates the opeation a_operations with a_value1 as first and a_value2 as
* second operand.
*
* @param a_value1
* @param a_operation
* @param 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.
*
*
* @param a_operation1
* @param a_operation2
*/
bool isOperationPriorityHigher(const std::string &a_operation1, const std::string &a_operation2) const;
int64_t convertValue(const std::string& a_valueText, size_t& a_pos);
/**
* 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.
*
* @param a_variableName
* @param a_value
*/
virtual bool getVariableValue(const std::string &a_variableName, int64_t &a_value) const;
static std::string getToken(const std::string& a_calcText, size_t& a_pos);
bool isOperation(const std::string& a_operation) const;
int64_t doOperation(const int64_t a_value1, const std::string& a_operation, const int64_t a_value2);
bool isOperationPriorityHigher(const std::string& a_operation1, const std::string& a_operation2) 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
* will be accepted as digits. When a_isBin is true, only 0 and 1 will be treated
* as digit.
*
* @param a_char
* @param a_isHex
* @param a_isBin
*/
static bool isDigit(const char a_char, const bool a_isHex = false, const bool a_isBin = false);
/**
* Returns the priority of the operation. A higher value means more priority.
*
* @param a_operation
*/
int16_t getPriority(const std::string &a_operation) const;
int16_t getPriority(const std::string& a_operation) const;
static void replace(std::string& a_haystack, const std::string& a_searchText, const std::string& a_replaceText);
/**
* replaces in a_haystack all a_searchText with a_replaceText (not greedy).
*
* @param a_haystack
* @param a_searchText
* @param a_replaceText
*/
static void replace(std::string &a_haystack, const std::string &a_searchText, const std::string &a_replaceText);
};
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* Edit boolean values
* $Id$
* $HeadURL$
* $Author$
*/
#include "LogViewBooleanEdit.hpp"
#include "LogViewField.hpp"
@@ -13,29 +8,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)
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)
{
const QString valueText = a_field->value(0);
setChecked(valueText.toInt() == 1);
setEnabled(!a_readonly);
if (a_telegram->isJsonTelegram())
a_telegram->setJsonValue(m_Field->jsonPath(), isChecked());
else
a_telegram->setUIntX(getSize(), isChecked());
return true;
}
return false;
}
// ---------------------------------------------------------------
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;
}
} // namespace N_LogView
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* Edit boolean values
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
@@ -13,14 +8,12 @@
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;
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "LogViewDateTimeEdit.hpp"
#include <time.h>
#include "LogViewField.hpp"
@@ -20,65 +20,67 @@
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)
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)
{
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);
setReadOnly(true);
setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft);
}
// ---------------------------------------------------------------
void LogViewDateTimeEdit::checkAndOvertakeContent()
qint64 unixTime = 0;
if (a_field->hasContent())
{
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());
}
if (a_field->isMSecsField())
unixTime = a_field->value(0, true).toLongLong();
else
{
a_telegram->setNextFieldAsGpsTimeField(); // fixme: muss noch der feldname auf GPS Zeit geprüft werden?
a_telegram->setUIntX(getSize(), dateTime().toMSecsSinceEpoch() / 1000);
}
return true;
unixTime = a_field->value(0, true).toInt() * 1000LL;
}
if (0 == unixTime && !a_readonly)
unixTime = ::time(nullptr) * 1000LL;
setDateTime(QDateTime::fromMSecsSinceEpoch(unixTime));
setDisplayFormat(QLatin1String("dd MMM yyyy hh:mm:ss"));
setCalendarPopup(true);
updateToolTip(QString::number(unixTime));
connect(this, &LogViewDateTimeEdit::editingFinished,
this, &LogViewDateTimeEdit::checkAndOvertakeContent);
}
void LogViewDateTimeEdit::checkAndOvertakeContent()
{
updateToolTip(QString::number(dateTime().toMSecsSinceEpoch() / 1000));
}
bool LogViewDateTimeEdit::saveContent(LogViewTelegram* a_telegram)
{
if (a_telegram->isJsonTelegram())
{
a_telegram->setJsonValue(m_Field->jsonPath(), dateTime().toMSecsSinceEpoch());
}
else
{
a_telegram->setNextFieldAsGpsTimeField();
a_telegram->setUIntX(getSize(), dateTime().toMSecsSinceEpoch() / 1000);
}
return true;
}
}
} // namespace N_LogView
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewWidget.hpp"
@@ -18,37 +18,23 @@
namespace N_LogView
{
/**
* Used for date & time
*
* @author alois.wismer
* @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:
/**
*
* @param a_field
* @param a_parent
* @param a_readonly
*/
LogViewDateTimeEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly);
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
bool saveContent(LogViewTelegram *a_telegram) override;
LogViewDateTimeEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly);
bool saveContent(LogViewTelegram* a_telegram) override;
public slots:
void checkAndOvertakeContent();
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "LogViewEnumEdit.hpp"
#include "LogViewXdrStruct.hpp"
#include "LogViewXdrValue.hpp"
@@ -23,82 +23,83 @@ 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)
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);
setToolTip(a_field->toolTipText());
bool bCurrentIndexSet = false;
int i = 0;
while (LogViewXdrValue* child = (static_cast<const LogViewXdrStruct*>(a_field->xdrElement()))->getChildAsValue(i++))
{
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<const LogViewXdrStruct *>(a_field->xdrElement()))->getChildAsValue(i++))
QString enumText = LogViewField::makeClean(child->getName());
if (!a_readonly || enumText == value)
{
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);
addItem(QStringLiteral("%1 (%2)").arg(enumText).arg(child->getValue()), QVariant::fromValue(child->getValue()));
if (a_readonly)
bCurrentIndexSet = true;
if (!a_readonly || (0 != a_index))
updateToolTip(itemData(currentIndex()).toString());
}
}
if (!bCurrentIndexSet)
if (enumText == value)
{
addItem(value);
setCurrentIndex(findText(value));
setCurrentIndex(a_readonly ? 0 : i - 1);
bCurrentIndexSet = true;
if (!a_readonly || (0 != a_index))
updateToolTip(itemData(currentIndex()).toString());
}
// connect signals
connect(this, QOverload<int>::of(&LogViewEnumEdit::currentIndexChanged), this, &LogViewEnumEdit::checkAndOvertakeContent);
}
// ---------------------------------------------------------------
uint16_t LogViewEnumEdit::getSize() const
if (!bCurrentIndexSet)
{
// todo: check ob wirklich ein struct
const LogViewXdrStruct *xdrStruct = static_cast<const LogViewXdrStruct *>(m_Field->xdrElement());
return xdrStruct->getEnumSize();
addItem(value);
setCurrentIndex(findText(value));
}
connect(this, QOverload<int>::of(&LogViewEnumEdit::currentIndexChanged),
this, &LogViewEnumEdit::checkAndOvertakeContent);
}
// ---------------------------------------------------------------
void LogViewEnumEdit::checkAndOvertakeContent()
uint16_t LogViewEnumEdit::getSize() const
{
const LogViewXdrStruct* xdrStruct = static_cast<const LogViewXdrStruct*>(m_Field->xdrElement());
return xdrStruct->getEnumSize();
}
void LogViewEnumEdit::checkAndOvertakeContent()
{
updateToolTip(itemData(currentIndex()).toString());
}
bool LogViewEnumEdit::saveContent(LogViewTelegram* a_telegram)
{
bool ok;
int value = itemData(currentIndex()).toInt(&ok);
if (ok)
{
updateToolTip(itemData(currentIndex()).toString());
if (a_telegram->isJsonTelegram())
a_telegram->setJsonValue(m_Field->jsonPath(), value);
else
a_telegram->setUIntX(getSize(), value);
return true;
}
return false;
}
// ---------------------------------------------------------------
// 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
}
} // namespace N_LogView
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewWidget.hpp"
@@ -18,41 +18,26 @@
namespace N_LogView
{
/**
* Used for enums
*
* @author alois.wismer
* @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:
/**
*
* @param a_field
* @param a_parent
* @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;
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
bool saveContent(LogViewTelegram *a_telegram) override;
bool saveContent(LogViewTelegram* a_telegram) override;
protected slots:
void checkAndOvertakeContent();
};
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewField.hpp"
#include <utility>
#include <QtCore/QDateTime>
@@ -20,260 +20,257 @@
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(const QString& a_name, const E_FieldKind a_kind, const LogViewXdrElement* a_xdrElement)
: 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),
m_logger(getLogger("LogViewField"))
{
}
LogViewField *LogViewField::clone(int arrayIdx) const
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 *f = new LogViewField(*this);
f->m_Child.clear();
f->m_bDeleteXdr = false;
for (auto *c : m_Child)
auto *clonedChild = c->clone(-1);
if (arrayIdx >= 0)
{
auto *clonedChild = c->clone(-1);
if (arrayIdx >= 0)
QStringList sl = clonedChild->jsonPath();
if (sl.size() > 1 && sl.at(sl.size() - 2).startsWith(QStringLiteral("index: ")))
{
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);
}
sl[sl.size() - 2] = QStringLiteral("index: %1").arg(arrayIdx);
clonedChild->setJsonPath(sl);
}
f->addChild(clonedChild);
}
for (auto &val : f->m_ValueList)
val.clear();
return f;
f->addChild(clonedChild);
}
for (auto &val : f->m_ValueList)
val.clear();
return f;
}
// ---------------------------------------------------------------
void LogViewField::addChild(LogViewField *a_child)
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<unsigned char>(c)));
}
QString LogViewField::value(int arrayIdx, const bool a_doNotMakeSpecialConversions) const
{
if (m_ValueList.size() > arrayIdx)
{
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<unsigned char>(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)
const QString &ret = m_ValueList.at(arrayIdx);
if (!a_doNotMakeSpecialConversions)
{
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;
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 QString();
return ret;
}
return QString();
}
// ---------------------------------------------------------------
int64_t LogViewField::getHighestValue() const
int64_t LogViewField::getHighestValue() const
{
switch (m_XdrElement->getKind())
{
switch (m_XdrElement->getKind())
{
case LogViewXdrElement::e_KindStandardType:
{
int64_t highest = 1;
//const LogViewXdrStandardType* xdrStandardType = static_cast<const LogViewXdrStandardType*>(m_XdrElement);
uint16_t bitSize = 8 * static_cast<const LogViewXdrStandardType *>(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;
case LogViewXdrElement::e_KindStandardType:
{
int64_t highest = 1;
uint16_t bitSize = 8*static_cast<const LogViewXdrStandardType*>(m_XdrElement)->getEditSize();
if ((0 == m_Name.compare(QLatin1String("utm nordwert"), Qt::CaseInsensitive)) ||
(0 == m_Name.compare(QLatin1String("utm ostwert"), Qt::CaseInsensitive)))
bitSize -= 8;
switch (static_cast<const LogViewXdrStandardType *>(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";
switch (static_cast<const LogViewXdrStandardType*>(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 0;
return highest;
}
default:
ERROR_LOG(m_logger) << "Case not implemented";
}
return 0;
}
// ---------------------------------------------------------------
int64_t LogViewField::getLowestValue() const
int64_t LogViewField::getLowestValue() const
{
switch (m_XdrElement->getKind())
{
switch (m_XdrElement->getKind())
{
case LogViewXdrElement::e_KindStandardType:
{
int64_t lowest = 0;
//const LogViewXdrStandardType* xdrStandardType = static_cast<const LogViewXdrStandardType*>(a_field->getXdrElement());
switch (static_cast<const LogViewXdrStandardType *>(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;
case LogViewXdrElement::e_KindStandardType:
{
int64_t lowest = 0;
switch (static_cast<const LogViewXdrStandardType*>(m_XdrElement)->getValueKind()) {
case LogViewXdrStandardType::e_Boolean:
return 0;
case LogViewXdrStandardType::e_Signed:
lowest = getHighestValue() + 1;
lowest = -lowest;
break;
default:
break;
}
return 0;
return lowest;
}
default:
ERROR_LOG(m_logger) << "Case not implemented";
break;
}
return 0;
}
// ---------------------------------------------------------------
void LogViewField::dump(const QString &a_indent) const
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;
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 << "]";
}
QString LogViewField::makeClean(const QString &text)
{
QString a_uncleanText = text;
if (a_uncleanText.endsWith(QLatin1String("_rt")))
a_uncleanText = a_uncleanText.left(a_uncleanText.length() - 3);
a_uncleanText = a_uncleanText.replace(QLatin1Char('_'), QLatin1Char(' '));
int pos = 0;
while (a_uncleanText.length() > 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 << "]";
a_uncleanText[pos] = a_uncleanText[pos].toUpper();
pos = a_uncleanText.indexOf(QLatin1Char(' '), pos + 1);
if (-1 == pos)
break;
pos++;
}
// ---------------------------------------------------------------
// Makes the text <a_uncleanText> 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;
}
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");
}
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;
}
} // namespace N_LogView
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"));
}
void LogViewField::setMaxArraySize(uint16_t newVal, const bool a_isDynamic)
{
m_MaxArraySize = newVal;
m_IsDynamicArray = a_isDynamic;
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QStringList>
@@ -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(); }
@@ -57,15 +57,8 @@ namespace N_LogView
void addValue(const QString &value);
void addValueBinaryHex(const QString &value);
/**
* 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.
*
* @param a_index
* @param a_doNotMakeSpecialConversions
*/
QString value(int arrayIdx, const bool a_doNotMakeSpecialConversions = false) const;
int valueListSize() const { return m_ValueList.size(); }
@@ -81,21 +74,12 @@ namespace N_LogView
int64_t getHighestValue() const;
int64_t getLowestValue() const;
/**
*
* @param a_indent
*/
void dump(const QString &a_indent = QString()) const;
/**
* Makes the text <a_uncleanText> pretty for human readable. It does following:
* - generates umlaute (ä, ö, ü)
* - removes _rt at end
* - replaces _ with space
* - uppercase of every word
*
* @param a_uncleanText
*/
static QString makeClean(const QString &text);
@@ -103,11 +87,10 @@ 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
*/
bool isDateTimeField() const;
bool isMSecsField() const;
@@ -115,9 +98,8 @@ namespace N_LogView
uint16_t maxArraySize() const { return m_MaxArraySize; }
void setMaxArraySize(uint16_t newVal, const bool a_isDynamic);
/**
* True if the array is dynamic.
*/
bool isDynamicArray() const { return m_IsDynamicArray; }
@@ -130,7 +112,6 @@ namespace N_LogView
QStringList jsonPath() const { return m_jsonPath; }
protected:
NGL::INGLLogger &m_logger;
QString m_Name;
QString m_type;
@@ -141,18 +122,18 @@ namespace N_LogView
uint16_t m_Offset;
int m_Size;
uint16_t m_MaxArraySize;
/**
* True if the array is dynamic.
*/
bool m_IsDynamicArray;
bool m_HasContent;
bool m_bDeleteXdr;
QVector<LogViewField *> m_Child;
QVector<LogViewField*> m_Child;
E_FieldKind m_Kind;
const LogViewXdrElement *m_XdrElement;
private:
NGL::INGLLogger &m_logger;
};
}
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -23,7 +23,7 @@
namespace N_LogView
{
class LogViewTelegram;
class LogViewTelegram;
}
class QTableView;
@@ -38,163 +38,151 @@ class QToolBox;
namespace N_LogView
{
class LogViewInjectionThread;
class TelegramEdit;
/**
* @author alois.wismer
* @version 1.0
* @created 03-Feb-2010 16:44:53
*/
class LogViewGui : public QMainWindow
{
Q_OBJECT
public:
explicit LogViewGui(QWidget *a_parent);
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<int> m_CentralTelegramFilterList;
QCheckBox *m_SentCentralTelCheckBox;
QCheckBox *m_ReceivedCentralTelCheckBox;
QCheckBox *m_PosCentralTelCheckBox;
QCheckBox *m_ackCentralTelCheckBox;
// Tetra
QGroupBox *m_TetraSelectionGroup;
std::set<int> 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<int> m_WlsTelegramFilterList;
QCheckBox *m_SentWlsTelCheckBox;
QCheckBox *m_ReceivedWlsTelCheckBox;
QCheckBox *m_PosWlsTelCheckBox;
QCheckBox *m_ackWlsTelCheckBox;
QString m_ActualLogfile;
qint64 m_LogfileSize;
bool m_DoReload;
QToolBox *m_ToolBox;
QTableView *m_ParticipantTableView;
ParticipantModel *m_participantModel;
QSortFilterProxyModel *m_participantProxyModel;
QTableView *m_logTelegramView;
TelegramModel *m_telegramModel;
TelegramProxyModel *m_telegramProxyModel;
QLabel *m_TelegramStatus;
QLabel *m_ParticipantStatus;
QGroupBox *m_ParticipantSelectionGroup;
TelegramEdit *m_EditTelegramController;
QTimer *m_TailTimer;
QSplitter *m_Splitter;
LogViewInjectionThread *m_InjectionThread;
QLabel *m_InjectionStatus;
// ausstg, telcount
QHash<int, int> m_participantListTelCount;
// ausstg, issi
QHash<int, int> m_participantListIssi;
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<LogViewTelegram> &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 closeEvent(QCloseEvent *a_closeEvent) override;
void createCentralSelectionWidget();
void createTetraSelectionWidget();
void createWlsSelectionWidget();
protected slots:
void addTelegramToEdit();
void showHexData();
void exportAsCsv();
void exportAsJson();
void onStartLogReplay();
void onReplayTimerTimeout();
void loadSpecificationFiles();
class LogViewInjectionThread;
class TelegramEdit;
void newTelegramFile();
class LogViewGui : public QMainWindow
{
Q_OBJECT
public:
explicit LogViewGui(QWidget* a_parent);
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;
QGroupBox *m_CentralSelectionGroup;
std::set<int> m_CentralTelegramFilterList;
QCheckBox* m_SentCentralTelCheckBox;
QCheckBox* m_ReceivedCentralTelCheckBox;
QCheckBox* m_PosCentralTelCheckBox;
QCheckBox* m_ackCentralTelCheckBox;
QGroupBox *m_TetraSelectionGroup;
std::set<int> 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;
QGroupBox *m_WlsSelectionGroup;
std::set<int> m_WlsTelegramFilterList;
QCheckBox* m_SentWlsTelCheckBox;
QCheckBox* m_ReceivedWlsTelCheckBox;
QCheckBox* m_PosWlsTelCheckBox;
QCheckBox* m_ackWlsTelCheckBox;
QString m_ActualLogfile;
qint64 m_LogfileSize;
bool m_DoReload;
QToolBox* m_ToolBox;
QTableView *m_ParticipantTableView;
ParticipantModel *m_participantModel;
QSortFilterProxyModel *m_participantProxyModel;
QTableView *m_logTelegramView;
TelegramModel *m_telegramModel;
TelegramProxyModel *m_telegramProxyModel;
QLabel *m_TelegramStatus;
QLabel *m_ParticipantStatus;
QGroupBox *m_ParticipantSelectionGroup;
TelegramEdit *m_EditTelegramController;
QTimer *m_TailTimer;
QSplitter *m_Splitter;
LogViewInjectionThread *m_InjectionThread;
QLabel *m_InjectionStatus;
QHash<int, int> m_participantListTelCount;
QHash<int, int> m_participantListIssi;
QAction *m_reloadAction;
QTimer *m_replayTimer;
int m_currentReplayRow;
NGL::INGLLogger &m_logger;
protected:
void readTelegramsFromLogFile(const QString& a_fileName, const qint64 a_filePos = 0);
void addToParticipantList(const QSharedPointer<LogViewTelegram> &a_telegram);
void syncParticipantList();
QCheckBox* createRadioButton(const QString& a_buttonName, const QString& a_iconName);
void startInjectionThread();
void closeEvent(QCloseEvent* a_closeEvent) override;
void createCentralSelectionWidget();
void createTetraSelectionWidget();
void createWlsSelectionWidget();
protected slots:
void addTelegramToEdit();
void showHexData();
void exportAsCsv();
void exportAsJson();
void onStartLogReplay();
void onReplayTimerTimeout();
void loadSpecificationFiles();
void loadTelegramFile();
void newTelegramFile();
/**
* 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 selectedParticipantChanged();
void loadTelegramFile();
void showTelegramTable();
//SLOT for creating the ContextMenu
void customMenuRequested(const QPoint &pos);
void updateLogfile();
void changeSettings();
void selectedParticipantChanged();
/**
* Toggles whether the logfile must be periodically checked for changes
*/
void reloadOnOff();
void showTelegramTable();
/**
*
* @param a_picName
* @param a_toopTipText
*/
void updateInjectionStatus(const QString &a_picName, const QString &a_toopTipText);
void customMenuRequested(const QPoint &pos);
void onLogTelegramViewDoubleClicked(const QModelIndex &index);
void changeSettings();
private:
NGL::INGLLogger &m_logger;
private slots:
void onSettingsChanged(uint32_t changedFlags);
};
void reloadOnOff();
void updateInjectionStatus(const QString& a_picName, const QString& a_toopTipText);
void onLogTelegramViewDoubleClicked(const QModelIndex &index);
private slots:
void onSettingsChanged(uint32_t changedFlags);
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "LogViewInjectionThread.hpp"
#include "LogViewTelegram.hpp"
@@ -23,118 +23,121 @@
namespace N_LogView
{
LogViewInjectionThread::LogViewInjectionThread()
: m_logger(getLogger("LogViewInjectionThread"))
, m_DoStartConnection(false)
, m_SendingPossible(false)
, m_Socket(nullptr)
, m_Timer(nullptr)
LogViewInjectionThread::LogViewInjectionThread()
: m_DoStartConnection(false)
, m_SendingPossible(false)
, m_Socket(nullptr)
, m_Timer(nullptr)
, m_logger(getLogger("LogViewInjectionThread"))
{
QSettings settings;
settings.beginGroup(LogViewOptionDialog::INJECTION_GROUP);
m_Hostname = settings.value(LogViewOptionDialog::INJECTION_HOSTNAME).toString();
if (m_Hostname.isEmpty())
{
// 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_Hostname = QLatin1String("localhost");
settings.setValue(LogViewOptionDialog::INJECTION_HOSTNAME, m_Hostname);
}
// ---------------------------------------------------------------
void LogViewInjectionThread::run()
m_Port = settings.value(LogViewOptionDialog::INJECTION_PORT).toInt();
if (0 == m_Port || m_Port > 65535)
{
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);
m_Port = 46666;
settings.setValue(LogViewOptionDialog::INJECTION_PORT, m_Port);
}
}
// ---------------------------------------------------------------
bool LogViewInjectionThread::isSendingPossible() const
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()
{
if (!m_Socket)
{
return m_SendingPossible;
m_Socket = new QTcpSocket(this);
connect(m_Socket, &QTcpSocket::connected, this, &LogViewInjectionThread::doConnect);
connect(m_Socket, &QTcpSocket::disconnected, this, &LogViewInjectionThread::doDisconnect);
}
// ---------------------------------------------------------------
void LogViewInjectionThread::tryToConnect()
if (!m_Timer)
{
//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 = 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);
}
// ---------------------------------------------------------------
void LogViewInjectionThread::doConnect()
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)
{
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));
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);
}
// ---------------------------------------------------------------
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);
}
} // namespace N_LogView
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QThread>
@@ -24,15 +24,13 @@ namespace N_LogView
{
class LogViewTelegram;
/**
* @author alois.wismer
* @version 1.0
* @created 05-Aug-2010 16:02:15
*/
class LogViewInjectionThread : public QThread
{
Q_OBJECT
public:
LogViewInjectionThread();
void run();
@@ -41,15 +39,12 @@ namespace N_LogView
bool isSendingPossible() const;
/**
*
* @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;
QString m_Hostname;
@@ -59,6 +54,7 @@ namespace N_LogView
QTimer *m_Timer;
private:
NGL::INGLLogger &m_logger;
protected:
protected slots:
void tryToConnect();
@@ -71,12 +67,10 @@ namespace N_LogView
public:
signals:
/**
*
* @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);
};
}
@@ -1,10 +1,9 @@
#include <nglapplication/nglapplication.h>
#include <QtGui/QScreen>
#include <QtGui/QWindow>
#include <QtCore/QSettings>
#include <QNetworkProxy>
#ifndef WIN32
#include <unistd.h>
#include <unistd.h>
#endif
#include "LogViewGui.hpp"
#include "logger.h"
@@ -21,22 +20,18 @@ 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
{
// fallback
} else {
dir = argv[0];
}
#endif
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));
@@ -53,14 +48,12 @@ 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())
{
logViewGui->windowHandle()->setScreen(screen);
}
Q_UNUSED(screen) // Qt6 removed QDesktopWidget (legacy passed QApplication::desktop()->screen(screenNbr) as the QWidget parent). The window is created parentless; LogViewGui restores its own size/position from QSettings (move(POS)).
N_LogView::LogViewGui* logViewGui = new N_LogView::LogViewGui(nullptr);
logViewGui->show();
int ret = app.exec();
delete logViewGui;
return ret;
}
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* some models for LogViewGui
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
@@ -21,95 +16,94 @@
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<int> &eqIds, const QVector<int> &issis, const QVector<int> &numberOfTelegrams);
void clearParticipants();
bool addUpdateParticipants(const QVector<int> &eqIds,
const QVector<int> &issis,
const QVector<int> &numberOfTelegrams);
protected:
void updateHeatMap() const;
protected:
QVector<QPair<int, int> > m_particpants;
QHash<int, int> m_particpantMap;
mutable QHash<int, QColor> m_participantHeatmap;
};
protected:
void updateHeatMap() const;
class TelegramModel final : public QAbstractTableModel
{
Q_OBJECT
public:
using QAbstractTableModel::QAbstractTableModel;
protected:
// eqId , issi
QVector<QPair<int, int>> m_particpants;
// eqid, count telegrams
QHash<int, int> m_particpantMap;
// eqId, QColor for heatmap
mutable QHash<int, QColor> m_participantHeatmap;
};
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
class TelegramModel final : public QAbstractTableModel
{
Q_OBJECT
public:
using QAbstractTableModel::QAbstractTableModel;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void clearTelegrams();
void appendTelegrams(const QVector<QSharedPointer<LogViewTelegram> > &telegrams);
void appendTelegram(const QSharedPointer<LogViewTelegram> &telegram);
QSharedPointer<LogViewTelegram> telegram(int row) const;
protected:
QVector<QSharedPointer<LogViewTelegram> > m_telegrams;
};
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
class TelegramProxyModel final : public QSortFilterProxyModel
{
Q_OBJECT
public:
using QSortFilterProxyModel::QSortFilterProxyModel;
void clearTelegrams();
void appendTelegrams(const QVector<QSharedPointer<LogViewTelegram>> &telegrams);
void appendTelegram(const QSharedPointer<LogViewTelegram> &telegram);
QSharedPointer<LogViewTelegram> telegram(int row) const;
void setFilterByEquipmentIds(bool bFilterByEquipmentIds);
void setAllowedEquipmentIds(const std::set<int> &allowedEquipmentIds);
protected:
QVector<QSharedPointer<LogViewTelegram>> m_telegrams;
};
void setFilteredCentralTelegramIds(const std::set<int> &filteredCentralTelegramIds);
void setFilteredTetraTelegramIds(const std::set<int> &filteredTetraTelegramIds);
void setFilteredWlsTelegramIds(const std::set<int> &filteredWlsTelegramIds);
class TelegramProxyModel final : public QSortFilterProxyModel
{
Q_OBJECT
public:
using QSortFilterProxyModel::QSortFilterProxyModel;
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 setFilterByEquipmentIds(bool bFilterByEquipmentIds);
void setAllowedEquipmentIds(const std::set<int> &allowedEquipmentIds);
void setFilterTetraLogin(bool bFilter);
void setFilterTetraFragmented(bool bFilter);
void setFilteredCentralTelegramIds(const std::set<int> &filteredCentralTelegramIds);
void setFilteredTetraTelegramIds(const std::set<int> &filteredTetraTelegramIds);
void setFilteredWlsTelegramIds(const std::set<int> &filteredWlsTelegramIds);
QSharedPointer<LogViewTelegram> 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<int> m_allowedEquipmentIds;
std::set<int> m_filteredCentralTelegramIds;
std::set<int> m_filteredTetraTelegramIds;
std::set<int> m_filteredWlsTelegramIds;
bool m_bFilterByEquipmentIds = false;
bool m_bFilterLoginTelegrams = false;
bool m_bFilterFragmentedTelegrams = false;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterCentralTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterTetraTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterWlsTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type> m_filterTetraPDU;
};
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<LogViewTelegram> 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<int> m_allowedEquipmentIds;
std::set<int> m_filteredCentralTelegramIds;
std::set<int> m_filteredTetraTelegramIds;
std::set<int> m_filteredWlsTelegramIds;
bool m_bFilterByEquipmentIds = false;
bool m_bFilterLoginTelegrams = false;
bool m_bFilterFragmentedTelegrams = false;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterCentralTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterTetraTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol> m_filterWlsTelegrams;
std::set<N_CoPrtCnv::CoPrtCnvRadioTelegram::E_PDU_Type> m_filterTetraPDU;
};
} // namespace N_LogView
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewOptionDialog.hpp"
#include <QtCore/QCoreApplication>
@@ -28,153 +28,155 @@
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");
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)
LogViewOptionDialog::LogViewOptionDialog(QWidget* a_parent)
: QDialog(a_parent)
{
QVBoxLayout* layout = new QVBoxLayout(this);
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();
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();
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);
}
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())
{
QVBoxLayout *layout = new QVBoxLayout(this);
// telegram specification files
m_P0Edit->setText(newFilename);
QDir dir;
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.setValue(DIR, dir.filePath(newFilename));
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()
void LogViewOptionDialog::browseP5File()
{
QString newFilename = QFileDialog::getOpenFileName(this, tr("Protokollkonverter - TETRA Spezifikations-Datei"), m_Settings.value(DIR).toString(), SPEC_FILES);
if (!newFilename.isEmpty())
{
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_P5Edit->setText(newFilename);
QDir dir;
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.setValue(DIR, dir.filePath(newFilename));
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
void LogViewOptionDialog::save()
{
uint32_t changedFlags = 0;
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();
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();
}
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -20,64 +20,58 @@ 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:
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;
/**
*
* @param a_parent a_parent
*/
explicit LogViewOptionDialog(QWidget *a_parent);
class LogViewOptionDialog : public QDialog
{
Q_OBJECT
public:
signals:
void settingsChanged(uint32_t changed); // bitfield of SettingsChangedFlag enum
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;
protected slots:
void browseP0File();
void browseP5File();
void save();
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;
explicit LogViewOptionDialog(QWidget* a_parent);
signals:
void settingsChanged(uint32_t changed);
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;
protected slots:
void browseP0File();
void browseP5File();
void save();
};
}
@@ -15,26 +15,4 @@
<file>image/ShowSend.png</file>
<file>image/Wls.png</file>
</qresource>
<qresource prefix="/icons/16x16">
<file alias="configure.png">../../Z/src/nglwidgets/icons/16x16/configure.png</file>
<file alias="dialog-ok-apply.png">../../Z/src/nglwidgets/icons/16x16/dialog-ok-apply.png</file>
<file alias="document-edit.png">../../Z/src/nglwidgets/icons/16x16/document-edit.png</file>
<file alias="document-import.png">../../Z/src/nglwidgets/icons/16x16/document-import.png</file>
<file alias="document-new.png">../../Z/src/nglwidgets/icons/16x16/document-new.png</file>
<file alias="document-open-data.png">../../Z/src/nglwidgets/icons/16x16/document-open-data.png</file>
<file alias="document-save.png">../../Z/src/nglwidgets/icons/16x16/document-save.png</file>
<file alias="edit-copy.png">../../Z/src/nglwidgets/icons/16x16/edit-copy.png</file>
<file alias="edit-delete.png">../../Z/src/nglwidgets/icons/16x16/edit-delete.png</file>
<file alias="edit-paste.png">../../Z/src/nglwidgets/icons/16x16/edit-paste.png</file>
<file alias="edit-redo.png">../../Z/src/nglwidgets/icons/16x16/edit-redo.png</file>
<file alias="go-down.png">../../Z/src/nglwidgets/icons/16x16/go-down.png</file>
<file alias="go-up.png">../../Z/src/nglwidgets/icons/16x16/go-up.png</file>
<file alias="list-add.png">../../Z/src/nglwidgets/icons/16x16/list-add.png</file>
<file alias="list-remove.png">../../Z/src/nglwidgets/icons/16x16/list-remove.png</file>
<file alias="mail-send.png">../../Z/src/nglwidgets/icons/16x16/mail-send.png</file>
<file alias="media-play-normal.png">../../Z/src/nglwidgets/icons/16x16/media-play-normal.png</file>
<file alias="media-playback-start.png">../../Z/src/nglwidgets/icons/16x16/media-playback-start.png</file>
<file alias="media-playback-stop.png">../../Z/src/nglwidgets/icons/16x16/media-playback-stop.png</file>
<file alias="rde_16x16.png">../../Z/src/nglwidgets/icons/16x16/rde_16x16.png</file>
</qresource>
</RCC>
@@ -1,58 +1,59 @@
// **************************************************************************
//
// (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);
// set the actual value
setValue(a_value);
LogViewSpinBox::LogViewSpinBox(LogViewField* a_field, QWidget* a_parent, const int a_value)
: QSpinBox(a_parent)
, LogViewWidget(a_field, this, a_parent, false)
{
uint16_t maxArraySize = a_field->maxArraySize();
setRange(0, maxArraySize);
// set tooltip-text
setToolTip(tr("<nobr>Wertebereich: 0..%1</nobr>").arg(maxArraySize));
setValue(a_value);
// connect
connect(this, &LogViewSpinBox::editingFinished, this, &LogViewSpinBox::finishEditing);
}
setToolTip(tr("<nobr>Wertebereich: 0..%1</nobr>").arg(maxArraySize));
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;
}
} // namespace N_LogView
bool LogViewSpinBox::saveContent(LogViewTelegram* a_telegram)
{
Q_UNUSED(a_telegram);
return false;
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtWidgets/QSpinBox>
@@ -18,44 +18,28 @@
namespace N_LogView
{
/**
* Used for changing size of dyn. arrays.
*
* @author alois.wismer
* @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:
/**
*
* @param a_field
* @param a_parent
* @param a_value
*/
LogViewSpinBox(LogViewField *a_field, QWidget *a_parent, const int a_value);
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
bool saveContent(LogViewTelegram *a_telegram) override;
LogViewSpinBox(LogViewField* a_field, QWidget* a_parent, const int a_value);
bool saveContent(LogViewTelegram* a_telegram) override;
protected slots:
void finishEditing();
signals:
/**
*
* @param a_newValue
*/
void valueEditingFinished(int a_newValue);
};
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewTabWidget.hpp"
#include <QtWidgets/QFrame>
@@ -25,116 +25,115 @@ 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)
LogViewTabWidget::LogViewTabWidget(LogViewField* a_field, LogViewTelegramDialog* a_parent, LogViewSpinBox* a_spinBox)
: QTabWidget(a_parent)
, LogViewWidget(a_field, this, a_parent, false)
, m_TelegramDialog(a_parent)
, m_SpinBox(a_spinBox)
{
setVisible(false);
}
void LogViewTabWidget::changeSize(const int a_newSize)
{
for (int i = count(); i < a_newSize; i++)
addTab(m_Field, true, i);
while (count() > a_newSize)
{
setVisible(false);
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();
// ---------------------------------------------------------------
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();
setVisible(a_newSize > 0);
m_TelegramDialog->makePretty();
}
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());
}
bool LogViewTabWidget::saveContent(LogViewTelegram* a_telegram)
{
if (a_telegram->isJsonTelegram())
return true;
}
// ---------------------------------------------------------------
void LogViewTabWidget::addTab(LogViewField *a_field, const bool a_isEmpty, int arrayIdx)
if (m_SpinBox)
{
if (arrayIdx < 0)
{
WARNING_LOG(m_logger) << "Invalid array index given: " << arrayIdx;
return;
}
if (!isValid())
return false;
a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, count());
}
return true;
}
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)
{
const auto *first = a_field->child(0);
if (first)
{
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);
}
}
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);
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;
}
} // namespace N_LogView
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)
{
const auto *first = a_field->child(0);
if (first)
{
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);
}
}
m_TelegramDialog->showTree(childTree, box);
if (m_SpinBox)
{
int spinValue = m_SpinBox->value();
if (spinValue < count())
m_SpinBox->setValue(count());
}
setVisible(true);
}
}
@@ -1,21 +1,20 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtWidgets/QTabWidget>
#include "LogViewWidget.hpp"
#include "logger.h"
namespace N_LogView
@@ -23,35 +22,28 @@ namespace N_LogView
class LogViewTelegramDialog;
class LogViewSpinBox;
/**
* Used for arrays of structures
*
* @author alois.wismer
* @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);
bool saveContent(LogViewTelegram *a_telegram) override;
void addTab(LogViewField *a_field, const bool a_isEmpty, int arrayIdx);
LogViewTabWidget(LogViewField* a_field, LogViewTelegramDialog* a_parent, LogViewSpinBox* a_spinBox);
bool saveContent(LogViewTelegram* a_telegram) override;
void addTab(LogViewField* a_field, const bool a_isEmpty, int arrayIdx);
public slots:
/**
*
* @param a_newSize
*/
void changeSize(const int a_newSize);
protected:
LogViewTelegramDialog *m_TelegramDialog;
LogViewSpinBox *m_SpinBox;
NGL::INGLLogger &m_logger;
LogViewTelegramDialog* m_TelegramDialog;
LogViewSpinBox* m_SpinBox;
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "LogViewTableWidget.hpp"
#include "LogViewField.hpp"
#include <QtWidgets/QHeaderView>
@@ -24,290 +24,288 @@ 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)
LogViewTableWidget::LogViewTableWidget(LogViewField* a_field, QWidget* a_parent, const bool a_readonly)
: QTableWidget(0, 2, a_parent)
, LogViewWidget(a_field, this, a_parent, a_readonly)
, m_IsFloat(false)
, m_IsEnum(false)
{
switch (m_Field->xdrElement()->getKind())
{
switch (m_Field->xdrElement()->getKind())
{
case LogViewXdrElement::e_KindEnum:
m_IsEnum = true;
break;
default:
m_IsFloat = LogViewXdrStandardType::e_Float == static_cast<const LogViewXdrStandardType *>(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")));
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<const LogViewXdrStandardType*>(a_field->getXdrElement())->getValueKind();
// INFO_LOG(m_logger) << "name=" << static_cast<const LogViewXdrStandardType*>(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);
case LogViewXdrElement::e_KindEnum:
m_IsEnum = true;
break;
default:
m_IsFloat = LogViewXdrStandardType::e_Float == static_cast<const LogViewXdrStandardType*>(m_Field->xdrElement())->getValueKind();
}
if (!m_IsFloat)
setColumnCount(3);
if (m_IsEnum)
setColumnCount(1);
// ---------------------------------------------------------------
void LogViewTableWidget::changeSize(const int a_newSize)
setHorizontalHeaderItem(0, new QTableWidgetItem(m_IsEnum ? tr("Enum") : tr("Dez")));
if (!m_IsEnum)
{
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
setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Hex")));
if (!m_IsFloat)
{
QTableWidgetItem *binField = item(row, 2);
if (binField)
binField->setText(toBin(intValue));
setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Bin")));
}
}
setAlternatingRowColors(true);
// ---------------------------------------------------------------
void LogViewTableWidget::makePretty()
updateToolTip();
int nbrOfRows = a_field->valueListSize();
setRowCount(nbrOfRows);
for (int i = 0; i < nbrOfRows; i++)
changeRow(i, a_field->value(i));
makePretty();
connect(this, &LogViewTableWidget::itemChanged,
this, &LogViewTableWidget::checkAndOvertakeContent);
}
void LogViewTableWidget::changeSize(const int a_newSize)
{
setRowCount(a_newSize);
disconnect(this, &LogViewTableWidget::itemChanged,
this, &LogViewTableWidget::checkAndOvertakeContent);
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)
{
if (m_IsEnum)
{
//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));
QWidget* enumItem = cellWidget(a_rowIndex, 0);
if (!enumItem)
setCellWidget(a_rowIndex, 0, new LogViewEnumEdit(m_Field, this, m_Readonly, a_rowIndex));
}
// ---------------------------------------------------------------
// Writes the content into telegram.
// Returns true if successful.
// ---------------------------------------------------------------
bool LogViewTableWidget::saveContent(LogViewTelegram *a_telegram)
else
{
if (!isValid())
return false;
if (a_telegram->isJsonTelegram())
QFont font;
font.setStyleHint(QFont::TypeWriter);
font.setFamily(QString());
QTableWidgetItem* decItem = item(a_rowIndex, 0);
if (!decItem)
{
if (m_Field->kind() == LogViewField::e_FieldKindPodArray)
decItem = new QTableWidgetItem();
decItem->setText(a_value);
decItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
if (!m_Readonly)
{
QJsonArray arr;
for (int i = 0; i < rowCount(); ++i)
arr += item(i, 0)->text().toInt();
a_telegram->setJsonValue(m_Field->jsonPath(), arr);
decItem->setFlags(decItem->flags() | Qt::ItemIsEditable);
}
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;
decItem->setFont(font);
decItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
setItem(a_rowIndex, 0, decItem);
}
uint16_t arraySize;
if (m_Field->isDynamicArray())
QTableWidgetItem* hexItem = item(a_rowIndex, 1);
if (!hexItem)
{
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
hexItem = new QTableWidgetItem();
hexItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
hexItem->setFont(font);
hexItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
setItem(a_rowIndex, 1, hexItem);
}
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);
}
}
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;
if (m_IsFloat)
floatValue = getFloat(text, (uint64_t&)intValue, ok, true);
else
intValue = getInteger(text, ok);
if (!ok)
{
setFocus();
setCurrentCell(row, 0);
return;
}
QTableWidgetItem* decField = item(row, 0);
if (decField) decField->setText(QString::number(m_IsFloat ? floatValue : intValue));
QTableWidgetItem* hexField = item(row, 1);
if (hexField) hexField->setText(toHex(intValue));
if (!m_IsFloat)
{
QTableWidgetItem* binField = item(row, 2);
if (binField) binField->setText(toBin(intValue));
}
}
void LogViewTableWidget::makePretty()
{
resizeColumnsToContents();
resizeRowsToContents();
}
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
{
// 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)
QString value;
value.reserve(rowCount() * 2);
for (int i = 0; i < rowCount(); ++i)
{
LogViewEnumEdit *enumEdit = dynamic_cast<LogViewEnumEdit *>(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<const LogViewXdrStandardType *>(m_Field->xdrElement());
LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder();
uint64_t hex;
getFloat(text, hex, m_Valid);
a_telegram->setUIntX(size, hex, byteOrder);
}
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;
}
} // namespace N_LogView
uint16_t arraySize;
if (m_Field->isDynamicArray())
{
arraySize = rowCount();
a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize);
}
else
{
arraySize = m_Field->maxArraySize();
}
INFO_LOG(m_logger) << "arraySize=" << arraySize;
for (int i = 0; i < arraySize; i++)
{
if (m_IsEnum)
{
LogViewEnumEdit *enumEdit = dynamic_cast<LogViewEnumEdit*>(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<const LogViewXdrStandardType*>(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;
}
}
@@ -1,59 +1,46 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QTableWidget>
#include "LogViewWidget.hpp"
#include "logger.h"
namespace N_LogView
{
/**
* Used for arrays of data (opaque)
*
* @author alois.wismer
* @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);
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @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;
};
}
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -32,28 +32,14 @@ namespace N_LogView
class LogViewTetraTelegramsParser;
class LogViewXdrParser;
class LogViewXdrType;
/**
* The header and the data of a logged or a edited telegram.
*
* Writing telegrams:
* 1. allocate a telegram with the constructor LogViewTelegram(N_CoPrtCnv::
* CoPrtCnvLogHeader::e_DestProtocolCentral, telegramId)
* 2. prepare with resetOffset()
* 3. write data with setUIntX()
* 4. finish with setNewSize();
*
* @author alois.wismer
* @version 1.0
* @created 04-Feb-2010 13:15:43
*/
class LogViewTelegram final
{
public:
/**
* @author alois.wismer
* @version 1.0
* @created 12-Mrz-2010 11:04:14
*/
enum E_Validity
{
e_NotYetEvaluated,
@@ -61,11 +47,8 @@ namespace N_LogView
e_Invalid
};
/**
* @author alois.wismer
* @version 1.0
* @created 05-Mai-2010 09:07:22
*/
enum E_Column
{
e_ColName,
@@ -78,83 +61,55 @@ namespace N_LogView
~LogViewTelegram();
/**
* The size of the field which defines the size of the dyn. array for central-
* telegrams
*/
static const uint16_t SIZE_CENTRAL_DYN_ARRAY_SIZE;
/**
* Copy ctor
*/
LogViewTelegram(const LogViewTelegram &o);
// no assignment (needed)
LogViewTelegram &operator=(const LogViewTelegram &o) = delete;
/**
* Constructor for new telegrams (only receive central-telegrams are allowd),
* which will be edited
*
* @param a_destination
* @param a_telId
*/
LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination, int telegramId);
/**
* Constructor for existing telegrams
*
* @param a_destination
* @param a_unixTime
* @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,
int telegramId);
/**
* 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.
*
* @param a_size
* @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);
LogViewTelegram(const N_CoPrtCnv::CoPrtCnvLogHeader::E_CoPrtCnvProtocol a_destination,
const quint64 a_unixTime,
const QByteArray &a_telegramData);
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.
* Returns false if a_offset is outside of range and therefore a_data could not be
* written.
*
* @param a_offset
* @param a_data
*/
bool setData(const uint16_t a_offset, const uint8_t a_data);
/**
* Returns the log-time of the telegram
*/
quint64 getLogTime() const { return m_LogTime; }
quint64 getLogTimeMsec() const;
/**
* Returns the log-time of the telegram as pretty formatted text
*/
QString getLogTimeText() const;
QString getDestinationText() const;
/**
* Returns the gps-time of the telegram
*/
quint64 getGpsTime() const { return m_GpsTime; }
/**
* 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 getGpsTimeText() const;
@@ -163,26 +118,19 @@ namespace N_LogView
int getParticipantId() const { return m_ParticipantId; }
/**
* 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 getDelay() const;
/**
* 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.
*
* @param a_col
*/
QString getToolTipText(const E_Column a_col);
void resetOffset();
LogViewField *getFieldTree();
LogViewField* getFieldTree();
void dump() const;
@@ -210,46 +158,34 @@ 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();
QByteArray getData(QJsonDocument::JsonFormat format = QJsonDocument::JsonFormat::Compact) const;
/**
* The time to wait after sending this telegram in milliseconds.
*/
uint32_t getWaitTime() const { return m_WaitTime; }
/**
* The time to wait after sending this telegram in milliseconds.
*
* @param newVal
*/
void setWaitTime(uint32_t newVal) { m_WaitTime = newVal; }
/**
* The name of the telegram, shown in edit-list
*/
QString getName() const { return m_Name; }
/**
* The name of the telegram, shown in edit-list
*
* @param newVal
*/
void setName(const QString &newVal) { m_Name = newVal; }
@@ -261,9 +197,8 @@ namespace N_LogView
void actualizeGpsTime();
/**
* Create the tooltip text for the column 'Name'
*/
void createToolTipTextForColName();
@@ -273,40 +208,32 @@ namespace N_LogView
static uint32_t floatToXdr(float in);
protected:
/**
* The name of the telegram, shown in edit-list
*/
QString m_Name;
/**
* The tooltip text for caching purposes
*/
std::vector<QString> m_ToolTipText;
/**
* The time to wait after sending this telegram in milliseconds.
*/
uint32_t m_WaitTime;
int m_ParticipantId;
/**
* The ISSI of TETRA-Protocol
*/
uint32_t m_ISSI;
/**
* 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<uint16_t> m_GpsFieldOffset;
int m_TelId;
/**
* used for dyn. array in TETRA-Protocol
*/
uint32_t m_LastUnsignedValue;
/**
* This value will be used for the dyn-array-method e_DynArrayMsgLength. This
* value will be subtracted from the message-length to get the size of the dynamic
* array.
*/
uint16_t m_MaxArraySize;
static const uint16_t START_OFFSET_CENTRAL;
static const uint16_t POS_CENTRAL_COUNTER;
@@ -335,14 +262,14 @@ namespace N_LogView
QJsonObject m_json;
N_CoPrtCnv::CoPrtCnvRadioTelegram *m_TetraTelegram;
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,
@@ -374,106 +301,70 @@ namespace N_LogView
static QString typeFromStructInformation(const StructInformation &si, const QString &name);
static MemberInformation memberFromStructInformation(const StructInformation &si, const QString &name);
/**
*
* @param a_offset
*/
uint16_t getUInt16(const uint16_t a_offset) const;
/**
*
* @param a_offset
*/
uint32_t getUInt32(const uint16_t a_offset) const;
/**
*
* @param a_offset
*/
int32_t getInt32(const uint16_t a_offset) const;
/**
*
* @param a_offset
* @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;
/**
*
* @param a_offset
* @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;
quint64 getUIntX(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;
/**
*
* @param a_offset
* @param a_size
*/
char getChar(const uint16_t a_offset, const uint8_t a_size) const;
/**
*
* @param a_standardType
* @param a_offset
* @param 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;
LogViewField* getContent(const LogViewXdrStandardType* a_standardType, uint16_t& a_offset, const uint16_t a_arraySize);
/**
*
* @param a_errorText
* @param a_title
*/
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;
bool isScalar(const LogViewXdrType* a_xdrType) 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); }
/**
*
* @param a_name
* @param a_text
* @param a_value
*/
static QString formatToolTipLine(const QString &a_name, const QString &a_text, const uint32_t a_value);
void showMessageBox(const QString& a_errorText, const QString& a_title = QObject::tr("Invalid telegram")) const;
static QString formatToolTipLine(const QString &a_name, const std::string &a_text, const uint32_t a_value)
uint16_t getDynArraySize(uint16_t& a_offset) const;
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 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)
{
return formatToolTipLine(a_name, QString::fromStdString(a_text), a_value);
}
/**
* returns the data-byte at a_offset. Returns 0 if a_offset is outside of range.
*
* @param a_offset
*/
uint8_t getData(const uint16_t a_offset) const;
private:
NGL::INGLLogger &m_logger;
friend class LogViewTabWidget;
};
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewTelegramDialog.hpp"
#include <utility>
@@ -42,454 +42,458 @@
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
LogViewTelegramDialog::LogViewTelegramDialog(QWidget *a_parent, const bool a_readonly, NGL::INGLLogger &logger)
: QDialog(a_parent)
, m_ReadOnly(a_readonly)
, m_logger(logger)
LogViewTelegramDialog::LogViewTelegramDialog(QWidget *a_parent, const bool a_readonly)
: QDialog(a_parent)
, m_ReadOnly(a_readonly)
, m_logger(getLogger("LogViewTelegramDialog"))
{
setAttribute(Qt::WA_DeleteOnClose);
}
void LogViewTelegramDialog::showDialog(const QSharedPointer<LogViewTelegram> &a_telegram)
{
delete layout();
hide();
m_Telegram = a_telegram;
a_telegram->dump();
m_fieldTree.reset(a_telegram->getFieldTree());
if (m_fieldTree)
{
setAttribute(Qt::WA_DeleteOnClose);
}
// ---------------------------------------------------------------
void LogViewTelegramDialog::showDialog(const QSharedPointer<LogViewTelegram> &a_telegram)
{
delete layout();
hide();
m_Telegram = a_telegram;
a_telegram->dump();
m_fieldTree.reset(a_telegram->getFieldTree());
if (m_fieldTree)
QGridLayout *dialogLayout = new QGridLayout;
if (!m_ReadOnly)
{
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);
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);
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);
}
//INFO_LOG(m_logger) << "--------------- create dialog " << fieldTree->getName().toStdString() << "--------------";
//m_fieldTree->dump();
showTree(m_fieldTree.data(), dialogLayout);
if (this->findChild<LogViewTableWidget *>() == 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();
QFrame *f = new QFrame(this);
f->setFrameShape(QFrame::HLine);
f->setFrameShadow(QFrame::Sunken);
dialogLayout->addWidget(f, dialogLayout->rowCount(), 0, 1, 2);
}
else
showDataDump(a_telegram, true);
}
showTree(m_fieldTree.data(), dialogLayout);
if (this->findChild<LogViewTableWidget *>() == nullptr)
dialogLayout->setRowStretch(dialogLayout->rowCount(), 1);
// ---------------------------------------------------------------
void LogViewTelegramDialog::showDataDump(const QSharedPointer<LogViewTelegram> &a_telegram, bool showErrorMessage)
{
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(new QLabel(tr("Telegramm-Dump")));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
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_contentsWidget = new QWidget;
m_contentsWidget->setLayout(dialogLayout);
// generate the telegram-dump
QString theDump = QLatin1String("<code>");
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'));
m_ScrollArea = new QScrollArea(this);
m_ScrollArea->setWidget(m_contentsWidget);
m_ScrollArea->setWidgetResizable(true);
theDump += QStringLiteral(" %1").arg(static_cast<unsigned char>(data[i]), 2, 16, QLatin1Char('0'));
if (7 == (i % 8))
theDump += QLatin1String("<br>");
}
theDump += QLatin1String("</code>");
mainLayout->addWidget(m_ScrollArea);
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);
showButtons(btnLayout);
mainLayout->addLayout(btnLayout);
setWindowTitle(m_fieldTree->cleanName() + QStringLiteral(" (%1)").arg(a_telegram->getTelId()));
setModal(true);
show();
makePretty();
}
else
showDataDump(a_telegram, true);
}
// ---------------------------------------------------------------
void LogViewTelegramDialog::makePretty()
void LogViewTelegramDialog::showDataDump(const QSharedPointer<LogViewTelegram> &a_telegram, bool showErrorMessage)
{
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(new QLabel(tr("Telegramm-Dump")));
if (showErrorMessage)
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())));
QString theDump = QLatin1String("<code>");
const QByteArray &data = a_telegram->getData();
for (int i = 0; i < data.size(); i++)
{
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();
if (0 == (i % 8))
theDump += QStringLiteral("%1:").arg(i, 4, 16, QLatin1Char('0'));
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 += QStringLiteral(" %1").arg(static_cast<unsigned char>(data[i]), 2, 16, QLatin1Char('0'));
if (7 == (i % 8))
theDump += QLatin1String("<br>");
}
theDump += QLatin1String("</code>");
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::showTree(LogViewField *a_fieldTree, QGridLayout *a_box)
void LogViewTelegramDialog::makePretty()
{
return;
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);
resize(QSize(newWidth, newHeight));
}
void LogViewTelegramDialog::showTree(LogViewField *a_fieldTree, QGridLayout *a_box)
{
int i = 0;
while (LogViewField *child = a_fieldTree->child(i++))
{
int i = 0;
while (LogViewField *child = a_fieldTree->child(i++))
if (!a_fieldTree->hasContent())
child->setHasContent(false);
switch (child->kind())
{
if (!a_fieldTree->hasContent())
child->setHasContent(false);
switch (child->kind())
{
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;
}
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;
}
}
// ---------------------------------------------------------------
void LogViewTelegramDialog::fillTelegram(LogViewTelegram *a_telegram)
{
INFO_LOG(m_logger) << "******************************************";
for (const auto ptr : std::as_const(m_EditInfoList))
case LogViewField::e_FieldKindTab:
showTab(child, a_box);
break;
case LogViewField::e_FieldKindTabChild:
{
if (!ptr->isValid())
{
INFO_LOG(m_logger) << ptr->field()->name() << " is invalid";
return; // abort when a value is not vaild
}
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;
}
// 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<const LogViewXdrStandardType*>(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<const LogViewXdrStandardType *>(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("<br>") && 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<const LogViewXdrStandardType *>(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<QTextEdit*>(valueWidget)->setReadOnly(true);
// // make proper width of widget
// QFontMetrics fm(valueWidget->font());
// // the 0 (at end) are here, because QFontMetrics does not understand the <code> and <b> 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<QWidget *>(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);
}
}
case LogViewField::e_FieldKindEdit:
case LogViewField::e_FieldKindPodArray:
case LogViewField::e_FieldKindPodArrayChild:
showEditField(child, a_box);
break;
}
}
}
// ---------------------------------------------------------------
void LogViewTelegramDialog::showTab(LogViewField *a_logViewField, QGridLayout *a_box)
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;
}
}
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());
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);
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);
connect(btnOk, &QPushButton::clicked, this, &LogViewTelegramDialog::saveTelegram);
a_layout->addWidget(btnOk);
}
}
void LogViewTelegramDialog::showEditField(LogViewField *a_logViewField, QGridLayout *a_box)
{
switch (a_logViewField->valueListSize())
{
case 1:
if (m_ReadOnly || !a_logViewField->isDynamicArray() || (LogViewXdrStandardType::e_Character == static_cast<const LogViewXdrStandardType *>(a_logViewField->xdrElement())->getValueKind()))
{
QLabel *label = new QLabel(a_logViewField->cleanName());
a_box->addWidget(label, a_box->rowCount(), 0);
LogViewWidget *valueWidget = nullptr;
{
if (LogViewXdrElement::e_KindEnum == a_logViewField->xdrElement()->getKind())
{
valueWidget = new LogViewEnumEdit(a_logViewField, this, m_ReadOnly, 0);
}
else
{
if (a_logViewField->isDateTimeField() || a_logViewField->isMSecsField())
{
valueWidget = new LogViewDateTimeEdit(a_logViewField, this, m_ReadOnly);
}
else
{
switch (static_cast<const LogViewXdrStandardType *>(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:
valueWidget = new LogViewTextEdit(a_logViewField, this, m_ReadOnly);
break;
}
}
}
if (valueWidget)
m_EditInfoList.push_back(valueWidget);
}
QWidget *w = dynamic_cast<QWidget *>(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;
}
Q_FALLTHROUGH();
case 0:
if (m_ReadOnly)
{
a_box->addWidget(new QLabel(tr("Keine %1").arg(a_logViewField->cleanName())));
break;
}
Q_FALLTHROUGH();
default:
{
QLabel *label = new QLabel(a_logViewField->cleanName());
a_box->addWidget(label, a_box->rowCount(), 0);
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);
spinBox = new LogViewSpinBox(a_logViewField, this, a_logViewField->valueListSize());
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<LogViewWidget *>(a_tabWidget));
a_box->addWidget(a_tabWidget, a_box->rowCount(), 0, 1, 2);
LogViewTableWidget *tableWidget = new LogViewTableWidget(a_logViewField, this, m_ReadOnly);
m_EditInfoList.push_back(tableWidget);
a_box->addWidget(tableWidget, 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);
connect(spinBox, &LogViewSpinBox::valueEditingFinished,
tableWidget, &LogViewTableWidget::changeSize);
}
}
break;
}
}
// ---------------------------------------------------------------
bool LogViewTelegramDialog::removeItemsFromEditInfoList(const QStringList &jsonPath)
void LogViewTelegramDialog::showTab(LogViewField *a_logViewField, QGridLayout *a_box)
{
LogViewSpinBox *spinBox = nullptr;
if (!m_ReadOnly && a_logViewField->isDynamicArray())
{
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;
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_EditInfoList.push_back(dynamic_cast<LogViewWidget *>(a_tabWidget));
a_box->addWidget(a_tabWidget, a_box->rowCount(), 0, 1, 2);
} // namespace N_LogView
if (spinBox)
{
connect(spinBox, &LogViewSpinBox::valueEditingFinished,
a_tabWidget, &LogViewTabWidget::changeSize);
}
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)
{
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;
}
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -25,54 +25,52 @@ 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"));
void showDialog(const QSharedPointer<LogViewTelegram> &a_telegram);
void showDataDump(const QSharedPointer<LogViewTelegram> &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);
class LogViewTelegramDialog : public QDialog
{
Q_OBJECT
public:
explicit LogViewTelegramDialog(QWidget *a_parent = nullptr, const bool a_readonly = true);
Q_SIGNALS:
void sendTelegram(const QSharedPointer<LogViewTelegram> &telegramToSend);
protected slots:
void saveTelegram();
void showDialog(const QSharedPointer<LogViewTelegram> &a_telegram);
void showDataDump(const QSharedPointer<LogViewTelegram> &a_telegram, bool showErrorMessage);
void makePretty();
void showTree(LogViewField *a_fieldTree, QGridLayout *a_box);
void sendCurrentTelegram();
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);
bool removeItemsFromEditInfoList(const QStringList &jsonPath);
private:
QSharedPointer<LogViewTelegram> m_Telegram;
QVector<LogViewWidget *> m_EditInfoList;
QScopedPointer<LogViewField> 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;
};
Q_SIGNALS:
void sendTelegram(const QSharedPointer<LogViewTelegram> &telegramToSend);
protected slots:
void saveTelegram();
void sendCurrentTelegram();
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);
private:
QSharedPointer<LogViewTelegram> m_Telegram;
QVector<LogViewWidget *> m_EditInfoList;
QScopedPointer<LogViewField> 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;
};
}
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,9 @@
/**
* @RDE_HEADER@
* some models for LogViewGui
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include "LogViewTelegram.hpp"
#include "logger.h"
#include <QtCore/QModelIndex>
class QAction;
@@ -17,110 +11,111 @@ 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<LogViewTelegram> &telegram);
void appendTelegram(const QSharedPointer<LogViewTelegram> &telegram);
void setInjectionThread(LogViewInjectionThread *a_injectionThread);
void setInjectionThread(LogViewInjectionThread* a_injectionThread);
bool isInjectionPossible() const;
bool isInjectionPossible() const;
protected:
QSharedPointer<LogViewTelegram> m_copyTelegram;
protected:
QSharedPointer<LogViewTelegram> m_copyTelegram;
QSharedPointer<LogViewTelegram> currentSelectedTelegram() const;
QSharedPointer<LogViewTelegram> currentSelectedTelegram() const;
QModelIndex currentSelectedIndex() const;
QModelIndex currentSelectedIndex() const;
QSharedPointer<LogViewTelegram> telegramAtRow(int row);
QSharedPointer<LogViewTelegram> 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;
protected Q_SLOTS:
static QString s_DIR();
static QString s_EDIT_TELEGRAM_GROUP();
static QString s_TELEGRAMLIST_FILE_ID();
static QString s_TELEGRAMLIST_FILES();
void addTelegram();
protected Q_SLOTS:
void injectTelegram(bool a_bAsCentralTelegram);
void addTelegram();
void injectTelegram(const QSharedPointer<LogViewTelegram> &a_telegram, bool a_bAsCentralTelegram);
void injectTelegram(bool a_bAsCentralTelegram);
void sendTelegram(const QSharedPointer<LogViewTelegram> &a_telegram);
void injectTelegram(const QSharedPointer<LogViewTelegram> &a_telegram, bool a_bAsCentralTelegram);
void sendCurrentTelegram();
void sendTelegram(const QSharedPointer<LogViewTelegram> &a_telegram);
void tableViewCustomContextMenu(const QPoint &pos);
void sendCurrentTelegram();
void editTelegram();
void tableViewCustomContextMenu(const QPoint &pos);
void showTelegram();
void editTelegram();
void deleteTelegram();
void showTelegram();
void injectCentralTelegram();
void deleteTelegram();
void injectTetraTelegram();
void injectCentralTelegram();
void loopTelegrams();
void injectTetraTelegram();
void loopNextTelegram();
void loopTelegrams();
void sequenceTelegrams();
void loopNextTelegram();
void sequenceNextTelegram();
void sequenceTelegrams();
void copy();
void sequenceNextTelegram();
void paste();
void copy();
void moveUp();
void paste();
void moveDown();
void moveUp();
void saveTelegramList();
void moveDown();
void loadTelegramListAppend();
void saveTelegramList();
void loadTelegramListReplace();
void loadTelegramListAppend();
void editTelegramDialogFinished();
void loadTelegramListReplace();
void onSelectionChanged();
};
void editTelegramDialogFinished();
void onSelectionChanged();
};
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* some models for LogViewGui
* $Id$
* $HeadURL$
* $Author$
*/
#include "LogViewTelegramEditModel.hpp"
#include <algorithm>
@@ -12,155 +7,157 @@
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;
}
int TelegramEditModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : m_telegrams.size();
}
// ---------------------------------------------------------------
QVariant TelegramEditModel::data(const QModelIndex &index, int role) const
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())
{
if (index.isValid() && index.row() < m_telegrams.size())
if (role == Qt::DisplayRole)
{
if (role == Qt::DisplayRole)
const QSharedPointer<LogViewTelegram> telegram = m_telegrams.at(index.row());
switch (index.column())
{
const QSharedPointer<LogViewTelegram> 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<LogViewTelegram> telegram = m_telegrams.at(index.row());
if (telegram->isJsonTelegram())
return telegram->getData(QJsonDocument::JsonFormat::Indented);
case 0:
return telegram->getName();
case 1:
return telegram->getParticipantId();
case 2:
return telegram->getWaitTime();
}
}
return QVariant();
}
// ---------------------------------------------------------------
QVariant TelegramEditModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
else if (role == Qt::ToolTipRole)
{
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<QSharedPointer<LogViewTelegram>> &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<LogViewTelegram> &telegram)
{
beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size());
m_telegrams.push_back(telegram);
telegram->rebuildJsonString();
endInsertRows();
return m_telegrams.size() - 1; // row
}
// ---------------------------------------------------------------
QSharedPointer<LogViewTelegram> TelegramEditModel::telegram(int row) const
{
if (row >= 0 && row < m_telegrams.size())
return m_telegrams.at(row);
return QSharedPointer<LogViewTelegram>();
}
// ---------------------------------------------------------------
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<int> &rows)
{
QList<int> 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();
const QSharedPointer<LogViewTelegram> telegram = m_telegrams.at(index.row());
if (telegram->isJsonTelegram())
return telegram->getData(QJsonDocument::JsonFormat::Indented);
}
}
return QVariant();
}
// ---------------------------------------------------------------
void TelegramEditModel::pasteRows(int row, const QSharedPointer<LogViewTelegram> &tele)
QVariant TelegramEditModel::headerData(int section,
Qt::Orientation orientation,
int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
if (row < 0 || row > m_telegrams.size())
return;
beginInsertRows(QModelIndex(), row, row);
m_telegrams.insert(row, QSharedPointer<LogViewTelegram>(new LogViewTelegram(*tele.data())));
endInsertRows();
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);
}
} // namespace N_LogView
void TelegramEditModel::clearTelegrams()
{
beginResetModel();
m_telegrams.clear();
endResetModel();
}
void TelegramEditModel::appendTelegrams(const QVector<QSharedPointer<LogViewTelegram> > &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<LogViewTelegram> &telegram)
{
beginInsertRows(QModelIndex(), m_telegrams.size(), m_telegrams.size());
m_telegrams.push_back(telegram);
telegram->rebuildJsonString();
endInsertRows();
return m_telegrams.size() - 1;
}
QSharedPointer<LogViewTelegram> TelegramEditModel::telegram(int row) const
{
if (row >= 0 && row < m_telegrams.size())
return m_telegrams.at(row);
return QSharedPointer<LogViewTelegram>();
}
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<int> &rows)
{
QList<int> rowList = rows.values();
std::sort(rowList.begin(), rowList.end());
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<LogViewTelegram> &tele)
{
if (row < 0 || row > m_telegrams.size())
return;
beginInsertRows(QModelIndex(), row, row);
m_telegrams.insert(row, QSharedPointer<LogViewTelegram>(new LogViewTelegram(*tele.data())));
endInsertRows();
}
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* some models for LogViewGui
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
@@ -15,34 +10,35 @@
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<QSharedPointer<LogViewTelegram>> &telegrams);
int appendTelegram(const QSharedPointer<LogViewTelegram> &telegram);
QSharedPointer<LogViewTelegram> telegram(int row) const;
void clearTelegrams();
void appendTelegrams(const QVector<QSharedPointer<LogViewTelegram> > &telegrams);
int appendTelegram(const QSharedPointer<LogViewTelegram> &telegram);
QSharedPointer<LogViewTelegram> 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<int> &rows);
void removeTelegrams(const QSet<int> &rows);
void pasteRows(int row, const QSharedPointer<LogViewTelegram> &tele);
void pasteRows(int row, const QSharedPointer<LogViewTelegram> &tele);
protected:
QVector<QSharedPointer<LogViewTelegram> > m_telegrams;
protected:
QVector<QSharedPointer<LogViewTelegram>> m_telegrams;
};
};
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewTelegramSelectionDialog.hpp"
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
@@ -22,40 +22,41 @@
namespace N_LogView
{
static int s_currentRow = 0;
// ---------------------------------------------------------------
LogViewTelegramSelectionDialog::LogViewTelegramSelectionDialog(QWidget *a_parent)
: QDialog(a_parent)
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)
{
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);
if (it.key() == 0)
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);
// ---------------------------------------------------------------
void LogViewTelegramSelectionDialog::selectTelegram(QListWidgetItem *a_telegramItem)
{
s_currentRow = m_TelegramList->currentRow();
m_SelectedTelegramId = a_telegramItem->data(Qt::UserRole).toInt();
accept();
}
setLayout(layout);
}
} // namespace N_LogView
void LogViewTelegramSelectionDialog::selectTelegram(QListWidgetItem* a_telegramItem)
{
s_currentRow = m_TelegramList->currentRow();
m_SelectedTelegramId = a_telegramItem->data(Qt::UserRole).toInt();
accept();
}
}
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -19,34 +19,28 @@ class QListWidgetItem;
namespace N_LogView
{
/**
* @author alois.wismer
* @version 1.0
* @created 05-Mai-2010 17:24:14
*/
class LogViewTelegramSelectionDialog : public QDialog
{
Q_OBJECT
public:
/**
*
* @param a_parent
*/
explicit LogViewTelegramSelectionDialog(QWidget *a_parent);
explicit LogViewTelegramSelectionDialog(QWidget* a_parent);
int getSelectedTelegramId() const { return m_SelectedTelegramId; }
protected slots:
/**
*
* @param a_telegramItem
*/
void selectTelegram(QListWidgetItem *a_telegramItem);
void selectTelegram(QListWidgetItem* a_telegramItem);
protected:
QListWidget *m_TelegramList;
int m_SelectedTelegramId;
};
};
}
File diff suppressed because it is too large. Load diff
@@ -1,97 +1,90 @@
/**
* Parses training_area_telegrams.h
* $Id$
* $HeadURL$
* $Author$
* Created by Christian Ehrlicher, SLSE, 2016-04-14
*/
#pragma once
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringView>
#include <QtCore/QStringList>
#include <QtCore/QVector>
#include "logger.h"
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;
QVector<MemberInformation> member;
bool isVisible = false;
};
QVector<MemberInformation> 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<EnumValue> values;
};
struct EnumInformation
{
QString ns;
QString type;
QVector<EnumValue> 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<int, QString> 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<QStringView> &lines, int iStartPos);
int parseEnum(const QVector<QStringView> &lines, int iStartPos, const QString &ns, StructInformation *si = nullptr);
int parseConstraint(const QVector<QStringView> &lines, int iStartPos);
void categorizeMember(MemberInformation &mi) const;
QVector<QStringView> tokenize(const QStringView &line) const;
static bool validStructTokens(const QVector<QStringView> &tokens);
private:
EnumInformation m_telegramIdEnum;
QVector<EnumInformation> m_enums;
QHash<QString, StructInformation> m_structs;
QHash<QString, PodInformation> m_pods;
QHash<int, QString> m_visibleTelegrams;
NGL::INGLLogger &m_logger;
};
} // namespace LogView
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<int, QString> 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 QStringList &lines, int iStartPos);
int parseEnum(const QStringList &lines, int iStartPos, const QString &ns, StructInformation *si = nullptr);
int parseConstraint(const QStringList &lines, int iStartPos);
void categorizeMember(MemberInformation &mi) const;
QStringList tokenize(const QString &line) const;
static bool validStructTokens(const QStringList &tokens);
private:
EnumInformation m_telegramIdEnum;
QVector<EnumInformation> m_enums;
QHash<QString, StructInformation> m_structs;
QHash<QString, PodInformation> m_pods;
QHash<int, QString> m_visibleTelegrams;
NGL::INGLLogger &m_logger;
};
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewTextEdit.hpp"
#include "LogViewField.hpp"
#include "LogViewTelegram.hpp"
@@ -18,78 +18,79 @@
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)
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)
{
const QString value = a_field->value(0);
setText(value);
setReadOnly(true);
setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft);
}
if (a_readonly)
{
setReadOnly(true);
setAlignment(a_field->isRightAligned() ? Qt::AlignRight : Qt::AlignLeft);
}
uint16_t maxArraySize = a_field->maxArraySize();
setMaxLength(maxArraySize);
updateToolTip(value);
// 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());
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);
}
connect(this, &LogViewTextEdit::editingFinished,
this, &LogViewTextEdit::checkAndOvertakeContent);
}
// ---------------------------------------------------------------
void LogViewTextEdit::checkAndOvertakeContent()
void LogViewTextEdit::checkAndOvertakeContent()
{
updateToolTip(text());
m_Valid = true;
}
bool LogViewTextEdit::saveContent(LogViewTelegram* a_telegram)
{
if (!isValid())
return false;
if (a_telegram->isJsonTelegram())
{
updateToolTip(text()); // fixme nach jedem zeichen updaten
m_Valid = true;
a_telegram->setJsonValue(m_Field->jsonPath(), text());
}
// ---------------------------------------------------------------
// Writes the content into telegram.
// Returns true if successful.
// ---------------------------------------------------------------
bool LogViewTextEdit::saveContent(LogViewTelegram *a_telegram)
else
{
if (!isValid())
return false;
if (a_telegram->isJsonTelegram())
uint16_t size = getSize();
QString content = text();
uint16_t arraySize;
if (m_Field->isDynamicArray())
{
a_telegram->setJsonValue(m_Field->jsonPath(), text());
arraySize = content.length();
a_telegram->setUIntX(LogViewTelegram::SIZE_CENTRAL_DYN_ARRAY_SIZE, arraySize);
}
else
{
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);
arraySize = m_Field->maxArraySize();
}
return true;
}
} // namespace N_LogView
for (int i = 0; i < arraySize; i++)
a_telegram->setUIntX(size, i < content.length() ? content[i].toLatin1() : 0);
}
return true;
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewWidget.hpp"
@@ -18,37 +18,23 @@
namespace N_LogView
{
/**
* Used for arrays of char and string.
*
* @author alois.wismer
* @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:
/**
*
* @param a_field
* @param a_parent
* @param a_readonly
*/
LogViewTextEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly);
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
bool saveContent(LogViewTelegram *a_telegram) override;
LogViewTextEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly);
bool saveContent(LogViewTelegram* a_telegram) override;
protected slots:
void checkAndOvertakeContent();
};
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewValueEdit.hpp"
#include "LogViewField.hpp"
#include "LogViewTelegram.hpp"
@@ -18,117 +18,118 @@
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<const LogViewXdrStandardType *>(m_Field->xdrElement());
m_IsFloat = (LogViewXdrStandardType::e_Float == stdType->getValueKind());
const QString valueText = a_field->value(0);
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<const LogViewXdrStandardType*>(m_Field->xdrElement());
m_IsFloat = (LogViewXdrStandardType::e_Float == stdType->getValueKind());
setText(valueText);
const QString valueText = a_field->value(0);
// checkAndOvertakeContent();
updateToolTip(valueText);
setText(valueText);
// make proper width of widget
QFontMetrics fm(font());
updateToolTip(valueText);
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);
}
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;
if (m_IsFloat)
floatValue = getFloat(text(), (uint64_t&)intValue, ok);
else
intValue = getInteger(text(), ok);
if (!ok)
{
setFocus();
selectAll();
return;
}
if (m_IsFloat)
setText(QString::number(floatValue));
else
setText(QString::number(intValue));
// ---------------------------------------------------------------
void LogViewValueEdit::checkAndOvertakeContent()
updateToolTip(text());
}
bool LogViewValueEdit::saveContent(LogViewTelegram* a_telegram)
{
if (m_Valid)
{
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)
uint64_t valueAsUint64;
const double value = getFloat(text(), valueAsUint64, ok);
if (ok)
{
// save the float or double-value
uint64_t valueAsUint64;
const double value = getFloat(text(), valueAsUint64, ok);
if (ok)
if (a_telegram->isJsonTelegram())
{
if (a_telegram->isJsonTelegram())
{
a_telegram->setJsonValue(m_Field->jsonPath(), value);
}
else
{
const LogViewXdrStandardType *stdType = static_cast<const LogViewXdrStandardType *>(m_Field->xdrElement());
LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder();
a_telegram->setUIntX(getSize(), valueAsUint64, byteOrder);
}
return true;
a_telegram->setJsonValue(m_Field->jsonPath(), value);
}
}
else
{
// save the integer-value
qint64 intValue = getInteger(text(), ok);
if (ok)
else
{
if (a_telegram->isJsonTelegram())
a_telegram->setJsonValue(m_Field->jsonPath(), intValue);
else
a_telegram->setUIntX(getSize(), intValue);
return true;
const LogViewXdrStandardType *stdType = static_cast<const LogViewXdrStandardType*>(m_Field->xdrElement());
LogViewXdrStandardType::E_ByteOrder byteOrder = stdType->getByteOrder();
a_telegram->setUIntX(getSize(), valueAsUint64, byteOrder);
}
return true;
}
}
else
{
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;
}
return false;
}
} // namespace N_LogView
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewWidget.hpp"
@@ -18,40 +18,27 @@
namespace N_LogView
{
/**
* Used for scalar signed or unsigned values
*
* @author alois.wismer
* @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:
/**
*
* @param a_field
* @param a_parent
* @param a_readonly
*/
LogViewValueEdit(LogViewField *a_field, QWidget *a_parent, const bool a_readonly);
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
bool saveContent(LogViewTelegram *a_telegram) override;
LogViewValueEdit(LogViewField* a_field, QWidget* a_parent, const bool a_readonly);
bool saveContent(LogViewTelegram* a_telegram) override;
protected:
bool m_IsFloat;
protected slots:
void checkAndOvertakeContent();
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "LogViewWidget.hpp"
#include "LogViewField.hpp"
@@ -23,210 +23,208 @@
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<const LogViewXdrStandardType *>(m_Field->xdrElement());
return xdrStandardType->getValueSize();
}
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"))
{
}
// ---------------------------------------------------------------
void LogViewWidget::showMessageBox(const QString &a_errorText) const
{
QMessageBox::warning(m_Parent, QObject::tr("Fehler"), a_errorText);
}
// ---------------------------------------------------------------
void LogViewWidget::updateToolTip(const QString &a_text)
uint16_t LogViewWidget::getSize() const
{
const LogViewXdrStandardType* xdrStandardType = static_cast<const LogViewXdrStandardType*>(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())
{
bool isList = m_Field->valueListSize() > 1 || m_Field->isDynamicArray();
switch (m_Field->xdrElement()->getKind())
case LogViewXdrElement::e_KindStandardType:
switch (static_cast<const LogViewXdrStandardType*>(m_Field->xdrElement())->getValueKind())
{
case LogViewXdrElement::e_KindStandardType:
switch (static_cast<const LogViewXdrStandardType *>(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<br><nobr>Maximal %2 Zeichen erlaubt</nobr>").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
{
if (m_Field->isDateTimeField())
{
case LogViewXdrStandardType::e_Character:
m_Widget->setToolTip(QObject::tr("%1 Zeichen").arg(a_text.length()));
if (!m_Readonly)
m_Widget->setToolTip(QObject::tr("%1<br><nobr>Maximal %2 Zeichen erlaubt</nobr>").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<b>%2</b> %3").arg(m_Widget->toolTip(), toHex(value), toBin(value)));
}
// range
if (!m_Field->isDateTimeField() && !m_Readonly)
{
const QString sep(isList ? QString() : QStringLiteral("<br>"));
m_Widget->setToolTip(
QStringLiteral("%1%2<nobr>Wertebereich: %3..%4</nobr>").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("<nobr>Wertebereich: +/-3.4e+/-38</nobr>"));
else
m_Widget->setToolTip(QStringLiteral("<nobr>Wertebereich: +/-1.7e+/-308</nobr>"));
break;
case LogViewXdrStandardType::e_Boolean:
m_Widget->setToolTip(QStringLiteral("true/false"));
m_Widget->setToolTip(QObject::tr("Unixzeit: %1 ").arg(a_text));
}
else
{
m_Widget->setToolTip(QString());
}
if (!isList)
{
int64_t value = a_text.toLong();
m_Widget->setToolTip(QStringLiteral("%1<b>%2</b> %3").arg(m_Widget->toolTip(), toHex(value), toBin(value)));
}
if (!m_Field->isDateTimeField() && !m_Readonly)
{
const QString sep(isList ? QString() : QStringLiteral("<br>"));
m_Widget->setToolTip(QStringLiteral("%1%2<nobr>Wertebereich: %3..%4</nobr>").arg(m_Widget->toolTip(), sep).arg(m_Field->getLowestValue()).arg(m_Field->getHighestValue()));
}
break;
case LogViewXdrElement::e_KindEnum:
{
uint64_t enumValue = a_text.toLong();
m_Widget->setToolTip(QStringLiteral("<b>%1 %2</b> %3").arg(enumValue).arg(toHex(enumValue), toBin(enumValue)));
break;
}
default:
ERROR_LOG(m_logger) << "Case not implemented";
break;
case LogViewXdrStandardType::e_Float:
if (4 == m_Field->size())
m_Widget->setToolTip(QStringLiteral("<nobr>Wertebereich: +/-3.4e+/-38</nobr>"));
else
m_Widget->setToolTip(QStringLiteral("<nobr>Wertebereich: +/-1.7e+/-308</nobr>"));
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("<b>%1 %2</b> %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)
{
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);
}
if (!a_ok)
showMessageBox(QStringLiteral("Inalid real value: '%1'").arg(a_text));
m_Valid = a_ok;
if (a_reverse)
{
int j = getSize() - 1;
uint64_t* ptr = &a_FloatAsData;
for (int i = 0; i < getSize() / 2; i++)
{
uint8_t data = ((uint8_t*)ptr)[j];
((uint8_t*)&a_FloatAsData)[j] = ((uint8_t*)&a_FloatAsData)[i];
((uint8_t*)&a_FloatAsData)[i] = data;
j--;
}
}
// ---------------------------------------------------------------
double LogViewWidget::getFloat(const QString &a_text, uint64_t &a_FloatAsData, bool &a_ok, const bool a_reverse)
if (4 == getSize())
{
// 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++)
{
uint8_t data = ((uint8_t *)ptr)[j];
((uint8_t *)&a_FloatAsData)[j] = ((uint8_t *)&a_FloatAsData)[i];
((uint8_t *)&a_FloatAsData)[i] = data;
j--;
}
}
// 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;
((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)
int64_t LogViewWidget::getInteger(const QString& a_text, bool& a_ok)
{
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)
{
// 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)
if (a_text != m_LastErrorValueText)
{
// todo: show exact error-message
showMessageBox(QString::fromUtf8("Die Berechnung '%1' ist falsch").arg(a_text));
m_LastErrorValueText = a_text;
}
a_ok = false;
}
else
{
int64_t highest = m_Field->getHighestValue();
if (value > highest)
{
a_ok = false;
if (a_text != m_LastErrorValueText)
{
showMessageBox(QString::fromUtf8("Die Berechnung '%1' ist falsch").arg(a_text));
showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu hoch. Maximalwert: %2").arg(a_text).arg(highest));
m_LastErrorValueText = a_text;
}
a_ok = false;
return value;
}
else
int64_t lowest = m_Field->getLowestValue();
if (value < lowest)
{
// check the range
int64_t highest = m_Field->getHighestValue();
if (value > highest)
a_ok = false;
if (a_text != m_LastErrorValueText)
{
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
showMessageBox(QString::fromUtf8("Der Wert '%1' ist zu tief. Minimalwert: %2").arg(a_text).arg(lowest));
m_LastErrorValueText = a_text;
}
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;
m_Valid = true;
}
return value;
}
} // namespace N_LogView
}
@@ -1,100 +1,83 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtWidgets/QWidget>
#include "logger.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
class QWidget;
class QFont;
namespace N_LogView
{
template <typename T> inline QString toHex(T num)
{
return QStringLiteral("0x%1").arg(num, 2, 16, QLatin1Char('0'));
}
template <typename T> inline QString toBin(T num)
{
return QStringLiteral("0b%1").arg(num, 8, 2, QLatin1Char('0'));
}
template <typename T>
inline QString toHex(T num)
{
return QStringLiteral("0x%1").arg(num, 2, 16, QLatin1Char('0'));
}
template <typename T>
inline QString toBin(T num)
{
return QStringLiteral("0b%1").arg(num, 8, 2, QLatin1Char('0'));
}
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;
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; }
/**
* Writes the content into telegram.
* Returns true if successful.
*
* @param a_telegram
*/
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);
/**
* 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.
*
* @param a_text
* @param a_ok
*/
int64_t getInteger(const QString &a_text, bool &a_ok);
class LogViewField;
class LogViewTelegram;
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;
LogViewField *m_Field;
class LogViewWidget
{
public:
LogViewWidget(LogViewField* a_field, QWidget* a_widget, QWidget* a_parent, bool a_readonly);
virtual ~LogViewWidget() = default;
QWidget *m_Parent;
virtual uint16_t getSize() const;
LogViewField* field() const { return m_Field; }
bool isValid() const { return m_Valid; }
LOGGER_T m_logger;
};
QString getText() const { return m_Text; }
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);
int64_t getInteger(const QString& a_text, bool& a_ok);
protected:
bool m_Readonly;
bool m_Valid;
QString m_Text;
QString m_LastErrorValueText;
QWidget *m_Widget;
LogViewField *m_Field;
QWidget *m_Parent;
NGL::INGLLogger &m_logger;
};
}
@@ -1,61 +1,61 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewXdrElement.hpp"
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))
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())
{
if (a_name.indexOf(QLatin1Char('<')) >= 0 || a_name.indexOf(QLatin1Char('[')) >= 0)
ERROR_LOG(m_logger) << "Element \'" << a_name.toStdString() << "\' has a problem";
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());
}
// ---------------------------------------------------------------
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());
}
} // namespace N_LogView
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QString>
@@ -18,19 +18,14 @@
namespace N_LogView
{
/**
* @author alois.wismer
* @version 1.0
* @created 05-Feb-2010 11:24:56
*/
class LogViewXdrElement
{
public:
/**
* @author alois.wismer
* @version 1.0
* @created 10-Feb-2010 11:34:47
*/
enum E_ElementKind
{
e_KindStandardType,
@@ -45,16 +40,12 @@ namespace N_LogView
virtual ~LogViewXdrElement() = default;
protected:
/**
* Constructor of a struct or enum
*
* @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;
@@ -62,8 +53,9 @@ namespace N_LogView
protected:
QString m_Name;
E_ElementKind m_Kind;
LOGGER_T m_logger;
QString getKindName() const;
NGL::INGLLogger &m_logger;
};
}
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QString>
@@ -19,7 +19,6 @@
#include "IntegerCalculator.hpp"
#include "logger.h"
#include "LogViewXdrStandardType.hpp"
#include "NGLLoggerBootstrap.h"
namespace N_LogView
{
@@ -29,21 +28,14 @@ namespace N_LogView
class LogViewXdrValue;
class LogViewXdrType;
/**
* @author alois.wismer
* @version 1.0
* @created 05-Feb-2010 10:46:58
*/
class LogViewXdrParser : public N_SST::IntegerCalculator
{
public:
/**
* Defines in which structure the parser is parsing now
*
* @author alois.wismer
* @version 1.0
* @created 08-Feb-2010 17:44:52
*/
enum E_ParseState
{
e_ParseMain,
@@ -57,46 +49,28 @@ namespace N_LogView
~LogViewXdrParser();
/**
*
* @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.
* The telegram will be defined with a_telegramId.
* The name will be delivered as return-parameter.
* If the telegram was not found, error-texts instead names will be returned.
*
* @param a_telegramId
*/
QString getTelegramName(int a_telegramId) const;
/**
* This function delivers the structure name of the telegram.
* The telegram will be defined with a_telegramId.
* The structure name will be delivered as return-parameter
* If the telegram was not found, error-texts instead names will be returned.
*
* @param a_telegramId
*/
QString getStructName(int a_telegramId) const;
/**
*
* @param a_name
* @param a_value
*/
bool getDefine(const QString &a_name, int64_t &a_value) const;
/**
*
* @param a_name
*/
const LogViewXdrElement *getElement(const QString &a_name) const;
bool getDefine(const QString& a_name, int64_t& a_value) const;
const LogViewXdrElement* getElement(const QString& a_name) const;
protected:
QString m_MessageBoxTitle;
bool m_WithinComment;
QString m_Line;
@@ -105,12 +79,10 @@ namespace N_LogView
bool m_DoReadUntilSemicolon;
QStringList m_WordList;
int m_WordListIndex;
/**
* This will be used to suppress an error-message when parsing the overall
* telegram structure.
*/
QString m_UnionType;
std::map<QString, LogViewXdrElement *> m_ElementMap;
std::map<QString, LogViewXdrElement*> m_ElementMap;
LogViewXdrStruct *m_ActElement;
@@ -120,150 +92,89 @@ namespace N_LogView
std::map<int, LogViewXdrType> m_TelegramMap;
/**
*
* @param a_name
* @param a_dataSize
* @param a_realSize
* @param a_kind
* @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,
const LogViewXdrStandardType::E_DynArraySizeMethod a_dynArraySizeMethod = LogViewXdrStandardType::e_DynArrayMsgLength,
const LogViewXdrStandardType::E_ByteOrder a_byteOrder = LogViewXdrStandardType::e_ByteOrderBigEndian);
/**
*
* @param a_line
*/
QString removeComments(const QString &a_line);
QString removeComments(const QString& a_line);
/**
*
* @param a_line
*/
void parseTypedef(const QString &a_line);
/**
*
* @param a_line
*/
void parseDefine(const QString &a_line);
/**
*
* @param a_line
* @param a_enumSize The size in bytes of an enum-value
*/
void parseEnum(const QString &a_line, const uint16_t a_enumSize = 4);
/**
*
* @param a_line
*/
void parseStruct(const QString &a_line);
/**
*
* @param a_line
*/
void parseUnion(const QString &a_line);
/**
*
* @param a_line
* @param a_name
* @param a_value
*/
bool parseEnumLine(const QString &a_line, QString &a_name, QString &a_value) const;
void parseUnion(const QString& a_line);
/**
* Shows an error-message containing the line-nbr, the line itself and an
* additional error-text
*
* @param a_errorText
*/
void showErrorMessage(const QString &a_errorText) const;
/**
*
* @param a_calcText
* @param a_isOk
*/
int64_t calcValue(const QString &a_calcText, bool &a_isOk);
bool parseEnumLine(const QString& a_line, QString& a_name, QString& a_value) const;
/**
*
* @param a_variableName
* @param a_value
*/
bool getVariableValue(const std::string &a_variableName, int64_t &a_value) const override;
/**
*
* @param a_name
* @param a_dynArrayMsgOffset This offset will be used for the dyn-array-method
* e_DynArrayMsgLength. Here the value in <x> 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;
void showErrorMessage(const QString& a_errorText) const;
int64_t calcValue(const QString& a_calcText, bool& a_isOk);
bool getVariableValue(const std::string& a_variableName, int64_t& a_value) const override;
uint16_t parseArray(QString& a_name, uint16_t& a_dynArrayMsgOffset) const;
/**
*
* @param a_word
* @param a_doIncrement
*/
bool isNextWord(const char *a_word, const bool a_doIncrement = true);
/**
*
* @param a_line
*/
void fillWordList(const QString &a_line);
void fillWordList(const QString& a_line);
/**
*
* @param a_errorText
*/
QString getNextWord(const char *a_errorText = nullptr);
/**
*
* @param a_ok
*/
QString getNextType(bool &a_ok);
/**
*
* @param a_enumStruct
*/
QString getNextEnum(const LogViewXdrStruct *&a_enumStruct);
QString getNextType(bool& a_ok);
/**
*
* @param a_fieldText
* @param a_firstBit
* @param a_lastBit
*/
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.
*
* If it exists, an error-message will be raised instead and false will be
* returned.
*
* @param a_name
* @param a_element
*/
bool addToElementMap(const QString &a_name, LogViewXdrElement *a_element);
QString getNextEnum(const LogViewXdrStruct*& a_enumStruct);
bool parseBitfield(const QString& a_fieldText, int16_t& a_firstBit, int16_t& a_lastBit) const;
bool addToElementMap(const QString& a_name, LogViewXdrElement* a_element);
private:
LOGGER_T m_logger;
NGL::INGLLogger &m_logger;
};
}
@@ -1,83 +1,84 @@
// **************************************************************************
//
// (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)
{
}
// ---------------------------------------------------------------
uint16_t LogViewXdrStandardType::getValueSize() const
{
return m_ValueSize;
}
// ---------------------------------------------------------------
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();
}
// ---------------------------------------------------------------
LogViewXdrStandardType::E_DynArraySizeMethod LogViewXdrStandardType::getDynArraySizeMethod() const
{
return m_DynArraySizeMethod;
}
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)
{}
// ---------------------------------------------------------------
LogViewXdrStandardType::E_ByteOrder LogViewXdrStandardType::getByteOrder() const
{
return m_ByteOrder;
}
uint16_t LogViewXdrStandardType::getValueSize() const
{
return m_ValueSize;
}
// ---------------------------------------------------------------
// The 'real' size of the value, which will be allowd when
// editing this value
// ---------------------------------------------------------------
uint16_t LogViewXdrStandardType::getEditSize() const
{
return m_EditSize;
}
LogViewXdrStandardType::E_ValueKind LogViewXdrStandardType::getValueKind() const
{
return m_ValueKind;
}
} // namespace N_LogView
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_ByteOrder LogViewXdrStandardType::getByteOrder() const
{
return m_ByteOrder;
}
uint16_t LogViewXdrStandardType::getEditSize() const
{
return m_EditSize;
}
}
@@ -1,106 +1,77 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewXdrElement.hpp"
namespace N_LogView
{
/**
* This class represents the standardtypes like int, char, ...
* It holds the the size of this type and its representation to user
* (signed/unsigned value or character)
*
* @author alois.wismer
* @version 1.0
* @created 16-Feb-2010 14:22:20
*/
class LogViewXdrStandardType final : public LogViewXdrElement
{
public:
/**
* @author alois.wismer
* @version 1.0
* @created 16-Feb-2010 14:34:38
*/
enum E_ValueKind
{
/**
* An unsigned 32-bit integer
*/
e_Unsigned,
/**
* An signed 32-bit integer
*/
e_Signed,
/**
* A floating-point number
*/
e_Float,
/**
* A character or string
*/
e_Character,
/**
* A boolean value
*/
e_Boolean,
/**
* Hex-Data "0000: F7 A5 07 ..."
*/
e_Data
};
/**
* @author alois.wismer
* @version 1.0
* @created 31-Mrz-2010 10:27:31
*/
enum E_ByteOrder
{
e_ByteOrderBigEndian,
e_ByteOrderLittleEndian
};
/**
* @author alois.wismer
* @version 1.0
* @created 29-Mrz-2010 13:58:44
*/
enum E_DynArraySizeMethod
{
/**
* Size of dyn array depends on message-size (size - m_DynArrayOffset) (or no dyn
* array)
* The value within <> in struct-element will be used for m_DynArrayOffset.
*/
e_DynArrayMsgLength,
/**
* Size of dyn array is defined by a field (StandardType must be Unsigned)
*/
e_DynArrayIndex,
/**
* Size of dyn array is defined by a field, which will be divided by 8 (used for
* bitfields) (StandardType must be Unsigned)
*/
e_DynArrayIndexDiv8
};
/**
* (a_valueKind must be Unsigned, if a_dynArraySizeMethod is e_DynArray...)
*
*/
LogViewXdrStandardType(const QString &a_name,
const int a_valueSize,
const int a_editSize,
@@ -123,25 +94,24 @@ namespace N_LogView
LogViewXdrStandardType::E_ByteOrder getByteOrder() const;
/**
* The 'real' size of the value, which will be allowd when editing this value
*/
uint16_t getEditSize() const;
protected:
/**
* The size of this value as stored data. It may be bigger as the real (edit) size.
*/
int m_ValueSize;
/**
* The 'real' size of the value, which will be allowd when editing this value
*/
int m_EditSize;
E_ValueKind m_ValueKind;
E_ByteOrder m_ByteOrder;
E_DynArraySizeMethod m_DynArraySizeMethod;
};
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#include "LogViewXdrStruct.hpp"
#include "LogViewXdrValue.hpp"
#include "LogViewXdrType.hpp"
@@ -18,94 +18,88 @@
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(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<LogViewXdrType*>(getChild(a_childIndex));
}
LogViewXdrValue* LogViewXdrStruct::getChildAsValue(const uint32_t a_childIndex) const
{
return static_cast<LogViewXdrValue*>(getChild(a_childIndex));
}
void LogViewXdrStruct::dump() const
{
INFO_LOG(m_logger) << "Element[" << getName().toStdString() << "]: kind=" << getKindName().toStdString() << " enumSize=" << getEnumSize();
INFO_LOG(m_logger) << "-------------- childs start -----------------";
std::vector<LogViewXdrElement*>::const_iterator iter = m_ChildList.begin();
while (iter != m_ChildList.end())
{
(*iter)->dump();
++iter;
}
INFO_LOG(m_logger) << "-------------- childs end -----------------";
}
LogViewXdrStruct::~LogViewXdrStruct()
uint32_t LogViewXdrStruct::getChildValue(const QString& a_name, bool* a_error) const
{
if (a_error)
*a_error = false;
std::vector<LogViewXdrElement*>::const_iterator iter = m_ChildList.begin();
while (iter != m_ChildList.end())
{
for (auto ptr : m_ChildList)
delete ptr;
if ((*iter)->getName() == a_name)
return static_cast<const LogViewXdrValue*>(*iter)->getValue();
++iter;
}
if (a_error)
*a_error = true;
return 0;
}
}
// ---------------------------------------------------------------
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<LogViewXdrType *>(getChild(a_childIndex)); // fixme: check ob es wirklich ein XdrType ist
}
// ---------------------------------------------------------------
LogViewXdrValue *LogViewXdrStruct::getChildAsValue(const uint32_t a_childIndex) const
{
return static_cast<LogViewXdrValue *>(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<LogViewXdrElement *>::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<LogViewXdrElement *>::const_iterator iter = m_ChildList.begin();
while (iter != m_ChildList.end())
{
if ((*iter)->getName() == a_name)
return static_cast<const LogViewXdrValue *>(*iter)->getValue();
++iter;
}
if (a_error)
*a_error = true;
return 0;
}
} // namespace N_LogView
@@ -1,23 +1,23 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QString>
#include "LogViewXdrElement.hpp"
#include <vector>
// forward declarations from stereotyped includes
namespace N_LogView
{
class LogViewXdrValue;
@@ -29,42 +29,32 @@ namespace N_LogView
namespace N_LogView
{
/**
* This class represents elements which have childs.
* This are enum and struct.
* @author alois.wismer
* @version 1.0
* @created 31-Mrz-2010 11:59:19
*/
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<LogViewXdrElement *> m_ChildList;
std::vector<LogViewXdrElement*> m_ChildList;
};
}
@@ -1,104 +1,106 @@
// **************************************************************************
//
// (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)
: 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;
}
uint16_t LogViewXdrType::getArraySize() const
{
return m_ArraySize;
}
bool LogViewXdrType::maskValue(uint32_t& a_value, const uint16_t a_size, QString& a_tooltip) const
{
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;
a_value = (a_value >> bitshift) & mask;
a_tooltip.insert(a_tooltip.length()-(a_size*8)+m_FirstBit, QLatin1String("<b>"));
a_tooltip.insert(a_tooltip.length()-(a_size*8)+m_LastBit+1, QLatin1String("</b>"));
return m_IsLast;
}
return 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)
{
}
uint16_t LogViewXdrType::getMaxArraySize() const
{
return m_MaxArraySize;
}
// ---------------------------------------------------------------
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("<b>"));
a_tooltip.insert(a_tooltip.length() - (a_size * 8) + m_LastBit + 1, QLatin1String("</b>"));
return m_IsLast;
}
return true;
}
// ---------------------------------------------------------------
uint16_t LogViewXdrType::getMaxArraySize() const
{
return m_MaxArraySize;
}
} // namespace N_LogView
}
@@ -1,115 +1,72 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewXdrElement.hpp"
namespace N_LogView
{
/**
* This class represents XDR-elements which have a type and an arraySize. This are
* typedefs and struct-elements.
* The arraySize has following possibilities:
* 0 => opaque
* 1 => scalar
* >1 => array
*
* @author alois.wismer
* @version 1.0
* @created 16-Feb-2010 15:48:24
*/
class LogViewXdrType final : public LogViewXdrElement
{
public:
/**
*
* @param a_name
* @param a_type
* @param a_arraySize
* @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);
/**
*
* @param a_name
* @param a_type
* @param a_arraySize
* @param a_dynArrayOffset
* @param a_kind
* @param a_firstBit
* @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);
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
* 1 => normal (scalar) element
* >1 => array
*/
uint16_t getArraySize() const;
/**
*
* @param a_value
* @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
* 1 => normal (scalar) element
* >1 => array
*/
uint16_t m_ArraySize;
/**
* The maximum size of the array. Interesting for dynamic arrays.
*/
uint16_t m_MaxArraySize;
/**
* The first relevant bit, if we have bitfield-enum
*/
int16_t m_FirstBit;
/**
* The last relevant bit, if we have bitfield-enum
*/
int16_t m_LastBit;
/**
* used to step to next values when reading out content-data of bit-fields
*/
bool m_IsLast;
};
}
@@ -1,41 +1,40 @@
// **************************************************************************
//
// (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;
}
} // namespace N_LogView
int64_t LogViewXdrValue::getValue() const
{
return m_Value;
}
}
@@ -1,39 +1,34 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "LogViewXdrElement.hpp"
namespace N_LogView
{
/**
* This class represents XDR-elements which have a value. This are #defines and
* enum-elements.
*
* @author alois.wismer
* @version 1.0
* @created 17-Feb-2010 11:17:53
*/
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;
};
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* Building Config - logging facility
* $Id$
* $HeadURL$
* $Author$
*/
#include "logger.h"
@@ -13,24 +8,25 @@
namespace N_LogView
{
LOGGER_T getLogger(const char *name)
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
{
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);
}
catch (const std::exception &ex)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
}
return NGL::NGLLoggerBootstrap::getNGLRootLogger().
getNGLLogger(loggerName);
}
catch (const std::exception &ex)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
}
}
} // namespace LogView
}
@@ -1,10 +1,5 @@
/**
* @RDE_HEADER@
* Logging for AudioVideoManagement
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
@@ -12,11 +7,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());
}
} // namespace LogView
LOGGER_T getLogger(const char *name);
inline LOGGER_T getLogger(const QString &loggerName)
{
return getLogger(loggerName.toUtf8().constData());
}
}
@@ -0,0 +1 @@
zsksxd_tetraForLogView.x
@@ -0,0 +1 @@
zsksxd_tetraForLogView_guez.x
File diff suppressed because it is too large. Load diff
@@ -1,87 +1,88 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
//
// Implementation of the Class AppComponent
// **************************************************************************
#include "AppComponent.hpp"
namespace N_AppComponent
{
int32_t AppComponent::create(NGL::Settings *settings)
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)
{
for (IAppComponent *c : m_Childs)
c->create(settings);
return 0;
a_child->setName(a_name);
m_Childs.push_back(a_child);
}
}
int32_t AppComponent::destroy()
IAppComponent *AppComponent::getChild(const QString &a_name)
{
for (IAppComponent *c : m_Childs)
{
for (IAppComponent *c : m_Childs)
c->destroy();
return 0;
if (a_name == c->getName())
return c;
}
return nullptr;
}
}
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;
}
} // namespace N_AppComponent
@@ -1,14 +1,14 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
//
// Implementation of the Class AppComponent
// **************************************************************************
#pragma once
@@ -16,32 +16,30 @@
#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<IAppComponent *> m_Childs;
};
protected:
void addChild(IAppComponent* a_child, const QString& a_name = QString());
IAppComponent* getChild(const QString& a_name);
private:
std::vector<IAppComponent*> m_Childs;
};
}
@@ -5,6 +5,10 @@
#
#ADD_SUBDIRECTORY(TetraTestServer)
ADD_SUBDIRECTORY(LastTest)
ADD_SUBDIRECTORY(LastTestAuswertung)
SET(PrtCnv_SRCS
logger.h
logger.cpp
@@ -59,7 +63,6 @@ NGL_TARGET_LINK_LIBRARIES(PrtCnvLib
)
NGL_TARGET_INCLUDE_DIRECTORIES(PrtCnvLib
PUBLIC
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../
)
@@ -1,21 +1,20 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
//
// Implementation of the Class IAppComponent
// **************************************************************************
#pragma once
#include <QtCore/QString>
namespace NGL
{
namespace NGL {
class Settings;
}
@@ -45,9 +44,14 @@ 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;
};
@@ -15,6 +15,7 @@ NGL_TARGET_LINK_LIBRARIES(PrtCnvLastTest
Qt6::Core
Qt6::Network
CoPrtCnv
PrtCnvLib
NGLLogger
ngltools
)
@@ -13,7 +13,7 @@ int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
// Check alle 30 Sekunden
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx_tetra.props", false);
NGL::INGLLogger &logger(NGL::NGLLoggerBootstrap::getNGLRootLogger());
@@ -41,7 +41,9 @@ 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();
@@ -1,9 +1,5 @@
/**
* Tetra-Interface für Lasttest
* $Id$
* $HeadURL$
* $Author$
*/
#include "tetra_if.h"
#include <utility>
@@ -34,11 +30,10 @@ TetraIF::TetraIF(const QHostAddress &addr, unsigned short port, unsigned short i
, m_secondFragment(0)
, 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);
@@ -53,7 +48,7 @@ void TetraIF::start()
void TetraIF::listenMode(const QStringList &args)
{
// take input and write them to and output directory
if (args.count() > 1)
usage();
m_outputDir = QCoreApplication::applicationDirPath();
@@ -61,7 +56,8 @@ 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,8 +96,10 @@ 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();
}
@@ -134,14 +132,19 @@ 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();
}
@@ -174,7 +177,7 @@ void TetraIF::onReadyRead()
do
{
DEBUG_LOG(m_logger) << "Got " << m_socket->bytesAvailable() << " bytes from socket";
// read the 4-byte frame-header for find out the length of whole telegram
N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader header;
if (m_socket->bytesAvailable() < int(sizeof(header)))
return;
@@ -182,12 +185,16 @@ void TetraIF::onReadyRead()
m_socket->peek(reinterpret_cast<char *>(&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);
@@ -200,12 +207,17 @@ 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);
}
@@ -222,28 +234,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;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp:
handleRegisterRsp(data.at(5));
break;
// payload telegram
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data);
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data);
break;
// ack-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq:
// handleReportIndReq(data);
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq:
break;
// air-interface-load-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq:
// handleAirInterfaceLoadReq(data);
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq:
break;
default:
return;
default:
return;
}
INFO_LOG(m_logger) << "PDU Type: " << type;
dumpData(data);
@@ -254,29 +266,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<QHostAddress> 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<QHostAddress> 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;
@@ -285,7 +297,7 @@ void TetraIF::handleRegisterRsp(const uint8_t a_registrationStatus)
void TetraIF::dumpData(const QByteArray &data)
{
// im Listen-Mode -> Ausgabe in Directory
if (m_outputDir.isEmpty())
return;
const qint64 msecs = QDateTime::currentMSecsSinceEpoch();
@@ -294,7 +306,10 @@ 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();
@@ -302,14 +317,22 @@ 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);
f.close();
}
@@ -318,7 +341,7 @@ void TetraIF::dumpData(const QByteArray &data)
void TetraIF::onSendData()
{
++m_secondFragment;
// we're called every 10ms
if (m_secondFragment == 100)
{
m_secondFragment = 0;
@@ -335,7 +358,7 @@ void TetraIF::onSendData()
{
for (unsigned short dest_issi : std::as_const(m_issiList))
{
// GEF_BESTAETIGUNG -> Dummy, gets overridden by setPayloadDataComplete()
m_data[0] = s_randomChar++;
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(GEF_BESTAETIGUNG, m_data.size(), dest_issi);
tele.setPayloadDataComplete(m_data);
@@ -360,7 +383,7 @@ void TetraIF::onSendData()
void TetraIF::parseISSIs(const QStringList &issiList)
{
m_issiList.clear();
// broadcast
if (issiList.count() == 0)
{
m_issiList += 0;
@@ -396,18 +419,18 @@ 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
delete radioTelegram;
}
}
@@ -415,7 +438,7 @@ void TetraIF::handleLoginTelegram(N_CoPrtCnv::CoPrtCnvRadioTelegram *a_loginTele
{
uint16_t identity = a_loginTelegram->getIdentity();
uint32_t issi = a_loginTelegram->getSrcISSI();
// is it a login request?
if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginRequest == (a_loginTelegram->getPayloadDataUInt8(2) & N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LoginStatusMask))
{
bool sent = sendLoginResponse(issi);
@@ -425,6 +448,7 @@ 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)
@@ -432,33 +456,33 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI)
++m_SendCounter;
N_CoPrtCnv::CoPrtCnvRadioTelegram *a_telegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTAETIGUNG, 20, a_ISSI);
a_telegram->setZaehler(m_SendCounter);
// set our ISSI
a_telegram->setDestISSI(a_ISSI);
a_telegram->setSrcISSI(2);
gef_telegramm_id_et telId = a_telegram->isNormalTelegram() ? a_telegram->getTelID() : GEF_BESTAETIGUNG;
// send telegram to radio
INFO_LOG(m_logger) << "Send telegram to radio: telId=" << telId << " wcounter=" << a_telegram->zaehler() << " size= 28";
// Protokoll-Byte wird hier mit als Datenbyte missbraucht...
a_telegram->setProtocolIdentifier(N_CoPrtCnv::CoPrtCnvRadioTelegram::e_TDSMessageWithoutSDS_TL);
a_telegram->setPayloadData(0x01);
a_telegram->setPayloadData(0x04);
// Bitanzahl anpassen
a_telegram->getData()[22] = 0x0d; // Warum 13 (bzw. 21) ??
a_telegram->getData()[22] = 0x0d;
char *data = a_telegram->getData();
// Header - complete Payload in Bytes
data[02] = 0x18; // 24 Bytes
// Len in Bits
data[02] = 0x18;
data[22] = 0x0d;
data[23] = 0x00;
// Len in Bytes
data[24] = 0x02;
data[25] = 0x00;
// Data
data[13] = 0x00;
data[26] = 0x01;
data[27] = 0x40;
@@ -466,6 +490,7 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI)
m_socket->write(data, 28);
delete a_telegram;
return m_socket->flush();
}
void TetraIF::setupTimer()
@@ -1,9 +1,5 @@
/**
* Tetra-Interface für Lasttest
* $Id$
* $HeadURL$
* $Author$
*/
#pragma once
#include <QtCore/QObject>
#include <QtNetwork/QHostAddress>
@@ -32,9 +28,8 @@ 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);
@@ -10,9 +10,10 @@
#include <QtCore/QTimer>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
init();
@@ -21,10 +22,10 @@ MainWindow::MainWindow(QWidget *parent)
MainWindow::~MainWindow()
{
m_files.clear();
//m_logfile.~QString();
//delete m_logfileList;
// m_logZeiten.~QString();
//delete ui;
}
void MainWindow::changeEvent(QEvent *e)
@@ -32,20 +33,20 @@ 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;
}
}
void MainWindow::init()
{
//Connect Signals & Slots
connect(ui->pushButtonOrdnerFinden, &QPushButton::clicked, this, &MainWindow::slot_findFolder);
connect(ui->pushButtonAnalysieren, &QPushButton::clicked, this, &MainWindow::slot_analysieren);
//m_logfileList = new QList<LogfileInfo>();
ui->progressBar->setValue(0);
ui->labelResult->setText(QString());
QIntValidator intVal;
@@ -56,19 +57,13 @@ void MainWindow::init()
void MainWindow::slot_findFolder()
{
//hier liegt der fehler???, der erst beim zweiten mal ausführen des Dateibrowsers in erscheinung tritt
/*QFileDialog dial(this);
dial.setFileMode(QFileDialog::Directory);
dial.setViewMode(QFileDialog::List);
QStringList files;
if (dial.exec())
files = dial.selectedFiles();
QString name = files.at(0);
//testblabla
*/
QString name = QFileDialog::getExistingDirectory(this, tr("Choose folder"), QDir::homePath(), QFileDialog::DontResolveSymlinks);
ui->lineEditOrdner->setText(name);
ui->labelResult->setText(QString());
}
void MainWindow::slot_analysieren()
@@ -79,7 +74,7 @@ void MainWindow::slot_analysieren()
ISSI = QLatin1String("1");
m_logfileList.clear();
//alle DAteien in dem Ordner finden
QDir folder(ui->lineEditOrdner->text());
m_files = folder.entryList();
folder.~QDir();
@@ -88,7 +83,7 @@ void MainWindow::slot_analysieren()
const QString issitext = ISSI + QLatin1String("-1");
for (int i = 0; i < m_files.count(); i++)
{
//Dateinamen entfernen, die keine Payload-Logs sind
QString name = m_files[i];
if (name.contains(paytext))
{
@@ -141,7 +136,7 @@ void MainWindow::readFiles()
QFile file(filename);
if (file.open(QIODevice::ReadOnly))
{
//Datei auslesen
QByteArray ar = file.read(150);
file.close();
if (ar.size() > 36)
@@ -149,25 +144,26 @@ void MainWindow::readFiles()
QString issi = getISSI(ar);
QByteArray bytes = ar;
//Laufende Nummer
bytes.remove(0, 34);
bytes.remove(2, 150);
uint nr = bytes[0] & 255;
nr *= 256;
nr += bytes[1] & 255;
//BytesNr 34+35
//Sendezeit
bytes = ar;
bytes.remove(0, 30);
bytes.remove(4, 150);
const QByteArray test = bytes.toHex();
qint64 zeit = test.toLongLong(nullptr, 16);
//Byte 30-33
const QDateTime timeStart(QDateTime::fromMSecsSinceEpoch(zeit * 1000));
writeToLogfile(issi, timeStart, getTimestamp(m_files[j]), m_files[j], nr);
writeLogZeiten(timeStart, getTimestamp(m_files[j]), issi);
}
}
file.close();
@@ -176,8 +172,9 @@ void MainWindow::readFiles()
val *= (j + 1);
val += 20;
ui->progressBar->setValue(int(val));
// ui->progressBar->repaint();
}
}
void MainWindow::openLogfile(const QString &folder, int count)
@@ -199,9 +196,14 @@ 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 &timestamp, const QString &filename, uint lfdNr, const QString &bytes)
void MainWindow::writeToLogfile(const QString &issi,
const QDateTime &timestamp,
const QString &filename,
uint lfdNr,
const QString &bytes)
{
QString text = issi;
text += QLatin1String(": ");
@@ -226,7 +228,11 @@ void MainWindow::writeToLogfile(const QString &issi, const QDateTime &timestamp,
m_logfileList.append(info);
}
void MainWindow::writeToLogfile(const QString &issi, const QDateTime &sendeZeit, const QDateTime &timestamp, const QString &filename, uint lfdNr)
void MainWindow::writeToLogfile(const QString &issi,
const QDateTime &sendeZeit,
const QDateTime &timestamp,
const QString &filename,
uint lfdNr)
{
QString text = issi;
text += QLatin1String(": ");
@@ -256,7 +262,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);
@@ -267,11 +273,11 @@ QDateTime MainWindow::getTimestamp(const QString &filename) const
QString MainWindow::getISSI(QByteArray ar)
{
//wird nur für die "2-timestamp"-Dateien verwendet
ar.remove(0, 5);
ar.remove(4, 200);
QByteArray issi = ar.toHex();
if (ar.size() == 4)
{
if (ar[2] == '\0' && ar[3] == '\0')
@@ -286,6 +292,7 @@ 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];
@@ -303,7 +310,7 @@ QString MainWindow::getISSI(QByteArray ar)
int MainWindow::auswerten()
{
//Logfile vorbereiten
QFile f(m_logfile);
if (!f.open(QIODevice::Append | QIODevice::Text))
return -1;
@@ -312,7 +319,7 @@ int MainWindow::auswerten()
issis.reserve(100);
for (int i = 0; i < m_logfileList.count(); i++)
{
//Unterschiedliche Issis finden
issis += m_logfileList.at(i).issi;
}
ui->progressBar->setValue(94);
@@ -322,7 +329,7 @@ int MainWindow::auswerten()
int i = 0;
for (const QString &issi : std::as_const(issis))
{
//für jede Issi die Nummern in timestampMap einlesen --> geordnet nach Zeitstempel
numList.clear();
for (int j = 0; j < m_logfileList.count(); j++)
{
@@ -337,7 +344,7 @@ int MainWindow::auswerten()
f.write(text);
fehlcount += fehlendeNumsEintragen(numList, f);
// delete numList;
double val = 5;
val /= issis.count();
@@ -353,7 +360,7 @@ int MainWindow::auswerten()
int MainWindow::fehlendeNumsEintragen(const QVector<uint> &numList, QFile &f)
{
//schreibt die fehlenden Nummern in das Logfile und die GUI
QVector<uint> fehlendeNums = getFehlendeNums(numList);
QByteArray text = QByteArray::number(fehlendeNums.count());
text += " lost messages\n";
@@ -363,7 +370,7 @@ int MainWindow::fehlendeNumsEintragen(const QVector<uint> &numList, QFile &f)
text += QByteArray::number(fehlendeNums.at(j));
text += ", ";
}
// delete fehlendeNums;
text += ")\n";
f.write(text);
@@ -373,13 +380,13 @@ int MainWindow::fehlendeNumsEintragen(const QVector<uint> &numList, QFile &f)
QVector<uint> MainWindow::getFehlendeNums(const QVector<uint> &numsDurchgang)
{
//ermittelt die fehlenden Nummern pro Durchgang
uint count = numsDurchgang.count();
uint maxnum = 0;
uint minnum = 999999;
for (uint k = 0; k < count; k++)
{
//höchste und niedrigste Num finden
if (numsDurchgang.at(k) > maxnum)
maxnum = numsDurchgang.at(k);
if (numsDurchgang.at(k) < minnum)
@@ -389,7 +396,7 @@ QVector<uint> MainWindow::getFehlendeNums(const QVector<uint> &numsDurchgang)
QVector<uint> fehlendeNum;
for (uint z = minnum; z <= maxnum; z++)
{
//liste nach fehlenden werten durchsuchen
bool vorhanden = false;
for (uint j = 0; j < count; j++)
{
@@ -418,5 +425,5 @@ void MainWindow::writeLogZeiten(const QDateTime &beginn, const QDateTime &end, c
file.write(msg.toUtf8());
file.close();
//delete end;
}
@@ -7,7 +7,7 @@
namespace Ui
{
class MainWindow;
class MainWindow;
}
struct LogfileInfo
@@ -41,9 +41,17 @@ private:
QString m_logfile;
QString m_logZeiten;
void openLogfile(const QString &folder, int count);
void writeToLogfile(const QString &issi, const QDateTime &timestamp, const QString &filename, uint lfdNr, const QString &bytes);
void writeToLogfile(const QString &issi, const QDateTime &sendeZeit, const QDateTime &timestamp, const QString &filename, uint lfdNr);
QString getISSI(QByteArray ar); //Für alte TPUS
void writeToLogfile(const QString &issi,
const QDateTime &timestamp,
const QString &filename,
uint lfdNr,
const QString &bytes);
void writeToLogfile(const QString &issi,
const QDateTime &sendeZeit,
const QDateTime &timestamp,
const QString &filename,
uint lfdNr);
QString getISSI(QByteArray ar);
int auswerten();
QVector<uint> getFehlendeNums(const QVector<uint> &numsDurchgang);
int fehlendeNumsEintragen(const QVector<uint> &numList, QFile &file);
@@ -57,4 +65,5 @@ private slots:
};
#endif // MAINWINDOW_H
#endif
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Implementation of the Class PrtCnvApplication
// **************************************************************************
#include "PrtCnvApplication.hpp"
#include "PrtCnvThreadStarter.hpp"
@@ -28,362 +28,382 @@
namespace PrtCnv
{
static std::string threadIdToString(PrtCnvApplication::E_ThreadId id)
static std::string threadIdToString(PrtCnvApplication::E_ThreadId id)
{
switch (id)
{
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);
}
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;
}
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)
{
case e_Central:
while (!(isConstructed(e_Db) &&
isConstructed(e_Radio) &&
isConstructed(e_Log) &&
isConstructed(e_Injection)))
{
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;
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
return std::to_string(id);
}
break;
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)
case e_Radio:
while (!(isConstructed(e_Db) &&
isConstructed(e_Central) &&
isConstructed(e_Log) &&
isConstructed(e_Injection)))
{
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;
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId);
}
break;
// ---------------------------------------------------------------
// 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)
case e_Db:
while (!(isConstructed(e_Radio) &&
isConstructed(e_Central)))
{
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;
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId);
break;
default:
break;
}
INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId);
}
// ---------------------------------------------------------------
// Synchronisation of threads before start().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForStart(E_ThreadId a_threadId)
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)
{
INFO_LOG(m_logger) << "Wait for others until we can start " << threadIdToString(a_threadId);
setInitialized(a_threadId);
switch (a_threadId)
case e_Central:
while (!(isCreated(e_Db) &&
isCreated(e_Radio)))
{
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;
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
INFO_LOG(m_logger) << "Now we can start " << threadIdToString(a_threadId);
}
break;
// ---------------------------------------------------------------
// 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)
case e_Radio:
while (!(isCreated(e_Db) &&
isCreated(e_Central)))
{
delete ti.thread;
ti.thread = nullptr;
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
}
break;
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())
case e_Db:
while (!(isCreated(e_Radio) &&
isCreated(e_Central)))
{
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");
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
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;
break;
default:
break;
}
INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId);
}
// ---------------------------------------------------------------
// Starts the childs and then the main application
// ---------------------------------------------------------------
int32_t PrtCnvApplication::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)
{
// start and create threads
for (const auto &ti : m_threadInfo)
ti.thread->start();
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;
N_AppComponent::AppComponent::start();
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;
return 0;
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);
}
// ---------------------------------------------------------------
// Returns the desired thread-starter
// ---------------------------------------------------------------
PrtCnv::PrtCnvThreadStarter *PrtCnvApplication::getThreadStarter(const E_ThreadId a_threadId)
void PrtCnvApplication::waitForExec(E_ThreadId a_threadId)
{
setStarted(a_threadId);
}
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)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return nullptr;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].thread;
delete ti.thread;
ti.thread = nullptr;
}
}
void PrtCnvApplication::setDatabaseConnectionParams(const QString &driver,
const QString &hostName,
const QString &database,
const QString &schemaName,
const QString &userName,
const QString &password)
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;
}
int32_t PrtCnvApplication::createApplication()
{
setName(QStringLiteral("Common"));
if (m_ConfigFileName.isEmpty())
{
m_dbDriver = driver;
m_dbHostName = hostName;
m_dbDatabaseName = database;
m_dbSchemaName = schemaName;
m_dbUserName = userName;
m_dbPassword = password;
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::logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool bIsSend)
{
const auto threadHandler = m_threadInfo[e_Log].thread;
PrtCnvTelegramLogThread *t = static_cast<PrtCnvTelegramLogThread *>(threadHandler ? threadHandler->getThread() : nullptr);
if (t)
t->writeWlsTelegramLog(tele, bIsSend, 0);
}
for (int i = 0; i < e_ThreadIdMax; i++)
m_threadInfo[i].thread = new PrtCnvThreadStarter((E_ThreadId)i, m_ConfigFileName, this);
// ---------------------------------------------------------------
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;
}
N_AppComponent::AppComponent::create(m_Config);
// ---------------------------------------------------------------
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;
}
return 0;
}
// ---------------------------------------------------------------
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;
}
int32_t PrtCnvApplication::start()
{
for (const auto &ti : m_threadInfo)
ti.thread->start();
// ---------------------------------------------------------------
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;
}
N_AppComponent::AppComponent::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;
}
return 0;
}
} // namespace PrtCnv
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<PrtCnvTelegramLogThread*>(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;
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Implementation of the Class PrtCnvApplication
// **************************************************************************
#pragma once
@@ -23,33 +23,20 @@
#include "prtcnvlib_export.h"
#include <TrainingAreaBase/training_area_telegrams.h>
/**
* Here are all project specific classes of protocol-converter implemented.
*/
namespace PrtCnv
{
class PrtCnvThreadStarter;
/**
* The main-application of protocol-converter. It is responsible for starting and
* controlling the threads of this application.
*
* @author alois.wismer
* @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
*
* @author alois.wismer
* @version 1.0
* @created 19-Jan-2010 17:09:00
*/
enum E_ThreadId
{
e_Central,
@@ -63,9 +50,8 @@ namespace PrtCnv
PrtCnvApplication();
~PrtCnvApplication();
/**
* Starts the main-application
*/
void startApp();
void shutdownApp();
static void setCleanDb(bool bCleanDb);
@@ -73,51 +59,33 @@ namespace PrtCnv
int exerciseId() const { return m_exerciseId; }
void setConfigFile(const QString &configFile);
/**
* Starts the childs and then the main application
*/
int32_t start() override;
/**
* Synchronisation of threads before init().
*
* @param a_threadId id of the calling thread
*/
void waitForInit(E_ThreadId a_threadId);
/**
* Synchronisation of threads before start().
*
* @param a_threadId id of the calling thread
*/
void waitForStart(E_ThreadId a_threadId);
/**
* Synchronisation of threads before create().
*
* @param a_threadId Id of the calling thread
*/
void waitForCreate(const E_ThreadId a_threadId);
/**
* Synchronisation of threads before execution of thread.
*
* @param a_threadId id of the calling thread
*/
void waitForExec(E_ThreadId a_threadId);
/**
* Returns the desired thread-starter
*
* @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
*/
void setDatabaseConnectionParams(const QString &driver,
const QString &hostName,
const QString &database,
@@ -131,69 +99,54 @@ 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
*/
int32_t createApplication();
/**
* Returns true when the specified thread is
* already constructed
*/
bool isConstructed(const E_ThreadId a_threadId) const;
/**
* The specifed thread is now constructed
*/
void setConstructed(const E_ThreadId a_threadId);
/**
* Returns true when the specified thread is
* already initialized
*/
bool isInitialized(const E_ThreadId a_threadId) const;
/**
* The specifed thread is now initialized
*/
void setInitialized(const E_ThreadId a_threadId);
/**
* Returns true when the specified thread is
* already created
*/
bool isCreated(const E_ThreadId a_threadId) const;
/**
* The specifed thread is now created
*/
void setCreated(const E_ThreadId a_threadId);
/**
* Returns true when the specified thread is
* already started
*/
bool isStarted(const E_ThreadId a_threadId) const;
/**
* The specifed thread is now started
*/
void setStarted(const E_ThreadId a_threadId);
protected:
/**
* Used to get configuration-parameter
*/
protected:
NGL::Settings *m_Config;
struct ThreadInfo
@@ -204,15 +157,14 @@ namespace PrtCnv
bool isInitialized = false;
bool isStarted = false;
} m_threadInfo[e_ThreadIdMax];
/**
* The name of the config-file
*/
QString m_ConfigFileName;
/**
* The exerciseId (or zero if not set)
*/
int m_exerciseId;
mutable QRecursiveMutex m_accessMutex;
@@ -224,6 +176,6 @@ namespace PrtCnv
QString m_dbPassword;
NGL::INGLLogger &m_logger;
};
};
}
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,15 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
@@ -29,7 +29,7 @@
namespace N_CoPrtCnv
{
class CoPrtCnvRadioTelegram;
class CoPrtCnvRadioTelegram;
}
#define MAX_BROADCAST_INDEX 65535
@@ -37,538 +37,321 @@ namespace N_CoPrtCnv
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
* - store and manage the broadcast-list
* - measure the Broadcast-Nachforderung-statistic
* @author wia
* @version 1.0
* @updated 30-Apr-2010 11:21:05
*/
class PrtCnvBroadcastMgr final : public QObject
class PrtCnvBroadcastMgr final : public QObject
{
Q_OBJECT
public:
enum E_State
{
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
};
PrtCnvBroadcastMgr();
/**
* returns true when the telegram should be sent to central
*
* @param a_radioTelegram
*/
bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
/**
* Creates all subcomponents
*/
int32_t create(NGL::Settings *settings);
/**
* Initializes the variables.
*/
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.
* Use the same a_actualTime in one tick-loop.
*
* @param a_beginSearchWithBroadcastIndex
* @param a_actualTime
* @param a_doDelete true if telegram must be deleted after using it
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> 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);
/**
* 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);
/**
* 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);
/**
* returns the next broadcast to send for nachforderungen
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextNachforderungTelegramToSend();
/**
* dumps important values, only for debugging
*/
void dump();
/**
* Restores data after crash for seamless proceeding of work.
*/
void restoreAfterCrash();
/**
* Returns the actual broadcast-index for normal broadcasts.
*/
uint16_t getBroadcastIndex() const;
/**
* Returns the broadcastindex for the next broadcast
*/
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,
* otherwise it will be marked as broadcast-only.
* If the there is already an broadcast-only-telegram attached, nothing will be
* done.
*
* @param a_broadcastOnlyTelegram
*/
void addBroadcastOnlyTelegramToMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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);
/**
* 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;
/**
* Adds the TNE to the nachforderungs-list
*
* @param a_radioTelegram
*/
void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter);
protected:
struct EquipNoBcIndex
{
int equipNo = 0;
int bcIndex = 0;
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<EquipNoBcIndex> 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;
/**
* the factor for widening claim-window before sending broadcasts when we have
* high load traffic
*/
uint16_t m_HighLoadFactor;
/**
* the number of TPUs needed for sending the broadcasts as broadcast instead
* directed
*/
uint16_t m_BroadcastLimit;
/**
* Used to get configuration-parameter.
*/
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;
/**
* The state of broadcast-manager.
*/
PrtCnvBroadcastMgr::E_State m_State;
uint16_t m_TickCounter;
/**
* The actual broadcast-index for sending nachforderungen
*/
PrtCnvDbThread *m_DbThread;
/**
* sorted by broadcast-index
*/
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_BroadcastMap;
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_broadcastTelegamsToSend;
/**
* Contains all telegrams which must only be stored once for nachforderungen
*/
std::map<gef_telegramm_id_et, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_LastTelegramMap;
/**
* Contains all wirkfeld-telegrams which must be stored for nachforderungen
* ordered by wirkfeldkennung.
*/
std::multimap<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_WirkfeldTelegramMapByKennung;
/**
* Contains all wirkfeld-telegrams which must be stored for nachforderungen
* ordered by expiration-time.
*/
std::multimap<time_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_WirkfeldTelegramMapByTime;
/**
* Contains all funktionsraum-telegrams which must be stored for nachforderungen
* ordered by funktionsraumkennung.
*/
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_FunktionsraumTelegramMap;
/**
* Contains all technik-funktionsraum-telegrams which must be stored for nachforderungen
* ordered by funktionsraumkennung.
*/
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_TechnikFunktionsraumTelegramMap;
/**
* The actual broadcast-index for normal broadcast
*/
uint16_t m_BroadcastIndex;
/**
* True if send-traffic is on full-load => no nachforderungen will be sent
*/
bool m_IsFullLoad;
/**
* The highest broadcast-index of 3rd time sent broadcast-telegram (for optimize
* by time)
*/
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;
/**
* adds the radio-telegram to the broadcast-map, or generates the sammeltelegramme
*
* @param a_radioTelegram
*/
void addToBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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
* 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.
*
* @param a_broadcastIndex
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> 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<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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.
* If a_attachTelegram in not NULL, this telegram will be attached to
* a_radioTelegram.
*
* @param a_radioTelegram The radio-telegram to be moved
* @param a_newBroadcastIndex The new broadcast-index
* @param a_attachTelegram The telegram to be attached
*/
void moveTelegramInBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram,
const uint16_t a_newBroadcastIndex,
const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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.
* If the telegram is an attached BC-only-telegram, it will be detached.
* The telegram itself will be deleted when a_doDeleteTelegram is true.
* ATTENTION: iterators to m_BroadcastMap could be invalid after calling this
* function
*
* @param a_radioTelegram
* @param a_doDeleteTelegram
*/
void removeFromBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void removeFromBroadcastMapFunc(const std::function<bool(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &)> &pred);
void removeDusMineDeactivationFromBroadcastMap(int dusMineId);
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccumulationTelegram(int curBcIndex,
int startBcIndex,
gef_telegramm_id_et telId,
const QMap<int, int> &bcIndex2Type,
int maxIdsPerTelegram,
int sizeOfSumField) const;
bool removeFromDeactivatedAesArea(int aesAreaId);
bool addToDeactivatedAesArea(int aesAreaId, int bcIndex);
// QHash<mineId, broadcastIndexDeactivated>
QHash<int, int> m_deactivatedAesArea2bcIndex;
// QMap<broadcastIndexDeactivated, mineId>, keep sorted!
QMap<int, int> m_deactivatedBcIndex2AesArea;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccuTeleDeactivatedAesAreas(int curBcIndex, int startBcIndex) const;
bool removeFromDeactivatedFuncArea(int aesAreaId);
bool addToDeactivatedFuncArea(int aesAreaId, int bcIndex);
// QHash<mineId, broadcastIndexDeactivated>
QHash<int, int> m_deactivatedFuncArea2bcIndex;
// QHash<broadcastIndexDeactivated, mineId>, keep sorted!
QMap<int, int> m_deactivatedBcIndex2FuncArea;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccuTeleDeactivatedFuncAreas(int curBcIndex, int startBcIndex) const;
bool removeFromDeactivatedDusMine(int dusMineId);
bool addToDeactivatedDusMine(int dusMineId, int bcIndex);
// QHash<mineId, broadcastIndexDeactivated>
QHash<int, int> m_deactivatedDusMine2bcIndex;
// QHash<broadcastIndexDeactivated, mineId>, keep sorted!
QMap<int, int> m_deactivatedBcIndex2DusMine;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccuTeleDeactivatedDusMines(int curBcIndex, int startBcIndex) const;
bool removeFromActivatedDusMine(int dusMineId);
void addToActivatedDusMine(int dusMineId);
QSet<int> m_activatedDusMines;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> 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
* braodcast-only-telegram will be deattached and inserted into broadcast-map.
* Returns true if kennung was successful removed, otherwise the kennung was not
* found within sammeltelegram
*
* @param a_sammelTelegram
* @param a_kennung
* @param a_anzahlPos
* @param a_anzahlSize
* @param a_sammelTelRemoved
*/
bool removeFromSammeltelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_newRadioTelegram);
/**
* Small helper to dump all wf-ids from a sammeltelegramm
*/
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);
/**
* Takes expired wirkfeld-telegrams out of maps.
*/
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.
* Finally the telegram will be deleted.
*
* @param a_kennung
*/
void removeWirkfeldTelegrams(const uint16_t a_kennung);
/**
* adds the wirkfeld-telegram to the by time and by kennung maps
*
* @param a_radioTelegram
* @param a_wirkfeldKennung
* @param a_telId
* @param a_minenKennung
*/
void addWirkfeldTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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.
* Returns true if the "WirkfeldstatusMinensperre"-telegram was already sent 3
* times as normal broadcast.
*
* @param a_wirkfeldKennung
* @param a_minenKennung
* @param 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<N_CoPrtCnv::CoPrtCnvRadioTelegram> 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.
* The telegram itself will be deleted when a_doDeleteTelegram is true.
* ATTENTION: iterators to all maps could be invalid after calling this function
*
* @param a_radioTelegram
* @param a_doDeleteTelegram
*/
void removeFromAllMaps(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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.
* The telegram itself will be deleted.
* ATTENTION: iterators to m_FunktionsraumTelegramMap could be invalid after
* calling this function
*
* @param 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.
* The telegram itself will be deleted.
* ATTENTION: iterators to m_WirkfeldTelegramMapByKennung and
* m_WirkfeldTelegramMapByTime could be invalid after calling this function
*
* @param a_wirkfeldTelegramMapByKennungIterator
*/
void removeFromWirkfeldAndBroadcastMaps(
const std::multimap<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>>::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<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
/**
* Prepares values for start sending nachforderungen
*/
void prepareForSendNachforderungen();
/**
* returns the next nachforderung to send and prepares collecting window if no
* more nachforderungen are to be sent
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> evaluateNextNachforderungToSend();
Q_SIGNALS:
void areaEffectSimulationActivated(int wirkfeldKennung);
void areaEffectSimulationDeactivated(int wirkfeldKennung);
private:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_loggerBcRequest;
e_ST_UNDEFINED,
e_ST_COLLECT,
e_ST_SEND_NACHFORDERUNG
};
PrtCnvBroadcastMgr();
bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
int32_t create(NGL::Settings *settings);
int32_t init();
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex,
const time_t a_currentTime);
void setDbThread(PrtCnvDbThread *a_dbThread);
void cleanAndInit(const bool a_deleteTelegrams);
void handleOverrunOfBroadcastCounter(const bool a_doRestore = false);
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextNachforderungTelegramToSend();
void dump();
void restoreAfterCrash();
uint16_t getBroadcastIndex() const;
uint16_t getNextBroadcastIndex();
void addBroadcastOnlyTelegramToMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_broadcastOnlyTelegram);
void incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad);
bool isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const;
void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter);
protected:
struct EquipNoBcIndex
{
int equipNo = 0;
int bcIndex = 0;
EquipNoBcIndex() = default;
EquipNoBcIndex(int e, int b) : equipNo(e), bcIndex(b) {}
};
std::vector<EquipNoBcIndex> m_claimerArray;
uint16_t m_ClaimWindow;
uint16_t m_HighLoadFactor;
uint16_t m_BroadcastLimit;
NGL::Settings *m_Config;
uint16_t m_ActClaimWindow;
PrtCnvBroadcastMgr::E_State m_State;
uint16_t m_TickCounter;
PrtCnvDbThread *m_DbThread;
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_BroadcastMap;
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_broadcastTelegamsToSend;
std::map<gef_telegramm_id_et, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_LastTelegramMap;
std::multimap<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_WirkfeldTelegramMapByKennung;
std::multimap<time_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_WirkfeldTelegramMapByTime;
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_FunktionsraumTelegramMap;
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_TechnikFunktionsraumTelegramMap;
uint16_t m_BroadcastIndex;
bool m_IsFullLoad;
uint16_t m_FinishedBroadcastIndex;
uint16_t m_FirstBroadcastIndexOfBc1;
void addToBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNachforderungsTelegram(int curBcIndex, int startBcIndex, int &nextBcIndex);
int getSammeltelegramIndex(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_sammelTelegram,
const uint16_t a_kennung) const;
void moveTelegramInBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram,
const uint16_t a_newBroadcastIndex,
const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_attachTelegram = {});
void removeFromBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void removeFromBroadcastMapFunc(const std::function<bool(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &)> &pred);
void removeDusMineDeactivationFromBroadcastMap(int dusMineId);
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccumulationTelegram(int curBcIndex,
int startBcIndex,
gef_telegramm_id_et telId,
const QMap<int, int> &bcIndex2Type,
int maxIdsPerTelegram,
int sizeOfSumField) const;
bool removeFromDeactivatedAesArea(int aesAreaId);
bool addToDeactivatedAesArea(int aesAreaId, int bcIndex);
QHash<int, int> m_deactivatedAesArea2bcIndex;
QMap<int, int> m_deactivatedBcIndex2AesArea;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>createAccuTeleDeactivatedAesAreas(int curBcIndex, int startBcIndex) const;
bool removeFromDeactivatedFuncArea(int aesAreaId);
bool addToDeactivatedFuncArea(int aesAreaId, int bcIndex);
QHash<int, int> m_deactivatedFuncArea2bcIndex;
QMap<int, int> m_deactivatedBcIndex2FuncArea;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>createAccuTeleDeactivatedFuncAreas(int curBcIndex, int startBcIndex) const;
bool removeFromDeactivatedDusMine(int dusMineId);
bool addToDeactivatedDusMine(int dusMineId, int bcIndex);
QHash<int, int> m_deactivatedDusMine2bcIndex;
QMap<int, int> m_deactivatedBcIndex2DusMine;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccuTeleDeactivatedDusMines(int curBcIndex, int startBcIndex) const;
bool removeFromActivatedDusMine(int dusMineId);
void addToActivatedDusMine(int dusMineId);
QSet<int> m_activatedDusMines;
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> createAccuTeleActivatedDusMines(int curBcIndex);
bool removeFromSammeltelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_sammelTelegram,
const uint16_t a_kennung,
const uint16_t a_anzahlPos,
const uint8_t a_anzahlSize,
bool &a_sammelTelRemoved);
void replaceLastTelegramAndAddAtEnd(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_newRadioTelegram);
std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram *sammelTelegram);
void getAllFinishedBroadcastsFromDb(const bool a_doRestore = false);
void removeExpiredTelegrams();
void removeWirkfeldTelegrams(const uint16_t a_kennung);
void addWirkfeldTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram,
const uint16_t a_wirkfeldKennung, const gef_telegramm_id_et a_telId = GEF_BESTAETIGUNG,
const uint16_t a_minenKennung = 0);
bool deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex);
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNopTelegram(const uint16_t a_from, const uint16_t a_to);
void removeFromAllMaps(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void detachTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
void removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
void removeFromWirkfeldAndBroadcastMaps(const std::multimap<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>>::iterator &a_wirkfeldTelegramMapByKennungIterator);
void reactivateDusMine(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void deactivateSingleMine(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
void prepareForSendNachforderungen();
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> evaluateNextNachforderungToSend();
Q_SIGNALS:
void areaEffectSimulationActivated(int wirkfeldKennung);
void areaEffectSimulationDeactivated(int wirkfeldKennung);
private:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_loggerBcRequest;
};
}
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Implementation of the Class PrtCnvCentralThread
// **************************************************************************
#pragma once
@@ -27,284 +27,209 @@ namespace PrtCnv
{
class PrtCnvRadioThread;
class PrtCnvThreadStarter;
/**
* This class handles the protocoll to central. This includes:
* - connection with files instead sockets (configurable)
* - send and receive telegrams
*
* @author
* @version 1.0
* @created 05-Jan-2006 13:34:28
*/
class PrtCnvCentralThread : public PrtCnv::PrtCnvThread
{
Q_OBJECT
private:
private:
public:
/**
* @author wia
* @version 1.0
* @updated 02-Jul-2009 14:32:58
*/
~PrtCnvCentralThread();
/**
* @param a_parent The pointer to the starter-thread
*/
explicit PrtCnvCentralThread(PrtCnvThreadStarter *a_parent);
/**
* Creates all subcomponents and connects signals to slots
*/
explicit PrtCnvCentralThread(PrtCnvThreadStarter* a_parent);
int32_t create(NGL::Settings *settings) override;
int32_t deinit() override;
/**
* Deallocates subcomponents.
*/
int32_t destroy() override;
/**
* Initializes the variables.
*/
int32_t init() override;
/**
* Starts the thread and connects to TCP-server
*/
int32_t start() override;
/**
* Stops the thread
*/
int32_t stop() override;
// for direct communication
void onDirectTextMessageReceived(const QByteArray &baJson);
signals:
// for direct communication
void directTextMessage(const QByteArray &baJson);
/**
* Signal to start sending a telegram to central
*/
void checkSendToCentral();
/**
* Signal to start sending a telegram to radio
*/
void checkSendToRadio();
/**
* Signal to stop radio
*/
void stopRadio();
/**
* Signal to start cleaning-process of radio-thread
*/
void cleanRadio();
/**
* Signal to restart work of radio-thread
*/
void startRadio();
protected:
/**
* For reading/writing json telegrams to socket
*/
QWebSocket *m_webSocket;
/**
* The send-counter (only for sockets)
*/
int32_t m_SendCounter;
public slots:
/**
* Checks whether a telegram must be sent and sends it.
*/
void checkSend();
/**
* Stores that radio-thread has stopped. Cleans the Db and reinitializes when
* central-thread has also stopped.
*/
void radioStopped();
/**
* Starts radio-thread and itself for proceeding work after cleaning the Db.
*/
void radioCleant();
/**
* 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)
*
* @param a_centralCounter
*/
void permanentStored(int32_t a_centralCounter);
// called from Radio thread to indicate current connection state
void onTetraConnectionState(bool bConnected);
// called from Radio thread to indicate the license state of an equipment
void onPlayerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind);
protected slots:
// an effect siumlation was (de)activated
void onAreaEffectSimulationDeactivated(int wirkfeldKennung);
void onAreaEffectSimulationActivated(int wirkfeldKennung);
// radio thread completely initialized
void onRadioThreadInitDone();
/**
* called when websocket is connected
*/
void connected();
/**
* called when websocket is disconnected
*/
void disconnected();
/**
* used to send periodically an ack to central
*/
void timeoutTick();
/**
* see base-class
*/
void timeoutAliveAndConnection();
void onTextMessageReceived(const QString &msg);
void stateChanged(QAbstractSocket::SocketState newState);
protected:
/**
* Sends a ack-telegram to central.
*/
void sendAck();
/**
* Stores a telegram to be sent to radio in volatile radio-list and permanent in
* DB.
*
* @param a_telegram
*/
void handleTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
bool checkAndUpdateReceiveCounter(const int32_t a_counter);
/**
* 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.
*
* @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);
/**
* Processes the telegram AnforderungStatistikBroadcastNachforderugen. The
* function fills the answer telegram StatistikBroadNachforderungen with the
* actual statistic.
*
* @param a_umgMldTelegram
*/
void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram,
PrtCnvStoredCentralTelegram *a_handle);
void handleAnforderungStatistikBroadcastNachforderungen();
/**
* Removes telegrams from ToCentral-table, if the central acknowledges their
* reception
*
* @param a_ackTelegram
*/
void handleAck(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
/**
* Calls clean of radio-thread and Db-thread and initializes the variables for
* rework.
*/
void cleanAndReinit();
/**
* returns true if telegram should be converted, stored and sent to radio
*
* @param a_telegram
*/
bool handleSpecialTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
/**
* Sends a central-telegram to socket or file, depending on configuration. Before
* sending, the send-counter will be set.
*
* @param a_telegram The central-telegram to be sent.
*/
void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
/**
* Connect as client to a TCP-server on ip-address configured as HostName and Port
* configured as Port
*/
void connectSocket();
/**
* Disconnects from TCP-server
*/
void disconnectSocket();
protected:
/**
* used for periodically send an ack to central
*/
PrtCnvRadioThread *m_RadioThread;
/**
* True if radio has stopped work
*/
bool m_RadioStopped;
/**
* True if central has stopped work
*/
bool m_CentralStopped;
/**
* Used for resending unacked telegrams
*/
int32_t m_LastSendCounter;
/**
* The (virtual) identify of the protocol-converter
*/
uint16_t m_VirtualTeilnehmerId;
/**
* The maximum equipment-ID for tetra - all telegrams with an higher ID will
* be silently ignored
*/
uint16_t m_maxEqID;
// timer to reconnect when no ack from central is coming anymore
QTimer *m_aliveTimer;
// timer to send ack to central
QTimer *m_sendAckTimer;
// timer to reconnect to central
QTimer *m_reconnectTimer;
/**
* True if the database has to be cleant up (used for fast empty of signal buffers)
*/
QAtomicInt m_DoCleanup;
PrtCnvDbThread *m_DbThread;
// log telegrams in file
PrtCnvTelegramLogThread *m_LogThread;
// get injected telegrams
PrtCnvInjectionThread *m_InjectionThread;
/**
* Counter of received telegrams (only for sockets)
*/
int32_t m_ReceiveCounter;
/**
* Acknowledged telegrams counter (only for sockets)
*/
int32_t m_ReceiveAckCounter;
/**
* The state-event-machine state
*/
PrtCnvSocketThread::E_State m_State;
// set with all already deactivated effect simulations to not send deactivate telegram twice
QSet<int> m_deactivatedAreaEffectSimulations;
// multimap with all mine areas and it's already triggered mines
QHash<int, QSet<int>> m_alreadyTriggeredMines;
// true when we don't use socket but direct connections (through onDirectTextMessageReceived)
bool m_bDirectConnection;
bool m_bRadioThreadInitDone;
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// Implementation of the Class PrtCnvDbThread
// **************************************************************************
#pragma once
@@ -37,459 +37,292 @@ namespace PrtCnv
class PrtCnvStoredCentralTelegram;
class PrtCnvStoredRadioTelegram;
class PrtCnvMember;
/**
* Handles all data which must be stored permanent:
* - central-telegrams
* - radio-telegrams
* - radio-members (TNE)
* - reset-counter
* - states
*
* @author wia
* @version 1.0
* @created 28-Jul-2009 16:08:53
*/
class PrtCnvDbThread : public PrtCnvThread
{
Q_OBJECT
public:
/**
* Constructor with thread-starter as argument
*
* @param a_parent
*/
PrtCnvDbThread(const QString &dbDriver,
const QString &dbHostName,
const QString &dbDatabaseName,
const QString &schemaName,
const QString &dbUserName,
const QString &dbPassword,
PrtCnvThreadStarter *a_parent);
PrtCnvThreadStarter* a_parent);
~PrtCnvDbThread();
/**
* starts this thread and its childs
*/
int32_t start() override;
/**
* stops this thread and its childs
*/
int32_t stop() override;
/**
* creates this thread and its childs
*/
int32_t create(NGL::Settings *settings) override;
/**
* initializes this thread and its childs
*/
int32_t init() override;
/**
* Indicates the Db, which telegrams were successful received by central. This
* will delete this telegrams from Db.
*
* @param a_counter
*/
void ackCentralTelegrams(int32_t a_counter);
/**
* returns the next telegram to send to central.
* returns NULL if no telegram found.
* ATTENTION: The caller is responsible to deallocate the returned
* centralTelegram!
*
* @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
*
* @param a_counter The counter the telegram has while sent
* @param a_handle The telegram-handle gotten from getNextCentralTelegram()
*/
void centralTelegramSent(const int32_t a_counter, PrtCnvStoredCentralTelegram *a_handle);
/**
* 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.
*
* @param a_handle The telegram-handle gotten from getNextCentralTelegram()
*/
void centralTelegramCouldNotBeSent(PrtCnvStoredCentralTelegram *a_handle);
/**
* Marks the radio-telegram as to be sent
*
* @param a_sendCounter
* @param a_handle
* @param a_broadcastIndex
*/
void radioTelegramSent(const uint32_t a_sendCounter, PrtCnvStoredRadioTelegram *a_handle, const uint32_t a_broadcastIndex);
/**
* returns the next telegram to send to radio, respecting the priority.
* returns NULL if no radio-telegram found.
*
* @param a_handle
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextRadioTelegram(PrtCnvStoredRadioTelegram *&a_handle);
/**
* returns the next broadcast-telegram from list.
* Deletes the telegram from this list.
* returns NULL if list empty.
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextBroadcastTelegram();
/**
* 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.
*
* @param a_centralTelegram
* @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<N_CoPrtCnv::CoPrtCnvCentralTelegram> &a_centralTelegram, const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
void storeCentralTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvCentralTelegram> &a_centralTelegram,
const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
/**
* 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.
*
*
* @param a_telegram
* @param a_readCounter
*/
void storeRadioTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_telegram, const int32_t a_readCounter);
/**
* This function causes acking a central-telegram, which must not be stored
* permanent in Db, because it will be handled immediately (i.e.
* AnforderungStatistikBroadcastNachforderungen).
*
* @param a_centralCounter The read-counter of the central-telegram
*/
void centralCounterReadyForAck(const int32_t a_centralCounter);
/**
* Adds an sql-command in the sql-command-list. On next iteration of
* storePermanent() all command in list will be executed.
*
* @param a_sqlCommand
*/
void addSqlCommand(const QString &sql);
/**
* erases and initializes the database
*/
void cleanAndInit();
/**
* 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.
*
* @param a_lastSendCounter The counter of the telegram we expect a ack-
* telegram has been received
*/
bool resendCentralTelegrams(const int32_t a_lastSendCounter);
/**
* Prepares the telegrams not yet acked from central for reconnection. This will
* be done by setting the write-counter to 0.
*/
void prepareCentralTelegramsForReconnection();
/**
* Blocks until all SQL-commands were written to DB.
*/
void waitUntilDbWritten();
/**
* returns NULL if no member found
*
* @param a_ISSI
*/
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* getMemberByISSI(const uint32_t a_ISSI) const;
PrtCnvMember* getMemberById(const uint16_t a_id);
/**
* Licenses the member
*
* @param a_member
* @param a_doLicense
*/
bool licenseMember(PrtCnvMember *a_member, const bool a_doLicense = true);
/**
* Updates the current exercise for this member
*/
void updateExerciseIdForMember(PrtCnvMember *a_member, int newExerciseId);
/**
* adds a member in the 2 maps, sorted by id and ISSI
* returns the new member
*
* @param a_identity
* @param 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);
PrtCnvMember* addMember(const int a_identity, const int a_ISSI);
void removeMember(PrtCnvMember* a_member);
/**
* Returns the actual reset-counter
*/
uint8_t getResetCounter() const;
/**
* Sets the actual reset-counter
*
* @param newVal
*/
void setResetCounter(uint8_t newVal);
/**
* The actual 'Betriebszustaende Gefechtsfeld' which will be sent to TNEs
* periodically
*/
uint8_t getBattleFieldOperatingState() const;
/**
* Sets or unsets pause, depending on a_doSet.
* (Bit 0 in UMGEBUNGS_MELDUNG(2))
* @param a_doSet
*/
void setPause(const bool a_doSet = true);
/**
* Set the inhibit time for position telegrams (1 .. 31 Seconds)
* (Bit 1-5 in UMGEBUNGS_MELDUNG(2))
* @param a_doSet
*/
void setPositionSendTime(unsigned int sendTime);
/**
* Set the current air load to be sent with the Umgebungsmeldung
* (Bit 6-7 in UMGEBUNGS_MELDUNG(2))
* @param airLoad The current air-load received from Tetra
*/
void setAirLoad(PrtCnvRadioThread::E_TrafficLoad airLoad);
/**
* Returns true if the resetCounter itself is different than the reset-counter of
* the environment-telegram
*/
bool isEnvironmentResetCounterOld() const;
/**
* Returns the actual Umgebungsmeldung
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getEnvironmentTelegram();
/**
* Sets the resetcounter of the environment-telegram to the actual reset-counter.
*/
void setResetCounterOnEnvironment();
/**
* Increments the counter for nachforderungen of the TNE with id a_identity.
*
* @param a_identity The identity of the TNE, which asked for nachforderung
*/
void incClaimCount(int a_identity);
/**
* Fills the map with nachforderungsstatistic.
* Returns the number of elements in map.
*
* @param a_statisticMap this map will be filled with pairs of
* ausstattungsnummer and amount of nachforderungen
*/
std::map<int32_t, int32_t> getClaimStatistics() const;
/**
* Sets the actual machine-state permanent, used to proceed cleaning db after a
* crash.
*
* @param a_newMachineState The new machine-state. 0 => working; 1 => cleaning
* DB
*/
void setMachineState(const int a_newMachineState);
/**
* Returns true if protocol-converter was crashed while cleanup DB.
*/
bool mustProceedCleanup() const;
protected:
void closeDb();
/**
* List of telegrams to be sent to central
*/
std::vector<PrtCnvStoredCentralTelegram *> m_CentralList;
std::vector<PrtCnvStoredCentralTelegram*> m_CentralList;
mutable QRecursiveMutex m_BattleFieldOpStateMutex;
mutable QRecursiveMutex m_MemberListByIdMutex;
mutable QRecursiveMutex m_CentralListMutex;
/**
* The permanent DB
*/
QSqlDatabase m_db;
/**
* The last counter received from central as ack. Used for deleting no longer used
* central-telegrams and for resending of central-telegrams.
*/
QAtomicInt m_CentralAckCounter;
/**
* Used for optimizing deletion of no longer needed central-telegrams.
*/
unsigned int m_OldCentralAckCounter;
/**
* List of telegrams to be sent to radio
*/
std::list<PrtCnvStoredRadioTelegram *> m_RadioList;
QAtomicInt m_CentralAckCounter;
unsigned int m_OldCentralAckCounter;
std::list<PrtCnvStoredRadioTelegram*> m_RadioList;
mutable QRecursiveMutex m_RadioListMutex;
std::vector<QString> m_SqlCommandList;
mutable QRecursiveMutex m_SqlCmdListMutex;
mutable QRecursiveMutex m_BroadcastMapMutex;
std::list<PrtCnvStoredRadioTelegram*> m_BroadcastList;
std::list<PrtCnvStoredRadioTelegram *> m_BroadcastList;
/**
* Used to wait until cleaning is finished and to suppress storing data within
* database while cleaning
*/
bool m_DoClean;
/**
* Used for waiting data written to DB
*/
bool m_DoWaitUntilSqlWritten;
/**
* Holds all logged in members ordered by Id.
*/
std::unordered_map<int, PrtCnvMember *> m_MemberListById;
/**
* Holds all logged in members ordered by ISSI
*/
std::unordered_map<int, PrtCnvMember *> m_MemberListByISSI;
/**
* Used to prevent data storing within DB while restoring after crash
*/
std::unordered_map<int,PrtCnvMember*> m_MemberListById;
std::unordered_map<int,PrtCnvMember*> m_MemberListByISSI;
bool m_DoStorePermanent;
/**
* the actual reset-counter
*/
uint8_t m_ResetCounter;
/**
* The actual 'Betriebszustaende Gefechtsfeld' which will be sent to TNEs
* periodically
*/
uint8_t m_BattleFieldOperatingState;
/**
* The actual telegram "Umgebungsmeldung"
*/
PrtCnvStoredRadioTelegram *m_EnvironmentTelegram;
/**
* True if cleanup has to be proceed after crash.
*/
PrtCnvStoredRadioTelegram* m_EnvironmentTelegram;
bool m_DoProceedCleanup;
/**
* Used to optimize send the signal permanentStored
*/
int32_t m_OldCentralCounter;
/**
* For ensure that not too much storePermanent-signals will be queued
*/
QBasicAtomicInt m_StorePermanentPending;
/**
* nbr of unsuccessful send-attempts, before telegram will be deleted without
* sending it
*/
uint32_t m_NbrOfAttempts;
/**
* creates or restores the permanent database
*/
bool createDatabase();
/**
* Sends a signal storePermanent if not already such a signal is pending
*/
void sendStorePermanentSignal();
/**
* Helper for storePermanent()
*/
void storeCentralTelegrams();
/**
* Helper for storePermanent()
*/
int32_t storeRadioTelegrams();
/**
* Helper for storePermanent()
*/
void handleSqlCommandList();
/**
* Delete all telegrams with the ids in telegramsToDelete
* from a given table
*/
void deleteTelegramsFromDbById(const QString &table);
/**
* Update the write counter for the telegrams in
* telegramsToUpdateCounter for the given table
*/
void updateTelegramsWriteCounter(const QString &table);
/**
* Update the broadcast counter for the telegrams in
* telegramsToUpdateCounter for the given table
*/
void updateTelegramsBroadcast(const QString &table);
/**
* Reinitialize the database
*/
void reinitDatabase();
QString toCentralTableName() const { return tableName(QStringLiteral("prtcnv_to_central")); }
@@ -499,43 +332,35 @@ namespace PrtCnv
QString versionTableName() const { return tableName(QStringLiteral("prtcnv_version")); }
QString tableName(const QString &table) const { return m_dbSchemaName.isEmpty() ? table : m_dbSchemaName + QLatin1Char('.') + table; }
protected slots:
/**
* Stores the radio-telegrams, central-telegrams in Db and executes the sql-
* command-list.
*/
void storePermanent();
/**
* cleans up this thread and its childs
*/
void clean();
public:
signals:
/**
* Signal to call storePermanent()
*/
void doStorePermanent();
/**
* Signal to inform central-thread about stored telegrams
*
* @param a_centralCounter
*/
void permanentStored(int32_t a_centralCounter);
/**
* a signal to erase the permanent database
*/
void doClean();
void playerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind);
private:
// local caches to memory (re)allocation all the time
// note: std::vector.clear() does not release memory and therefore
// a reallocation in the next turn is not neccessary
std::vector<int64_t> m_telegramsToDelete;
std::vector<std::pair<int64_t, int32_t>> m_telegramsToUpdateCounter;
std::vector<std::pair<int64_t, int32_t>> m_telegramsToUpdateBC;
std::vector<std::pair<PrtCnvStoredCentralTelegram *, int64_t>> m_telegramsToInsert;
std::vector<std::pair<int64_t, int32_t> > m_telegramsToUpdateCounter;
std::vector<std::pair<int64_t, int32_t> > m_telegramsToUpdateBC;
std::vector<std::pair<PrtCnvStoredCentralTelegram*, int64_t> > m_telegramsToInsert;
QString m_dbDriver;
QString m_dbHostName;
QString m_dbDatabaseName;
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "PrtCnvInjectionSocket.hpp"
#include <CoPrtCnv/CoPrtCnvInjectionHeader.hpp>
#include <CoPrtCnv/CoPrtCnvCentralTelegram.hpp>
@@ -22,63 +22,64 @@
namespace PrtCnv
{
PrtCnvInjectionSocket::PrtCnvInjectionSocket()
: m_Socket(nullptr)
, m_Server(nullptr)
, m_logger(getLogger("PrtCnvInjectionSocket"))
{
}
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);
}
PrtCnvInjectionSocket::~PrtCnvInjectionSocket()
{
delete m_Socket;
}
// ---------------------------------------------------------------
// Reads in TCP-data and handles them
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::processInputData()
void PrtCnvInjectionSocket::disconnectClient()
{
INFO_LOG(m_logger) << "A client has disconnected from the injection-server";
emit disconnected(this);
}
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)
{
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)
if (injectionHeader.isIdCorrect())
{
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;
}
m_Socket->read((char*)&injectionHeader, sizeof(injectionHeader));
if (injectionHeader.isIdCorrect())
{
// 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);
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:
switch (injectionHeader.m_Kind)
{
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral:
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio:
{
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = new N_CoPrtCnv::CoPrtCnvCentralTelegram(data);
@@ -96,31 +97,31 @@ namespace PrtCnv
}
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();
}
}
}
// ---------------------------------------------------------------
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)
else
{
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection);
ERROR_LOG(m_logger) << "Corrupt injection-telegram received => reconnect";
m_Socket->disconnectFromHost();
}
}
}
} // namespace PrtCnv
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)
{
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection);
}
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QObject>
@@ -21,26 +21,19 @@ class QTcpSocket;
namespace PrtCnv
{
class PrtCnvInjectionThread;
/**
* Used for receiving the socket signals
*
* @author alois.wismer
* @version 1.0
* @created 06-Aug-2010 16:41:44
*/
class PrtCnvInjectionSocket : public QObject
{
Q_OBJECT
public:
PrtCnvInjectionSocket();
~PrtCnvInjectionSocket();
/**
*
* @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;
@@ -49,24 +42,22 @@ namespace PrtCnv
NGL::INGLLogger &m_logger;
protected slots:
/**
* Disconnects a TCP-client
*/
void disconnectClient();
/**
* Reads in TCP-data and handles them
*/
void processInputData();
public:
signals:
/**
*
* @param a_injectSocket
*/
void disconnected(PrtCnvInjectionSocket *a_injectSocket);
void disconnected(PrtCnvInjectionSocket* a_injectSocket);
};
}
@@ -1,17 +1,17 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "PrtCnvInjectionThread.hpp"
#include "PrtCnvInjectionSocket.hpp"
@@ -23,155 +23,160 @@
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)
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);
if (m_Enabled)
{
m_Name = QStringLiteral("Injection");
m_Server = new QTcpServer(this);
if (m_Server)
connect(m_Server, &QTcpServer::newConnection, this, &PrtCnvInjectionThread::connectClient, Qt::QueuedConnection);
}
PrtCnvInjectionThread::~PrtCnvInjectionThread()
return 0;
}
int32_t PrtCnvInjectionThread::init()
{
INFO_LOG(m_logger) << "init";
PrtCnvThread::init();
m_Port = m_Config->getInteger(getName(), QStringLiteral("Port"), 46666);
return 0;
}
int32_t PrtCnvInjectionThread::start()
{
INFO_LOG(m_logger) << "Start";
PrtCnvThread::start();
if (m_Enabled)
{
delete m_CentralListMutex;
delete m_RadioListMutex;
m_Server->setMaxPendingConnections(1);
m_Server->listen(QHostAddress::Any, m_Port);
INFO_LOG(m_logger) << "Injection-Server is listening on port " << m_Port;
}
// ---------------------------------------------------------------
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;
}
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)
{
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;
}
// ---------------------------------------------------------------
// 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);
}
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);
}
// ---------------------------------------------------------------
// 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;
}
// ---------------------------------------------------------------
// 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;
}
// ---------------------------------------------------------------
// 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::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);
}
// ---------------------------------------------------------------
void PrtCnvInjectionThread::addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram)
{
QMutexLocker l(m_RadioListMutex);
m_RadioTelegramList.push(a_telegram);
}
} // namespace PrtCnv
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;
}
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);
}
}
@@ -1,16 +1,16 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "PrtCnvThread.hpp"
@@ -22,33 +22,24 @@ 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.
* This mechanism will be used for inject telegrams to protocol-converter.
*
* @author alois.wismer
* @version 1.0
* @created 05-Aug-2010 11:17:06
*/
class PrtCnvInjectionThread : public PrtCnvThread
{
Q_OBJECT
public:
~PrtCnvInjectionThread();
/**
*
* @param a_parent
*/
explicit PrtCnvInjectionThread(PrtCnvThreadStarter *a_parent);
explicit PrtCnvInjectionThread(PrtCnvThreadStarter* a_parent);
int32_t create(NGL::Settings *settings) override;
@@ -56,48 +47,31 @@ namespace PrtCnv
int32_t init() override;
/**
* Starts the thread and listen for TCP-clients
*/
int32_t start() override;
/**
* 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 *getNextCentralInjectionTelegram();
/**
* 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 *getNextRadioInjectionTelegram();
/**
*
* @param a_telegram
*/
void addToCentralList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
/**
*
* @param a_telegram
*/
void addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
protected: /**
* The port of the injection-server (configurable with key 'Port' in group
* [Injection])
*/
protected:
uint16_t m_Port;
/**
* true if injection-server is enabled (configurable with key 'Enable' in group
* [Injection])
*/
bool m_Enabled;
QTcpServer *m_Server;
@@ -110,20 +84,18 @@ namespace PrtCnv
QMutex *m_RadioListMutex;
std::set<PrtCnvInjectionSocket *> m_SocketList;
std::set<PrtCnvInjectionSocket*> m_SocketList;
public slots:
/**
* Connects a TCP-client
*/
void connectClient();
/**
* Disconnects a TCP-client
*
* @param a_injectionSocket
*/
void disconnectClient(PrtCnvInjectionSocket *a_injectionSocket);
void connectClient();
void disconnectClient(PrtCnvInjectionSocket* a_injectionSocket);
};
}
@@ -1,24 +1,18 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
/*!
*
* \page Tetra-Interface Tetra-Interface
*
* This component is needed to communicate between the Server software and the players in
* the field via Tetra. It's an extra component due to historical reasons only.
*
*/
#include "PrtCnvApplication.hpp"
#include <NGLLogger/INGLLogger.h>
@@ -31,54 +25,49 @@
#include <unistd.h>
#endif
// ---------------------------------------------------------------
// Become a daemon
// ---------------------------------------------------------------
static void daemonize()
{
#ifndef WIN32
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);
}
/* At this point we are executing as the child process */
/* Change the file mode mask */
umask(0);
/* 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)
{
exit(EXIT_FAILURE);
}
freopen( "/dev/null", "r", stdin);
freopen( "/dev/null", "w", stdout);
freopen( "/dev/null", "w", stderr);
#endif
}
@@ -86,17 +75,25 @@ 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);
@@ -1,97 +1,98 @@
// **************************************************************************
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
// **************************************************************************
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
// **************************************************************************
// manual class headers
#include "PrtCnvMember.hpp"
#include <CoPrtCnv/CoPrtCnvRadioTelegram.hpp>
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(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();
}
void PrtCnvMember::addFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram)
{
m_FragmentedTelegramList.insert(std::make_pair(a_radioTelegram.getFragmentCounter(),
new N_CoPrtCnv::CoPrtCnvRadioTelegram(a_radioTelegram)));
}
gef_telegramm_id_et PrtCnvMember::getFragmentedTelegramId() const
{
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();
}
PrtCnvMember::~PrtCnvMember()
{
clearFragmentedList();
}
return GEF_BESTAETIGUNG;
}
// ---------------------------------------------------------------
// 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)
{
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)
}
// ---------------------------------------------------------------
// 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();
}
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
QByteArray PrtCnvMember::getUnfragmentedTelegramData() const
{
return N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(m_FragmentedTelegramList);
}
bool PrtCnvMember::isFragmentedListEmpty() const
{
return m_FragmentedTelegramList.empty();
}
}
Loaded 100 of 15957 files, more files were not shown because too many files have changed in this diff. Show more