Projekt

Obecné

Profil

Stáhnout (15 KB) Statistiky
| Větev: | Tag: | Revize:
1
#include "curvedataserver.h"
2

    
3
#include <QDebug>
4
#include <QHostAddress>
5
#include <QAbstractSocket>
6
#include <QVector4D>
7
#include <chrono>
8

    
9
#include "../element/trajectory.hpp"
10

    
11
// Utility functions ///////////////////////////////////////////////////////////////////////////////////////////////////
12

    
13
static QByteArray message8(uint16_t messageId, uint8_t content = 0) {
14
    QByteArray result(2 + 1, 0);
15
    result[0] = ((uint8_t*) &messageId)[0];
16
    result[1] = ((uint8_t*) &messageId)[1];
17
    result[2] = content;
18
    return result;
19
}
20

    
21
static QByteArray message16(uint16_t messageId, uint16_t content = 0) {
22
    QByteArray result(2 + 2, 0);
23
    result[0] = ((uint8_t*) &messageId)[0];
24
    result[1] = ((uint8_t*) &messageId)[1];
25
    result[2] = ((uint8_t*) &content)[0];
26
    result[3] = ((uint8_t*) &content)[1];
27
    return result;
28
}
29

    
30
static QByteArray message32(uint16_t messageId, uint32_t content = 0) {
31
    QByteArray result(2 + 4, 0);
32
    result[0] = ((uint8_t*) &messageId)[0];
33
    result[1] = ((uint8_t*) &messageId)[1];
34
    result[2] = ((uint8_t*) &content)[0];
35
    result[3] = ((uint8_t*) &content)[1];
36
    result[4] = ((uint8_t*) &content)[2];
37
    result[5] = ((uint8_t*) &content)[3];
38
    return result;
39
}
40

    
41
static QByteArray message64(uint16_t messageId, uint64_t content = 0) {
42
    QByteArray result(2 + 8, 0);
43
    result[0] = ((uint8_t*) &messageId)[0];
44
    result[1] = ((uint8_t*) &messageId)[1];
45
    result[2] = ((uint8_t*) &content)[0];
46
    result[3] = ((uint8_t*) &content)[1];
47
    result[4] = ((uint8_t*) &content)[2];
48
    result[5] = ((uint8_t*) &content)[3];
49
    result[6] = ((uint8_t*) &content)[4];
50
    result[7] = ((uint8_t*) &content)[5];
51
    result[8] = ((uint8_t*) &content)[6];
52
    result[9] = ((uint8_t*) &content)[7];
53
    return result;
54
}
55

    
56
static QByteArray message128(uint16_t messageId,
57
                             uint32_t contentX = 0,
58
                             uint32_t contentY = 0,
59
                             uint32_t contentZ = 0,
60
                             uint32_t contentW = 0)
