Projekt

Obecné

Profil

Stáhnout (2.34 KB) Statistiky
| Větev: | Tag: | Revize:
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
public slots:
46
    void onNewConnection();
47
    void onSocketStateChanged(QAbstractSocket::SocketState socketState);
48
    void onReadyRead();
49

    
50
private:
51
    QList<Client>::iterator clientOf(QTcpSocket *socket);
52

    
53
    void handleMessage(Client& client, uint16_t messageId, void* content);
54
    void handleProtocolMagic(Client& client, char* content);
55
    void handleVersion(Client& client, uint8_t content);
56
    void handlePong(Client& client, void* content);
57
    void handleEOT(Client& client, void* content);
58

    
59
    void validPreamble(Client& client);
60
    void removeSocket(QTcpSocket *socket);
61
    void terminateConnection(Client& client, std::string&& reason);
62
    void sendPing(Client& client);
63

    
64
    void sendPreamble(QTcpSocket *socket);
65
    void sendProtocolMagic(QTcpSocket *socket);
66
    void sendVersion(QTcpSocket *socket);
67
    void sendEot(QTcpSocket *socket, std::string&& message);
68

    
69
    void sendMessageToAllConnected(QByteArray &message);
70

    
71
    void threadFunction();
72

    
73
    QTcpServer _server;
74
    std::thread _pingThread;
75

    
76
    volatile bool _threadIsRunning = true;
77

    
78
    std::recursive_mutex _socketsLock;
79
    QList<Client> _sockets;
80

    
81
    std::recursive_mutex _currentCurveLock;
82
    QList<QVector3D> _currentCurve;
83
};
84

    
85
#endif // CURVEDATASERVER_H
(3-3/19)