-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.cpp
78 lines (59 loc) · 1.87 KB
/
connection.cpp
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
#include "connection.h"
#include <QJsonDocument>
#include <QJsonObject>
Connection::Connection(QObject *parent) :
QTcpSocket(parent)
{
connect(this, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
connect(this, SIGNAL(connected()), this, SLOT(processConnected()));
connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
}
bool Connection::sendEventMessage(const QString &eventMessage, const QVariant &data)
{
if(eventMessage.isEmpty())
return false;
QByteArray buffer = QString("{ \"type\": \"eventMessage\", \"identifier\": \"" + eventMessage + "\", \"data\": \"" + data.toString() + "\" }").toUtf8();
if(this->write(buffer) == buffer.size())
return true;
return false;
}
bool Connection::sendQMLRequest()
{
QString request = "{ \"type\" : \"eventMessage\", \"identifier\": \"QMLRequest\", \"data\": \"main\" }";
if(this->write(request.toUtf8()) == request.toUtf8().size())
return true;
return false;
}
int Connection::readDataIntoBuffer(int maxSize)
{
if(maxSize > MAX_BUFFER_SIZE)
return 0;
int bufferSizeBeforeRead = this->buffer.size();
if(bufferSizeBeforeRead >= MAX_BUFFER_SIZE)
{
this->abort();
return 0;
}
while(this->bytesAvailable() && this->buffer.size() < maxSize)
{
this->buffer.append(this->read(1));
}
return this->buffer.size() - bufferSizeBeforeRead;
}
void Connection::processReadyRead()
{
if(this->readDataIntoBuffer() <= 0)
return;
QJsonDocument tempDocument = QJsonDocument::fromJson(this->buffer);
QJsonObject recievedData = tempDocument.object();
if(recievedData["type"].toString() == "QMLCode")
{
emit newQMLCodeRecieved(recievedData["data"].toString());
this->buffer.clear();
return;
}
}
void Connection::processConnected()
{
this->sendQMLRequest();
}