61
{
62
    QByteArray result(2 + 16, 0);
63
    result[0] = ((uint8_t*) &messageId)[0];
64
    result[1] = ((uint8_t*) &messageId)[1];
65

    
66
    result[2] = ((uint8_t*) &contentX)[0];
67
    result[3] = ((uint8_t*) &contentX)[1];
68
    result[4] = ((uint8_t*) &contentX)[2];
69
    result[5] = ((uint8_t*) &contentX)[3];
70

    
71
    result[6] = ((uint8_t*) &contentY)[0];
72
    result[7] = ((uint8_t*) &contentY)[1];
73
    result[8] = ((uint8_t*) &contentY)[2];
74
    result[9] = ((uint8_t*) &contentY)[3];
75

    
76
    result[10] = ((uint8_t*) &contentZ)[0];
77
    result[11] = ((uint8_t*) &contentZ)[1];
78
    result[12] = ((uint8_t*) &contentZ)[2];
79
    result[13] = ((uint8_t*) &contentZ)[3];
80

    
81
    result[14] = ((uint8_t*) &contentW)[0];
82
    result[15] = ((uint8_t*) &contentW)[1];
83
    result[16] = ((uint8_t*) &contentW)[2];
84
    result[17] = ((uint8_t*) &contentW)[3];
85
    return result;
86
}
87

    
88
static QByteArray messageVarLength(uint16_t messageId, uint32_t length, const char* content = nullptr) {
89
    QByteArray result(2 + 4 + length, 0);
90
    result[0] = ((uint8_t*) &messageId)[0];
91
    result[1] = ((uint8_t*) &messageId)[1];
92
    result[2] = ((uint8_t*) &length)[0];
93
    result[3] = ((uint8_t*) &length)[1];
94
    result[4] = ((uint8_t*) &length)[2];
95
    result[5] = ((uint8_t*) &length)[3];
96

    
97
    if (content) {
98
        for (uint32_t i = 0; i < length; i++) {
99
            result[6 + i] = content[i];
100
        }
101
    }
102
    return result;
103
}
104

    
105
inline uint64_t currentTimeMillis() {
106
    return std::chrono::duration_cast<std::chrono::milliseconds>(
107
                std::chrono::steady_clock::now().time_since_epoch())
108
            .count();
109
}
110

    
111

    
112
// Client //////////////////////////////////////////////////////////////////////////////////////////////////////////////
113

    
114
CurveDataServer::Client::Client(QTcpSocket* socket) :
115
    socket(socket),
116
    lastPong(currentTimeMillis()),
117
    bufUsed(0)
118
{}
119

    
120

    
121
// Server //////////////////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
CurveDataServer::CurveDataServer() :
124
    _server(this),
125
    _pingThread([this](){threadFunction();}),
126
    _sockets()
