-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.cpp
65 lines (55 loc) · 1.48 KB
/
connector.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
#include "connector.h"
#include <QTimer>
#include <QDebug>
Connector::Connector(QObject *parent) : QObject(parent),
m_socket(new QWebSocket()),
m_url("ws://192.168.101.101:8001/ws"),
m_reconnectTimer(new QTimer(this))
{
connect(m_socket, &QWebSocket::connected, this, &Connector::onSocketConnected);
connect(m_socket, &QWebSocket::disconnected, this, &Connector::onSocketDisconnected);
connect(m_socket, &QWebSocket::textMessageReceived, this, &Connector::onSocketMessageReceived);
connect(m_reconnectTimer, &QTimer::timeout, this, [=]() {
m_socket->abort();
m_socket->open(m_url);
});
}
Connector::~Connector()
{
delete m_socket;
}
void Connector::setConnectCallback(std::function<void (bool)> callback)
{
m_callback = callback;
}
void Connector::setJsonParserCallback(std::function<void (const QString &)> callback)
{
m_jsonParser = callback;
}
void Connector::setSendCallback(std::function<void ()> callback)
{
m_sendCallback = callback;
}
void Connector::open()
{
m_socket->open(m_url);
}
void Connector::onSocketDisconnected()
{
qDebug() << "disconnected ...";
m_callback(false);
}
void Connector::onSocketConnected()
{
qDebug() << "connected ...";
m_callback(true);
m_sendCallback();
}
void Connector::onSocketMessageReceived(const QString &message)
{
m_jsonParser(message);
}
void Connector::sendSocketMessage(const QByteArray &data)
{
/*qDebug() << "size : " << */m_socket->sendBinaryMessage(data);
}