aboutsummaryrefslogtreecommitdiffstats
path: root/app/qafbwsclient.cpp
blob: 633a66f5532c1bb66820c0c1119aabec8e260891 (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
 * Copyright (C) 2018 IoT.bzh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "qafbwsclient.h"
#include "qafbwsmsg.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QtDebug>

QAfbWsClient::QAfbWsClient(QObject* parent)
    : QObject{parent}
    , m_nextCallId{0}
{
    connect(&m_socket, SIGNAL(connected()), this, SLOT(onSocketConnected()));
    connect(&m_socket, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));
    connect(&m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
}

QUrl QAfbWsClient::url() const
{
    return m_socket.requestUrl();
}

QSharedPointer<QAfbWsMsg> QAfbWsClient::call(const QString& api, const QString& verb, const QJsonValue& args)
{
    while(m_calls.constFind(m_nextCallId) != m_calls.cend()) m_nextCallId++; // Make sure that callId is not currently used

    qDebug() << "QAfbWsClient::call(" << api << ", " << verb << ", " << args << ")";
    QJsonArray arr;
    arr.append(static_cast<int>(AfMsgType::Call));
    arr.append(m_nextCallId);
    arr.append(api + "/" + verb);
    arr.append(args);

    QJsonDocument doc;
    doc.setArray(arr);

    QSharedPointer<QAfbWsMsg> msg(new QAfbWsMsg(m_nextCallId, api, verb));
    m_calls[m_nextCallId] = msg;

    // TODO: handle failure of sendTextMessage
    m_socket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
    qDebug() << "m_socket.sendTextMessage(" << doc.toJson(QJsonDocument::Compact) << ")";

    m_nextCallId++;

    return msg;
}

void QAfbWsClient::onSocketConnected()
{
    qDebug() << "QAfbWsClient::onSocketConnected()";
    connect(&m_socket, SIGNAL(textMessageReceived(QString)), this, SLOT(onSocketTextMessageReceived(QString)));
    emit connected();
}

void QAfbWsClient::onSocketDisconnected()
{
    qDebug() << "QAfbWsClient::onSocketDisconnected()";
    m_nextCallId = 0;
    disconnect(&m_socket, SIGNAL(textMessageReceived(QString)), this, SLOT(onSocketTextMessageReceived(QString)));
    emit disconnected();
}

void QAfbWsClient::onSocketError(QAbstractSocket::SocketError err)
{
    qDebug() << "QAfbWsClient::onSocketError(" << err << ")";
    emit error(err, m_socket.errorString());
}

void QAfbWsClient::onSocketTextMessageReceived(QString msg)
{
    qDebug() << "QAfbWsClient::onSocketTextMessageReceived(" << msg << ")";

    if (msg.size() == 0)
    {
        qCritical() << "QAfbWsClient::onSocketTextMessageReceived: received an empty message.";
        return;
    }

    QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8());
    if (doc.isEmpty() || doc.isNull() || !doc.isArray())
    {
        qCritical() << "QAfbWsClient::onSocketTextMessageReceived: received an invalid message.";
        return;
    }

    QJsonArray arr = doc.array();
    AfMsgType msgType = static_cast<AfMsgType>(arr[0].toInt());
    int callId = arr[1].isString() ? arr[1].toString().toInt() : arr[1].toInt();
    QString api;
    QJsonValue value;

    switch(msgType)
    {
    case AfMsgType::Call:
        qCritical() << "QAfbWsClient::onSocketTextMessageReceived: Client received a call, which should not happen.";
        break;

    case AfMsgType::Event:
        qDebug() << "QAfbWsClient::onSocketTextMessageReceived: Client received an event.";
        // TODO: handle events
        value = arr[3];
        break;

    case AfMsgType::RetOk:
    case AfMsgType::RetErr:
        {
            value = arr[2];
            QMap<int, QSharedPointer<QAfbWsMsg>>::const_iterator it = m_calls.find(callId);
            if (it == m_calls.end())
            {
                qCritical() << "QAfbWsClient::onSocketTextMessageReceived: received a response to a not found query.";
                return;
            }

            QSharedPointer<QAfbWsMsg> m = *it;
            m_calls.remove(callId);
            m->close(msgType, value);
        }
        break;

    default:
        qCritical() << "QAfbWsClient::onSocketTextMessageReceived: Client received an unsupported message.";
        break;
    }
}

void QAfbWsClient::open(const QUrl& url)
{
    qDebug() << "QAfbWsClient::open(" << url << ")";
    m_socket.open(url);
}

void QAfbWsClient::close()
{
    qDebug() << "QAfbWsClient::close()";
    m_socket.close();
}