127
{
128
    _server.listen(QHostAddress::Any, 4242);
129
    connect(&_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
130
}
131

    
132
CurveDataServer::~CurveDataServer()
133
{
134
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
135
    for (auto& client : _sockets)
136
    {
137
        terminateConnection(client, "Server is stopping");
138
    }
139
    _sockets.clear();
140

    
141
    _threadIsRunning = false;
142
}
143

    
144
void CurveDataServer::onNewConnection()
145
{
146
    QTcpSocket *clientSocket = _server.nextPendingConnection();
147
    connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
148
    connect(clientSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
149

    
150
    sendPreamble(clientSocket);
151
    _sockets.push_back(Client(clientSocket));
152
}
153

    
154
void CurveDataServer::onSocketStateChanged(QAbstractSocket::SocketState socketState)
155
{
156
    if (socketState == QAbstractSocket::UnconnectedState)
157
    {
158
        QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
159

    
160
        removeSocket(sender);
161
    }
162
}
163

    
164
void CurveDataServer::onReadyRead()
165
{
166
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
167

    
168
    QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
169
    auto it = clientOf(sender);
170
    if (it == _sockets.end()) {
171
        return;
172
    }
173
    Client& client = *it;
174

    
175
    while (sender->bytesAvailable()) {
176
        if (client.bufUsed < Client::MESSAGE_ID_SIZE) {
177
            qint64 toRead = qMin(qint64(Client::MESSAGE_ID_SIZE - client.bufUsed), sender->bytesAvailable());
178
            client.bufUsed += sender->read(&client.buf[client.bufUsed], toRead);
179
        }
180

    
181
        if (client.bufUsed < 2) {
182
            // no ID yet, wait for more data
183
            return;
184
        }
185

    
186
        uint16_t messageId = *((uint16_t*) client.buf);
187
        qint64 contentSize;
188
        switch (messageId & 0xF000) {
189
        case 0x0000:
190
            contentSize = 1;
191
            break;
192
        case 0x1000:
193
            contentSize = 2;
194
            break;
195
        case 0x2000:
196
            contentSize = 4;
197
            break;
198
        case 0x3000:
199
            contentSize = 8;
200
            break;
201
        case 0x4000:
202
            contentSize = 16;
203
            break;
204
        case 0xF000:
205
            // TODO - implement support for variable length messages
206
            contentSize = 0;
207
            break;
208
        default:
209
            // unsupported message size
210
            return;
211
        }
212

    
213
        qint64 toRead = qMin(qint64(contentSize - (client.bufUsed - Client::MESSAGE_ID_SIZE)), sender->bytesAvailable());
214
        if (toRead > 0) {
215
            client.bufUsed += sender->read(&client.buf[client.bufUsed], toRead);
216
        }
217

    
218
        if (client.bufUsed == (Client::MESSAGE_ID_SIZE + contentSize)) {
219
            handleMessage(client, messageId, &client.buf[Client::MESSAGE_ID_SIZE]);
220
            client.bufUsed = 0;
221
        }
222
    }
223
}
224

    
225
void CurveDataServer::handleMessage(Client& client, uint16_t messageId, void *content) {
226
    switch (messageId) {
227
    case 0x3001:
228
        qDebug() << "Magic arrived!";
229
        handleProtocolMagic(client, (char *) content);
230
        break;
231
    case 0x2002:
232
        qDebug() << "Version arrived!";
233
        handleVersion(client, *((uint8_t*) content));
234
        break;
235
    case 0x3005:
236
        qDebug() << "Pong " << *((uint64_t*) content) << " arrived!";
237
        handlePong(client, (uint64_t*) content);
238
        break;
239
    case 0xF006:
240
        qDebug() << "EOT!";
241
        handleEOT(client, (char *) content);
242
        break;
243
    }
244
}
245

    
246
void CurveDataServer::handleProtocolMagic(Client& client, char *content)
247
{
248
    char *correct = "DeltaRVr";
249

    
250
    if (strncmp(content, correct, 8) == 0) {
251
        client.magic = true;
252
    }
253
}
254

    
255
void CurveDataServer::handleVersion(Client& client, uint8_t content)
256
{
257
    if (((uint8_t*) &content)[0] == 1)
258
    {
259
        client.version = true;
260
    }
261
}
262

    
263
void CurveDataServer::handlePong(Client& client, uint64_t* content)
264
{
265

    
266
    uint64_t time = currentTimeMillis();
267

    
268
    uint64_t number = *content;
269

    
270
    uint64_t timeSent = client.ping.at(number);
271

    
272
    client.ping.erase(number);
273

    
274
    client.latency = time - timeSent;
275
    client.lastPong = time;
276
    //qDebug() << "prisel pong" << number;
277
}
278

    
279
void CurveDataServer::handleEOT(Client& client, char* content)
280
{
281
    qDebug() << "Client" << client.socket->peerName() << "disconnected:" << content;
282
    terminateConnection(client, "Recieved EOT from client");
283
}
284

    
285

    
286
void CurveDataServer::terminateConnection(Client& client, std::string&& reason)
287
{
288
    if (client.socket->isOpen())
289
    {
290
        sendEot(client.socket, std::forward<std::string&&>(reason));
291

    
292
        client.socket->close();
293
    }
294

    
295
    removeSocket(client.socket);
296
}
297

    
298
void CurveDataServer::sendActuatorPosition(float x, float y, float z)
299
{
300
    QByteArray message = message128(0x4003,
301
                                    *((uint32_t*) &x),
302
                                    *((uint32_t*) &y),
303
                                    *((uint32_t*) &z));
304

    
305
    sendMessageToAllConnected(message);
306
}
307

    
308
void CurveDataServer::sendActualDirection(float x, float y, float z)
309
{
310
    QByteArray message = message128(0x4007,
311
                                    *((uint32_t*) &x),
312
                                    *((uint32_t*) &y),
313
                                    *((uint32_t*) &z));
314

    
315
    sendMessageToAllConnected(message);
316
}
317

    
318
void CurveDataServer::sendTargetDirection(float x, float y, float z)
319
{
320
    QByteArray message = message128(0x4008,
321
                                    *((uint32_t*) &x),
322
                                    *((uint32_t*) &y),
323
                                    *((uint32_t*) &z));
324

    
325
    sendMessageToAllConnected(message);
326
}
327

    
328
void CurveDataServer::sendNewCurve(QList<QVector3D> &points)
329
{
330
    int size = points.size();
331

    
332
    QByteArray message = messageVarLength(0xF009, (uint32_t) size * 12);
333

    
334
    for (int i = 0; i < size; i++)
335
    {
336
        float xf = points[i].x();
337
        float yf = points[i].y();
338
        float zf = points[i].z();
339

    
340
        uint8_t *x = ((uint8_t*) &xf);
341
        uint8_t *y = ((uint8_t*) &yf);
342
        uint8_t *z = ((uint8_t*) &zf);
343

    
344
        message[2 + 4 + i*12 + 0] = x[0];
345
        message[2 + 4 + i*12 + 1] = x[1];
346
        message[2 + 4 + i*12 + 2] = x[2];
347
        message[2 + 4 + i*12 + 3] = x[3];
348

    
349
        message[2 + 4 + i*12 + 4] = y[0];
350
        message[2 + 4 + i*12 + 5] = y[1];
351
        message[2 + 4 + i*12 + 6] = y[2];
352
        message[2 + 4 + i*12 + 7] = y[3];
353

    
354
        message[2 + 4 + i*12 + 8] = z[0];
355
        message[2 + 4 + i*12 + 9] = z[1];
356
        message[2 + 4 + i*12 + 10] = z[2];
357
        message[2 + 4 + i*12 + 11] = z[3];
358
    }
359

    
360
    sendMessageToAllConnected(message);
361

    
362

    
363
    std::lock_guard<decltype (_currentCurveLock)> l(_currentCurveLock);
364
    _currentCurve.clear();
365
    _currentCurve.append(points);
366
}
367

    
368
void CurveDataServer::sendNewCurve(QList<QVector4D> &points)
369
{
370
    QList<QVector3D> curve3d;
371
    int itemCount = points.size();
372

    
373
    curve3d.clear();
374
    if (itemCount > MAX_CURVE_SIZE)
375
        itemCount = MAX_CURVE_SIZE;
376
    for (int i = 0; i < itemCount; i++)
377
    {
378
        curve3d.append(points[i].toVector3D());
379
    }
380

    
381
    sendNewCurve(curve3d);
382
}
383

    
384
QList<CurveDataServer::Client>::iterator CurveDataServer::clientOf(QTcpSocket *socket) {
385
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
386
    for (auto it = _sockets.begin(); it != _sockets.end(); it++) {
387
        if (it->socket == socket) {
388
            return it;
389
        }
390
    }
391
    return _sockets.end();
392
}
393

    
394
void CurveDataServer::sendPreamble(QTcpSocket *socket)
395
{
396
    sendProtocolMagic(socket);
397
    sendVersion(socket);
398
}
399

    
400
void CurveDataServer::sendProtocolMagic(QTcpSocket *socket)
401
{
402
    char *messageContent = "DeltaRVr";
403
    QByteArray message = message64(0x3001, *((uint64_t*) messageContent));
404

    
405
    socket->write(message);
406

    
407
    qDebug() << "Sent Protocol Magic to" << socket->peerAddress();
408
}
409

    
410
void CurveDataServer::sendVersion(QTcpSocket *socket)
411
{
412
    QByteArray message = message32(0x2002, 1);
413

    
414
    socket->write(message);
415

    
416
    qDebug() << "Sent Protocol Version to" << socket->peerAddress();
417
}
418

    
419
void CurveDataServer::sendEot(QTcpSocket *socket, std::string&& reason)
420
{
421
    QByteArray message = messageVarLength(0xF006, ((uint32_t) reason.length()), reason.c_str());
422
    socket->write(message);
423
}
424

    
425

    
426

    
427
void CurveDataServer::sendMessageToAllConnected(QByteArray &message)
428
{
429
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
430
    for (auto& client : _sockets) {
431
        if (client.magic && client.version)
432
        {
433
            client.socket->write(message);
434
        }
435
    }
436
}
437

    
438
void CurveDataServer::threadFunction()
439
{
440
    while (_threadIsRunning)
441
    {
442
        //processPings();
443

    
444
        // TODO tim se zpravilo varovani se socketama
445

    
446
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
447
    }
448
}
449

    
450
void CurveDataServer::processPings()
451
{
452
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
453
    for (auto& client : _sockets) {
454

    
455
        if (client.magic && client.version)
456
        {
457
            if (client.lastPong  < currentTimeMillis() - 10000)
458
            {
459
                terminateConnection(client, "Timeout");
460
                continue;
461
            }
462

    
463
            sendPing(client);
464

    
465
            std::lock_guard<decltype (_currentCurveLock)> l(_currentCurveLock);
466
            if (!client.initialized && !_currentCurve.isEmpty())
467
            {
468
                sendCurve(client);
469
                client.initialized = true;
470
            }
471
        }
472
        else if (client.lastPong  < currentTimeMillis() - 10000)
473
        {
474
            terminateConnection(client, "Preamble timeout");
475
            continue;
476
        }
477
    }
478
}
479

    
480
void CurveDataServer::removeSocket(QTcpSocket *socket)
481
{
482
    std::lock_guard<decltype (_socketsLock)> l(_socketsLock);
483
    for (auto it = _sockets.begin(); it != _sockets.end(); it++) {
484
        if (it->socket == socket) {
485
            _sockets.erase(it);
486
            break;
487
        }
488
    }
489
}
490

    
491
void CurveDataServer::sendPing(Client& client)
492
{
493
    uint64_t number = (((uint64_t) rand()) << 32) + (uint64_t) rand();
494

    
495
    //qDebug() << "posilam ping" << ((qint64) number) << ".";
496

    
497
    client.ping.emplace(std::make_pair(number, currentTimeMillis()));
498
    //client.ping.insert({number, currentTimeMillis()});
499

    
500
    client.socket->write(message64(0x3004, (uint64_t) number));
501
}
502

    
503
void CurveDataServer::sendCurve(Client &client)
504
{
505
    int size = _currentCurve.size();
506

    
507
    QByteArray message = messageVarLength(0xF009, (uint32_t) size * 12);
508

    
509
    for (int i = 0; i < size; i++)
510
    {
511
        float xf = _currentCurve[i].x();
512
        float yf = _currentCurve[i].y();
513
        float zf = _currentCurve[i].z();
514

    
515
        uint8_t *x = ((uint8_t*) &xf);
516
        uint8_t *y = ((uint8_t*) &yf);
517
        uint8_t *z = ((uint8_t*) &zf);
518

    
519
        message[2 + 4 + i*12 + 0] = x[0];
520
        message[2 + 4 + i*12 + 1] = x[1];
521
        message[2 + 4 + i*12 + 2] = x[2];
522
        message[2 + 4 + i*12 + 3] = x[3];
523

    
524
        message[2 + 4 + i*12 + 4] = y[0];
525
        message[2 + 4 + i*12 + 5] = y[1];
526
        message[2 + 4 + i*12 + 6] = y[2];
527
        message[2 + 4 + i*12 + 7] = y[3];
528

    
529
        message[2 + 4 + i*12 + 8] = z[0];
530
        message[2 + 4 + i*12 + 9] = z[1];
531
        message[2 + 4 + i*12 + 10] = z[2];
532
        message[2 + 4 + i*12 + 11] = z[3];
533
    }
534

    
535
    client.socket->write(message);
536
}
(2-2/19)