1
|
#ifndef CURVEDATASERVER_H
|
2
|
#define CURVEDATASERVER_H
|
3
|
|
4
|
#include <QObject>
|
5
|
#include <QTcpServer>
|
6
|
#include <QTcpSocket>
|
7
|
#include <map>
|
8
|
#include <mutex>
|
9
|
#include <thread>
|
10
|
|
11
|
class CurveDataServer : QObject
|
12
|
{
|
13
|
Q_OBJECT
|
14
|
|
15
|
public:
|
16
|
struct Client {
|
17
|
static const size_t BUF_SIZE = 4096;
|
18
|
static const size_t MESSAGE_ID_SIZE = 2;
|
19
|
|
20
|
QTcpSocket* socket;
|
21
|
std::map<uint64_t, uint64_t> ping; ///< key: ping ID; value: ping timestamp (msec);
|
22
|
uint64_t latency; ///< client's latency
|
23
|
uint64_t lastPong; ///< timestamp of last pong
|
24
|
|
25
|
char buf[BUF_SIZE];
|
26
|
size_t bufUsed;
|
27
|
|
28
|
bool magic = false;
|
29
|
bool version = false;
|
30
|
bool initialized = false;
|
31
|
|
32
|
Client(QTcpSocket* socket);
|
33
|
};
|
34
|
|
35
|
explicit CurveDataServer();
|
36
|
~CurveDataServer();
|
37
|
|
38
|
void sendActuatorPosition(float x, float y, float z);
|
39
|
void sendActualDirection(float x, float y, float z);
|
40
|
void sendTargetDirection(float x, float y, float z);
|
41
|
void sendNewCurve(QList<QVector4D> &points);
|
42
|
void sendNewCurve(QList<QVector3D> &points);
|
43
|
void sendCurve(Client &client);
|
44
|
|
45
|
void processPings(); ///< send pings, check timeouts
|
46
|
|
47
|
public slots:
|
48
|
void onNewConnection();
|
49
|
void onSocketStateChanged(QAbstractSocket::SocketState socketState);
|
50
|
void onReadyRead();
|
51
|
|
52
|
private:
|
53
|
QList<Client>::iterator clientOf(QTcpSocket *socket);
|
54
|
|
55
|
void handleMessage(Client& client, uint16_t messageId, void* content);
|
56
|
void handleProtocolMagic(Client& client, char* content);
|
57
|
void handleVersion(Client& client, uint8_t content);
|
58
|
void handlePong(Client& client, uint64_t* content);
|
59
|
void handleEOT(Client& client, char* content);
|
60
|
|
61
|
void validPreamble(Client& client);
|
62
|
void removeSocket(QTcpSocket *socket);
|
63
|
void terminateConnection(Client& client, std::string&& reason);
|
64
|
void sendPing(Client& client);
|
65
|
|
66
|
void sendPreamble(QTcpSocket *socket);
|
67
|
void sendProtocolMagic(QTcpSocket *socket);
|
68
|
void sendVersion(QTcpSocket *socket);
|
69
|
void sendEot(QTcpSocket *socket, std::string&& message);
|
70
|
|
71
|
void sendMessageToAllConnected(QByteArray &message);
|
72
|
|
73
|
void threadFunction();
|
74
|
|
75
|
QTcpServer _server;
|
76
|
std::thread _pingThread;
|
77
|
|
78
|
volatile bool _threadIsRunning = true;
|
79
|
|
80
|
std::recursive_mutex _socketsLock;
|
81
|
QList<Client> _sockets;
|
82
|
|
83
|
std::recursive_mutex _currentCurveLock;
|
84
|
QList<QVector3D> _currentCurve;
|
85
|
};
|
86
|
|
87
|
#endif // CURVEDATASERVER_H
|