make protoconnection to invalid host less blocking

Former-commit-id: e7a89c87b15fbe9809ec63468b59ecc55c6d3e72
This commit is contained in:
redpanther 2016-02-25 15:21:25 +01:00
parent 878538eb50
commit ea89a85ddb
2 changed files with 45 additions and 9 deletions

View File

@ -7,6 +7,7 @@
#include <QColor>
#include <QImage>
#include <QTcpSocket>
#include <QTimer>
#include <QMap>
// hyperion util
@ -19,8 +20,11 @@
///
/// Connection class to setup an connection to the hyperion server and execute commands
///
class ProtoConnection
class ProtoConnection : public QObject
{
Q_OBJECT
public:
///
/// Constructor
@ -74,10 +78,13 @@ public:
///
void sendMessage(const proto::HyperionRequest & message);
private:
private slots:
/// Try to connect to the Hyperion host
void connectToHost();
private:
///
/// Parse a reply message
///
@ -99,4 +106,7 @@ private:
/// Skip receiving reply messages from Hyperion if set
bool _skipReply;
QTimer _timer;
QAbstractSocket::SocketState _prevSocketState;
};

View File

@ -9,7 +9,8 @@
ProtoConnection::ProtoConnection(const std::string & a) :
_socket(),
_skipReply(false)
_skipReply(false),
_prevSocketState(QAbstractSocket::UnconnectedState)
{
QString address(a.c_str());
QStringList parts = address.split(":");
@ -29,10 +30,18 @@ ProtoConnection::ProtoConnection(const std::string & a) :
// try to connect to host
std::cout << "Connecting to Hyperion: " << _host.toStdString() << ":" << _port << std::endl;
connectToHost();
// start the connection timer
_timer.setInterval(5000);
_timer.setSingleShot(false);
connect(&_timer,SIGNAL(timeout()), this, SLOT(connectToHost()) );
_timer.start();
}
ProtoConnection::~ProtoConnection()
{
_timer.stop();
_socket.close();
}
@ -91,20 +100,37 @@ void ProtoConnection::clearAll()
void ProtoConnection::connectToHost()
{
_socket.connectToHost(_host, _port);
if (_socket.waitForConnected()) {
std::cout << "Connected to Hyperion host" << std::endl;
// try connection only when
if (_socket.state() == QAbstractSocket::UnconnectedState)
{
_socket.connectToHost(_host, _port);
//_socket.waitForConnected(1000);
}
}
void ProtoConnection::sendMessage(const proto::HyperionRequest &message)
{
if (_socket.state() == QAbstractSocket::UnconnectedState)
// print out connection message only when state is changed
if (_socket.state() != _prevSocketState )
{
std::cout << "Currently disconnected: trying to connect to host" << std::endl;
connectToHost();
switch (_socket.state() )
{
case QAbstractSocket::UnconnectedState:
std::cout << "No connection to Hyperion: " << _host.toStdString() << ":" << _port << std::endl;
break;
case QAbstractSocket::ConnectedState:
std::cout << "Connected to Hyperion: " << _host.toStdString() << ":" << _port << std::endl;
break;
default:
//std::cout << "Connecting to Hyperion: " << _host.toStdString() << ":" << _port << std::endl;
break;
}
_prevSocketState = _socket.state();
}
if (_socket.state() != QAbstractSocket::ConnectedState)
{
return;