Formats minimally release source files based on former clang-format

This commit is contained in:
torsten committed 2026-10-14 13:28:01 +00:00
1 parent b662e4daf9
commit 5644914fe3
387 files changed
+37323 -38074

No files matched your search

@@ -16,73 +16,72 @@
namespace N_AppComponent
{
int32_t AppComponent::create(NGL::Settings *settings)
{
for (IAppComponent *c : m_Childs)
c->create(settings);
return 0;
}
int32_t AppComponent::destroy()
{
for (IAppComponent *c : m_Childs)
c->destroy();
return 0;
}
int32_t AppComponent::init()
{
for (IAppComponent *c : m_Childs)
c->init();
return 0;
}
int32_t AppComponent::deinit()
{
for (IAppComponent *c : m_Childs)
c->deinit();
return 0;
}
int32_t AppComponent::start()
{
for (IAppComponent *c : m_Childs)
c->start();
return 0;
}
int32_t AppComponent::stop()
{
for (IAppComponent *c : m_Childs)
c->stop();
return 0;
}
void AppComponent::addChild(IAppComponent *a_child, const QString &a_name)
{
if (a_child)
int32_t AppComponent::create(NGL::Settings *settings)
{
a_child->setName(a_name);
m_Childs.push_back(a_child);
for (IAppComponent *c : m_Childs)
c->create(settings);
return 0;
}
}
IAppComponent *AppComponent::getChild(const QString &a_name)
{
for (IAppComponent *c : m_Childs)
int32_t AppComponent::destroy()
{
if (a_name == c->getName())
return c;
for (IAppComponent *c : m_Childs)
c->destroy();
return 0;
}
int32_t AppComponent::init()
{
for (IAppComponent *c : m_Childs)
c->init();
return 0;
}
int32_t AppComponent::deinit()
{
for (IAppComponent *c : m_Childs)
c->deinit();
return 0;
}
int32_t AppComponent::start()
{
for (IAppComponent *c : m_Childs)
c->start();
return 0;
}
int32_t AppComponent::stop()
{
for (IAppComponent *c : m_Childs)
c->stop();
return 0;
}
void AppComponent::addChild(IAppComponent *a_child, const QString &a_name)
{
if (a_child)
{
a_child->setName(a_name);
m_Childs.push_back(a_child);
}
}
IAppComponent *AppComponent::getChild(const QString &a_name)
{
for (IAppComponent *c : m_Childs)
{
if (a_name == c->getName())
return c;
}
return nullptr;
}
return nullptr;
}
} // namespace N_AppComponent
@@ -1,12 +1,12 @@
// **************************************************************************
//
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
//
// **************************************************************************
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
//
//
// Implementation of the Class AppComponent
// **************************************************************************
@@ -16,30 +16,32 @@
#include "IAppComponent.hpp"
#include "prtcnvlib_export.h"
namespace NGL {
class Settings;
namespace NGL
{
class Settings;
}
namespace N_AppComponent
{
class PRTCNVLIB_EXPORT AppComponent : public N_AppComponent::IAppComponent
{
public:
AppComponent() = default;
~AppComponent() = default;
class PRTCNVLIB_EXPORT AppComponent : public N_AppComponent::IAppComponent
{
public:
AppComponent() = default;
~AppComponent() = default;
int32_t create(NGL::Settings *settings) override;
int32_t deinit() override;
int32_t destroy() override;
int32_t init() override;
int32_t start() override;
int32_t stop() override;
int32_t create(NGL::Settings *settings) override;
int32_t deinit() override;
int32_t destroy() override;
int32_t init() override;
int32_t start() override;
int32_t stop() override;
protected:
void addChild(IAppComponent* a_child, const QString& a_name = QString());
IAppComponent* getChild(const QString& a_name);
private:
std::vector<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;
};
}
@@ -1,12 +1,12 @@
// **************************************************************************
//
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
//
// **************************************************************************
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
//
//
// Implementation of the Class IAppComponent
// **************************************************************************
@@ -14,7 +14,8 @@
#include <QtCore/QString>
namespace NGL {
namespace NGL
{
class Settings;
}
@@ -44,14 +45,9 @@ namespace N_AppComponent
virtual int32_t stop() = 0;
inline const QString& getName() const
{
return m_Name;
}
inline void setName(const QString& newVal)
{
m_Name = newVal;
}
inline const QString &getName() const { return m_Name; }
inline void setName(const QString &newVal) { m_Name = newVal; }
protected:
QString m_Name;
};
@@ -41,9 +41,7 @@ int main(int argc, char **argv)
TetraIF::usage();
}
const QString mode = args[3].toLower();
if (mode != QLatin1String("listen") &&
mode != QLatin1String("send_random") &&
mode != QLatin1String("send_file"))
if (mode != QLatin1String("listen") && mode != QLatin1String("send_random") && mode != QLatin1String("send_file"))
{
ERROR_LOG(logger) << "Invalid mode " << args[3];
TetraIF::usage();
@@ -35,9 +35,10 @@ TetraIF::TetraIF(const QHostAddress &addr, unsigned short port, unsigned short i
, m_timer(nullptr)
, m_SendCounter(0)
),
m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) {
m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger())
{
connect(m_socket, &QTcpSocket::connected, this, &TetraIF::onConnected);
connect(m_socket, &QTcpSocket::disconnected, this, &TetraIF::onDisconnected);
connect(m_socket, &QTcpSocket::disconnected, this, &TetraIF::onDisconnected);
connect(m_socket, &QTcpSocket::readyRead, this, &TetraIF::onReadyRead);
connect(m_socket, &QAbstractSocket::errorOccurred, this, &TetraIF::onError);
@@ -60,8 +61,7 @@ void TetraIF::listenMode(const QStringList &args)
m_outputDir = args[0];
if (!QDir().mkpath(m_outputDir))
{
ERROR_LOG(m_logger) << "Error creating directory "
<< m_outputDir;
ERROR_LOG(m_logger) << "Error creating directory " << m_outputDir;
usage();
}
@@ -100,10 +100,8 @@ void TetraIF::randomMode(const QStringList &args)
parseISSIs(args.mid(3));
INFO_LOG(m_logger) << "Sending " << m_data.size()
<< " bytes, " << m_telegramsPerSecond
<< " telegrams/second for " << m_count
<< " time(s) to issi(s) " << getIssisAsString();
INFO_LOG(m_logger) << "Sending " << m_data.size() << " bytes, " << m_telegramsPerSecond << " telegrams/second for " << m_count << " time(s) to issi(s) "
<< getIssisAsString();
setupTimer();
}
@@ -136,19 +134,14 @@ void TetraIF::fileMode(const QStringList &args)
}
if (!f.open(QIODevice::ReadOnly))
{
ERROR_LOG(m_logger) << "Error opening file "
<< f.fileName()
<< " for reading - error: "
<< f.errorString();
ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for reading - error: " << f.errorString();
}
m_data = f.readAll();
parseISSIs(args.mid(3));
INFO_LOG(m_logger) << "Sending " << m_data.size()
<< " bytes, " << m_telegramsPerSecond
<< " telegrams/second for " << m_count
<< " time(s) to issi(s) " << getIssisAsString();
INFO_LOG(m_logger) << "Sending " << m_data.size() << " bytes, " << m_telegramsPerSecond << " telegrams/second for " << m_count << " time(s) to issi(s) "
<< getIssisAsString();
setupTimer();
}
@@ -189,16 +182,12 @@ void TetraIF::onReadyRead()
m_socket->peek(reinterpret_cast<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);
@@ -211,17 +200,12 @@ void TetraIF::onReadyRead()
m_socket->read(buf.data(), dataSize);
handleReceivedTelegram(buf);
}
while (m_socket->bytesAvailable());
} while (m_socket->bytesAvailable());
}
void TetraIF::onError(QAbstractSocket::SocketError err)
{
ERROR_LOG(m_logger) << "Socket error "
<< err
<< " ("
<< m_socket->errorString()
<< ") - aborting";
ERROR_LOG(m_logger) << "Socket error " << err << " (" << m_socket->errorString() << ") - aborting";
exit(2);
}
@@ -238,28 +222,28 @@ void TetraIF::handleReceivedTelegram(const QByteArray &data)
switch (type)
{
// response to register indication
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp:
handleRegisterRsp(data.at(5)); // registration status
break;
// response to register indication
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterRsp:
handleRegisterRsp(data.at(5)); // registration status
break;
// payload telegram
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data);
break;
// payload telegram
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data);
break;
// ack-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq:
// handleReportIndReq(data);
break;
// ack-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_ReportIndReq:
// handleReportIndReq(data);
break;
// air-interface-load-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq:
// handleAirInterfaceLoadReq(data);
break;
// air-interface-load-telegram - not handled here
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_AirInterfaceLoadReq:
// handleAirInterfaceLoadReq(data);
break;
default:
return;
default:
return;
}
INFO_LOG(m_logger) << "PDU Type: " << type;
dumpData(data);
@@ -270,29 +254,29 @@ void TetraIF::handleRegisterRsp(const uint8_t a_registrationStatus)
QByteArray logText;
switch (a_registrationStatus)
{
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_IssiSuccessfulRegistered:
INFO_LOG(m_logger) << "Valid register response from Tetra ";
if (m_timer)
m_timer->start();
return;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DuplicateISSI:
logText = "TETRA: Register-Response: Status=Duplicate ISSI";
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidISSI:
logText = "TETRA: Register-Response: Status=Invalid ISSI";
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_InvalidIpAddress:
logText = "TETRA: Register-Response: Status=Invalid IP address => Configure TETRA for accepting our IP-address (";
{
const QList<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;
@@ -310,10 +294,7 @@ void TetraIF::dumpData(const QByteArray &data)
QFile f(m_outputDir + timeStr + QLatin1String(".dat"));
if (!f.open(QIODevice::WriteOnly))
{
ERROR_LOG(m_logger) << "Error opening file "
<< f.fileName()
<< " for writing - error: "
<< f.errorString();
ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for writing - error: " << f.errorString();
}
f.write(data);
f.close();
@@ -321,20 +302,12 @@ void TetraIF::dumpData(const QByteArray &data)
if (data.size() > 27)
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tele(data);
INFO_LOG(m_logger) << "Got telegram from "
<< tele.getSrcISSI()
<< " with size "
<< data.size()
<< " and payload size "
<< tele.getPayloadSize();
INFO_LOG(m_logger) << "Got telegram from " << tele.getSrcISSI() << " with size " << data.size() << " and payload size " << tele.getPayloadSize();
NGL::NGLLoggerHelper::hexDumpHelper(m_logger, NGL::LogLevel::Info, tele.data());
QFile f(m_outputDir + QStringLiteral("payload-%1-%2.dat").arg(QString::number(tele.getSrcISSI()), timeStr));
if (!f.open(QIODevice::WriteOnly))
{
ERROR_LOG(m_logger) << "Error opening file "
<< f.fileName()
<< " for writing - error: "
<< f.errorString();
ERROR_LOG(m_logger) << "Error opening file " << f.fileName() << " for writing - error: " << f.errorString();
}
// 27 Bytes Header entfernen
f.write(&data.data()[27], data.size() - 27);
@@ -423,15 +396,15 @@ void TetraIF::handleDataIndReq(const QByteArray &data)
switch (radioTelegram->getFragmentStatus())
{
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented:
handleLoginTelegram(radioTelegram);
break;
default:
ERROR_LOG(m_logger) << "Unknown payload-status!: " << radioTelegram->getFragmentStatus();
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_MiddleFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_LastFragment:
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_NotFragmented:
handleLoginTelegram(radioTelegram);
break;
default:
ERROR_LOG(m_logger) << "Unknown payload-status!: " << radioTelegram->getFragmentStatus();
break;
}
delete radioTelegram; // this deletes also a_data
@@ -452,7 +425,6 @@ void TetraIF::handleLoginTelegram(N_CoPrtCnv::CoPrtCnvRadioTelegram *a_loginTele
INFO_LOG(m_logger) << "Login: New TPU with Id=" << identity << " and ISSI=" << issi << " is NOT logged in";
}
}
bool TetraIF::sendLoginResponse(const uint32_t a_ISSI)
@@ -474,12 +446,12 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI)
a_telegram->setPayloadData(0x01);
a_telegram->setPayloadData(0x04);
// Bitanzahl anpassen
a_telegram->getData()[22] = 0x0d; // Warum 13 (bzw. 21) ??
a_telegram->getData()[22] = 0x0d; // Warum 13 (bzw. 21) ??
char *data = a_telegram->getData();
// Header - complete Payload in Bytes
data[02] = 0x18; // 24 Bytes
data[02] = 0x18; // 24 Bytes
// Len in Bits
data[22] = 0x0d;
data[23] = 0x00;
@@ -494,7 +466,6 @@ bool TetraIF::sendLoginResponse(const uint32_t a_ISSI)
m_socket->write(data, 28);
delete a_telegram;
return m_socket->flush();
}
void TetraIF::setupTimer()
@@ -32,8 +32,9 @@ protected Q_SLOTS:
void onReadyRead();
void onError(QAbstractSocket::SocketError);
void onSendData();
protected:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_logger;
void doInitialLogin();
void handleReceivedTelegram(const QByteArray &data);
void handleRegisterRsp(const uint8_t a_registrationStatus);
@@ -10,10 +10,9 @@
#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();
@@ -33,11 +32,11 @@ void MainWindow::changeEvent(QEvent *e)
QMainWindow::changeEvent(e);
switch (e->type())
{
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
@@ -70,7 +69,6 @@ void MainWindow::slot_findFolder()
QString name = QFileDialog::getExistingDirectory(this, tr("Choose folder"), QDir::homePath(), QFileDialog::DontResolveSymlinks);
ui->lineEditOrdner->setText(name);
ui->labelResult->setText(QString());
}
void MainWindow::slot_analysieren()
@@ -170,7 +168,6 @@ void MainWindow::readFiles()
writeToLogfile(issi, timeStart, getTimestamp(m_files[j]), m_files[j], nr);
writeLogZeiten(timeStart, getTimestamp(m_files[j]), issi);
}
}
file.close();
@@ -181,7 +178,6 @@ void MainWindow::readFiles()
ui->progressBar->setValue(int(val));
// ui->progressBar->repaint();
}
}
void MainWindow::openLogfile(const QString &folder, int count)
@@ -203,14 +199,9 @@ void MainWindow::openLogfile(const QString &folder, int count)
file.write("ISSI;Sending Time ; Receiving Time\n");
file.close();
}
}
void MainWindow::writeToLogfile(const QString &issi,
const QDateTime &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(": ");
@@ -235,11 +226,7 @@ void MainWindow::writeToLogfile(const QString &issi,
m_logfileList.append(info);
}
void MainWindow::writeToLogfile(const QString &issi,
const QDateTime &sendeZeit,
const QDateTime &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(": ");
@@ -269,7 +256,7 @@ QDateTime MainWindow::getTimestamp(const QString &filename) const
const auto list1 = filename.split(QLatin1Char('-'));
if (list1.size() < 2)
return {};
const QString &fn = list1.at(1);
const auto list2 = fn.split(QLatin1Char('.'));
auto str = list2.at(0);
@@ -284,7 +271,7 @@ QString MainWindow::getISSI(QByteArray ar)
ar.remove(0, 5);
ar.remove(4, 200);
QByteArray issi = ar.toHex();
if (ar.size() == 4)
{
if (ar[2] == '\0' && ar[3] == '\0')
@@ -299,7 +286,6 @@ QString MainWindow::getISSI(QByteArray ar)
hex[i] = c - '0';
else if (c >= 'a' && c <= 'f')
hex[i] = c - 'a' + 10;
}
int sum = 0;
sum += hex[1];
@@ -7,7 +7,7 @@
namespace Ui
{
class MainWindow;
class MainWindow;
}
struct LogfileInfo
@@ -41,17 +41,9 @@ private:
QString m_logfile;
QString m_logZeiten;
void openLogfile(const QString &folder, int count);
void writeToLogfile(const QString &issi,
const QDateTime &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); //Für alte TPUS
int auswerten();
QVector<uint> getFehlendeNums(const QVector<uint> &numsDurchgang);
int fehlendeNumsEintragen(const QVector<uint> &numList, QFile &file);
@@ -65,5 +57,4 @@ private slots:
};
#endif // MAINWINDOW_H
@@ -28,382 +28,362 @@
namespace PrtCnv
{
static std::string threadIdToString(PrtCnvApplication::E_ThreadId id)
{
switch (id)
static std::string threadIdToString(PrtCnvApplication::E_ThreadId id)
{
case PrtCnvApplication::e_Central:
return "Central";
case PrtCnvApplication::e_Radio:
return "Radio";
case PrtCnvApplication::e_Db:
return "Db";
case PrtCnvApplication::e_Log:
return "Log";
case PrtCnvApplication::e_Injection:
return "Injection";
case PrtCnvApplication::e_RadioTraffic:
return "RadioTraffic";
case PrtCnvApplication::e_ThreadIdMax:
break;
switch (id)
{
case PrtCnvApplication::e_Central:
return "Central";
case PrtCnvApplication::e_Radio:
return "Radio";
case PrtCnvApplication::e_Db:
return "Db";
case PrtCnvApplication::e_Log:
return "Log";
case PrtCnvApplication::e_Injection:
return "Injection";
case PrtCnvApplication::e_RadioTraffic:
return "RadioTraffic";
case PrtCnvApplication::e_ThreadIdMax:
break;
}
return std::to_string(id);
}
return std::to_string(id);
}
PrtCnvApplication::PrtCnvApplication()
: m_Config(nullptr)
, m_exerciseId(0)
, m_logger(getLogger("PrtCnvApplication"))
{}
PrtCnvApplication::~PrtCnvApplication()
{
delete m_Config;
for (const auto &ti : m_threadInfo)
delete ti.thread;
}
// ---------------------------------------------------------------
// Synchronisation of threads before create().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForCreate(const E_ThreadId a_threadId)
{
INFO_LOG(m_logger) << "Wait for others until we can create " << threadIdToString(a_threadId);
setConstructed(a_threadId);
switch (a_threadId)
PrtCnvApplication::PrtCnvApplication()
: m_Config(nullptr)
, m_exerciseId(0)
, m_logger(getLogger("PrtCnvApplication"))
{
case e_Central:
while (!(isConstructed(e_Db) &&
isConstructed(e_Radio) &&
isConstructed(e_Log) &&
isConstructed(e_Injection)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isConstructed(e_Db) &&
isConstructed(e_Central) &&
isConstructed(e_Log) &&
isConstructed(e_Injection)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Db:
while (!(isConstructed(e_Radio) &&
isConstructed(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
}
INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId);
}
// ---------------------------------------------------------------
// Synchronisation of threads before init().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForInit(E_ThreadId a_threadId)
{
INFO_LOG(m_logger) << "Wait for others until we can initialize " << threadIdToString(a_threadId);
setCreated(a_threadId);
switch (a_threadId)
PrtCnvApplication::~PrtCnvApplication()
{
case e_Central:
while (!(isCreated(e_Db) &&
isCreated(e_Radio)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isCreated(e_Db) &&
isCreated(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Db:
while (!(isCreated(e_Radio) &&
isCreated(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
delete m_Config;
for (const auto &ti : m_threadInfo)
delete ti.thread;
}
INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId);
}
// ---------------------------------------------------------------
// Synchronisation of threads before start().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForStart(E_ThreadId a_threadId)
{
INFO_LOG(m_logger) << "Wait for others until we can start " << threadIdToString(a_threadId);
setInitialized(a_threadId);
switch (a_threadId)
// ---------------------------------------------------------------
// Synchronisation of threads before create().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForCreate(const E_ThreadId a_threadId)
{
case e_Central:
while (!(isStarted(e_Db) &&
isInitialized(e_Radio) &&
isStarted(e_Log) &&
isStarted(e_Injection)))
INFO_LOG(m_logger) << "Wait for others until we can create " << threadIdToString(a_threadId);
setConstructed(a_threadId);
switch (a_threadId)
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Central:
while (!(isConstructed(e_Db) && isConstructed(e_Radio) && isConstructed(e_Log) && isConstructed(e_Injection)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isStarted(e_Db) &&
isInitialized(e_Central) &&
isStarted(e_Log) &&
isStarted(e_Injection) &&
isInitialized(e_RadioTraffic)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isConstructed(e_Db) && isConstructed(e_Central) && isConstructed(e_Log) && isConstructed(e_Injection)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Db:
while (!(isInitialized(e_Radio) &&
isInitialized(e_Central) &&
isStarted(e_Log)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
case e_Db:
while (!(isConstructed(e_Radio) && isConstructed(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
}
break;
case e_RadioTraffic:
while (!(isInitialized(e_Radio) &&
isStarted(e_Log)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
INFO_LOG(m_logger) << "Now we can create " << threadIdToString(a_threadId);
}
INFO_LOG(m_logger) << "Now we can start " << threadIdToString(a_threadId);
}
// ---------------------------------------------------------------
// Synchronisation of threads before execution of thread.
// ---------------------------------------------------------------
void PrtCnvApplication::waitForExec(E_ThreadId a_threadId)
{
setStarted(a_threadId);
}
// ---------------------------------------------------------------
// Starts the main-application
// ---------------------------------------------------------------
void PrtCnvApplication::startApp()
{
createApplication();
init();
start();
}
void PrtCnvApplication::shutdownApp()
{
stop();
deinit();
destroy();
for (const auto &ti : m_threadInfo)
ti.thread->quit();
for (const auto &ti : m_threadInfo)
ti.thread->wait();
for (auto &ti : m_threadInfo)
// ---------------------------------------------------------------
// Synchronisation of threads before init().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForInit(E_ThreadId a_threadId)
{
delete ti.thread;
ti.thread = nullptr;
INFO_LOG(m_logger) << "Wait for others until we can initialize " << threadIdToString(a_threadId);
setCreated(a_threadId);
switch (a_threadId)
{
case e_Central:
while (!(isCreated(e_Db) && isCreated(e_Radio)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isCreated(e_Db) && isCreated(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Db:
while (!(isCreated(e_Radio) && isCreated(e_Central)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
}
INFO_LOG(m_logger) << "Now we can initialize " << threadIdToString(a_threadId);
}
}
void PrtCnvApplication::setCleanDb(bool bCleanDb)
{
PrtCnvThread::m_DoCleanDb = bCleanDb;
}
void PrtCnvApplication::setExerciseId(int exerciseId)
{
m_exerciseId = exerciseId;
}
void PrtCnvApplication::setConfigFile(const QString &configFile)
{
m_ConfigFileName = configFile;
}
// ---------------------------------------------------------------
// Creates the childs
// ---------------------------------------------------------------
int32_t PrtCnvApplication::createApplication()
{
setName(QStringLiteral("Common"));
if (m_ConfigFileName.isEmpty())
// ---------------------------------------------------------------
// Synchronisation of threads before start().
// ---------------------------------------------------------------
void PrtCnvApplication::waitForStart(E_ThreadId a_threadId)
{
m_ConfigFileName = QCoreApplication::applicationDirPath();
if (m_exerciseId > 0)
m_ConfigFileName += QStringLiteral("/PrtCnv_ex_") + QString::number(m_exerciseId) + QStringLiteral(".dat");
else
m_ConfigFileName += QStringLiteral("/PrtCnv.dat");
INFO_LOG(m_logger) << "Wait for others until we can start " << threadIdToString(a_threadId);
setInitialized(a_threadId);
switch (a_threadId)
{
case e_Central:
while (!(isStarted(e_Db) && isInitialized(e_Radio) && isStarted(e_Log) && isStarted(e_Injection)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Radio:
while (!(isStarted(e_Db) && isInitialized(e_Central) && isStarted(e_Log) && isStarted(e_Injection) && isInitialized(e_RadioTraffic)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_Db:
while (!(isInitialized(e_Radio) && isInitialized(e_Central) && isStarted(e_Log)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
case e_RadioTraffic:
while (!(isInitialized(e_Radio) && isStarted(e_Log)))
{
DEBUG_LOG(m_logger) << "wait...";
QThread::sleep(1);
}
break;
default:
break;
}
INFO_LOG(m_logger) << "Now we can start " << threadIdToString(a_threadId);
}
m_Config = new NGL::Settings(m_ConfigFileName);
std::cout << "Use config-file: " << qPrintable(m_ConfigFileName) << std::endl;
for (int i = 0; i < e_ThreadIdMax; i++)
m_threadInfo[i].thread = new PrtCnvThreadStarter((E_ThreadId)i, m_ConfigFileName, this);
N_AppComponent::AppComponent::create(m_Config);
return 0;
}
// ---------------------------------------------------------------
// Starts the childs and then the main application
// ---------------------------------------------------------------
int32_t PrtCnvApplication::start()
{
// start and create threads
for (const auto &ti : m_threadInfo)
ti.thread->start();
N_AppComponent::AppComponent::start();
return 0;
}
// ---------------------------------------------------------------
// Returns the desired thread-starter
// ---------------------------------------------------------------
PrtCnv::PrtCnvThreadStarter *PrtCnvApplication::getThreadStarter(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return nullptr;
// ---------------------------------------------------------------
// Synchronisation of threads before execution of thread.
// ---------------------------------------------------------------
void PrtCnvApplication::waitForExec(E_ThreadId a_threadId)
{
setStarted(a_threadId);
}
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].thread;
}
// ---------------------------------------------------------------
// Starts the main-application
// ---------------------------------------------------------------
void PrtCnvApplication::startApp()
{
createApplication();
init();
start();
}
void PrtCnvApplication::setDatabaseConnectionParams(const QString &driver,
const QString &hostName,
const QString &database,
const QString &schemaName,
const QString &userName,
const QString &password)
{
m_dbDriver = driver;
m_dbHostName = hostName;
m_dbDatabaseName = database;
m_dbSchemaName = schemaName;
m_dbUserName = userName;
m_dbPassword = password;
}
void PrtCnvApplication::shutdownApp()
{
stop();
deinit();
destroy();
for (const auto &ti : m_threadInfo)
ti.thread->quit();
for (const auto &ti : m_threadInfo)
ti.thread->wait();
for (auto &ti : m_threadInfo)
{
delete ti.thread;
ti.thread = nullptr;
}
}
void PrtCnvApplication::logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele,
bool bIsSend)
{
const auto threadHandler = m_threadInfo[e_Log].thread;
PrtCnvTelegramLogThread *t = static_cast<PrtCnvTelegramLogThread*>(threadHandler ? threadHandler->getThread() : nullptr);
if (t)
t->writeWlsTelegramLog(tele, bIsSend, 0);
}
void PrtCnvApplication::setCleanDb(bool bCleanDb)
{
PrtCnvThread::m_DoCleanDb = bCleanDb;
}
// ---------------------------------------------------------------
bool PrtCnvApplication::isConstructed(const E_ThreadId a_threadId) const
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return false;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].isConstructed;
}
void PrtCnvApplication::setExerciseId(int exerciseId)
{
m_exerciseId = exerciseId;
}
// ---------------------------------------------------------------
void PrtCnvApplication::setConstructed(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return;
QMutexLocker l(&m_accessMutex);
m_threadInfo[a_threadId].isConstructed = true;
}
void PrtCnvApplication::setConfigFile(const QString &configFile)
{
m_ConfigFileName = configFile;
}
// ---------------------------------------------------------------
bool PrtCnvApplication::isInitialized(const E_ThreadId a_threadId) const
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return false;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].isInitialized;
}
// ---------------------------------------------------------------
// Creates the childs
// ---------------------------------------------------------------
int32_t PrtCnvApplication::createApplication()
{
setName(QStringLiteral("Common"));
if (m_ConfigFileName.isEmpty())
{
m_ConfigFileName = QCoreApplication::applicationDirPath();
if (m_exerciseId > 0)
m_ConfigFileName += QStringLiteral("/PrtCnv_ex_") + QString::number(m_exerciseId) + QStringLiteral(".dat");
else
m_ConfigFileName += QStringLiteral("/PrtCnv.dat");
}
m_Config = new NGL::Settings(m_ConfigFileName);
std::cout << "Use config-file: " << qPrintable(m_ConfigFileName) << std::endl;
// ---------------------------------------------------------------
void PrtCnvApplication::setInitialized(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return;
QMutexLocker l(&m_accessMutex);
m_threadInfo[a_threadId].isInitialized = true;
}
for (int i = 0; i < e_ThreadIdMax; i++)
m_threadInfo[i].thread = new PrtCnvThreadStarter((E_ThreadId)i, m_ConfigFileName, this);
// ---------------------------------------------------------------
bool PrtCnvApplication::isCreated(const E_ThreadId a_threadId) const
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return false;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].isCreated;
}
N_AppComponent::AppComponent::create(m_Config);
// ---------------------------------------------------------------
void PrtCnvApplication::setCreated(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return;
QMutexLocker l(&m_accessMutex);
m_threadInfo[a_threadId].isCreated = true;
}
return 0;
}
// ---------------------------------------------------------------
bool PrtCnvApplication::isStarted(const E_ThreadId a_threadId) const
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return false;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].isStarted;
}
// ---------------------------------------------------------------
// Starts the childs and then the main application
// ---------------------------------------------------------------
int32_t PrtCnvApplication::start()
{
// start and create threads
for (const auto &ti : m_threadInfo)
ti.thread->start();
// ---------------------------------------------------------------
void PrtCnvApplication::setStarted(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return;
QMutexLocker l(&m_accessMutex);
m_threadInfo[a_threadId].isStarted = true;
}
N_AppComponent::AppComponent::start();
return 0;
}
// ---------------------------------------------------------------
// Returns the desired thread-starter
// ---------------------------------------------------------------
PrtCnv::PrtCnvThreadStarter *PrtCnvApplication::getThreadStarter(const E_ThreadId a_threadId)
{
if (a_threadId < e_Central || a_threadId >= e_ThreadIdMax)
return nullptr;
QMutexLocker l(&m_accessMutex);
return m_threadInfo[a_threadId].thread;
}
void PrtCnvApplication::setDatabaseConnectionParams(const QString &driver,
const QString &hostName,
const QString &database,
const QString &schemaName,
const QString &userName,
const QString &password)
{
m_dbDriver = driver;
m_dbHostName = hostName;
m_dbDatabaseName = database;
m_dbSchemaName = schemaName;
m_dbUserName = userName;
m_dbPassword = password;
}
void PrtCnvApplication::logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool bIsSend)
{
const auto threadHandler = m_threadInfo[e_Log].thread;
PrtCnvTelegramLogThread *t = static_cast<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;
}
} // namespace PrtCnv
@@ -37,11 +37,12 @@ namespace PrtCnv
* @version 1.0
* @created 23-Jun-2009 17:48:47
*/
class PRTCNVLIB_EXPORT PrtCnvApplication : public QObject, public N_AppComponent::AppComponent
class PRTCNVLIB_EXPORT PrtCnvApplication
: public QObject
, public N_AppComponent::AppComponent
{
Q_OBJECT
public:
/**
* This enum will be used to unique identify the threads
*
@@ -112,7 +113,7 @@ namespace PrtCnv
* @param a_threadId Id of the desired thread-started (corresponding thread has
* the same id)
*/
PrtCnvThreadStarter* getThreadStarter(const E_ThreadId a_threadId);
PrtCnvThreadStarter *getThreadStarter(const E_ThreadId a_threadId);
/**
* @brief Set the database connection parameter when used as library
@@ -130,15 +131,16 @@ namespace PrtCnv
QString databaseUserName() const { return m_dbUserName; }
QString databasePassword() const { return m_dbPassword; }
public slots:
public slots:
void logWlsTelegram(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool bIsSend);
signals:
signals:
void textMessageFromPrtCnvToCentral(const QByteArray &ba);
void textMessageFromCentralToPrtCnv(const QByteArray &ba);
void outgoingBroadcastTelegramsRequest(int equipmentNumber, int broadcastIndex, int resetCounter);
void warehouseMessageFromPtrCnv(const QByteArray &jsonData);
protected:
protected:
/**
* Creates the childs
*/
@@ -188,7 +190,7 @@ protected:
*/
void setStarted(const E_ThreadId a_threadId);
protected:
protected:
/**
* Used to get configuration-parameter
*/
@@ -211,7 +213,6 @@ protected:
*/
int m_exerciseId;
mutable QRecursiveMutex m_accessMutex;
@@ -223,6 +224,6 @@ protected:
QString m_dbPassword;
NGL::INGLLogger &m_logger;
};
};
}
File diff suppressed because it is too large. Load diff
@@ -29,7 +29,7 @@
namespace N_CoPrtCnv
{
class CoPrtCnvRadioTelegram;
class CoPrtCnvRadioTelegram;
}
#define MAX_BROADCAST_INDEX 65535
@@ -37,9 +37,9 @@ class CoPrtCnvRadioTelegram;
namespace PrtCnv
{
class PrtCnvDbThread;
class PrtCnvDbThread;
/**
/**
* This class is responsible for handling all the broadcast stuff. This includes:
* - sending the broadcast 3 times
* - sending Broadcast-Nachforderungen to TNE
@@ -49,45 +49,44 @@ class PrtCnvDbThread;
* @version 1.0
* @updated 30-Apr-2010 11:21:05
*/
class PrtCnvBroadcastMgr final : public QObject
{
Q_OBJECT
public:
/**
class PrtCnvBroadcastMgr final : public QObject
{
Q_OBJECT
public:
/**
* The different states the broadcast-manager can be.
* @author wia
* @version 1.0
* @updated 30-Apr-2010 11:21:05
*/
enum E_State
{
e_ST_UNDEFINED,
e_ST_COLLECT,
e_ST_SEND_NACHFORDERUNG
};
enum E_State
{
e_ST_UNDEFINED,
e_ST_COLLECT,
e_ST_SEND_NACHFORDERUNG
};
PrtCnvBroadcastMgr();
PrtCnvBroadcastMgr();
/**
/**
* returns true when the telegram should be sent to central
*
* @param a_radioTelegram
*/
bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
bool handleRadioTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram);
/**
/**
* Creates all subcomponents
*/
int32_t create(NGL::Settings *settings);
int32_t create(NGL::Settings *settings);
/**
/**
* Initializes the variables.
*/
int32_t init();
int32_t init();
/**
/**
* returns the next normal broadcast to send.
* a_doDelete is true, when the caller has to delete the telegram when no longer
* using it.
@@ -97,62 +96,61 @@ public:
* @param a_actualTime
* @param a_doDelete true if telegram must be deleted after using it
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextBroadcastTelegramToSend(const uint16_t a_beginSearchWithBroadcastIndex,
const time_t a_currentTime);
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);
void setDbThread(PrtCnvDbThread *a_dbThread);
/**
/**
* Initializes the broadcast-manager. If a_deleteTelegrams is true, all stored
* telegrams and maps will be deleted.
*
* @param a_deleteTelegrams
*/
void cleanAndInit(const bool a_deleteTelegrams);
void cleanAndInit(const bool a_deleteTelegrams);
/**
/**
* Removes all Nop out of broadcast-list and numerates the broadcast-index of kept
* broadcast-telegrams new.
*
* @param a_doRestore
*/
void handleOverrunOfBroadcastCounter(const bool a_doRestore = false);
void handleOverrunOfBroadcastCounter(const bool a_doRestore = false);
/**
/**
* returns the next broadcast to send for nachforderungen
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextNachforderungTelegramToSend();
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNextNachforderungTelegramToSend();
/**
/**
* dumps important values, only for debugging
*/
void dump();
void dump();
/**
/**
* Restores data after crash for seamless proceeding of work.
*/
void restoreAfterCrash();
void restoreAfterCrash();
/**
/**
* Returns the actual broadcast-index for normal broadcasts.
*/
uint16_t getBroadcastIndex() const;
uint16_t getBroadcastIndex() const;
/**
/**
* Returns the broadcastindex for the next broadcast
*/
uint16_t getNextBroadcastIndex();
uint16_t getNextBroadcastIndex();
/**
/**
* Adds the telegram a_broadcastOnlyTelegram (which must have set already the
* broadcast-index) to the broadcast-map. The telegram will be attached to an
* already existing broadcast-telegram with same broadcast-index in the map,
@@ -162,152 +160,156 @@ public:
*
* @param a_broadcastOnlyTelegram
*/
void addBroadcastOnlyTelegramToMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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);
void incTickAndSetTrafficLoad(const bool a_isHighLoad, const bool a_isFullLoad);
/**
/**
* Checks if the given id is in m_deactivatedAesMine2bcIndex/m_deactivatedDusMine2bcIndex/m_deactivatedFuncAreaMine2bcIndex
*
* @brief isEffectSimulationIdDeactivated
* @param effectsimulationId
* @return
*/
bool isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const;
bool isEffectSimulationIdDeactivated(const uint16_t effectsimulationId) const;
/**
/**
* Adds the TNE to the nachforderungs-list
*
* @param a_radioTelegram
*/
void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter);
void handleNachforderungBroadcastTelegram(int identity, int broadcastIndex, int resetCounter);
protected:
struct EquipNoBcIndex
{
int equipNo = 0;
int bcIndex = 0;
protected:
struct EquipNoBcIndex
{
int equipNo = 0;
int bcIndex = 0;
EquipNoBcIndex() = default;
EquipNoBcIndex(int e, int b) : equipNo(e), bcIndex(b) {}
};
/**
EquipNoBcIndex() = default;
EquipNoBcIndex(int e, int b)
: equipNo(e)
, bcIndex(b)
{
}
};
/**
* Map of TNE, that sent a NachforderungBroadcast-Telegram.
* Key: identity of TNE; Value: broadcast-counter
*/
std::vector<EquipNoBcIndex> m_claimerArray;
/**
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;
/**
uint16_t m_ClaimWindow;
/**
* the factor for widening claim-window before sending broadcasts when we have
* high load traffic
*/
uint16_t m_HighLoadFactor;
/**
uint16_t m_HighLoadFactor;
/**
* the number of TPUs needed for sending the broadcasts as broadcast instead
* directed
*/
uint16_t m_BroadcastLimit;
/**
uint16_t m_BroadcastLimit;
/**
* Used to get configuration-parameter.
*/
NGL::Settings *m_Config;
/**
NGL::Settings *m_Config;
/**
* Actual time (in SendGap-ticks) spent for collection NachforderungeBroadcast,
* before sending broadcasts begins. This value changes depending on downlink-load.
*/
uint16_t m_ActClaimWindow;
/**
uint16_t m_ActClaimWindow;
/**
* The state of broadcast-manager.
*/
PrtCnvBroadcastMgr::E_State m_State;
uint16_t m_TickCounter;
/**
PrtCnvBroadcastMgr::E_State m_State;
uint16_t m_TickCounter;
/**
* The actual broadcast-index for sending nachforderungen
*/
PrtCnvDbThread *m_DbThread;
PrtCnvDbThread *m_DbThread;
/**
/**
* sorted by broadcast-index
*/
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_BroadcastMap;
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_BroadcastMap;
std::vector<std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_broadcastTelegamsToSend;
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;
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;
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;
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;
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;
std::map<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>> m_TechnikFunktionsraumTelegramMap;
/**
/**
* The actual broadcast-index for normal broadcast
*/
uint16_t m_BroadcastIndex;
uint16_t m_BroadcastIndex;
/**
/**
* True if send-traffic is on full-load => no nachforderungen will be sent
*/
bool m_IsFullLoad;
/**
bool m_IsFullLoad;
/**
* The highest broadcast-index of 3rd time sent broadcast-telegram (for optimize
* by time)
*/
uint16_t m_FinishedBroadcastIndex;
/**
uint16_t m_FinishedBroadcastIndex;
/**
* The broadcast-index of the 1st broadcast-telegram which has been sent 1 time
* only (for optimize by time)
*/
uint16_t m_FirstBroadcastIndexOfBc1;
uint16_t m_FirstBroadcastIndexOfBc1;
/**
/**
* adds the radio-telegram to the broadcast-map, or generates the sammeltelegramme
*
* @param a_radioTelegram
*/
void addToBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &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
@@ -319,19 +321,18 @@ protected:
*
* @param a_broadcastIndex
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNachforderungsTelegram(int curBcIndex, int startBcIndex, int &nextBcIndex);
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;
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.
@@ -342,11 +343,11 @@ protected:
* @param a_newBroadcastIndex The new broadcast-index
* @param a_attachTelegram The telegram to be attached
*/
void moveTelegramInBroadcastMap(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram,
const uint16_t a_newBroadcastIndex,
const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_attachTelegram = {});
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.
@@ -358,47 +359,47 @@ protected:
* @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);
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;
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 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 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 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);
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
@@ -412,40 +413,40 @@ protected:
* @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);
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);
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);
std::string dumpSammeldeaktivierung(const N_CoPrtCnv::CoPrtCnvRadioTelegram *sammelTelegram);
/**
/**
* Gets the braodcast-telegrams from Db, which were sent 1st time and adds them to
* the maps. Expired telegrams will be removed.
*
* @param a_doRestore
*/
void getAllFinishedBroadcastsFromDb(const bool a_doRestore = false);
void getAllFinishedBroadcastsFromDb(const bool a_doRestore = false);
/**
/**
* Takes expired wirkfeld-telegrams out of maps.
*/
void removeExpiredTelegrams();
void removeExpiredTelegrams();
/**
/**
* Removes the wirkfeld-telegrams with this kennung from the by time and by
* kennung maps.
* Replace this telegrams with Nop in BC-list.
@@ -453,9 +454,9 @@ protected:
*
* @param a_kennung
*/
void removeWirkfeldTelegrams(const uint16_t a_kennung);
void removeWirkfeldTelegrams(const uint16_t a_kennung);
/**
/**
* adds the wirkfeld-telegram to the by time and by kennung maps
*
* @param a_radioTelegram
@@ -463,11 +464,12 @@ protected:
* @param a_telId
* @param a_minenKennung
*/
void addWirkfeldTelegram(const std::shared_ptr<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);
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.
@@ -478,16 +480,16 @@ protected:
* @param a_minenKennung
* @param a_broadcastIndex
*/
bool deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex);
bool deactivateEinzelmineFromMinensperre(const uint16_t a_wirkfeldKennung, const uint16_t a_minenKennung, const uint16_t a_broadcastIndex);
/**
/**
* Returns a NOP-telegramm filled with the desired values.
*
* @param a_from
* @param a_to
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> getNopTelegram(const uint16_t a_from, const uint16_t 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.
@@ -497,16 +499,16 @@ protected:
* @param a_radioTelegram
* @param a_doDeleteTelegram
*/
void removeFromAllMaps(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
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);
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.
@@ -516,10 +518,10 @@ protected:
*
* @param a_funktionsraumKennung
*/
void removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
void removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
void removeFromFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
void removeFromTechnikFunktionsAndBroadcastMaps(const uint16_t a_funktionsraumKennung);
/**
/**
* Removes the telegram where wirkfeldTelegramMapByKennungIterator points to from
* wirkfeld-maps and from the broadcast-map.
* If the telegram is a attached BC-only-telegram, it will be detached.
@@ -529,43 +531,44 @@ protected:
*
* @param a_wirkfeldTelegramMapByKennungIterator
*/
void removeFromWirkfeldAndBroadcastMaps(const std::multimap<uint16_t, std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram>>::iterator &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);
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);
void deactivateSingleMine(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram);
/**
/**
* Prepares values for start sending nachforderungen
*/
void prepareForSendNachforderungen();
void prepareForSendNachforderungen();
/**
/**
* returns the next nachforderung to send and prepares collecting window if no
* more nachforderungen are to be sent
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> evaluateNextNachforderungToSend();
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> evaluateNextNachforderungToSend();
Q_SIGNALS:
void areaEffectSimulationActivated(int wirkfeldKennung);
void areaEffectSimulationDeactivated(int wirkfeldKennung);
Q_SIGNALS:
void areaEffectSimulationActivated(int wirkfeldKennung);
void areaEffectSimulationDeactivated(int wirkfeldKennung);
private:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_loggerBcRequest;
};
private:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_loggerBcRequest;
};
}
File diff suppressed because it is too large. Load diff
@@ -40,9 +40,7 @@ namespace PrtCnv
{
Q_OBJECT
private:
private:
public:
/**
* @author wia
@@ -54,7 +52,7 @@ private:
/**
* @param a_parent The pointer to the starter-thread
*/
explicit PrtCnvCentralThread(PrtCnvThreadStarter* a_parent);
explicit PrtCnvCentralThread(PrtCnvThreadStarter *a_parent);
/**
* Creates all subcomponents and connects signals to slots
*/
@@ -192,8 +190,7 @@ private:
* @param a_telegram The central-telegram to be sent.
* @param a_handle The handle assigned to telegram to be sent, we got from Db.
*/
void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram,
PrtCnvStoredCentralTelegram *a_handle);
void sendTelegram(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram, PrtCnvStoredCentralTelegram *a_handle);
/**
* Processes the telegram AnforderungStatistikBroadcastNachforderugen. The
* function fills the answer telegram StatistikBroadNachforderungen with the
File diff suppressed because it is too large. Load diff
@@ -37,7 +37,7 @@ namespace PrtCnv
class PrtCnvStoredCentralTelegram;
class PrtCnvStoredRadioTelegram;
class PrtCnvMember;
/**
/**
* Handles all data which must be stored permanent:
* - central-telegrams
* - radio-telegrams
@@ -65,7 +65,7 @@ namespace PrtCnv
const QString &schemaName,
const QString &dbUserName,
const QString &dbPassword,
PrtCnvThreadStarter* a_parent);
PrtCnvThreadStarter *a_parent);
~PrtCnvDbThread();
/**
@@ -100,7 +100,7 @@ namespace PrtCnv
*
* @param a_handle
*/
N_CoPrtCnv::CoPrtCnvCentralTelegram *getNextCentralTelegram(PrtCnvStoredCentralTelegram *& a_handle);
N_CoPrtCnv::CoPrtCnvCentralTelegram *getNextCentralTelegram(PrtCnvStoredCentralTelegram *&a_handle);
/**
* Marks the central-telegram as to be sent
@@ -158,8 +158,7 @@ namespace PrtCnv
* @param a_radioTelegram Must be the same telegram like the central-telegram
* (used for storing the telegram in Db)
*/
void storeCentralTelegram(const std::shared_ptr<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.
@@ -220,14 +219,14 @@ namespace PrtCnv
*
* @param a_ISSI
*/
PrtCnvMember* getMemberByISSI(const uint32_t a_ISSI) const;
PrtCnvMember *getMemberByISSI(const uint32_t a_ISSI) const;
/**
* returns NULL if member not found
*
* @param a_id
*/
PrtCnvMember* getMemberById(const uint16_t a_id);
PrtCnvMember *getMemberById(const uint16_t a_id);
/**
* Licenses the member
@@ -249,14 +248,14 @@ namespace PrtCnv
* @param a_identity
* @param a_ISSI
*/
PrtCnvMember* addMember(const int a_identity, const int a_ISSI);
PrtCnvMember *addMember(const int a_identity, const int a_ISSI);
/**
* removes the member in the 2 maps, sorted by id and ISSI
*
* @param a_member
*/
void removeMember(PrtCnvMember* a_member);
void removeMember(PrtCnvMember *a_member);
/**
* Returns the actual reset-counter
@@ -349,17 +348,14 @@ namespace PrtCnv
/**
* List of telegrams to be sent to central
*/
std::vector<PrtCnvStoredCentralTelegram*> m_CentralList;
std::vector<PrtCnvStoredCentralTelegram *> m_CentralList;
mutable QRecursiveMutex m_BattleFieldOpStateMutex;
mutable QRecursiveMutex m_MemberListByIdMutex;
mutable QRecursiveMutex m_CentralListMutex;
@@ -380,22 +376,22 @@ namespace PrtCnv
/**
* List of telegrams to be sent to radio
*/
std::list<PrtCnvStoredRadioTelegram*> m_RadioList;
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
@@ -408,11 +404,11 @@ namespace PrtCnv
/**
* Holds all logged in members ordered by Id.
*/
std::unordered_map<int,PrtCnvMember*> m_MemberListById;
std::unordered_map<int, PrtCnvMember *> m_MemberListById;
/**
* Holds all logged in members ordered by ISSI
*/
std::unordered_map<int,PrtCnvMember*> m_MemberListByISSI;
std::unordered_map<int, PrtCnvMember *> m_MemberListByISSI;
/**
* Used to prevent data storing within DB while restoring after crash
*/
@@ -429,7 +425,7 @@ namespace PrtCnv
/**
* The actual telegram "Umgebungsmeldung"
*/
PrtCnvStoredRadioTelegram* m_EnvironmentTelegram;
PrtCnvStoredRadioTelegram *m_EnvironmentTelegram;
/**
* True if cleanup has to be proceed after crash.
*/
@@ -537,9 +533,9 @@ namespace PrtCnv
// note: std::vector.clear() does not release memory and therefore
// a reallocation in the next turn is not neccessary
std::vector<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;
@@ -22,64 +22,63 @@
namespace PrtCnv
{
PrtCnvInjectionSocket::PrtCnvInjectionSocket()
: m_Socket(nullptr)
, m_Server(nullptr)
, m_logger(getLogger("PrtCnvInjectionSocket"))
{}
PrtCnvInjectionSocket::~PrtCnvInjectionSocket()
{
delete m_Socket;
}
// ---------------------------------------------------------------
// Disconnects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::disconnectClient()
{
INFO_LOG(m_logger) << "A client has disconnected from the injection-server";
emit disconnected(this);
}
// ---------------------------------------------------------------
// Reads in TCP-data and handles them
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::processInputData()
{
INFO_LOG(m_logger) << "Injection-server has data received";
N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader;
qint64 bytesRead = m_Socket->peek((char*)&injectionHeader, sizeof(injectionHeader));
if (sizeof(injectionHeader) == bytesRead)
PrtCnvInjectionSocket::PrtCnvInjectionSocket()
: m_Socket(nullptr)
, m_Server(nullptr)
, m_logger(getLogger("PrtCnvInjectionSocket"))
{
if (injectionHeader.isIdCorrect())
}
PrtCnvInjectionSocket::~PrtCnvInjectionSocket()
{
delete m_Socket;
}
// ---------------------------------------------------------------
// Disconnects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::disconnectClient()
{
INFO_LOG(m_logger) << "A client has disconnected from the injection-server";
emit disconnected(this);
}
// ---------------------------------------------------------------
// Reads in TCP-data and handles them
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::processInputData()
{
INFO_LOG(m_logger) << "Injection-server has data received";
N_CoPrtCnv::CoPrtCnvInjectionHeader injectionHeader;
qint64 bytesRead = m_Socket->peek((char *)&injectionHeader, sizeof(injectionHeader));
if (sizeof(injectionHeader) == bytesRead)
{
// check whether all bytes are available
qint64 available = m_Socket->bytesAvailable();
if (available < qint64(injectionHeader.m_Size + sizeof(injectionHeader)))
{
INFO_LOG(m_logger) << "not enough bytes available - waiting for more data: "
<< "headersize=" << sizeof(injectionHeader) << " id1="
<< injectionHeader.m_Id1 << " id2=" << injectionHeader.m_Id2
<< " kind=" << (int)injectionHeader.m_Kind << " size="
<< injectionHeader.m_Size;
return; // try it later, when (maybe) enough bytes are available...
}
// enough bytes => read now all in
m_Socket->read((char*)&injectionHeader, sizeof(injectionHeader));
if (injectionHeader.isIdCorrect())
{
//INFO_LOG(m_logger) << "kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size;
// read the data
QByteArray data(injectionHeader.m_Size, Qt::Uninitialized);
m_Socket->read(data.data(), injectionHeader.m_Size);
switch (injectionHeader.m_Kind)
// check whether all bytes are available
qint64 available = m_Socket->bytesAvailable();
if (available < qint64(injectionHeader.m_Size + sizeof(injectionHeader)))
{
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral:
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio:
INFO_LOG(m_logger) << "not enough bytes available - waiting for more data: "
<< "headersize=" << sizeof(injectionHeader) << " id1=" << injectionHeader.m_Id1 << " id2=" << injectionHeader.m_Id2
<< " kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size;
return; // try it later, when (maybe) enough bytes are available...
}
// enough bytes => read now all in
m_Socket->read((char *)&injectionHeader, sizeof(injectionHeader));
if (injectionHeader.isIdCorrect())
{
//INFO_LOG(m_logger) << "kind=" << (int)injectionHeader.m_Kind << " size=" << injectionHeader.m_Size;
// read the data
QByteArray data(injectionHeader.m_Size, Qt::Uninitialized);
m_Socket->read(data.data(), injectionHeader.m_Size);
switch (injectionHeader.m_Kind)
{
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eCentral:
case N_CoPrtCnv::CoPrtCnvInjectionHeader::eRadio:
{
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = new N_CoPrtCnv::CoPrtCnvCentralTelegram(data);
@@ -97,31 +96,31 @@ void PrtCnvInjectionSocket::processInputData()
}
break;
default:
ERROR_LOG(m_logger) << "Unknown kind (" << injectionHeader.m_Kind << ") of injection-telegram";
break;
default:
ERROR_LOG(m_logger) << "Unknown kind (" << injectionHeader.m_Kind << ") of injection-telegram";
break;
}
}
}
}
else
{
ERROR_LOG(m_logger) << "Corrupt injection-telegram received => reconnect";
m_Socket->disconnectFromHost();
else
{
ERROR_LOG(m_logger) << "Corrupt injection-telegram received => reconnect";
m_Socket->disconnectFromHost();
}
}
}
}
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::setSocket(QTcpSocket* a_socket, PrtCnvInjectionThread* a_server)
{
m_Socket = a_socket;
m_Server = a_server;
connect(this, &PrtCnvInjectionSocket::disconnected, m_Server, &PrtCnvInjectionThread::disconnectClient, Qt::QueuedConnection);
if (m_Socket)
// ---------------------------------------------------------------
void PrtCnvInjectionSocket::setSocket(QTcpSocket *a_socket, PrtCnvInjectionThread *a_server)
{
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection);
m_Socket = a_socket;
m_Server = a_server;
connect(this, &PrtCnvInjectionSocket::disconnected, m_Server, &PrtCnvInjectionThread::disconnectClient, Qt::QueuedConnection);
if (m_Socket)
{
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvInjectionSocket::processInputData, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvInjectionSocket::disconnectClient, Qt::QueuedConnection);
}
}
}
} // namespace PrtCnv
@@ -10,7 +10,7 @@
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <QtCore/QObject>
@@ -21,7 +21,7 @@ class QTcpSocket;
namespace PrtCnv
{
class PrtCnvInjectionThread;
/**
/**
* Used for receiving the socket signals
*
* @author alois.wismer
@@ -32,7 +32,6 @@ namespace PrtCnv
{
Q_OBJECT
public:
PrtCnvInjectionSocket();
~PrtCnvInjectionSocket();
@@ -41,7 +40,7 @@ namespace PrtCnv
* @param a_socket
* @param a_server
*/
void setSocket(QTcpSocket* a_socket, PrtCnvInjectionThread* a_server);
void setSocket(QTcpSocket *a_socket, PrtCnvInjectionThread *a_server);
protected:
QTcpSocket *m_Socket;
@@ -67,9 +66,7 @@ namespace PrtCnv
*
* @param a_injectSocket
*/
void disconnected(PrtCnvInjectionSocket* a_injectSocket);
void disconnected(PrtCnvInjectionSocket *a_injectSocket);
};
}
@@ -23,160 +23,155 @@
namespace PrtCnv
{
// ---------------------------------------------------------------
PrtCnvInjectionThread::PrtCnvInjectionThread(PrtCnvThreadStarter* a_parent)
: PrtCnvThread(a_parent, "PrtCnvInjectionThread")
, m_Port(46666)
, m_Enabled(false)
, m_Server(nullptr)
, m_CentralListMutex(nullptr)
, m_RadioListMutex(nullptr)
{
m_Name = QStringLiteral("Injection");
}
PrtCnvInjectionThread::~PrtCnvInjectionThread()
{
delete m_CentralListMutex;
delete m_RadioListMutex;
}
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::create(NGL::Settings *settings)
{
INFO_LOG(m_logger) << "create";
PrtCnvThread::create(settings);
m_CentralListMutex = new QMutex;
m_RadioListMutex = new QMutex;
m_Enabled = m_Config->getBoolean(getName(), QStringLiteral("Enable"), false);
// prepare a tcp-server for simulating central
if (m_Enabled)
// ---------------------------------------------------------------
PrtCnvInjectionThread::PrtCnvInjectionThread(PrtCnvThreadStarter *a_parent)
: PrtCnvThread(a_parent, "PrtCnvInjectionThread")
, m_Port(46666)
, m_Enabled(false)
, m_Server(nullptr)
, m_CentralListMutex(nullptr)
, m_RadioListMutex(nullptr)
{
m_Server = new QTcpServer(this);
if (m_Server)
connect(m_Server, &QTcpServer::newConnection, this, &PrtCnvInjectionThread::connectClient, Qt::QueuedConnection);
m_Name = QStringLiteral("Injection");
}
return 0;
}
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::init()
{
INFO_LOG(m_logger) << "init";
PrtCnvThread::init();
m_Port = m_Config->getInteger(getName(), QStringLiteral("Port"), 46666);
return 0;
}
// ---------------------------------------------------------------
// Starts the thread and listen for TCP-clients
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::start()
{
INFO_LOG(m_logger) << "Start";
PrtCnvThread::start();
// start the TCP-server
if (m_Enabled)
PrtCnvInjectionThread::~PrtCnvInjectionThread()
{
m_Server->setMaxPendingConnections(1);
m_Server->listen(QHostAddress::Any, m_Port);
INFO_LOG(m_logger) << "Injection-Server is listening on port " << m_Port;
delete m_CentralListMutex;
delete m_RadioListMutex;
}
return 0;
}
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::create(NGL::Settings *settings)
{
INFO_LOG(m_logger) << "create";
PrtCnvThread::create(settings);
m_CentralListMutex = new QMutex;
m_RadioListMutex = new QMutex;
m_Enabled = m_Config->getBoolean(getName(), QStringLiteral("Enable"), false);
// prepare a tcp-server for simulating central
if (m_Enabled)
{
m_Server = new QTcpServer(this);
if (m_Server)
connect(m_Server, &QTcpServer::newConnection, this, &PrtCnvInjectionThread::connectClient, Qt::QueuedConnection);
}
return 0;
}
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::init()
{
INFO_LOG(m_logger) << "init";
PrtCnvThread::init();
m_Port = m_Config->getInteger(getName(), QStringLiteral("Port"), 46666);
// ---------------------------------------------------------------
// Connects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionThread::connectClient()
{
INFO_LOG(m_logger) << "A client has connected to the injection-server";
PrtCnvInjectionSocket* injectSocket = new PrtCnvInjectionSocket;
m_SocketList.insert(injectSocket);
INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected";
injectSocket->setSocket(m_Server->nextPendingConnection(), this);
}
return 0;
}
// ---------------------------------------------------------------
// Starts the thread and listen for TCP-clients
// ---------------------------------------------------------------
int32_t PrtCnvInjectionThread::start()
{
INFO_LOG(m_logger) << "Start";
PrtCnvThread::start();
// ---------------------------------------------------------------
// Disconnects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionThread::disconnectClient(PrtCnvInjectionSocket *a_injectionSocket)
{
auto it = m_SocketList.find(a_injectionSocket);
if (it != m_SocketList.end())
m_SocketList.erase(it);
INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected";
delete a_injectionSocket;
}
// start the TCP-server
if (m_Enabled)
{
m_Server->setMaxPendingConnections(1);
m_Server->listen(QHostAddress::Any, m_Port);
INFO_LOG(m_logger) << "Injection-Server is listening on port " << m_Port;
}
return 0;
}
// ---------------------------------------------------------------
// Returns the next central-telegram to be injected. It will
// automatically be taken out of the list.
// The caller is responsible to delete the telegram, if no
// longer used.
// Returns NULL if no central-telegram available
// ---------------------------------------------------------------
N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextCentralInjectionTelegram()
{
QMutexLocker l(m_CentralListMutex);
if (m_CentralTelegramList.empty())
return nullptr;
auto centralTelegram = m_CentralTelegramList.front();
m_CentralTelegramList.pop();
return centralTelegram;
}
// ---------------------------------------------------------------
// Connects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionThread::connectClient()
{
INFO_LOG(m_logger) << "A client has connected to the injection-server";
PrtCnvInjectionSocket *injectSocket = new PrtCnvInjectionSocket;
m_SocketList.insert(injectSocket);
INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected";
injectSocket->setSocket(m_Server->nextPendingConnection(), this);
}
// ---------------------------------------------------------------
// Returns the next radio-telegram to be injected. It will
// automatically be taken out of the list.
// The caller is responsible to delete the telegram, if no
// longer used.
// Returns NULL if no radio-telegram available
// ---------------------------------------------------------------
N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextRadioInjectionTelegram()
{
QMutexLocker l(m_RadioListMutex);
if (m_RadioTelegramList.empty())
return nullptr;
auto radioTelegram = m_RadioTelegramList.front();
m_RadioTelegramList.pop();
return radioTelegram;
}
// ---------------------------------------------------------------
// Disconnects a TCP-client
// ---------------------------------------------------------------
void PrtCnvInjectionThread::disconnectClient(PrtCnvInjectionSocket *a_injectionSocket)
{
auto it = m_SocketList.find(a_injectionSocket);
if (it != m_SocketList.end())
m_SocketList.erase(it);
INFO_LOG(m_logger) << "Now are " << m_SocketList.size() << " injection-client(s) connected";
delete a_injectionSocket;
}
// ---------------------------------------------------------------
void PrtCnvInjectionThread::addToCentralList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram)
{
QMutexLocker l(m_CentralListMutex);
m_CentralTelegramList.push(a_telegram);
}
// ---------------------------------------------------------------
// Returns the next central-telegram to be injected. It will
// automatically be taken out of the list.
// The caller is responsible to delete the telegram, if no
// longer used.
// Returns NULL if no central-telegram available
// ---------------------------------------------------------------
N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextCentralInjectionTelegram()
{
QMutexLocker l(m_CentralListMutex);
if (m_CentralTelegramList.empty())
return nullptr;
auto centralTelegram = m_CentralTelegramList.front();
m_CentralTelegramList.pop();
return centralTelegram;
}
// ---------------------------------------------------------------
void PrtCnvInjectionThread::addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram)
{
QMutexLocker l(m_RadioListMutex);
m_RadioTelegramList.push(a_telegram);
}
// ---------------------------------------------------------------
// Returns the next radio-telegram to be injected. It will
// automatically be taken out of the list.
// The caller is responsible to delete the telegram, if no
// longer used.
// Returns NULL if no radio-telegram available
// ---------------------------------------------------------------
N_CoPrtCnv::CoPrtCnvCentralTelegram *PrtCnvInjectionThread::getNextRadioInjectionTelegram()
{
QMutexLocker l(m_RadioListMutex);
if (m_RadioTelegramList.empty())
return nullptr;
auto radioTelegram = m_RadioTelegramList.front();
m_RadioTelegramList.pop();
return radioTelegram;
}
// ---------------------------------------------------------------
void PrtCnvInjectionThread::addToCentralList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram)
{
QMutexLocker l(m_CentralListMutex);
m_CentralTelegramList.push(a_telegram);
}
// ---------------------------------------------------------------
void PrtCnvInjectionThread::addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram)
{
QMutexLocker l(m_RadioListMutex);
m_RadioTelegramList.push(a_telegram);
}
} // namespace PrtCnv
@@ -10,7 +10,7 @@
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "PrtCnvThread.hpp"
@@ -22,13 +22,13 @@ class QMutex;
namespace N_CoPrtCnv
{
class CoPrtCnvCentralTelegram;
class CoPrtCnvCentralTelegram;
}
namespace PrtCnv
{
class PrtCnvInjectionSocket;
/**
/**
* This class represents a thread, which acts as TCP-Server. The LogView-
* application can connect to it and send radio- or central-telegrams. The
* telegrams will be stored within this class and can be taken by another thread.
@@ -42,14 +42,13 @@ namespace PrtCnv
{
Q_OBJECT
public:
~PrtCnvInjectionThread();
/**
*
* @param a_parent
*/
explicit PrtCnvInjectionThread(PrtCnvThreadStarter* a_parent);
explicit PrtCnvInjectionThread(PrtCnvThreadStarter *a_parent);
int32_t create(NGL::Settings *settings) override;
@@ -90,7 +89,7 @@ namespace PrtCnv
*/
void addToRadioList(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_telegram);
protected: /**
protected: /**
* The port of the injection-server (configurable with key 'Port' in group
* [Injection])
*/
@@ -111,22 +110,20 @@ namespace PrtCnv
QMutex *m_RadioListMutex;
std::set<PrtCnvInjectionSocket*> m_SocketList;
std::set<PrtCnvInjectionSocket *> m_SocketList;
public slots:
/**
/**
* Connects a TCP-client
*/
void connectClient();
/**
void connectClient();
/**
* Disconnects a TCP-client
*
* @param a_injectionSocket
*/
void disconnectClient(PrtCnvInjectionSocket* a_injectionSocket);
void disconnectClient(PrtCnvInjectionSocket *a_injectionSocket);
};
}
@@ -40,16 +40,18 @@ static void daemonize()
pid_t pid, sid;
/* already a daemon */
if ( getppid() == 1 )
if (getppid() == 1)
return;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
if (pid < 0)
{
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
if (pid > 0)
{
exit(EXIT_SUCCESS);
}
@@ -60,20 +62,20 @@ static void daemonize()
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
if (sid < 0)
{
exit(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
if ((chdir("/")) < 0)
{
exit(EXIT_FAILURE);
}
if (freopen( "/dev/null", "r", stdin ) == nullptr
|| freopen( "/dev/null", "w", stdout ) == nullptr
|| freopen( "/dev/null", "w", stderr ) == nullptr)
if (freopen("/dev/null", "r", stdin) == nullptr || freopen("/dev/null", "w", stdout) == nullptr || freopen("/dev/null", "w", stderr) == nullptr)
{
exit(EXIT_FAILURE);
}
@@ -84,25 +86,17 @@ class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser
{
public:
CmdLineParser()
: LtsCommandLineParser(ProvideCommandLineParameterOptions(ExerciseId|CustomConfigFile))
: LtsCommandLineParser(ProvideCommandLineParameterOptions(ExerciseId | CustomConfigFile))
{
addOption( { QStringList() << QStringLiteral("d") << QStringLiteral("daemonize"),
QStringLiteral("Start in background") } );
addOption( { QStringList() << QStringLiteral("c") << QStringLiteral("cleandb"),
QStringLiteral("Start over with clean database") } );
addOption({QStringList() << QStringLiteral("d") << QStringLiteral("daemonize"), QStringLiteral("Start in background")});
addOption({QStringList() << QStringLiteral("c") << QStringLiteral("cleandb"), QStringLiteral("Start over with clean database")});
}
bool daemonize() const
{
return isSet(QStringLiteral("d"));
}
bool cleanDb() const
{
return isSet(QStringLiteral("c"));
}
bool daemonize() const { return isSet(QStringLiteral("d")); }
bool cleanDb() const { return isSet(QStringLiteral("c")); }
};
int main(int argc, char** argv)
int main(int argc, char **argv)
{
QNetworkProxy::setApplicationProxy(QNetworkProxy());
NGLCoreApplication app(argc, argv);
@@ -1,16 +1,16 @@
// **************************************************************************
//
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
//
// **************************************************************************
//
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
//
// **************************************************************************
// manual class headers
#include "PrtCnvMember.hpp"
#include <CoPrtCnv/CoPrtCnvRadioTelegram.hpp>
@@ -18,81 +18,80 @@
namespace PrtCnv
{
// ---------------------------------------------------------------
// Constructor with id and ISSI as parameter
// ---------------------------------------------------------------
PrtCnvMember::PrtCnvMember(int a_id, int a_issi)
: m_ISSI(a_issi)
, m_ClaimCount(0)
, m_loggedInExerciseId(0)
, m_Id(a_id)
, m_Licensed(false)
{}
PrtCnvMember::~PrtCnvMember()
{
clearFragmentedList();
}
// ---------------------------------------------------------------
// Adds a radio-telegram-fragment to this member.
// ---------------------------------------------------------------
void PrtCnvMember::addFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram)
{
m_FragmentedTelegramList.insert(std::make_pair(a_radioTelegram.getFragmentCounter(),
new N_CoPrtCnv::CoPrtCnvRadioTelegram(a_radioTelegram)));
}
// ---------------------------------------------------------------
// Returns the telegram-Id of the fragmented telegram assiged
// to this member.
// If not evaluable: 0 will be returned.
// ---------------------------------------------------------------
gef_telegramm_id_et PrtCnvMember::getFragmentedTelegramId() const
{
// the fragment with the highest counter is the first fragment
for (auto rit = m_FragmentedTelegramList.rbegin(); rit != m_FragmentedTelegramList.rend(); ++rit)
// ---------------------------------------------------------------
// Constructor with id and ISSI as parameter
// ---------------------------------------------------------------
PrtCnvMember::PrtCnvMember(int a_id, int a_issi)
: m_ISSI(a_issi)
, m_ClaimCount(0)
, m_loggedInExerciseId(0)
, m_Id(a_id)
, m_Licensed(false)
{
N_CoPrtCnv::CoPrtCnvRadioTelegram *firstFragment = rit->second;
if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == firstFragment->getFragmentStatus())
return firstFragment->getTelID();
}
return GEF_BESTAETIGUNG; // no telegram found => return 0 (= GEF_BESTAETIGUNG)
}
PrtCnvMember::~PrtCnvMember()
{
clearFragmentedList();
}
// ---------------------------------------------------------------
// Erases the radio-telegram-fragments assiged to this member.
// The fragments itself will be deleted.
// ---------------------------------------------------------------
void PrtCnvMember::clearFragmentedList()
{
for (auto it : m_FragmentedTelegramList)
delete it.second;
m_FragmentedTelegramList.clear();
}
// ---------------------------------------------------------------
// Adds a radio-telegram-fragment to this member.
// ---------------------------------------------------------------
void PrtCnvMember::addFragmentedTelegram(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_radioTelegram)
{
m_FragmentedTelegramList.insert(std::make_pair(a_radioTelegram.getFragmentCounter(), new N_CoPrtCnv::CoPrtCnvRadioTelegram(a_radioTelegram)));
}
// ---------------------------------------------------------------
// Returns the radio-telegram-fragments assembled to a only
// big radio-telegram. The fragments will not be deleted.
// Returns NULL if it was impossible to assemble the telegram.
// ---------------------------------------------------------------
QByteArray PrtCnvMember::getUnfragmentedTelegramData() const
{
return N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(m_FragmentedTelegramList);
}
// ---------------------------------------------------------------
// Returns the telegram-Id of the fragmented telegram assiged
// to this member.
// If not evaluable: 0 will be returned.
// ---------------------------------------------------------------
gef_telegramm_id_et PrtCnvMember::getFragmentedTelegramId() const
{
// the fragment with the highest counter is the first fragment
for (auto rit = m_FragmentedTelegramList.rbegin(); rit != m_FragmentedTelegramList.rend(); ++rit)
{
N_CoPrtCnv::CoPrtCnvRadioTelegram *firstFragment = rit->second;
if (N_CoPrtCnv::CoPrtCnvRadioTelegram::e_FirstFragment == firstFragment->getFragmentStatus())
return firstFragment->getTelID();
}
return GEF_BESTAETIGUNG; // no telegram found => return 0 (= GEF_BESTAETIGUNG)
}
// ---------------------------------------------------------------
// Returns true if the fragment-list is empty
// ---------------------------------------------------------------
bool PrtCnvMember::isFragmentedListEmpty() const
{
return m_FragmentedTelegramList.empty();
}
// ---------------------------------------------------------------
// Erases the radio-telegram-fragments assiged to this member.
// The fragments itself will be deleted.
// ---------------------------------------------------------------
void PrtCnvMember::clearFragmentedList()
{
for (auto it : m_FragmentedTelegramList)
delete it.second;
m_FragmentedTelegramList.clear();
}
// ---------------------------------------------------------------
// Returns the radio-telegram-fragments assembled to a only
// big radio-telegram. The fragments will not be deleted.
// Returns NULL if it was impossible to assemble the telegram.
// ---------------------------------------------------------------
QByteArray PrtCnvMember::getUnfragmentedTelegramData() const
{
return N_CoPrtCnv::CoPrtCnvRadioTelegram::getUnfragmentedData(m_FragmentedTelegramList);
}
// ---------------------------------------------------------------
// Returns true if the fragment-list is empty
// ---------------------------------------------------------------
bool PrtCnvMember::isFragmentedListEmpty() const
{
return m_FragmentedTelegramList.empty();
}
} // namespace PrtCnv
@@ -10,7 +10,7 @@
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include <CoPrtCnv/tetra_telegram_ids.h>
@@ -37,7 +37,6 @@ namespace PrtCnv
class PrtCnvMember final
{
public:
/**
* The status of the member
* @author wia
@@ -102,7 +101,7 @@ namespace PrtCnv
private:
// Map of radio-telegram-fragments ordered by fragment-number
std::multimap<uint16_t,N_CoPrtCnv::CoPrtCnvRadioTelegram*> m_FragmentedTelegramList;
std::multimap<uint16_t, N_CoPrtCnv::CoPrtCnvRadioTelegram *> m_FragmentedTelegramList;
};
}
File diff suppressed because it is too large. Load diff
@@ -26,19 +26,19 @@
namespace PrtCnv
{
struct BiteError
{
int errorNumber = 0;
int canDeviceNumber = 0;
int subdeviceNumber = 0;
int uniqueId = 0;
};
struct BiteError
{
int errorNumber = 0;
int canDeviceNumber = 0;
int subdeviceNumber = 0;
int uniqueId = 0;
};
class PrtCnvCentralThread;
class PrtCnvMember;
class PrtCnvRadioTrafficThread;
class PrtCnvStoredRadioTelegram;
/**
/**
* This class handles the protocol to radio. This includes:
* - handle login and licensing of TNEs
* - send and receive normal telegrams
@@ -53,9 +53,8 @@ struct BiteError
{
Q_OBJECT
public:
PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter* a_parent);
public:
PrtCnvRadioThread(int exerciseId, PrtCnvThreadStarter *a_parent);
/**
* Creates all subcomponents and connects signals to slots
*/
@@ -86,12 +85,14 @@ public:
void sendEnvironmentTelegramTimerNow();
void exerciseEquipmentChanged(const TrainingAreaBase::TetraIcd::ExerciseEquipmentAssignmentComplete &data);
protected:
void onCheckMemberForValidLogin(int identity, int issi);
void sendLoginAccept(int identity, int issi, int exerciseId, bool bWithMastering);
bool isIdentityInCurrentExercise(int identity) const;
int exerciseIdForIdentity(int identity) const;
void removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram, PrtCnvMember *member,
void removeMasteringMember(const N_CoPrtCnv::CoPrtCnvRadioTelegram &a_loginTelegram,
PrtCnvMember *member,
PrtCnvMember *issiMember,
int masterIdentity,
int masterIssi);
@@ -107,8 +108,7 @@ public:
*/
PrtCnvRadioTrafficThread *m_radioTrafficThread;
public:
public:
Q_SIGNALS:
/**
* Signal to start sending a telegram to central
@@ -147,6 +147,7 @@ public:
// a player was (un)licensed
void playerLicencedChanged(int equipNo, N_CoPrtCnv::E_LicensingKind kind);
void warehouseMessageFromPtrCnv(const QByteArray &jsonData);
protected:
/**
* Counts the sended telegrams
@@ -250,7 +251,6 @@ public:
void handleRegisterRsp(const uint8_t a_regsitrationStatus);
public:
/**
* @author alois.wismer
* @version 1.0
@@ -263,6 +263,7 @@ public:
HighLoad,
FullLoad
};
protected:
/**
* Holds the radio-telegram for sending Umgebungsmeldung periodically
@@ -405,8 +406,7 @@ public:
uint32_t ergebnisAusstattung,
uint32_t aktuelleKonfiguration,
uint32_t konfigurationsvergleich,
const QList<PrtCnv::BiteError> &fehlerListe
);
const QList<PrtCnv::BiteError> &fehlerListe);
/**
* Sends a login-telegram to radio
@@ -417,7 +417,9 @@ public:
*/
void sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, const uint32_t a_ISSI);
void sendLoginResponse(const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_LoginStatus a_loginTelegramStatus,
const uint16_t a_identity, const uint32_t a_ISSI, const TrainingAreaBase::TetraIcd::GroupIssiInformation &group);
const uint16_t a_identity,
const uint32_t a_ISSI,
const TrainingAreaBase::TetraIcd::GroupIssiInformation &group);
/**
* Sends a telegram "LizenzierungTNE" to radio
@@ -427,7 +429,8 @@ public:
* @param a_licensingKind
* @param a_errorCause
*/
void sendLizenzierungTneToRadio(const uint16_t a_identity, const uint32_t a_issi,
void sendLizenzierungTneToRadio(const uint16_t a_identity,
const uint32_t a_issi,
const N_CoPrtCnv::E_LicensingKind a_licensingKind,
const N_CoPrtCnv::E_LicensingErrorCode a_errorCause);
@@ -453,7 +456,7 @@ public:
* @param a_line
* @param a_fileName
*/
uint16_t readIdentity(const QByteArray& a_idAsText, const uint32_t a_line, const QString& a_fileName);
uint16_t readIdentity(const QByteArray &a_idAsText, const uint32_t a_line, const QString &a_fileName);
/**
* Checks whether the playerId is allowd.
*
@@ -23,186 +23,183 @@
namespace PrtCnv
{
PrtCnvRadioTrafficThread::PrtCnvRadioTrafficThread(PrtCnvThreadStarter* a_parent)
: PrtCnvThread(a_parent, "PrtCnvRadioTrafficThread")
, m_receiveLoad(PrtCnvRadioThread::E_TrafficLoad::Unknown)
, m_fullLoad(100)
, m_highLoad(50)
, m_hystLoad(5)
, m_calcTimeout(1000)
, m_cleanupTimeout(5000)
, m_mutex()
{}
void PrtCnvRadioTrafficThread::newTelegramArrived(unsigned int size)
{
time_t curTime = time(nullptr);
QMutexLocker l(&m_mutex);
DEBUG_LOG(m_logger) << "newTelegramArrived with size " << size << " at " << curTime;
m_data[curTime] += size;
m_telegrams[curTime]++;
}
int32_t PrtCnvRadioTrafficThread::start()
{
// read data from m_Config
const QString trafficControlGroup(QStringLiteral("TrafficControl"));
int highLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHighLoad"), 60);
int fullLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueFullLoad"), 80);
int hystLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHysteresis"), 5);
int avgTime = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveAveragingTime"), 5);
float trafficPerReceiverKB = m_Config->getFloat(trafficControlGroup, QStringLiteral("ReceiveThroughput"), 3.6f);
int cntTransceiver = m_Config->getInteger(trafficControlGroup, QStringLiteral("TransceiverCount"), 6);
// sanity checks
if (highLoad < 0 || highLoad > 100)
highLoad = 60;
if (fullLoad < highLoad || fullLoad > 100)
fullLoad = 80;
if (hystLoad < 0 || hystLoad > 10)
hystLoad = 5;
if (avgTime <= 0 || avgTime > 60)
avgTime = 5;
if (trafficPerReceiverKB < 1 || trafficPerReceiverKB > 1000)
trafficPerReceiverKB = 3.6f;
if (cntTransceiver < 1 || cntTransceiver > 100)
cntTransceiver = 6;
float maxTrafficBytes = trafficPerReceiverKB * cntTransceiver * 1024;
m_fullLoad = maxTrafficBytes * fullLoad / 100.f;
m_highLoad = maxTrafficBytes * highLoad / 100.f;
m_hystLoad = maxTrafficBytes * hystLoad / 100.f;
m_cleanupTimeout = avgTime * 1000; // ms
DEBUG_LOG(m_logger) << "Read config ReceiveQueueHighLoad: " << highLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveQueueFullLoad: " << fullLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveQueueHysteresis: " << hystLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveAveragingTime: " << avgTime;
DEBUG_LOG(m_logger) << "Read config ReceiveThroughput: " << trafficPerReceiverKB;
DEBUG_LOG(m_logger) << "Read config TransceiverCount: " << cntTransceiver;
INFO_LOG(m_logger) << "Using to following limits: high - " << m_highLoad
<< " full - " << m_fullLoad
<< " hyst - " << m_hystLoad
<< " avg. time - " << m_cleanupTimeout / 1000;
QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad);
QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout);
return 0;
}
void PrtCnvRadioTrafficThread::onCalculateTrafficLoad()
{
const time_t curTime = time(nullptr);
unsigned int payload = 0;
PrtCnvRadioTrafficThread::PrtCnvRadioTrafficThread(PrtCnvThreadStarter *a_parent)
: PrtCnvThread(a_parent, "PrtCnvRadioTrafficThread")
, m_receiveLoad(PrtCnvRadioThread::E_TrafficLoad::Unknown)
, m_fullLoad(100)
, m_highLoad(50)
, m_hystLoad(5)
, m_calcTimeout(1000)
, m_cleanupTimeout(5000)
, m_mutex()
{
}
void PrtCnvRadioTrafficThread::newTelegramArrived(unsigned int size)
{
time_t curTime = time(nullptr);
QMutexLocker l(&m_mutex);
// fuer aktuelle Sekunde haben wir noch nicht alle Daten
for (int i = 1; i <= m_cleanupTimeout / 1000; ++i)
payload += m_data.value(curTime - i);
DEBUG_LOG(m_logger) << "newTelegramArrived with size " << size << " at " << curTime;
m_data[curTime] += size;
m_telegrams[curTime]++;
}
// Durchschnitt ...
payload /= (m_cleanupTimeout / 1000);
INFO_LOG(m_logger) << "Average Payload in the last "
<< m_cleanupTimeout << " Milliseconds: "
<< payload << " Bytes/sec, last sec: "
<< m_data[curTime - 1] << " Bytes, #telegrams: " << m_telegrams[curTime - 1];
PrtCnvRadioThread::E_TrafficLoad newReceiveLoad;
if (payload >= m_fullLoad)
int32_t PrtCnvRadioTrafficThread::start()
{
// full load
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad;
// Hysterese nach oben
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad)
{
// wenn cnt in Bereich m_fullLoad ... m_fullLoad + m_hystLoad
// -> noch warten
if(payload < m_fullLoad + m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
}
// read data from m_Config
const QString trafficControlGroup(QStringLiteral("TrafficControl"));
int highLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHighLoad"), 60);
int fullLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueFullLoad"), 80);
int hystLoad = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveQueueHysteresis"), 5);
int avgTime = m_Config->getInteger(trafficControlGroup, QStringLiteral("ReceiveAveragingTime"), 5);
float trafficPerReceiverKB = m_Config->getFloat(trafficControlGroup, QStringLiteral("ReceiveThroughput"), 3.6f);
int cntTransceiver = m_Config->getInteger(trafficControlGroup, QStringLiteral("TransceiverCount"), 6);
// sanity checks
if (highLoad < 0 || highLoad > 100)
highLoad = 60;
if (fullLoad < highLoad || fullLoad > 100)
fullLoad = 80;
if (hystLoad < 0 || hystLoad > 10)
hystLoad = 5;
if (avgTime <= 0 || avgTime > 60)
avgTime = 5;
if (trafficPerReceiverKB < 1 || trafficPerReceiverKB > 1000)
trafficPerReceiverKB = 3.6f;
if (cntTransceiver < 1 || cntTransceiver > 100)
cntTransceiver = 6;
float maxTrafficBytes = trafficPerReceiverKB * cntTransceiver * 1024;
m_fullLoad = maxTrafficBytes * fullLoad / 100.f;
m_highLoad = maxTrafficBytes * highLoad / 100.f;
m_hystLoad = maxTrafficBytes * hystLoad / 100.f;
m_cleanupTimeout = avgTime * 1000; // ms
DEBUG_LOG(m_logger) << "Read config ReceiveQueueHighLoad: " << highLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveQueueFullLoad: " << fullLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveQueueHysteresis: " << hystLoad;
DEBUG_LOG(m_logger) << "Read config ReceiveAveragingTime: " << avgTime;
DEBUG_LOG(m_logger) << "Read config ReceiveThroughput: " << trafficPerReceiverKB;
DEBUG_LOG(m_logger) << "Read config TransceiverCount: " << cntTransceiver;
INFO_LOG(m_logger) << "Using to following limits: high - " << m_highLoad << " full - " << m_fullLoad << " hyst - " << m_hystLoad << " avg. time - "
<< m_cleanupTimeout / 1000;
QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad);
QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout);
return 0;
}
else if (payload >= m_highLoad)
{
// high load
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
// Hysterese nach oben
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::NormalLoad)
{
// wenn cnt in Bereich m_highLoad ... m_highLoad + m_hystLoad
// -> noch warten
if (payload < m_highLoad + m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad;
}
// Hysterese nach unten
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::FullLoad)
{
// wenn cnt in Bereich m_fullLoad ... m_fullLoad - m_hystLoad
// -> noch warten
if (payload >= m_fullLoad - m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad;
}
}
else
{
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad;
// Hysterese nach unten
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad)
{
// wenn cnt in Bereich m_highLoad ... m_highLoad - m_hystLoad
// -> noch warten
if(payload >= m_highLoad - m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
}
}
if (m_receiveLoad != newReceiveLoad)
{
m_receiveLoad = newReceiveLoad;
// Achtung: Nicht mehr als 31 Sekunden erlaubt
unsigned int wartezeit_posmldg = (static_cast<unsigned int>(m_receiveLoad) * 10) + 1;
INFO_LOG(m_logger) << "New traffic load: " << m_receiveLoad;
PrtCnvDbThread *dbThread = qobject_cast<PrtCnvDbThread*>(m_Parent->getOtherThread(PrtCnvApplication::e_Db));
if (dbThread)
{
dbThread->setAirLoad(m_receiveLoad);
dbThread->setPositionSendTime(wartezeit_posmldg);
void PrtCnvRadioTrafficThread::onCalculateTrafficLoad()
{
const time_t curTime = time(nullptr);
Q_ASSERT(QThread::currentThreadId() == m_currentThreadId);
unsigned int payload = 0;
{
QMutexLocker l(&m_mutex);
// fuer aktuelle Sekunde haben wir noch nicht alle Daten
for (int i = 1; i <= m_cleanupTimeout / 1000; ++i)
payload += m_data.value(curTime - i);
}
// Durchschnitt ...
payload /= (m_cleanupTimeout / 1000);
INFO_LOG(m_logger) << "Average Payload in the last " << m_cleanupTimeout << " Milliseconds: " << payload << " Bytes/sec, last sec: " << m_data[curTime - 1]
<< " Bytes, #telegrams: " << m_telegrams[curTime - 1];
PrtCnvRadioThread::E_TrafficLoad newReceiveLoad;
if (payload >= m_fullLoad)
{
// full load
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad;
// Hysterese nach oben
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad)
{
// wenn cnt in Bereich m_fullLoad ... m_fullLoad + m_hystLoad
// -> noch warten
if (payload < m_fullLoad + m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
}
}
else if (payload >= m_highLoad)
{
// high load
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
// Hysterese nach oben
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::NormalLoad)
{
// wenn cnt in Bereich m_highLoad ... m_highLoad + m_hystLoad
// -> noch warten
if (payload < m_highLoad + m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad;
}
// Hysterese nach unten
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::FullLoad)
{
// wenn cnt in Bereich m_fullLoad ... m_fullLoad - m_hystLoad
// -> noch warten
if (payload >= m_fullLoad - m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::FullLoad;
}
}
else
ERROR_LOG(m_logger) << "Could not get PrtCnvDbThread!";
}
QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad);
}
void PrtCnvRadioTrafficThread::onCleanupTimeout()
{
const time_t curTime = time(nullptr);
{
QMutexLocker l(&m_mutex);
QMap<time_t, unsigned int>::iterator it = m_data.begin();
while (it != m_data.end())
{
const time_t key = it.key();
// 10 als Puffer (siehe auch onCalculateTrafficLoad())
if (key < curTime - m_cleanupTimeout - 10)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::NormalLoad;
// Hysterese nach unten
if (m_receiveLoad == PrtCnvRadioThread::E_TrafficLoad::HighLoad)
{
m_data.erase(it++);
m_telegrams.remove(key);
continue;
// wenn cnt in Bereich m_highLoad ... m_highLoad - m_hystLoad
// -> noch warten
if (payload >= m_highLoad - m_hystLoad)
newReceiveLoad = PrtCnvRadioThread::E_TrafficLoad::HighLoad;
}
break; // arbitrarily ordered
}
if (m_receiveLoad != newReceiveLoad)
{
m_receiveLoad = newReceiveLoad;
// Achtung: Nicht mehr als 31 Sekunden erlaubt
unsigned int wartezeit_posmldg = (static_cast<unsigned int>(m_receiveLoad) * 10) + 1;
INFO_LOG(m_logger) << "New traffic load: " << m_receiveLoad;
PrtCnvDbThread *dbThread = qobject_cast<PrtCnvDbThread *>(m_Parent->getOtherThread(PrtCnvApplication::e_Db));
if (dbThread)
{
dbThread->setAirLoad(m_receiveLoad);
dbThread->setPositionSendTime(wartezeit_posmldg);
Q_ASSERT(QThread::currentThreadId() == m_currentThreadId);
}
else
ERROR_LOG(m_logger) << "Could not get PrtCnvDbThread!";
}
QTimer::singleShot(m_calcTimeout, this, &PrtCnvRadioTrafficThread::onCalculateTrafficLoad);
}
QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout);
}
void PrtCnvRadioTrafficThread::onCleanupTimeout()
{
const time_t curTime = time(nullptr);
{
QMutexLocker l(&m_mutex);
QMap<time_t, unsigned int>::iterator it = m_data.begin();
while (it != m_data.end())
{
const time_t key = it.key();
// 10 als Puffer (siehe auch onCalculateTrafficLoad())
if (key < curTime - m_cleanupTimeout - 10)
{
m_data.erase(it++);
m_telegrams.remove(key);
continue;
}
break; // arbitrarily ordered
}
}
QTimer::singleShot(m_cleanupTimeout, this, &PrtCnvRadioTrafficThread::onCleanupTimeout);
}
} // namespace PrtCnv
@@ -21,76 +21,75 @@
namespace PrtCnv
{
/**
/**
* This class handles the traffic counting for the
* incoming radio data
*/
class PrtCnvRadioTrafficThread final : public PrtCnvThread
{
Q_OBJECT
public:
explicit PrtCnvRadioTrafficThread(PrtCnvThreadStarter* a_parent);
class PrtCnvRadioTrafficThread final : public PrtCnvThread
{
Q_OBJECT
public:
explicit PrtCnvRadioTrafficThread(PrtCnvThreadStarter *a_parent);
/**
/**
* A new telegram arrived.
*/
void newTelegramArrived(unsigned int size);
void newTelegramArrived(unsigned int size);
/**
/**
* Start the thread handling
*/
int32_t start() override;
int32_t start() override;
protected Q_SLOTS:
/**
protected Q_SLOTS:
/**
* Timeout to recalculate traffic load
*/
void onCalculateTrafficLoad();
void onCalculateTrafficLoad();
/**
/**
* Timeout to throw away old data
*/
void onCleanupTimeout();
void onCleanupTimeout();
protected:
/**
protected:
/**
* The current traffic load
*/
PrtCnvRadioThread::E_TrafficLoad m_receiveLoad;
PrtCnvRadioThread::E_TrafficLoad m_receiveLoad;
/**
/**
* Full load
*/
unsigned int m_fullLoad;
unsigned int m_fullLoad;
/**
/**
* High load
*/
unsigned int m_highLoad;
unsigned int m_highLoad;
/**
/**
* Hysterese
*/
unsigned int m_hystLoad;
unsigned int m_hystLoad;
/**
/**
* Timeout for recalculation
*/
int m_calcTimeout;
int m_calcTimeout;
/**
/**
* Timeout until data is thrown away
*/
int m_cleanupTimeout;
int m_cleanupTimeout;
QRecursiveMutex m_mutex;
QRecursiveMutex m_mutex;
/**
/**
* map<time, nTelegrams>
*/
QMap<time_t, unsigned int> m_data;
QMap<time_t, unsigned int> m_telegrams;
};
QMap<time_t, unsigned int> m_data;
QMap<time_t, unsigned int> m_telegrams;
};
} // namespace PrtCnv
@@ -25,359 +25,359 @@
namespace PrtCnv
{
// ---------------------------------------------------------------
// Constructor with pointer to thread-starter as parameter
// ---------------------------------------------------------------
PrtCnvSocketThread::PrtCnvSocketThread(PrtCnv::PrtCnvThreadStarter* a_parent, const char *loggerName)
: PrtCnvThread(a_parent, loggerName)
, m_ConnectionTimer(nullptr)
, m_Socket(nullptr)
, m_TickTimer(nullptr)
, m_ReceiveCounter(0)
, m_ReceiveAckCounter(0)
, m_State(PrtCnvSocketThread::e_INITIAL)
, m_DbThread(nullptr)
, m_ConnectTimeout(2000)
, m_DisconnectTimeout(10000)
, m_AliveTimeout(3000)
, m_TickTimeout(900)
, m_DoCleanup(false)
, m_LogThread(nullptr)
, m_InjectionThread(nullptr)
, m_currentHostAdressIndex(0)
{}
PrtCnvSocketThread::~PrtCnvSocketThread()
{
cleanup();
}
// ---------------------------------------------------------------
// Creates all subcomponents and connects signals to slots
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::create(NGL::Settings *settings)
{
PrtCnvThread::create(settings);
createNewSocket();
m_ConnectionTimer = new QTimer(this);
connect(m_ConnectionTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutAliveAndConnection);
m_TickTimer = new QTimer(this);
connect(m_TickTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutTick);
m_DbThread = qobject_cast<PrtCnvDbThread*>(m_Parent->getOtherThread(PrtCnvApplication::e_Db));
m_LogThread = qobject_cast<PrtCnvTelegramLogThread*>(m_Parent->getOtherThread(PrtCnvApplication::e_Log));
m_InjectionThread = qobject_cast<PrtCnvInjectionThread*>(m_Parent->getOtherThread(PrtCnvApplication::e_Injection));
return 0;
}
// ---------------------------------------------------------------
// Creates a new socket to avoid getting old stuff from the
// former socket when reconnecting
// ---------------------------------------------------------------
void PrtCnvSocketThread::createNewSocket()
{
INFO_LOG(m_logger) << "createNewSocket m_oldSocket=" << m_Socket;
Q_ASSERT(QThread::currentThreadId() == m_currentThreadId);
if (m_Socket)
// ---------------------------------------------------------------
// Constructor with pointer to thread-starter as parameter
// ---------------------------------------------------------------
PrtCnvSocketThread::PrtCnvSocketThread(PrtCnv::PrtCnvThreadStarter *a_parent, const char *loggerName)
: PrtCnvThread(a_parent, loggerName)
, m_ConnectionTimer(nullptr)
, m_Socket(nullptr)
, m_TickTimer(nullptr)
, m_ReceiveCounter(0)
, m_ReceiveAckCounter(0)
, m_State(PrtCnvSocketThread::e_INITIAL)
, m_DbThread(nullptr)
, m_ConnectTimeout(2000)
, m_DisconnectTimeout(10000)
, m_AliveTimeout(3000)
, m_TickTimeout(900)
, m_DoCleanup(false)
, m_LogThread(nullptr)
, m_InjectionThread(nullptr)
, m_currentHostAdressIndex(0)
{
m_Socket->disconnectFromHost(); // Falls noch connected
m_Socket->disconnect(); // Alle Signals/Slots aufräumen
if (m_Socket->state() != QAbstractSocket::UnconnectedState)
m_Socket->waitForDisconnected();
m_Socket->deleteLater(); // und weg damit
}
m_Socket = new QTcpSocket(this);
qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
connect(m_Socket, &QTcpSocket::connected, this, &PrtCnvSocketThread::connected, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvSocketThread::disconnected, Qt::QueuedConnection);
connect(m_Socket, &QAbstractSocket::errorOccurred, this, &PrtCnvSocketThread::error, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::hostFound, this, &PrtCnvSocketThread::hostFound, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::stateChanged, this, &PrtCnvSocketThread::stateChanged);
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvSocketThread::readyRead, Qt::QueuedConnection);
}
// ---------------------------------------------------------------
// Deallocates subcomponents.
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::destroy()
{
PrtCnvThread::destroy();
cleanup();
return 0;
}
void PrtCnvSocketThread::cleanup()
{
delete m_Socket; m_Socket = nullptr;
delete m_ConnectionTimer; m_ConnectionTimer = nullptr;
delete m_TickTimer; m_TickTimer = nullptr;
}
// ---------------------------------------------------------------
// Initializes the variables.
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::init()
{
INFO_LOG(m_logger) << "PrtCnvSocketThread::init()";
PrtCnvThread::init();
m_State = e_INITIAL;
m_ConnectTimeout = m_Config->getInteger(getName(), QStringLiteral("ConnectTimeout"), 2000);
m_DisconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000);
m_AliveTimeout = m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000);
return 0;
}
// ---------------------------------------------------------------
// Connect as client to a TCP-server on ip-address configured
// as HostName and Port configured as Port
// ---------------------------------------------------------------
void PrtCnvSocketThread::connectSocket()
{
int sockState = m_Socket ? m_Socket->state() : -1;
INFO_LOG(m_logger) << "connectSocket m_Socket=" << m_Socket << " state=" << m_State << " socketState=" << sockState;
if (e_WORKING != m_State && e_REGISTERING != m_State)
PrtCnvSocketThread::~PrtCnvSocketThread()
{
if (m_Socket)
{
m_Socket->disconnectFromHost(); // Falls noch connected
if (m_Socket->state() != QAbstractSocket::UnconnectedState)
m_Socket->waitForDisconnected();
}
cleanup();
}
// ---------------------------------------------------------------
// Creates all subcomponents and connects signals to slots
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::create(NGL::Settings *settings)
{
PrtCnvThread::create(settings);
createNewSocket();
if(m_hostAdresses.isEmpty())
readHostAdresses();
const QString hostname = m_hostAdresses.at(m_currentHostAdressIndex).first;
const uint16_t port = m_hostAdresses.at(m_currentHostAdressIndex).second;
m_currentHostAdressIndex = ((m_currentHostAdressIndex + 1) % m_hostAdresses.size());
INFO_LOG(m_logger) << "Connecting to " << hostname << ":" << port << " m_Socket=" << m_Socket;
m_Socket->connectToHost(hostname, port);
m_State = e_CONNECTING;
startConnectionTimer();
m_ConnectionTimer = new QTimer(this);
connect(m_ConnectionTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutAliveAndConnection);
m_TickTimer = new QTimer(this);
connect(m_TickTimer, &QTimer::timeout, this, &PrtCnvSocketThread::timeoutTick);
m_DbThread = qobject_cast<PrtCnvDbThread *>(m_Parent->getOtherThread(PrtCnvApplication::e_Db));
m_LogThread = qobject_cast<PrtCnvTelegramLogThread *>(m_Parent->getOtherThread(PrtCnvApplication::e_Log));
m_InjectionThread = qobject_cast<PrtCnvInjectionThread *>(m_Parent->getOtherThread(PrtCnvApplication::e_Injection));
return 0;
}
else
// ---------------------------------------------------------------
// Creates a new socket to avoid getting old stuff from the
// former socket when reconnecting
// ---------------------------------------------------------------
void PrtCnvSocketThread::createNewSocket()
{
WARNING_LOG(m_logger) << getName() << ": connectSocket called, but m_State is " << m_State;
}
}
INFO_LOG(m_logger) << "createNewSocket m_oldSocket=" << m_Socket;
Q_ASSERT(QThread::currentThreadId() == m_currentThreadId);
// ---------------------------------------------------------------
// Disconnects from TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::disconnectSocket()
{
m_Socket->disconnectFromHost();
startDisconnectionTimer();
m_State = e_DISCONNECTING;
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have connected to
// TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::connected()
{
INFO_LOG(m_logger) << "connected (implement connected() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have disconnected
// to TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::disconnected()
{
INFO_LOG(m_logger) << "got signal 'disconnected' (implement disconnected() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have have read
// data over socket
// ---------------------------------------------------------------
void PrtCnvSocketThread::readyRead()
{
INFO_LOG(m_logger) << "got signal 'newData' (implement newData() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// this slot is used for connection, disconnection and alive
// timeouts
// ---------------------------------------------------------------
void PrtCnvSocketThread::timeoutAliveAndConnection()
{
INFO_LOG(m_logger) << "got signal 'reconnectTimeout' (implement reconnectTimeout() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have a socket-error
// ---------------------------------------------------------------
void PrtCnvSocketThread::error(QAbstractSocket::SocketError a_socketError)
{
switch (a_socketError)
{
case QAbstractSocket::ConnectionRefusedError:
ERROR_LOG(m_logger) << getName() << ": ConnectionRefusedError m_State=" << m_State;
break;
case QAbstractSocket::RemoteHostClosedError:
ERROR_LOG(m_logger) << getName() << ": RemoteHostClosedError";
break;
case QAbstractSocket::HostNotFoundError:
//ERROR_LOG(m_logger) << getName() << ": HostNotFoundError";
break;
default:
ERROR_LOG(m_logger) << getName() << ": got signal 'error(QAbstractSocket::SocketError=" << a_socketError << ")'";
}
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when the host was found
// ---------------------------------------------------------------
void PrtCnvSocketThread::hostFound()
{
// INFO_LOG(m_logger) << "got signal 'hostFound' (implement hostFound() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when socket-state has
// changed
// ---------------------------------------------------------------
void PrtCnvSocketThread::stateChanged(QAbstractSocket::SocketState a_socketState)
{
Q_UNUSED(a_socketState);
// INFO_LOG(m_logger) << "got signal 'stateChanged(" << ao_socketState << ")' (implement stateChanged() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// calls storeRadioTelegram of DbThread, see there
// ---------------------------------------------------------------
void PrtCnvSocketThread::storeRadioTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_telegram,
const uint32_t a_readCounter)
{
m_DbThread->storeRadioTelegram(a_telegram, a_readCounter);
}
// ---------------------------------------------------------------
// used to check whether the other side is still alive
// ---------------------------------------------------------------
void PrtCnvSocketThread::startAliveTimer()
{
m_ConnectionTimer->setInterval(m_AliveTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used to retry connection
// ---------------------------------------------------------------
void PrtCnvSocketThread::startConnectionTimer()
{
m_ConnectionTimer->setInterval(m_ConnectTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used to abort connection, when normal disconnection is not
// successful
// ---------------------------------------------------------------
void PrtCnvSocketThread::startDisconnectionTimer()
{
m_ConnectionTimer->setInterval(m_DisconnectTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used for periodically ticks (i.e. for acks or sending
// nachforderungen)
// ---------------------------------------------------------------
void PrtCnvSocketThread::startTickTimer()
{
// INFO_LOG(m_logger) << "start timer";
m_TickTimer->setInterval(m_TickTimeout);
m_TickTimer->start();
}
// ---------------------------------------------------------------
// The counter will be set to a_startCounter if a_maxCounter
// is reached
// returns true if receive-counter is ok
// returns false if a telegram is repeated or lost
// ---------------------------------------------------------------
bool PrtCnvSocketThread::checkAndUpdateReceiveCounter(const uint32_t a_counter, const uint32_t a_maxCounter, const uint32_t a_startCounter)
{
TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter;
// check for wrap
if (a_maxCounter == ++m_ReceiveCounter)
{
m_ReceiveCounter = a_startCounter;
}
// has the counter the expected value?
if (m_ReceiveCounter != a_counter)
{
//if (m_ReceiveCounter != 1)
if (m_Socket)
{
if (m_ReceiveCounter > a_counter)
{
ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from "
<< getName() << "! Expected: " << m_ReceiveCounter;
}
else
{
ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName()
<< ": receive-counter of received telegram: " << a_counter << "; Expected: " << m_ReceiveCounter;
}
m_Socket->disconnectFromHost(); // Falls noch connected
m_Socket->disconnect(); // Alle Signals/Slots aufräumen
if (m_Socket->state() != QAbstractSocket::UnconnectedState)
m_Socket->waitForDisconnected();
m_Socket->deleteLater(); // und weg damit
}
m_Socket = new QTcpSocket(this);
qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
connect(m_Socket, &QTcpSocket::connected, this, &PrtCnvSocketThread::connected, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::disconnected, this, &PrtCnvSocketThread::disconnected, Qt::QueuedConnection);
connect(m_Socket, &QAbstractSocket::errorOccurred, this, &PrtCnvSocketThread::error, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::hostFound, this, &PrtCnvSocketThread::hostFound, Qt::QueuedConnection);
connect(m_Socket, &QTcpSocket::stateChanged, this, &PrtCnvSocketThread::stateChanged);
connect(m_Socket, &QTcpSocket::readyRead, this, &PrtCnvSocketThread::readyRead, Qt::QueuedConnection);
}
// ---------------------------------------------------------------
// Deallocates subcomponents.
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::destroy()
{
PrtCnvThread::destroy();
cleanup();
return 0;
}
void PrtCnvSocketThread::cleanup()
{
delete m_Socket;
m_Socket = nullptr;
delete m_ConnectionTimer;
m_ConnectionTimer = nullptr;
delete m_TickTimer;
m_TickTimer = nullptr;
}
// ---------------------------------------------------------------
// Initializes the variables.
// ---------------------------------------------------------------
int32_t PrtCnvSocketThread::init()
{
INFO_LOG(m_logger) << "PrtCnvSocketThread::init()";
PrtCnvThread::init();
m_State = e_INITIAL;
m_ConnectTimeout = m_Config->getInteger(getName(), QStringLiteral("ConnectTimeout"), 2000);
m_DisconnectTimeout = m_Config->getInteger(getName(), QStringLiteral("DisconnectTimeout"), 10000);
m_AliveTimeout = m_Config->getInteger(getName(), QStringLiteral("AliveTimeout"), 3000);
return 0;
}
// ---------------------------------------------------------------
// Connect as client to a TCP-server on ip-address configured
// as HostName and Port configured as Port
// ---------------------------------------------------------------
void PrtCnvSocketThread::connectSocket()
{
int sockState = m_Socket ? m_Socket->state() : -1;
INFO_LOG(m_logger) << "connectSocket m_Socket=" << m_Socket << " state=" << m_State << " socketState=" << sockState;
if (e_WORKING != m_State && e_REGISTERING != m_State)
{
if (m_Socket)
{
m_Socket->disconnectFromHost(); // Falls noch connected
if (m_Socket->state() != QAbstractSocket::UnconnectedState)
m_Socket->waitForDisconnected();
}
createNewSocket();
if (m_hostAdresses.isEmpty())
readHostAdresses();
const QString hostname = m_hostAdresses.at(m_currentHostAdressIndex).first;
const uint16_t port = m_hostAdresses.at(m_currentHostAdressIndex).second;
m_currentHostAdressIndex = ((m_currentHostAdressIndex + 1) % m_hostAdresses.size());
INFO_LOG(m_logger) << "Connecting to " << hostname << ":" << port << " m_Socket=" << m_Socket;
m_Socket->connectToHost(hostname, port);
m_State = e_CONNECTING;
startConnectionTimer();
}
else
{
WARNING_LOG(m_logger) << getName() << ": connectSocket called, but m_State is " << m_State;
}
}
// ---------------------------------------------------------------
// Disconnects from TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::disconnectSocket()
{
m_Socket->disconnectFromHost();
startDisconnectionTimer();
m_State = e_DISCONNECTING;
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have connected to
// TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::connected()
{
INFO_LOG(m_logger) << "connected (implement connected() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have disconnected
// to TCP-server
// ---------------------------------------------------------------
void PrtCnvSocketThread::disconnected()
{
INFO_LOG(m_logger) << "got signal 'disconnected' (implement disconnected() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have have read
// data over socket
// ---------------------------------------------------------------
void PrtCnvSocketThread::readyRead()
{
INFO_LOG(m_logger) << "got signal 'newData' (implement newData() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// this slot is used for connection, disconnection and alive
// timeouts
// ---------------------------------------------------------------
void PrtCnvSocketThread::timeoutAliveAndConnection()
{
INFO_LOG(m_logger) << "got signal 'reconnectTimeout' (implement reconnectTimeout() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when we have a socket-error
// ---------------------------------------------------------------
void PrtCnvSocketThread::error(QAbstractSocket::SocketError a_socketError)
{
switch (a_socketError)
{
case QAbstractSocket::ConnectionRefusedError:
ERROR_LOG(m_logger) << getName() << ": ConnectionRefusedError m_State=" << m_State;
break;
case QAbstractSocket::RemoteHostClosedError:
ERROR_LOG(m_logger) << getName() << ": RemoteHostClosedError";
break;
case QAbstractSocket::HostNotFoundError:
//ERROR_LOG(m_logger) << getName() << ": HostNotFoundError";
break;
default:
ERROR_LOG(m_logger) << getName() << ": got signal 'error(QAbstractSocket::SocketError=" << a_socketError << ")'";
}
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when the host was found
// ---------------------------------------------------------------
void PrtCnvSocketThread::hostFound()
{
// INFO_LOG(m_logger) << "got signal 'hostFound' (implement hostFound() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// Will be called from Qt-Framework when socket-state has
// changed
// ---------------------------------------------------------------
void PrtCnvSocketThread::stateChanged(QAbstractSocket::SocketState a_socketState)
{
Q_UNUSED(a_socketState);
// INFO_LOG(m_logger) << "got signal 'stateChanged(" << ao_socketState << ")' (implement stateChanged() in inherited class, if you want use this signal...)";
}
// ---------------------------------------------------------------
// calls storeRadioTelegram of DbThread, see there
// ---------------------------------------------------------------
void PrtCnvSocketThread::storeRadioTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_telegram, const uint32_t a_readCounter)
{
m_DbThread->storeRadioTelegram(a_telegram, a_readCounter);
}
// ---------------------------------------------------------------
// used to check whether the other side is still alive
// ---------------------------------------------------------------
void PrtCnvSocketThread::startAliveTimer()
{
m_ConnectionTimer->setInterval(m_AliveTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used to retry connection
// ---------------------------------------------------------------
void PrtCnvSocketThread::startConnectionTimer()
{
m_ConnectionTimer->setInterval(m_ConnectTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used to abort connection, when normal disconnection is not
// successful
// ---------------------------------------------------------------
void PrtCnvSocketThread::startDisconnectionTimer()
{
m_ConnectionTimer->setInterval(m_DisconnectTimeout);
m_ConnectionTimer->start();
}
// ---------------------------------------------------------------
// used for periodically ticks (i.e. for acks or sending
// nachforderungen)
// ---------------------------------------------------------------
void PrtCnvSocketThread::startTickTimer()
{
// INFO_LOG(m_logger) << "start timer";
m_TickTimer->setInterval(m_TickTimeout);
m_TickTimer->start();
}
// ---------------------------------------------------------------
// The counter will be set to a_startCounter if a_maxCounter
// is reached
// returns true if receive-counter is ok
// returns false if a telegram is repeated or lost
// ---------------------------------------------------------------
bool PrtCnvSocketThread::checkAndUpdateReceiveCounter(const uint32_t a_counter, const uint32_t a_maxCounter, const uint32_t a_startCounter)
{
TRACE_LOG(m_logger) << "checkAndUpdateReceiveCounter: " << a_counter << ", " << m_ReceiveCounter;
// check for wrap
if (a_maxCounter == ++m_ReceiveCounter)
{
m_ReceiveCounter = a_startCounter;
}
// has the counter the expected value?
if (m_ReceiveCounter != a_counter)
{
//if (m_ReceiveCounter != 1)
{
if (m_ReceiveCounter > a_counter)
{
ERROR_LOG(m_logger) << "It seems, the telegram with counter " << a_counter << " was resent from " << getName() << "! Expected: " << m_ReceiveCounter;
}
else
{
ERROR_LOG(m_logger) << "It seems, we lost one or several telegrams from " << getName() << ": receive-counter of received telegram: " << a_counter
<< "; Expected: " << m_ReceiveCounter;
}
}
#if 0
m_ReceiveCounter--;
return false; // failure
#else
m_ReceiveCounter = a_counter;
return true;
m_ReceiveCounter = a_counter;
return true;
#endif
}
return true; // all ok
}
return true; // all ok
}
void PrtCnvSocketThread::readHostAdresses()
{
QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("127.0.0.1"));
uint16_t port = m_Config->getInteger(getName(), QStringLiteral("Port"), 4934);
m_hostAdresses.push_back(qMakePair(host, port));
for (int i = 1; i < 10; ++i) {
const QString hostName = QLatin1String("HostName") + QString::number(i);
const QString portName = QLatin1String("Port") + QString::number(i);
host = m_Config->getString(getName(), hostName, QString());
port = m_Config->getInteger(getName(), portName, 0);
if (host.isEmpty() || port == 0)
continue;
void PrtCnvSocketThread::readHostAdresses()
{
QString host = m_Config->getString(getName(), QStringLiteral("HostName"), QStringLiteral("127.0.0.1"));
uint16_t port = m_Config->getInteger(getName(), QStringLiteral("Port"), 4934);
m_hostAdresses.push_back(qMakePair(host, port));
for (int i = 1; i < 10; ++i)
{
const QString hostName = QLatin1String("HostName") + QString::number(i);
const QString portName = QLatin1String("Port") + QString::number(i);
host = m_Config->getString(getName(), hostName, QString());
port = m_Config->getInteger(getName(), portName, 0);
if (host.isEmpty() || port == 0)
continue;
m_hostAdresses.push_back(qMakePair(host, port));
}
for (const auto &p : std::as_const(m_hostAdresses))
{
INFO_LOG(m_logger) << "Read Host Adress " << p.first << ":" << p.second << " from settings";
}
}
for (const auto &p : std::as_const(m_hostAdresses)) {
INFO_LOG(m_logger) << "Read Host Adress " << p.first
<< ":" << p.second
<< " from settings";
}
}
} // namespace PrtCnv
} // namespace PrtCnv
@@ -49,7 +49,6 @@ namespace PrtCnv
{
Q_OBJECT
public:
/**
* The different states for the state-event-machine
*
@@ -71,7 +70,7 @@ namespace PrtCnv
*
* @param a_parent
*/
PrtCnvSocketThread(PrtCnvThreadStarter* a_parent, const char *loggerName);
PrtCnvSocketThread(PrtCnvThreadStarter *a_parent, const char *loggerName);
~PrtCnvSocketThread();
/**
* Creates all subcomponents and connects signals to slots
@@ -199,7 +198,7 @@ namespace PrtCnv
/**
* A vector with hostname - port pairs to connect to
*/
QVector<QPair<QString, uint16_t> > m_hostAdresses;
QVector<QPair<QString, uint16_t>> m_hostAdresses;
/**
* The current index to connect to in m_hostAdresses
@@ -13,39 +13,40 @@
namespace PrtCnv
{
class PrtCnvStoredCentralTelegram : public PrtCnv::PrtCnvStoredTelegram
{
public:
PrtCnvStoredCentralTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvCentralTelegram> &a_centralTelegram,
const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram)
: PrtCnvStoredTelegram(a_radioTelegram)
, m_CentralTelegram(a_centralTelegram)
{}
class PrtCnvStoredCentralTelegram : public PrtCnv::PrtCnvStoredTelegram
{
public:
PrtCnvStoredCentralTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvCentralTelegram> &a_centralTelegram,
const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_radioTelegram)
: PrtCnvStoredTelegram(a_radioTelegram)
, m_CentralTelegram(a_centralTelegram)
{
}
int writeCounter() const { return m_WriteCounter; }
int writeCounter() const { return m_WriteCounter; }
/**
/**
* Assigned central-telegram.
*/
std::shared_ptr<N_CoPrtCnv::CoPrtCnvCentralTelegram> m_CentralTelegram;
/**
std::shared_ptr<N_CoPrtCnv::CoPrtCnvCentralTelegram> m_CentralTelegram;
/**
* The number of unsuccessful attempts to send the telegram to central
*/
uint32_t m_Attempts = 0;
/**
uint32_t m_Attempts = 0;
/**
* The counter while sending this telegram to central
*/
int m_WriteCounter = 0;
/**
int m_WriteCounter = 0;
/**
* True if the telegram must be resent.
*/
bool m_DoResend = false;
/**
bool m_DoResend = false;
/**
* True if the telegram must be deleted.
* Use this boolean only if you want delete a telegram as an exception (i.e.
* corrupt telegram, which cannot be sent)
*/
bool m_DoDelete = false;
};
bool m_DoDelete = false;
};
}
@@ -12,32 +12,32 @@
namespace PrtCnv
{
class PrtCnvStoredRadioTelegram : public PrtCnv::PrtCnvStoredTelegram
{
public:
using PrtCnv::PrtCnvStoredTelegram::PrtCnvStoredTelegram;
class PrtCnvStoredRadioTelegram : public PrtCnv::PrtCnvStoredTelegram
{
public:
using PrtCnv::PrtCnvStoredTelegram::PrtCnvStoredTelegram;
/**
/**
* The counter while reading this telegram from central
*/
int32_t m_ReadCounter = 0;
/**
int32_t m_ReadCounter = 0;
/**
* The broadcast index if it is a broadcast-telegram and it was sent first time,
* otherwise 0.
*/
uint16_t m_BroadcastIndex = 0;
/**
uint16_t m_BroadcastIndex = 0;
/**
* The frame-counter while sending this telegram to radio.
*/
uint8_t m_WriteCounter = 0;
/**
uint8_t m_WriteCounter = 0;
/**
* True if telegram must be deleted.
*/
bool m_DoDelete = false;
/**
bool m_DoDelete = false;
/**
* True if telegram was sent.
*/
bool m_IsSent = false;
};
bool m_IsSent = false;
};
}
@@ -13,16 +13,17 @@
namespace PrtCnv
{
class PrtCnvStoredTelegram
{
public:
explicit PrtCnvStoredTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_telegram)
: m_RadioTelegram(a_telegram)
{}
class PrtCnvStoredTelegram
{
public:
explicit PrtCnvStoredTelegram(const std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> &a_telegram)
: m_RadioTelegram(a_telegram)
{
}
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> m_RadioTelegram;
int64_t m_Id = 0;
bool m_WriteCounterChanged = false;
};
std::shared_ptr<N_CoPrtCnv::CoPrtCnvRadioTelegram> m_RadioTelegram;
int64_t m_Id = 0;
bool m_WriteCounterChanged = false;
};
}
@@ -27,7 +27,8 @@
static int gettimeofday(struct timeval *__p, void *__t)
{
union {
union
{
unsigned long long ns100; /*time since 1 Jan 1601 in 100ns units */
FILETIME ft;
} now;
@@ -48,135 +49,126 @@ static int gettimeofday(struct timeval *__p, void *__t)
namespace PrtCnv
{
// ---------------------------------------------------------------
PrtCnvTelegramLogThread::PrtCnvTelegramLogThread(PrtCnvThreadStarter* a_parent)
: PrtCnvThread(a_parent, "PrtCnvTelegramLogThread")
, m_DoLogCentralTelegram(true)
, m_DoLogWlsTelegram(true)
, m_DoLogRadioTelegram(true)
{
m_Name = QStringLiteral("TelegramLog");
}
// ---------------------------------------------------------------
PrtCnvTelegramLogThread::PrtCnvTelegramLogThread(PrtCnvThreadStarter *a_parent)
: PrtCnvThread(a_parent, "PrtCnvTelegramLogThread")
, m_DoLogCentralTelegram(true)
, m_DoLogWlsTelegram(true)
, m_DoLogRadioTelegram(true)
{
m_Name = QStringLiteral("TelegramLog");
}
// ---------------------------------------------------------------
int32_t PrtCnvTelegramLogThread::create(NGL::Settings *settings)
{
PrtCnvThread::create(settings);
// ---------------------------------------------------------------
int32_t PrtCnvTelegramLogThread::create(NGL::Settings *settings)
{
PrtCnvThread::create(settings);
connect(this, &PrtCnvTelegramLogThread::telegramLogReceived,
this, &PrtCnvTelegramLogThread::writeTelegramLog,
Qt::QueuedConnection);
connect(this, &PrtCnvTelegramLogThread::telegramLogReceived, this, &PrtCnvTelegramLogThread::writeTelegramLog, Qt::QueuedConnection);
return 0;
}
return 0;
}
// ---------------------------------------------------------------
int32_t PrtCnvTelegramLogThread::init()
{
PrtCnvThread::init();
m_DoLogCentralTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogCentralTelegrams"), true);
m_DoLogWlsTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogWlsTelegrams"), true);
m_DoLogRadioTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogRadioTelegrams"), true);
QString path = m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPath"), QStringLiteral("."));
if (!QDir::isAbsolutePath(path))
path = QCoreApplication::applicationDirPath() + QStringLiteral("/../") + path;
// ---------------------------------------------------------------
int32_t PrtCnvTelegramLogThread::init()
{
PrtCnvThread::init();
m_DoLogCentralTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogCentralTelegrams"), true);
m_DoLogWlsTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogWlsTelegrams"), true);
m_DoLogRadioTelegram = m_Config->getBoolean(QStringLiteral("Common"), QStringLiteral("LogRadioTelegrams"), true);
QString path = m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPath"), QStringLiteral("."));
if (!QDir::isAbsolutePath(path))
path = QCoreApplication::applicationDirPath() + QStringLiteral("/../") + path;
m_LogTelegramPathWithPrefix = path + QLatin1Char('/') + m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPrefix"), QStringLiteral("PrtCnv_"));
if (!m_LogTelegramPathWithPrefix.endsWith(QLatin1Char('_')))
m_LogTelegramPathWithPrefix += QLatin1Char('_');
m_LogTelegramPathWithPrefix = path + QLatin1Char('/') + m_Config->getString(QStringLiteral("Common"), QStringLiteral("LogTelegramPrefix"), QStringLiteral("PrtCnv_"));
if (!m_LogTelegramPathWithPrefix.endsWith(QLatin1Char('_')))
m_LogTelegramPathWithPrefix += QLatin1Char('_');
// create the telegram-log-path when it not yet exists
QFileInfo fileInfo(m_LogTelegramPathWithPrefix);
QDir dir;
dir.mkpath(fileInfo.absolutePath());
// create the telegram-log-path when it not yet exists
QFileInfo fileInfo(m_LogTelegramPathWithPrefix);
QDir dir;
dir.mkpath(fileInfo.absolutePath());
INFO_LOG(m_logger);
INFO_LOG(m_logger);
return 0;
}
return 0;
}
static inline int setSend(int protocol, bool bIsSend)
{
return (protocol | (bIsSend ? N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend : N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive));
}
static inline int setSend(int protocol, bool bIsSend)
{
return (protocol | (bIsSend ? N_CoPrtCnv::CoPrtCnvLogHeader::e_DestSend : N_CoPrtCnv::CoPrtCnvLogHeader::e_DestReceive));
}
// ---------------------------------------------------------------
// Writes a received or sent central-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeCentralTelegramLog(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_centralTelegram, bool a_isSend, int a_priority)
{
if (!m_DoLogCentralTelegram)
return;
// ---------------------------------------------------------------
// Writes a received or sent central-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeCentralTelegramLog(N_CoPrtCnv::CoPrtCnvCentralTelegram *a_centralTelegram, bool a_isSend, int a_priority)
{
if (!m_DoLogCentralTelegram)
return;
emit telegramLogReceived(a_centralTelegram->data(),
setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, a_isSend),
a_priority);
}
emit telegramLogReceived(a_centralTelegram->data(), setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolCentral, a_isSend), a_priority);
}
// ---------------------------------------------------------------
// Writes a received or sent wls-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeWlsTelegramLog(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool a_isSend, int a_priority)
{
if (!m_DoLogWlsTelegram)
return;
// ---------------------------------------------------------------
// Writes a received or sent wls-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeWlsTelegramLog(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tele, bool a_isSend, int a_priority)
{
if (!m_DoLogWlsTelegram)
return;
N_CoPrtCnv::CoPrtCnvCentralTelegram central(*tele);
emit telegramLogReceived(central.data(),
setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls, a_isSend),
a_priority);
}
N_CoPrtCnv::CoPrtCnvCentralTelegram central(*tele);
emit telegramLogReceived(central.data(), setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolWls, a_isSend), a_priority);
}
// ---------------------------------------------------------------
// Writes a received or sent radio-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeRadioTelegramLog(const QByteArray &tele, bool a_isSend, int a_priority)
{
if (!m_DoLogRadioTelegram)
return;
// ---------------------------------------------------------------
// Writes a received or sent radio-telegram into log-file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeRadioTelegramLog(const QByteArray &tele, bool a_isSend, int a_priority)
{
if (!m_DoLogRadioTelegram)
return;
emit telegramLogReceived(tele,
setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra, a_isSend),
a_priority);
}
emit telegramLogReceived(tele, setSend(N_CoPrtCnv::CoPrtCnvLogHeader::e_DestProtocolTetra, a_isSend), a_priority);
}
// ---------------------------------------------------------------
// Writes the telegram to the file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeTelegramLog(const QByteArray &a_data, int a_protocolType, int a_priority)
{
// get time with microseconds
timeval tv;
gettimeofday(&tv, nullptr);
uint64_t exactTime = tv.tv_sec;
exactTime = exactTime << 32;
exactTime += tv.tv_usec;
// ---------------------------------------------------------------
// Writes the telegram to the file
// ---------------------------------------------------------------
void PrtCnvTelegramLogThread::writeTelegramLog(const QByteArray &a_data, int a_protocolType, int a_priority)
{
// get time with microseconds
timeval tv;
gettimeofday(&tv, nullptr);
uint64_t exactTime = tv.tv_sec;
exactTime = exactTime << 32;
exactTime += tv.tv_usec;
// generate the filename of the telegram-file: "PrefixYYMMDD_HH.krlog"
QString fileName = QStringLiteral("%1%2.krlog")
.arg(m_LogTelegramPathWithPrefix, QDateTime::fromSecsSinceEpoch(tv.tv_sec).toString(QStringLiteral("yyMMdd_hh")));
// generate the filename of the telegram-file: "PrefixYYMMDD_HH.krlog"
QString fileName = QStringLiteral("%1%2.krlog").arg(m_LogTelegramPathWithPrefix, QDateTime::fromSecsSinceEpoch(tv.tv_sec).toString(QStringLiteral("yyMMdd_hh")));
// open the log-file
QFile telegramFile(fileName);
(void)telegramFile.open(QIODevice::WriteOnly | QIODevice::Append);
// open the log-file
QFile telegramFile(fileName);
(void)telegramFile.open(QIODevice::WriteOnly | QIODevice::Append);
// write header
N_CoPrtCnv::CoPrtCnvLogHeader lh;
lh.m_Length = a_data.size() + sizeof(N_CoPrtCnv::CoPrtCnvLogHeader);
lh.m_Version = 3;
lh.m_Priority = a_priority;
lh.m_Protocol = a_protocolType;
lh.m_Time = exactTime;
lh.m_Reserved = 0;
telegramFile.write(reinterpret_cast<const char*>(&lh), sizeof(N_CoPrtCnv::CoPrtCnvLogHeader));
// write header
N_CoPrtCnv::CoPrtCnvLogHeader lh;
lh.m_Length = a_data.size() + sizeof(N_CoPrtCnv::CoPrtCnvLogHeader);
lh.m_Version = 3;
lh.m_Priority = a_priority;
lh.m_Protocol = a_protocolType;
lh.m_Time = exactTime;
lh.m_Reserved = 0;
telegramFile.write(reinterpret_cast<const char *>(&lh), sizeof(N_CoPrtCnv::CoPrtCnvLogHeader));
// write telegram-data
telegramFile.write(a_data);
telegramFile.close();
}
// write telegram-data
telegramFile.write(a_data);
telegramFile.close();
}
} // namespace PrtCnv
@@ -10,27 +10,27 @@
// $LastChangedRevision$
//
// **************************************************************************
#pragma once
#include "PrtCnvThread.hpp"
namespace N_CoPrtCnv
{
class CoPrtCnvCentralTelegram;
class CoPrtCnvCentralTelegram;
}
namespace TrainingAreaBase
{
namespace TetraIcd
{
struct TrainingAreaTelegram;
}
namespace TetraIcd
{
struct TrainingAreaTelegram;
}
}
namespace PrtCnv
{
/**
/**
* This thread is used to log telegrams in a log-file. This action is separated
* from central/radio-thead because of 2 reasons:
*
@@ -49,7 +49,7 @@ namespace PrtCnv
*
* @param a_parent
*/
explicit PrtCnvTelegramLogThread(PrtCnvThreadStarter* a_parent);
explicit PrtCnvTelegramLogThread(PrtCnvThreadStarter *a_parent);
int32_t create(NGL::Settings *settings) override;
@@ -18,57 +18,57 @@ namespace PrtCnv
{
bool PrtCnvThread::m_DoCleanDb = false;
bool PrtCnvThread::m_DoCleanDb = false;
// ---------------------------------------------------------------
// Constructor with thread-starter as parameter
// ---------------------------------------------------------------
PrtCnvThread::PrtCnvThread(PrtCnv::PrtCnvThreadStarter* a_parent, const char *loggerName)
: m_Parent(a_parent)
, m_currentThreadId(nullptr)
, m_logger(getLogger(loggerName))
{}
// ---------------------------------------------------------------
// Constructor with thread-starter as parameter
// ---------------------------------------------------------------
PrtCnvThread::PrtCnvThread(PrtCnv::PrtCnvThreadStarter *a_parent, const char *loggerName)
: m_Parent(a_parent)
, m_currentThreadId(nullptr)
, m_logger(getLogger(loggerName))
{
}
int32_t PrtCnvThread::create(NGL::Settings *settings)
{
m_currentThreadId = QThread::currentThreadId();
m_Config = settings;
int32_t PrtCnvThread::create(NGL::Settings *settings)
{
m_currentThreadId = QThread::currentThreadId();
m_Config = settings;
INFO_LOG(m_logger) << "create " << m_Name
<< " - current thread id is " << m_currentThreadId;
return 0;
}
INFO_LOG(m_logger) << "create " << m_Name << " - current thread id is " << m_currentThreadId;
return 0;
}
int32_t PrtCnvThread::init()
{
INFO_LOG(m_logger) << "init " << m_Name;
return 0;
}
int32_t PrtCnvThread::init()
{
INFO_LOG(m_logger) << "init " << m_Name;
return 0;
}
int32_t PrtCnvThread::start()
{
INFO_LOG(m_logger) << "start " << m_Name;
return 0;
}
int32_t PrtCnvThread::start()
{
INFO_LOG(m_logger) << "start " << m_Name;
return 0;
}
int32_t PrtCnvThread::stop()
{
return 0;
}
int32_t PrtCnvThread::stop()
{
return 0;
}
int32_t PrtCnvThread::deinit()
{
return 0;
}
int32_t PrtCnvThread::deinit()
{
return 0;
}
int32_t PrtCnvThread::destroy()
{
return 0;
}
int32_t PrtCnvThread::destroy()
{
return 0;
}
} // namespace PrtCnv
@@ -21,7 +21,7 @@
namespace PrtCnv
{
class PrtCnvThreadStarter;
/**
/**
* The father-class of all threads in protocol-converter. It implements access to
* config-system and knows whether we have a restart after crash or a normal start
* (from scratch).
@@ -29,14 +29,16 @@ namespace PrtCnv
* @version 1.0
* @updated 21-Jan-2010 08:38:23
*/
class PrtCnvThread : public QObject, public N_AppComponent::IAppComponent
class PrtCnvThread
: public QObject
, public N_AppComponent::IAppComponent
{
Q_OBJECT
protected:
protected:
/**
* Used to get configuration-parameter
*/
NGL::Settings* m_Config;
NGL::Settings *m_Config;
/**
* Pointer to ThreadStarter
*/
@@ -47,6 +49,7 @@ protected:
Qt::HANDLE m_currentThreadId;
NGL::INGLLogger &m_logger;
public:
/**
* Indicates what happens with the DB while startup. True => it will be cleant;
@@ -59,7 +62,7 @@ protected:
*
* @param a_parent
*/
PrtCnvThread(PrtCnvThreadStarter* a_parent, const char *loggerName);
PrtCnvThread(PrtCnvThreadStarter *a_parent, const char *loggerName);
int32_t create(NGL::Settings *settings) override;
@@ -68,7 +71,7 @@ protected:
int32_t init() override;
int32_t start() override;
int32_t start() override;
int32_t stop() override;
@@ -78,7 +81,6 @@ protected:
int32_t destroy() override;
};
}
@@ -1,14 +1,14 @@
// **************************************************************************
//
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
//
// **************************************************************************
//
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
//
// Implementation of the Class PrtCnvThreadStarter
// **************************************************************************
#include "PrtCnvThreadStarter.hpp"
@@ -23,103 +23,101 @@
namespace PrtCnv
{
// ---------------------------------------------------------------
// Constructor with id and ptr to main-app as parameters.
// ---------------------------------------------------------------
PrtCnvThreadStarter::PrtCnvThreadStarter(const PrtCnv::PrtCnvApplication::E_ThreadId a_id,
const QString &configFileName,
PrtCnv::PrtCnvApplication* a_mainApp)
: m_Thread(nullptr)
, m_Application(a_mainApp)
, m_Id(a_id)
, m_settings(new NGL::Settings(configFileName))
, m_logger(getLogger("PrtCnvThreadStarter"))
{
DEBUG_LOG(m_logger) << "Using Config file '" << configFileName << "'";
}
PrtCnvThreadStarter::~PrtCnvThreadStarter()
{
delete m_settings;
}
// ---------------------------------------------------------------
// The run()-function, which will be called by Qt-Framework,
// when starting the thread.
// ---------------------------------------------------------------
void PrtCnvThreadStarter::run()
{
INFO_LOG(m_logger) << "Entering event loop for thread " << this << ", id: " << m_Id;
// allocate the thread
switch (m_Id)
// ---------------------------------------------------------------
// Constructor with id and ptr to main-app as parameters.
// ---------------------------------------------------------------
PrtCnvThreadStarter::PrtCnvThreadStarter(const PrtCnv::PrtCnvApplication::E_ThreadId a_id, const QString &configFileName, PrtCnv::PrtCnvApplication *a_mainApp)
: m_Thread(nullptr)
, m_Application(a_mainApp)
, m_Id(a_id)
, m_settings(new NGL::Settings(configFileName))
, m_logger(getLogger("PrtCnvThreadStarter"))
{
case PrtCnvApplication::e_Central:
m_Thread = new PrtCnvCentralThread(this);
break;
case PrtCnvApplication::e_Radio:
m_Thread = new PrtCnvRadioThread(m_Application->exerciseId(), this);
break;
case PrtCnvApplication::e_Db:
m_Thread = new PrtCnvDbThread(m_Application->databaseDriver(),
m_Application->databaseHostName(),
m_Application->databaseName(),
m_Application->databaseSchemaName(),
m_Application->databaseUserName(),
m_Application->databasePassword(),
this);
break;
case PrtCnvApplication::e_Log:
m_Thread = new PrtCnvTelegramLogThread(this);
break;
case PrtCnvApplication::e_Injection:
m_Thread = new PrtCnvInjectionThread(this);
break;
case PrtCnvApplication::e_RadioTraffic:
m_Thread = new PrtCnvRadioTrafficThread(this);
break;
case PrtCnvApplication::e_ThreadIdMax:
break;
DEBUG_LOG(m_logger) << "Using Config file '" << configFileName << "'";
}
if (!m_Thread)
PrtCnvThreadStarter::~PrtCnvThreadStarter()
{
ERROR_LOG(m_logger) << "Unknown threadId: " << m_Id;
return;
delete m_settings;
}
while (!m_Application)
sleep(1);
m_Application->waitForCreate(m_Id);
m_Thread->create(m_settings);
m_Application->waitForInit(m_Id);
m_Thread->init();
m_Application->waitForStart(m_Id);
m_Thread->start();
m_Application->waitForExec(m_Id);
// ---------------------------------------------------------------
// The run()-function, which will be called by Qt-Framework,
// when starting the thread.
// ---------------------------------------------------------------
void PrtCnvThreadStarter::run()
{
INFO_LOG(m_logger) << "Entering event loop for thread " << this << ", id: " << m_Id;
// allocate the thread
switch (m_Id)
{
case PrtCnvApplication::e_Central:
m_Thread = new PrtCnvCentralThread(this);
break;
exec();
case PrtCnvApplication::e_Radio:
m_Thread = new PrtCnvRadioThread(m_Application->exerciseId(), this);
break;
INFO_LOG(m_logger) << "Leaving event loop for thread " << this << ", id: " << m_Id;
delete m_Thread;
m_Thread = nullptr;
}
case PrtCnvApplication::e_Db:
m_Thread = new PrtCnvDbThread(m_Application->databaseDriver(),
m_Application->databaseHostName(),
m_Application->databaseName(),
m_Application->databaseSchemaName(),
m_Application->databaseUserName(),
m_Application->databasePassword(),
this);
break;
case PrtCnvApplication::e_Log:
m_Thread = new PrtCnvTelegramLogThread(this);
break;
case PrtCnvApplication::e_Injection:
m_Thread = new PrtCnvInjectionThread(this);
break;
case PrtCnvApplication::e_RadioTraffic:
m_Thread = new PrtCnvRadioTrafficThread(this);
break;
case PrtCnvApplication::e_ThreadIdMax:
break;
}
if (!m_Thread)
{
ERROR_LOG(m_logger) << "Unknown threadId: " << m_Id;
return;
}
while (!m_Application)
sleep(1);
m_Application->waitForCreate(m_Id);
m_Thread->create(m_settings);
m_Application->waitForInit(m_Id);
m_Thread->init();
m_Application->waitForStart(m_Id);
m_Thread->start();
m_Application->waitForExec(m_Id);
exec();
INFO_LOG(m_logger) << "Leaving event loop for thread " << this << ", id: " << m_Id;
delete m_Thread;
m_Thread = nullptr;
}
// ---------------------------------------------------------------
// Returns the desired thread.
// ---------------------------------------------------------------
PrtCnvThread *PrtCnvThreadStarter::getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const
{
return m_Application->getThreadStarter(a_threadId)->m_Thread;
}
// ---------------------------------------------------------------
// Returns the desired thread.
// ---------------------------------------------------------------
PrtCnvThread *PrtCnvThreadStarter::getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const
{
return m_Application->getThreadStarter(a_threadId)->m_Thread;
}
} // namespace PrtCnv
@@ -1,14 +1,14 @@
// **************************************************************************
//
//
// (C) Copyright 2009 Swiss SIMTEC AG
//
//
// **************************************************************************
//
//
// $HeadURL$
// $LastChangedBy$
// $LastChangedDate$
// $LastChangedRevision$
//
//
// Implementation of the Class PrtCnvThreadStarter
// **************************************************************************
#pragma once
@@ -16,14 +16,15 @@
#include "PrtCnvApplication.hpp"
#include <QtCore/QThread>
namespace NGL {
namespace NGL
{
class Settings;
}
namespace PrtCnv
{
class PrtCnvThread;
/**
/**
* This class is responsible for starting threads. It also impelements an access
* to other threads.
* @author wia
@@ -33,7 +34,7 @@ namespace PrtCnv
class PrtCnvThreadStarter : public QThread
{
Q_OBJECT
protected:
protected:
/**
* Pointer to the started thread
*/
@@ -52,6 +53,7 @@ protected:
NGL::Settings *m_settings;
NGL::INGLLogger &m_logger;
public:
/**
* Constructor with id and ptr to main-app as parameters.
@@ -59,9 +61,7 @@ protected:
* @param a_id
* @param a_mainApp The pointer to the main-app
*/
PrtCnvThreadStarter(const PrtCnvApplication::E_ThreadId a_id,
const QString &settingsFile,
PrtCnvApplication *a_mainApp);
PrtCnvThreadStarter(const PrtCnvApplication::E_ThreadId a_id, const QString &settingsFile, PrtCnvApplication *a_mainApp);
~PrtCnvThreadStarter();
@@ -73,6 +73,7 @@ protected:
* @param a_threadId The id of the desired thread.
*/
PrtCnvThread *getOtherThread(PrtCnvApplication::E_ThreadId a_threadId) const;
protected:
/**
* The run()-function, which will be called by Qt-Framework, when starting the
@@ -31,97 +31,77 @@ int main(int argc, char **argv)
LtsCommandLineParser::LtsCommandLineParser options(LtsCommandLineParser::LtsCommandLineParser::CustomConfigFile);
options.addOption({ QStringList() << QLatin1String("p") << QLatin1String("player")
, QLatin1String("number of players to be simulated.")
, QLatin1String("Default value")
, QLatin1String("5")
});
options.addOption({QStringList() << QLatin1String("p") << QLatin1String("player"),
QLatin1String("number of players to be simulated."),
QLatin1String("Default value"),
QLatin1String("5")});
options.addOption({ QStringList() << QLatin1String("n") << QLatin1String("northing")
, QLatin1String("initial position UTM north.")
, QLatin1String("Default value")
, QLatin1String("77777")
});
options.addOption({QStringList() << QLatin1String("n") << QLatin1String("northing"),
QLatin1String("initial position UTM north."),
QLatin1String("Default value"),
QLatin1String("77777")});
options.addOption({ QStringList() << QLatin1String("e") << QLatin1String("easting")
, QLatin1String("initial position UTM east.")
, QLatin1String("Default value")
, QLatin1String("99999")
});
options.addOption({QStringList() << QLatin1String("e") << QLatin1String("easting"),
QLatin1String("initial position UTM east."),
QLatin1String("Default value"),
QLatin1String("99999")});
options.addOption({ QStringList() << QLatin1String("f") << QLatin1String("first-id")
, QLatin1String("first equipment ID to use.")
, QLatin1String("Default value")
, QLatin1String("1101")
});
options.addOption({QStringList() << QLatin1String("f") << QLatin1String("first-id"),
QLatin1String("first equipment ID to use."),
QLatin1String("Default value"),
QLatin1String("1101")});
options.addOption({ QStringList() << QLatin1String("r") << QLatin1String("pprow")
, QLatin1String("players per row.")
, QLatin1String("Default value")
, QLatin1String("25")
});
options.addOption(
{QStringList() << QLatin1String("r") << QLatin1String("pprow"), QLatin1String("players per row."), QLatin1String("Default value"), QLatin1String("25")});
options.addOption({ QStringList() << QLatin1String("s") << QLatin1String("pspacing")
, QLatin1String("utm based spacing between the players.")
, QLatin1String("Default value")
, QLatin1String("100")
});
options.addOption({QStringList() << QLatin1String("s") << QLatin1String("pspacing"),
QLatin1String("utm based spacing between the players."),
QLatin1String("Default value"),
QLatin1String("100")});
options.addOption({ QStringList() << QLatin1String("z") << QLatin1String("issi")
, QLatin1String("DestinationIssi / HostISSI")
, QLatin1String("Default value")
, QLatin1String("2")
});
options.addOption(
{QStringList() << QLatin1String("z") << QLatin1String("issi"), QLatin1String("DestinationIssi / HostISSI"), QLatin1String("Default value"), QLatin1String("2")});
options.addOption({ QStringList() << QLatin1String("m") << QLatin1String("movements")
, QLatin1String("how many movements per milliseconds to make.")
, QLatin1String("Default value")
, QLatin1String("2000")
});
options.addOption({QStringList() << QLatin1String("m") << QLatin1String("movements"),
QLatin1String("how many movements per milliseconds to make."),
QLatin1String("Default value"),
QLatin1String("2000")});
options.addOption({ QStringList() << QLatin1String("d") << QLatin1String("death")
, QLatin1String("minimum times, after the movements timer is triggered, a dead player can revive.")
, QLatin1String("Default value")
, QLatin1String("100")
});
options.addOption({QStringList() << QLatin1String("d") << QLatin1String("death"),
QLatin1String("minimum times, after the movements timer is triggered, a dead player can revive."),
QLatin1String("Default value"),
QLatin1String("100")});
options.addOption({ QStringList() << QLatin1String("o") << QLatin1String("death-offset")
, QLatin1String("maximum times, after the movements timer is triggered, a dead player can revive.")
, QLatin1String("(0 -> identical to min)")
, QLatin1String("0")
});
options.addOption({QStringList() << QLatin1String("o") << QLatin1String("death-offset"),
QLatin1String("maximum times, after the movements timer is triggered, a dead player can revive."),
QLatin1String("(0 -> identical to min)"),
QLatin1String("0")});
options.addOption({ QStringList() << QLatin1String("t") << QLatin1String("pattern")
, QLatin1String("pattern the player has to walk [enter pattern by hand or pattern alias-name from settings file]\r\nfor more info, enter '--pattern-help'.")
, QLatin1String("Default value")
, QLatin1String("3,30,20#3,30,-20#3,-30,-20#3,-30,20")
});
options.addOption(
{QStringList() << QLatin1String("t") << QLatin1String("pattern"),
QLatin1String("pattern the player has to walk [enter pattern by hand or pattern alias-name from settings file]\r\nfor more info, enter '--pattern-help'."),
QLatin1String("Default value"),
QLatin1String("3,30,20#3,30,-20#3,-30,-20#3,-30,20")});
options.addOption({ QStringList() << QLatin1String("demand-old-broadcast-telegrams")
, QLatin1String("player demand old broadcast telegrams starting at BCI <default value>")
, QLatin1String("Default value")
, QLatin1String("0")
});
options.addOption({QStringList() << QLatin1String("demand-old-broadcast-telegrams"),
QLatin1String("player demand old broadcast telegrams starting at BCI <default value>"),
QLatin1String("Default value"),
QLatin1String("0")});
options.addOption({ QStringList() << QLatin1String("deactivate-single-mines")
, QLatin1String("the first player deactivates single mines with ids from minimum-mine-id to maximum-mine-id")
});
options.addOption({QStringList() << QLatin1String("deactivate-single-mines"),
QLatin1String("the first player deactivates single mines with ids from minimum-mine-id to maximum-mine-id")});
options.addOption({ QStringList() << QLatin1String("minimum-mine-id")
, QLatin1String("sets the value for minimum-mine-id used within deactivate-single-mines command")
, QLatin1String("Default value")
, QLatin1String("minimum-mine-id 2048")
});
options.addOption({QStringList() << QLatin1String("minimum-mine-id"),
QLatin1String("sets the value for minimum-mine-id used within deactivate-single-mines command"),
QLatin1String("Default value"),
QLatin1String("minimum-mine-id 2048")});
options.addOption({ QStringList() << QLatin1String("maximum-mine-id")
, QLatin1String("sets the value for maximum-mine-Id used within deactivate-single-mines command")
, QLatin1String("Default value")
, QLatin1String("maximum-mine-id 2100")
});
options.addOption({QStringList() << QLatin1String("maximum-mine-id"),
QLatin1String("sets the value for maximum-mine-Id used within deactivate-single-mines command"),
QLatin1String("Default value"),
QLatin1String("maximum-mine-id 2100")});
options.addOption({ QStringList() << QLatin1String("pattern-help")
, QLatin1String("help for the pattern interpreter.")
});
options.addOption({QStringList() << QLatin1String("pattern-help"), QLatin1String("help for the pattern interpreter.")});
if (!options.init())
@@ -166,8 +146,7 @@ int main(int argc, char **argv)
WARNING_LOG(logger) << " ... DestinationIssi/HostIssi: " << ttsArgs.destIssi;
WARNING_LOG(logger) << " ... on Position n/e: " << ttsArgs.position.y() << "/" << ttsArgs.position.x();
WARNING_LOG(logger) << " ... first equipmentID is: " << ttsArgs.eqIdStart;
WARNING_LOG(logger) << " ... player is reborn randomly after minimum " << ttsArgs.minimumDeathTicks
<< " ticks and maximum " << ttsArgs.maximumDeathTicks << " ticks";
WARNING_LOG(logger) << " ... player is reborn randomly after minimum " << ttsArgs.minimumDeathTicks << " ticks and maximum " << ttsArgs.maximumDeathTicks << " ticks";
WARNING_LOG(logger) << " ... pattern = " << ttsArgs.pattern;
WARNING_LOG(logger) << " ... max. " << ttsArgs.pprow << " players per row";
WARNING_LOG(logger) << " ... spacing of '" << ttsArgs.pspacing << " UTM east' between players";
@@ -177,8 +156,7 @@ int main(int argc, char **argv)
if (!s->listen(QHostAddress::Any, serverSettings.value(QLatin1String("Radio/Port"), 4200).toInt()))
{
ERROR_LOG(logger) << "Error listening on localhost:" << serverSettings.value(QLatin1String("Radio/Port"), 52010).toInt() << ": "
<< s->errorString();
ERROR_LOG(logger) << "Error listening on localhost:" << serverSettings.value(QLatin1String("Radio/Port"), 52010).toInt() << ": " << s->errorString();
delete s;
return -1;
}
@@ -14,9 +14,9 @@
TTServer::TTServer(const TTSArgs &ttsArgs) : m_ttsArgs(ttsArgs)
.getNGLLogger("TTServer")),
m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger()) {
connect(this, &TTServer::newConnection,
this, &TTServer::onNewConnection);
m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger())
{
connect(this, &TTServer::newConnection, this, &TTServer::onNewConnection);
}
void TTServer::onNewConnection()
@@ -24,16 +24,13 @@ void TTServer::onNewConnection()
QTcpSocket *sock = nextPendingConnection();
if (!sock)
return;
NOTICE_LOG(m_logger) << "New incoming connection from "
<< sock->peerName() << ":"
<< sock->peerPort();
NOTICE_LOG(m_logger) << "New incoming connection from " << sock->peerName() << ":" << sock->peerPort();
TTWorker *ttw = new TTWorker(sock, m_ttsArgs);
if (!ttw->init())
exit(5);
connect(sock, &QTcpSocket::disconnected,
this, &TTServer::onDisconnect);
connect(sock, &QTcpSocket::disconnected, this, &TTServer::onDisconnect);
}
void TTServer::onDisconnect()
@@ -24,9 +24,9 @@ struct runningPattern
struct TTSArgs
{
QPointF position;
QString pattern;
QSettings *settings = nullptr;
QPointF position;
QString pattern;
QSettings *settings = nullptr;
int destIssi = 0;
unsigned int cntPlayer = 0;
unsigned int eqIdStart = 0;
@@ -37,9 +37,9 @@ struct TTSArgs
unsigned int movs_per_msec = ~0U;
unsigned int minimumMineId = 0;
unsigned int maximumMineId = 0;
bool demandOldBraodcastTelegrams = false;
int demandOldBraodcastTelegramsCounter = 0;
bool deactivationSingleMines = false;
bool demandOldBraodcastTelegrams = false;
int demandOldBraodcastTelegramsCounter = 0;
bool deactivationSingleMines = false;
};
class TTServer : public QTcpServer
@@ -53,7 +53,6 @@ protected Q_SLOTS:
void onDisconnect();
protected:
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_logger;
TTSArgs m_ttsArgs;
};
@@ -33,14 +33,10 @@ TTWorker::TTWorker(QTcpSocket *socket, const TTSArgs &ttsArgs)
bool TTWorker::init()
{
connect(m_socket, &QTcpSocket::disconnected,
this, &TTWorker::deleteLater);
connect(m_socket, &QAbstractSocket::errorOccurred,
this, &TTWorker::onSocketError);
connect(m_socket, &QTcpSocket::readyRead,
this, &TTWorker::onReadyRead);
connect(m_timer, &QTimer::timeout,
this, &TTWorker::onSendPlayerPositions);
connect(m_socket, &QTcpSocket::disconnected, this, &TTWorker::deleteLater);
connect(m_socket, &QAbstractSocket::errorOccurred, this, &TTWorker::onSocketError);
connect(m_socket, &QTcpSocket::readyRead, this, &TTWorker::onReadyRead);
connect(m_timer, &QTimer::timeout, this, &TTWorker::onSendPlayerPositions);
if (m_ttsArgs.movs_per_msec < 200)
{
@@ -74,9 +70,9 @@ void TTWorker::startExecution()
if (m_ttsArgs.demandOldBraodcastTelegrams)
QTimer::singleShot(1000, this, &TTWorker::onSendNachforderungBroadcastTelegramm);
// QTimer::singleShot(25000, this , &TTWorker::onSendNlosSimulatorDirection);
// QTimer::singleShot(120000, this , &TTWorker::onSendNlosFireResult);
}
// QTimer::singleShot(25000, this , &TTWorker::onSendNlosSimulatorDirection);
// QTimer::singleShot(120000, this , &TTWorker::onSendNlosFireResult);
}
QVector<runningPattern> TTWorker::interpretPattern(QString pattern) const
{
@@ -106,11 +102,11 @@ QVector<runningPattern> TTWorker::interpretPattern(QString pattern) const
if (pattern.at(pattern.count() - 1) == QLatin1Char('#')) // delete the character ';' if there is one at the end of string - because of strtok/split
pattern.remove(pattern.count() - 1, 1);
QVector<runningPattern> newPatternList; // list we give back to replace the patternList in this class
runningPattern rp; // pattern we use (and reuse) to add a new runningPattern instance to the patternList
QVector<runningPattern> newPatternList; // list we give back to replace the patternList in this class
runningPattern rp; // pattern we use (and reuse) to add a new runningPattern instance to the patternList
QStringList strings = pattern.split(QLatin1Char('#')); // list of pattern (f.g. "1,2,3", "1,2,3");
QStringList stringy; // list of pattern-ingredients ;) (f.g. "1", "2", "3")
int i; // counter, global because of error message at the end of this function (see variable "strings")
QStringList stringy; // list of pattern-ingredients ;) (f.g. "1", "2", "3")
int i; // counter, global because of error message at the end of this function (see variable "strings")
for (i = 0; i < strings.count(); i++)
{
@@ -121,14 +117,20 @@ QVector<runningPattern> TTWorker::interpretPattern(QString pattern) const
bool ok = true;
rp.steps = stringy.at(0).toInt(&ok); if (!ok) break; // is not a number, so throw an error and exit this application
rp.ethering = stringy.at(1).toInt(&ok); if (!ok) break; // ^
rp.northering = stringy.at(2).toInt(&ok); if (!ok) break; // ^
rp.steps = stringy.at(0).toInt(&ok);
if (!ok)
break; // is not a number, so throw an error and exit this application
rp.ethering = stringy.at(1).toInt(&ok);
if (!ok)
break; // ^
rp.northering = stringy.at(2).toInt(&ok);
if (!ok)
break; // ^
newPatternList.append(rp); // add a new instance to the list (i hope this will create an instance and does not use a reference !!1)
if (i == strings.count() - 1) // are we at the end of the strings.count ? if yes, then return the list - important to NOT throw a error message
return newPatternList; // IMPORTANT! Or an wrong error message will be thrown
return newPatternList; // IMPORTANT! Or an wrong error message will be thrown
}
ERROR_LOG(m_logger) << "INVALID PATTERN: '" << strings.at(i) << "'. Cannot start without correct pattern!";
@@ -158,16 +160,14 @@ void TTWorker::onReadyRead()
if (N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER != header.m_MagicNumber)
{
ERROR_LOG(m_logger) << "Disconnect because radio-Telegram does not begin with magic-number A5: I got "
<< header.m_MagicNumber;
ERROR_LOG(m_logger) << "Disconnect because radio-Telegram does not begin with magic-number A5: I got " << header.m_MagicNumber;
m_socket->disconnectFromHost();
return;
}
if (!N_CoPrtCnv::CoPrtCnvRadioTelegram::isTelegramLengthOk(header.m_Length))
{
WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length
<< " - but I proceed with this telegram.";
WARNING_LOG(m_logger) << "Radio-Telegram length to big: " << header.m_Length << " - but I proceed with this telegram.";
}
// prepare data-bucket for entire telegram
@@ -197,20 +197,19 @@ void TTWorker::handleReceivedTelegram(const QByteArray &data)
// evaluate PDU-Type
switch (data.at(4))
{
// response to register indication
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd:
handleRegisterInd();
startExecution();
break;
// response to register indication
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_RegisterInd:
handleRegisterInd();
startExecution();
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data); // tele->getDestISSI() == ISSI an des angesprochenen Teilnehmers
// data is deleted inside handleDataIndReq()
break;
default:
INFO_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << (int)data[4]
<< " not implemented!";
break;
case N_CoPrtCnv::CoPrtCnvRadioTelegram::e_DataIndReq:
handleDataIndReq(data); // tele->getDestISSI() == ISSI an des angesprochenen Teilnehmers
// data is deleted inside handleDataIndReq()
break;
default:
INFO_LOG(m_logger) << "Radio-Telegram with PDU-Type=" << (int)data[4] << " not implemented!";
break;
}
}
@@ -231,15 +230,14 @@ void TTWorker::onSendNachforderungBroadcastTelegramm()
if (p->isLogin)
{
N_CoPrtCnv::CoPrtCnvRadioTelegram tel(GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME,
10, p->eqId);
N_CoPrtCnv::CoPrtCnvRadioTelegram tel(GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME, 10, p->eqId);
tel.setZaehler(0);
tel.setBroadcastIndex(0);
tel.setDestISSI(m_ttsArgs.destIssi);
tel.setSrcISSI(p->issi);
tel.setPayload4Byte(0); // gps_zeit
tel.setPayload1Byte(0); // ruecksetzzaehler
tel.setPayload2Byte(m_ttsArgs.demandOldBraodcastTelegramsCounter); // broadcast index
tel.setPayload4Byte(0); // gps_zeit
tel.setPayload1Byte(0); // ruecksetzzaehler
tel.setPayload2Byte(m_ttsArgs.demandOldBraodcastTelegramsCounter); // broadcast index
m_socket->write(tel.data());
}
else
@@ -366,7 +364,6 @@ void TTWorker::sendSanitationReport(uint32_t eqId, uint32_t issi)
mat.emplace_back(i);
tele.sanitaryMaterialStock = mat;
sendTelegram(tele, issi);
}
// void TTWorker::sendSanitation(uint32_t eqId, uint32_t issi)
@@ -426,103 +423,105 @@ void TTWorker::handleDataIndReq(const QByteArray &data)
return;
}
#endif
case GEF_TAKTISCHER_STATUS: // just resend this one to answer the station's question
{
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
TrainingAreaBase::TetraIcd::StateChange sc = TrainingAreaBase::TetraIcd::StateChange::fromJson(tele->jsonData());
delete tele;
DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got state: " << static_cast<int>(sc.vulnerabilityState) << " and this bits here: " << sc.vulnerabilityBits;
sc.header.timeStamp = time(nullptr) * 1000;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
case GEF_TAKTISCHER_STATUS: // just resend this one to answer the station's question
{
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
TrainingAreaBase::TetraIcd::StateChange sc = TrainingAreaBase::TetraIcd::StateChange::fromJson(tele->jsonData());
delete tele;
DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got state: " << static_cast<int>(sc.vulnerabilityState)
<< " and this bits here: " << sc.vulnerabilityBits;
sc.header.timeStamp = time(nullptr) * 1000;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
{
issi = m_playerList.at(i)->issi;
break;
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
{
issi = m_playerList.at(i)->issi;
break;
}
}
ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << static_cast<int>(sc.vulnerabilityState)
<< " and this bits here: " << sc.vulnerabilityBits;
sendTelegram(sc, issi); // resend
return;
}
ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << static_cast<int>(sc.vulnerabilityState) << " and this bits here: " << sc.vulnerabilityBits;
sendTelegram(sc, issi); // resend
return;
}
case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN:
{
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
TrainingAreaBase::TetraIcd::Sanitation sc = TrainingAreaBase::TetraIcd::Sanitation::fromJson(tele->jsonData());
delete tele;
DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got procedure: " << sc.proceduresTaken;
sc.header.timeStamp = time(nullptr) * 1000;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN:
{
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
{
issi = m_playerList.at(i)->issi;
break;
}
}
N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
TrainingAreaBase::TetraIcd::Sanitation sc = TrainingAreaBase::TetraIcd::Sanitation::fromJson(tele->jsonData());
delete tele;
ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << sc.proceduresTaken;
sendTelegram(sc, issi); // resend
return;
}
case GEF_TREFFER_AUSLOESUNG: // we have got a new status (f.g. wounded lying) and send back our new status
case GEF_INIT: // ?? .. or just act like this is a treffer ausloesung ....... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
TrainingAreaBase::TetraIcd::StateChange tele;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
DEBUG_LOG(m_logger) << " Try to Resetnd State " << sc.header.equipmentNumber << " we got procedure: " << sc.proceduresTaken;
sc.header.timeStamp = time(nullptr) * 1000;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
{
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
{
issi = m_playerList.at(i)->issi;
break;
}
}
ERROR_LOG(m_logger) << " Try to Resetnd S2tate " << sc.header.equipmentNumber << " we got state: " << sc.proceduresTaken;
sendTelegram(sc, issi); // resend
return;
}
case GEF_TREFFER_AUSLOESUNG: // we have got a new status (f.g. wounded lying) and send back our new status
case GEF_INIT: // ?? .. or just act like this is a treffer ausloesung ....... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
TrainingAreaBase::TetraIcd::StateChange tele;
uint32_t issi = 0;
for (int i = 0; i < m_playerList.count(); i++) // get issi from player's eqId
{
issi = m_playerList.at(i)->issi;
break;
if (radioTelegram->getIdentity() == m_playerList.at(i)->eqId)
{
issi = m_playerList.at(i)->issi;
break;
}
}
TrainingAreaBase::TetraIcd::VulnerabilityState state = (telID == GEF_TREFFER_AUSLOESUNG)
? static_cast<TrainingAreaBase::TetraIcd::VulnerabilityState>(radioTelegram->getPayloadDataUInt8(7))
: TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady; //get vbg from radio
tele.originatorType = TrainingAreaBase::TetraIcd::OriginatorType::Initialisation; //set origin
tele.header.equipmentNumber = radioTelegram->getIdentity(); //set header
tele.header.timeStamp = time(nullptr) * 1000;
uint32_t vulcomplete = radioTelegram->getPayloadDataUInt32(8, 2);
uint32_t vitality = vulcomplete &= 0xF000;
vitality >>= 12;
tele.tasVulnerabilityKindId = vulcomplete &= 0x0FFF;
//including vitality
tele.tasVulnerabilityKindId <<= 16;
tele.tasVulnerabilityKindId |= 0xB1;
tele.tasVitality = (vitality - 1) * 10;
if (tele.tasVitality < 0)
tele.tasVitality = 100;
if (state == TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && vitality > 0)
tele.vulnerabilityState = TrainingAreaBase::TetraIcd::VulnerabilityState::MediumDamage;
else
tele.vulnerabilityState = state;
sendTelegram(tele, issi); // send new status
return;
}
TrainingAreaBase::TetraIcd::VulnerabilityState state = (telID == GEF_TREFFER_AUSLOESUNG)
? static_cast<TrainingAreaBase::TetraIcd::VulnerabilityState>(radioTelegram->getPayloadDataUInt8(7))
: TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady; //get vbg from radio
// case GEF_NLOS_DATENVERKEHR_TDS_GEF:
// {
// ERROR_LOG(m_logger) << "NlosTargetData empfangen";
// N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
// TrainingAreaBase::TetraIcd::NlosTargetData sc = TrainingAreaBase::TetraIcd::NlosTargetData::fromJson(tele->jsonData());
// delete tele;
// QJsonDocument doc(sc.toJson());
// ERROR_LOG(m_logger) << "Receive NlosTargetData Size: " << radioTelegram.data()->getSize() << "\n Structure: " << doc.toJson(QJsonDocument::Indented);
// return;
tele.originatorType = TrainingAreaBase::TetraIcd::OriginatorType::Initialisation; //set origin
tele.header.equipmentNumber = radioTelegram->getIdentity(); //set header
tele.header.timeStamp = time(nullptr) * 1000;
uint32_t vulcomplete = radioTelegram->getPayloadDataUInt32(8, 2);
uint32_t vitality = vulcomplete &= 0xF000;
vitality >>= 12;
tele.tasVulnerabilityKindId = vulcomplete &= 0x0FFF;
//including vitality
tele.tasVulnerabilityKindId <<= 16;
tele.tasVulnerabilityKindId |= 0xB1;
tele.tasVitality = (vitality - 1) * 10;
if (tele.tasVitality < 0)
tele.tasVitality = 100;
if (state == TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && vitality > 0)
tele.vulnerabilityState = TrainingAreaBase::TetraIcd::VulnerabilityState::MediumDamage;
else
tele.vulnerabilityState = state;
sendTelegram(tele, issi); // send new status
return;
}
// case GEF_NLOS_DATENVERKEHR_TDS_GEF:
// {
// ERROR_LOG(m_logger) << "NlosTargetData empfangen";
// N_CoPrtCnv::CoPrtCnvCentralTelegram *tele = N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToCentral(radioTelegram.data());
// TrainingAreaBase::TetraIcd::NlosTargetData sc = TrainingAreaBase::TetraIcd::NlosTargetData::fromJson(tele->jsonData());
// delete tele;
// QJsonDocument doc(sc.toJson());
// ERROR_LOG(m_logger) << "Receive NlosTargetData Size: " << radioTelegram.data()->getSize() << "\n Structure: " << doc.toJson(QJsonDocument::Indented);
// return;
// }
// }
}
// miscellaneous messages..
@@ -555,8 +554,7 @@ void TTWorker::handleDataIndReq(const QByteArray &data)
static void fillHeader(char *data, int len)
{
N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *hdr
= (N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *)data;
N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *hdr = (N_CoPrtCnv::CoPrtCnvRadioTelegram::PrtCnvRadioGwHeader *)data;
hdr->m_MagicNumber = N_CoPrtCnv::CoPrtCnvRadioTelegram::MAGIC_NUMBER;
hdr->m_Counter = 0;
hdr->m_Length = len;
@@ -582,12 +580,14 @@ void TTWorker::movePlayer(Player *p) // move the player like the pattern says
// use all variables from the Player POINTER (do not use new instances)
if (p->patternInList > m_patternList.count() - 1) // if patternInList is HIGHER than the list-count is, then jump back to position 0 to start again
p->patternInList = 0; // set to list-start
p->patternInList = 0; // set to list-start
else
{
if (p->stepInPattern > m_patternList.at(p->patternInList).steps) // if we have less steps than the stepInPattern says, then we have obsolved all wnted steps, so we can jump to the new pattern in the List
if (p->stepInPattern >
m_patternList.at(p->patternInList)
.steps) // if we have less steps than the stepInPattern says, then we have obsolved all wnted steps, so we can jump to the new pattern in the List
{
p->stepInPattern = 1; // reset steps for the new pattern
p->stepInPattern = 1; // reset steps for the new pattern
if (p->patternInList == m_patternList.count() - 1) // if there is NOT a next pattern, then reset pattern counter to 0
p->patternInList = 0;
else
@@ -595,10 +595,8 @@ void TTWorker::movePlayer(Player *p) // move the player like the pattern says
}
}
p->posUTM.setX(p->posUTM.x() +
m_patternList.at(p->patternInList).northering); // increase northering as the pattern says
p->posUTM.setY(p->posUTM.y() +
m_patternList.at(p->patternInList).ethering); // ^^^^^^^^ ethering ^^^^^^^^^^^^^^^^^^^
p->posUTM.setX(p->posUTM.x() + m_patternList.at(p->patternInList).northering); // increase northering as the pattern says
p->posUTM.setY(p->posUTM.y() + m_patternList.at(p->patternInList).ethering); // ^^^^^^^^ ethering ^^^^^^^^^^^^^^^^^^^
p->stepInPattern++; // increase the step counter before we leave, so the player can be moved the next time!!
}
@@ -621,8 +619,13 @@ void TTWorker::onSendPlayerPositions()
playerCount++;
// respawn :
if (p->vbg != TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady && p->isEndOfTicks()) // only count to zero (isEndOfTicks = are the ticks running out ?) for respawn, if Player is NOT alive!
sendTaktischerStatus(p->eqId, p->issi, TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady); // only give rebirth, do not kill //(unsigned short)!p->isAlive); // kill Player if he is alive, give rebirth to Player if he is dead
if (p->vbg != TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady &&
p->isEndOfTicks()) // only count to zero (isEndOfTicks = are the ticks running out ?) for respawn, if Player is NOT alive!
sendTaktischerStatus(
p->eqId,
p->issi,
TrainingAreaBase::TetraIcd::VulnerabilityState::
CombatReady); // only give rebirth, do not kill //(unsigned short)!p->isAlive); // kill Player if he is alive, give rebirth to Player if he is dead
tele.header.equipmentNumber = p->eqId;
if (m_toogle)
@@ -27,17 +27,14 @@ class QTimer;
class Player
{
private:
NGL::INGLLogger &m_logger;
void randomizeDeathTicks()
{
deathTicks = ((qrand() % (maximumDeathTicks - minimumDeathTicks + 1)) + minimumDeathTicks);
}
NGL::INGLLogger &m_logger;
void randomizeDeathTicks() { deathTicks = ((qrand() % (maximumDeathTicks - minimumDeathTicks + 1)) + minimumDeathTicks); }
public:
// PU simulation vars:
uint32_t eqId;
uint32_t issi;
QPointF posUTM;
QPointF posUTM;
// PU login-state vars:
bool isLogin;
@@ -54,17 +51,17 @@ public:
uint32_t maximumDeathTicks;
Player(int eqId_, int issi_, uint32_t minimumDeathTicks_, uint32_t maximumDeathTicks_, const QPointF &posUTM_)
: eqId(eqId_)
, issi(issi_)
, posUTM(posUTM_)
, isLogin(false)
, isValidBITE(false)
, vbg(TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady)
, patternInList(0)
, stepInPattern(1)
, deathTicks(0)
, minimumDeathTicks(minimumDeathTicks_)
, maximumDeathTicks(maximumDeathTicks_)
: eqId(eqId_)
, issi(issi_)
, posUTM(posUTM_)
, isLogin(false)
, isValidBITE(false)
, vbg(TrainingAreaBase::TetraIcd::VulnerabilityState::CombatReady)
, patternInList(0)
, stepInPattern(1)
, deathTicks(0)
, minimumDeathTicks(minimumDeathTicks_)
, maximumDeathTicks(maximumDeathTicks_)
{
randomizeDeathTicks();
}
@@ -107,8 +104,7 @@ protected:
void handleDataIndReq(const QByteArray &data);
void sendTelegram(N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram, uint32_t issi);
template <typename T>
void sendTelegram(const T &tele, uint32_t issi)
template <typename T> void sendTelegram(const T &tele, uint32_t issi)
{
N_CoPrtCnv::CoPrtCnvCentralTelegram ct(tele);
sendTelegram(N_CoPrtCnv::CoPrtCnvTelegramConverter::convertToRadio(&ct), issi);
@@ -13,23 +13,24 @@
namespace PrtCnv
{
LOGGER_T getLogger(const char *name)
{
static const char ns[] = "PRT.";
std::string loggerName;
const size_t len = strlen(name);
loggerName.reserve(sizeof(ns) + len);
loggerName.append(ns, sizeof(ns) - 1);
loggerName.append(name, len);
try {
return NGL::NGLLoggerBootstrap::getNGLRootLogger().
getNGLLogger( loggerName );
} catch ( const std::exception &ex )
LOGGER_T getLogger(const char *name)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
static const char ns[] = "PRT.";
std::string loggerName;
const size_t len = strlen(name);
loggerName.reserve(sizeof(ns) + len);
loggerName.append(ns, sizeof(ns) - 1);
loggerName.append(name, len);
try
{
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName);
}
catch (const std::exception &ex)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
}
}
}
} // namespace PrtCnv
@@ -13,11 +13,11 @@
namespace PrtCnv
{
typedef NGL::INGLLogger& LOGGER_T;
typedef NGL::INGLLogger &LOGGER_T;
LOGGER_T getLogger(const char *name);
inline LOGGER_T getLogger(const QString &loggerName)
{
return getLogger(loggerName.toUtf8().constData());
}
LOGGER_T getLogger(const char *name);
inline LOGGER_T getLogger(const QString &loggerName)
{
return getLogger(loggerName.toUtf8().constData());
}
} // namespace PrtCnv