forked from hydronautics-team/PoolsideGUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathudp_client.cpp
More file actions
94 lines (78 loc) · 2.27 KB
/
udp_client.cpp
File metadata and controls
94 lines (78 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "udp_client.h"
#include <QNetworkDatagram>
#include <sstream>
UDP_Client::UDP_Client()
{
uv_interface = new IServerData();
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 7755);
connect(udpSocket, &QUdpSocket::readyRead,
this, &UDP_Client::readPendingDatagrams);
udpHostAddress = "127.0.0.1";
udpHostPort = 26782;
messageType = MESSAGE_NORMAL;
}
UDP_Client::~UDP_Client()
{
udpSocket->close();
delete udpSocket;
delete uv_interface;
delete timeoutTimer;
}
void UDP_Client::run()
{
try {
connectToHost();
}
catch (const std::invalid_argument& error) {
qDebug() << "[UDP_CLIENT_ERROR] " << error.what();
}
exec();
}
int UDP_Client::exec()
{
while(1)
{
QByteArray msg;
msg = uv_interface->generateMessage(messageType);
// qDebug() << "[UDP_CLIENT] Sending message type " << messageType << "||" << msg.size();
QNetworkDatagram datagram;
datagram.setData(msg);
udpSocket->writeDatagram(datagram);
msleep(100);
}
}
void UDP_Client::readPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
QNetworkDatagram datagram = udpSocket->receiveDatagram();
QByteArray msg = datagram.data();
bool exception_caught = false;
try {
uv_interface->parseMessage(msg, messageType);
}
catch(const std::invalid_argument& error) {
// qDebug() << "[UDP_CLIENT_ERROR] " << error.what();
exception_caught = true;
}
if(!exception_caught) {
// qDebug() << "[UDP_CLIENT] Message parced " << messageType << "||" << msg.size();
emit dataUpdated();
}
}
}
void UDP_Client::connectToHost()
{
QHostAddress udpQHostAddress;
if(!udpQHostAddress.setAddress(udpHostAddress)) {
std::stringstream stream;
stream << "Parsing UDP Host Address error. Address: [" <<
udpHostAddress.toStdString() << "]";
throw std::invalid_argument(stream.str());
return;
}
udpSocket->connectToHost(udpHostAddress, udpHostPort);
if (!udpSocket->waitForConnected(1000)) {
throw std::invalid_argument("Can't connect to host, connection timeout");
}
}