1 #include "aglsocketwrapper.h"
8 #include <QJsonDocument>
21 AglSocketWrapper::AglSocketWrapper(QObject *parent) :
23 , m_socket(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this))
25 connect(m_socket, &QWebSocket::connected, this, &AglSocketWrapper::connected);
26 connect(m_socket, &QWebSocket::disconnected, this, &AglSocketWrapper::disconnected);
27 connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
28 [](QAbstractSocket::SocketError error) -> void {
29 qWarning() << "AglSocketWrapper internal socket error" << error;
31 connect(m_socket, &QWebSocket::textMessageReceived,
32 this, [this](const QString &msg) -> void {
33 const QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8());
35 const QJsonArray msgArray = doc.array();
36 if (msgArray.count() >= 3) {
37 const int msgType = msgArray.at(0).toInt();
41 auto callbackIt = m_callbacks.find( msgArray.at(1).toString());
42 if (callbackIt != m_callbacks.constEnd()) {
43 (*callbackIt)(msgType == Success, msgArray.at(2));
44 m_callbacks.erase(callbackIt);
49 const QJsonObject eventObj = msgArray.at(2).toObject();
50 emit eventReceived(msgArray.at(1).toString(), eventObj.value(vshl::DATA_TAG));
59 qWarning() << "Unsupported message format:" << msg;
63 void AglSocketWrapper::open(const QUrl &url)
68 void AglSocketWrapper::close()
73 void AglSocketWrapper::apiCall(const QString &api, const QString &verb, const QJsonValue &args,
74 AglSocketWrapper::ApiCallback callback)
76 const QString id = QUuid::createUuid().toString();
78 m_callbacks.insert(id, callback);
81 callData.append(Call);
83 callData.append(api + QLatin1String("/") + verb);
84 callData.append(args);
86 const QString msg = QLatin1String(QJsonDocument(callData).toJson(QJsonDocument::Compact));
87 m_socket->sendTextMessage(msg);
89 qDebug() << Q_FUNC_INFO << "Data sent:" << msg;