87 lines
2.6 KiB
C++
Executable File
87 lines
2.6 KiB
C++
Executable File
/**
|
|
* @RDE_HEADER@
|
|
* Access Data from TRIMBLE and emit contents as QByteArray
|
|
* $Id$
|
|
* $HeadURL$
|
|
* $Author$
|
|
*/
|
|
|
|
#include "socketreader.h"
|
|
|
|
#include <NGLLogger/NGLLoggerBootstrap.h>
|
|
|
|
#include <QtNetwork/QTcpSocket>
|
|
#include <QtCore/QTimer>
|
|
#include <QtCore/QCoreApplication>
|
|
#include <QtCore/QMetaEnum>
|
|
|
|
namespace HighLevelArchitecture {
|
|
|
|
SocketReader::SocketReader(QObject *parent)
|
|
: QThread(parent)
|
|
, m_socket(new QTcpSocket(this))
|
|
, m_hlaRequestIdentifier(0)
|
|
, m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("SocketReader"))
|
|
{
|
|
}
|
|
|
|
bool SocketReader::init(const QString &host, quint16 port, int hlaRequestIdentifier)
|
|
{
|
|
DEBUG_LOG(m_logger) << "SR " << hlaRequestIdentifier << ": Trying to establish connection to " << host << ":" << port;
|
|
|
|
m_hlaRequestIdentifier = hlaRequestIdentifier;
|
|
connect(m_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
|
|
connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
|
|
|
|
m_socket->connectToHost(host, port, QIODevice::ReadOnly);
|
|
return m_socket->waitForConnected(1000);
|
|
}
|
|
|
|
SocketReader::~SocketReader()
|
|
{
|
|
m_socket->disconnectFromHost();
|
|
// Gracely try to disconnect. If not successfull within 1000msecs, abort the socket.
|
|
if (m_socket->state() != QAbstractSocket::UnconnectedState &&
|
|
!m_socket->waitForDisconnected(1000))
|
|
m_socket->abort();
|
|
|
|
delete m_socket;
|
|
m_socket = 0;
|
|
}
|
|
|
|
void SocketReader::onReadyRead()
|
|
{
|
|
// Checked if this works and the whole chunk is read.
|
|
// No problems in extensive testing.
|
|
// Otherwise, we had to inspect the data and search for start and ending!
|
|
DEBUG_LOG(m_logger) << "SR "<< m_hlaRequestIdentifier << ": Data received, transmitting";
|
|
QByteArray ba(m_socket->readAll());
|
|
TRACE_LOG(m_logger) << "SR "<< m_hlaRequestIdentifier << ": Data contents: " << ba.constData();
|
|
emit newData(ba, m_hlaRequestIdentifier);
|
|
}
|
|
|
|
void SocketReader::stopThread()
|
|
{
|
|
QTimer::singleShot(0, this, SLOT(quit()));
|
|
while (!isFinished())
|
|
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
|
|
deleteLater();
|
|
}
|
|
|
|
void SocketReader::onSocketError(const QAbstractSocket::SocketError &error)
|
|
{
|
|
QString errorValue;
|
|
QMetaObject meta = QAbstractSocket::staticMetaObject;
|
|
for (int i=0; i < meta.enumeratorCount(); ++i) {
|
|
QMetaEnum m = meta.enumerator(i);
|
|
if (QString::fromLatin1(m.name()) == QLatin1String("SocketError")) {
|
|
errorValue = QLatin1String(m.valueToKey(error));
|
|
break;
|
|
}
|
|
}
|
|
|
|
ERROR_LOG(m_logger) << "SR "<< m_hlaRequestIdentifier << ": Socket Error: " << errorValue;
|
|
}
|
|
|
|
} // namespace HLA
|