-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqgpclient.cpp
More file actions
97 lines (83 loc) · 2.74 KB
/
qgpclient.cpp
File metadata and controls
97 lines (83 loc) · 2.74 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
95
96
97
#include "qgpclient.h"
void QGPClient::receiveData()
{
QByteArray data = tcpSocket->readAll();
int delimiter_index = data.indexOf("\r\n", 0);
while (data.size())
{
bufferMutex.lock();
buffer.append(data.mid(0, delimiter_index));
if (notificationSetting.testFlag(QGPClient::notifyEveryMsg))
emit msgReceived(buffer.last());
if (buffer.size() >= bufferSize){
if(notificationSetting.testFlag(QGPClient::notifyFullBuffer))
emit msgReceived(buffer.last());
while (buffer.size() > bufferSize)
buffer.removeFirst();
}
bufferMutex.unlock();
data.remove(0, delimiter_index+2);
delimiter_index = data.indexOf("\r\n", 0);
}
if(notificationSetting.testFlag(QGPClient::notifyEveryCycle))
emit msgReceived(buffer.last());
}
QGPClient::QGPClient(QObject * parent) : QObject(parent),
tcpSocket(new QTcpSocket())
{
ipPort = 4242;
ipAddress = "127.0.0.1";
bufferSize = 60*60*3;
connect(tcpSocket, &QTcpSocket::readyRead, this, &QGPClient::receiveData);
notificationSetting.setFlag(QGPClient::notifyEveryCycle, true);
//signal forwarding
connect(tcpSocket, &QTcpSocket::hostFound, this, &QGPClient::hostFound);
connect(tcpSocket, &QTcpSocket::connected, this, &QGPClient::connected);
connect(tcpSocket, &QTcpSocket::disconnected, this, &QGPClient::disconnected);
connect(tcpSocket, &QTcpSocket::stateChanged, this, &QGPClient::stateChanged);
connect(tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &QGPClient::error);
}
QGPClient::~QGPClient()
{
tcpSocket->abort();
delete tcpSocket;
}
bool QGPClient::clientConnect()
{
tcpSocket->connectToHost(ipAddress, ipPort);
if (tcpSocket->waitForConnected(1000)) return true;
return false;
}
bool QGPClient::clientDisconnect()
{
tcpSocket->disconnectFromHost();
if (tcpSocket->state() == QTcpSocket::UnconnectedState
|| tcpSocket->waitForDisconnected(1000))
return true;
return false;
}
void QGPClient::getMsgBuffer(QList<QByteArray> &data)
{
bufferMutex.lock();
data.clear();
buffer.swap(data);
bufferMutex.unlock();
}
QByteArray QGPClient::getLastMsg()
{
QByteArray temp;
bufferMutex.lock();
if (buffer.isEmpty()) return temp;
else {
temp = buffer.takeLast();
}
buffer.clear();
bufferMutex.unlock();
return temp;
}
void QGPClient::sendCmd(QByteArray cmd)
{
cmd = cmd + "\r\n";
tcpSocket->write(cmd, cmd.size());
tcpSocket->flush();
}