summaryrefslogtreecommitdiffstats
path: root/src/AwsClient.cpp
blob: 856eef071d23454fbc991474be890d1385c4c5d2 (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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#include "AwsClient.h"

#include <filesystem>

#include "aws_iot_config.h"
#include "aws_iot_mqtt_client_interface.h"

#include <nlohmann/json.hpp>

#include "CloudType.h"
#include "ClientManager.h"

#include <glib.h>
#include <afb/afb-binding.h> // for AFB_* logger

namespace
{

void aws_subscribe_callback(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen,
                            IoT_Publish_Message_Params *params, void *pData)
{
    (void)pClient;
    AFB_INFO("AWS subscribe callback: %.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, (char *) params->payload);

    if (!pData)
    {
        AFB_INFO("AwsClient is null");
        return;
    }

    AwsClient* aws = (AwsClient*)pData;

    std::string topic;
    if (topicName && topicNameLen > 0)
        topic.assign(topicName, topicNameLen);

    if (topic != aws->conf().mqtt_in_topic)
    {
        AFB_WARNING("Received message topic is not equal to configured: '%s'", topic.c_str());
        return;
    }

    if (!params || !params->payload || params->payloadLen <= 0)
    {
        AFB_WARNING("Received message doesn't contain payload");
        return;
    }

    const auto& pmsg = AwsClient::parseMessage(std::string((char*)params->payload, params->payloadLen));
    const auto& appid = pmsg.first;
    const auto& data = pmsg.second;
    if (appid.empty())
    {
        AFB_ERROR("Can't parse received message");
        return;
    }

    ClientManager::instance().emitReceivedMessage(appid, CloudType::Aws, data);
}

void aws_disconnect_callback(AWS_IoT_Client *pClient, void *data)
{
    (void)data;
    AFB_WARNING("AWS MQTT disconnect");
    IoT_Error_t rc = IoT_Error_t::FAILURE;

    if(pClient)
        return;

    if(aws_iot_is_autoreconnect_enabled(pClient))
    {
        AFB_INFO("Auto Reconnect is enabled. Reconnecting attempt will start now");
    }
    else
    {
        AFB_WARNING("Auto Reconnect not enabled. Starting manual reconnect...");
        rc = aws_iot_mqtt_attempt_reconnect(pClient);

        if(IoT_Error_t::NETWORK_RECONNECTED == rc)
            AFB_WARNING("Manual Reconnect Successful");
        else
            AFB_WARNING("Manual Reconnect Failed - %d", rc);
    }
}

} // end namespace

AwsClient::AwsClient() = default;

AwsClient::~AwsClient()
{
    stop();
}

// static
std::pair<std::string, std::string> AwsClient::parseMessage(const std::string& msg)
{
    std::string appid;
    std::string data;
    std::string cloud;
    try
    {
        const nlohmann::json& jmsg = nlohmann::json::parse(msg);
        appid = jmsg.at("application_id").get<std::string>();
        data = jmsg.at("data").get<std::string>();
    }
    catch (const std::exception& ex)
    {
        AFB_ERROR("Can't parse message (%s): %s", msg.c_str(), ex.what());
        appid.clear(); // indicate error
    }

    return {appid, data};
}

// static
std::string AwsClient::getApplicationId(const std::string& msg)
{
    std::string appid;
    try
    {
        const nlohmann::json& jmsg = nlohmann::json::parse(msg);
        appid = jmsg.at("application_id").get<std::string>();
    }
    catch (const std::exception& ex)
    {
        AFB_ERROR("Can't parse message (%s): %s", msg.c_str(), ex.what());
    }

    return appid;
}

void AwsClient::main_loop()
{
    IoT_Publish_Message_Params params;
    params.qos = QoS::QOS1;
    params.isRetained = 0;

    while(!m_thread_stop)
    {
        IoT_Error_t rc = aws_iot_mqtt_yield(m_aws_client.get(), 100);
        if(IoT_Error_t::NETWORK_ATTEMPTING_RECONNECT == rc)
        {
            // If the client is attempting to reconnect we will skip the rest of the loop.
            continue;
        }

        std::string data;
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            if (m_queue.empty())
                continue;

            data = std::move(m_queue.front());
            m_queue.pop_front();
        }
        params.payload = const_cast<char*>(data.c_str());
        params.payloadLen = data.length();


        std::string appid{getApplicationId(data)};
        if (appid.empty())
        {
            AFB_ERROR("Can't obtain application_id from scheduled message (msg will be dropped)");
            // ClientManager::instance().emitSendMessageConfirmation(appid, false);
            continue;
        }

        rc = IoT_Error_t::FAILURE;
        if (!appid.empty())
        {
            rc = aws_iot_mqtt_publish(m_aws_client.get(), m_conf.mqtt_out_topic.c_str(), (uint16_t)m_conf.mqtt_out_topic.length(), &params);
            if (rc == IoT_Error_t::MQTT_REQUEST_TIMEOUT_ERROR)
            {
                AFB_WARNING("Publish ack not received");
                //???? rc = IoT_Error_t::SUCCESS;
            }
        }

        ClientManager::instance().emitSendMessageConfirmation(appid, CloudType::Aws, rc == IoT_Error_t::SUCCESS);
    }
}

void AwsClient::start()
{
    if (m_started)
        return;

    if (!m_aws_client || !m_connected)
    {
        AFB_ERROR("Can't start AWS thread: connection is not created");
        return;
    }

    m_thread_stop = false;
    m_thread = std::thread(&AwsClient::main_loop, this);
    m_started = true;
}

void AwsClient::stop()
{
    if (m_thread.joinable())
    {
        AFB_DEBUG("Wait AWS thread...");
        m_thread_stop = true;
        m_thread.join();
        AFB_DEBUG("AWS thread joined");

        if (m_connected)
        {
            AFB_DEBUG("AWS disconnecting...");
            aws_iot_mqtt_unsubscribe(m_aws_client.get(), m_conf.mqtt_in_topic.c_str(), (uint16_t)m_conf.mqtt_in_topic.length());
            aws_iot_mqtt_disconnect(m_aws_client.get());
            aws_iot_mqtt_yield(m_aws_client.get(), 100);
            AFB_DEBUG("AWS disconnected");
        }
    }

    m_started = false;
}

bool AwsClient::createConnection()
{
    AFB_NOTICE("%s called", __FUNCTION__);

    if (m_aws_client)
    {
        AFB_ERROR("AWS connection already created");
        return false;
    }

    m_aws_client.reset(new AWS_IoT_Client);

    IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
    IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;

    AFB_DEBUG("rootCA cert %s", m_conf.root_ca_cert_path.c_str());
    AFB_DEBUG("client cert %s", m_conf.device_cert_path.c_str());
    AFB_DEBUG("client key %s", m_conf.device_priv_key_path.c_str());

    mqttInitParams.enableAutoReconnect = false; // We enable this later below
    mqttInitParams.pHostURL = const_cast<char*>(m_conf.mqtt_host.c_str());
    mqttInitParams.port = m_conf.mqtt_port;
    mqttInitParams.pRootCALocation = const_cast<char*>(m_conf.root_ca_cert_path.c_str());
    mqttInitParams.pDeviceCertLocation = const_cast<char*>(m_conf.device_cert_path.c_str());
    mqttInitParams.pDevicePrivateKeyLocation = const_cast<char*>(m_conf.device_priv_key_path.c_str());
    mqttInitParams.mqttCommandTimeout_ms = 20000;
    mqttInitParams.tlsHandshakeTimeout_ms = 5000;
    mqttInitParams.isSSLHostnameVerify = true;
    mqttInitParams.disconnectHandler = aws_disconnect_callback;
    mqttInitParams.disconnectHandlerData = nullptr;

    IoT_Error_t rc = aws_iot_mqtt_init(m_aws_client.get(), &mqttInitParams);
    if(IoT_Error_t::SUCCESS != rc)
    {
        AFB_ERROR("aws_iot_mqtt_init returned error: %d ", rc);
        return false;
    }

    connectParams.keepAliveIntervalInSec = 600;
    connectParams.isCleanSession = true;
    connectParams.MQTTVersion = MQTT_Ver_t::MQTT_3_1_1;
    connectParams.pClientID = const_cast<char*>(m_conf.mqtt_client_id.c_str());
    connectParams.clientIDLen = (uint16_t)m_conf.mqtt_client_id.size();
    connectParams.isWillMsgPresent = false;

    AFB_NOTICE("Connecting...");
    rc = aws_iot_mqtt_connect(m_aws_client.get(), &connectParams);
    if(IoT_Error_t::SUCCESS != rc)
    {
        AFB_NOTICE("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port);
        return false;
    }

    AFB_NOTICE("Subscribing...");
    rc = aws_iot_mqtt_subscribe(m_aws_client.get(), m_conf.mqtt_in_topic.c_str(), (uint16_t)m_conf.mqtt_in_topic.length(), QOS1, aws_subscribe_callback, this);
    if(IoT_Error_t::SUCCESS != rc)
    {
        AFB_ERROR("Error subscribing: %d ", rc);
        return false;
    }

    /*
      Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
       #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
       #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
    */
    rc = aws_iot_mqtt_autoreconnect_set_status(m_aws_client.get(), true);
    if(IoT_Error_t::SUCCESS != rc)
    {
        AFB_ERROR("Unable to set AutoReconnect to true: %d", rc);
        return false;
    }

    m_connected = true;

    if (!m_started)
        start();

    return true;
}

bool AwsClient::sendMessage(const std::string& appid, const std::string& data)
{
    if (!m_aws_client || !m_connected)
    {
        AFB_ERROR("AwsClient is not ready for message sending");
        return false;
    }

    nlohmann::json jmsg{
        {"application_id", appid},
        {"data", data}
    };

    const std::string& msg = jmsg.dump();

    {
        std::lock_guard<std::mutex> lock(m_mutex);

        if (m_queue.size() < MAX_QUEUE_SIZE)
        {
            m_queue.push_back(msg);
            AFB_DEBUG("AWS queue size: %lu", m_queue.size());
            return true;
        }
        else
        {
            AFB_ERROR("Can't send message: AWS queue size exceeded: %lu", m_queue.size());
        }
    }

    return false;
}

bool AwsClient::enabled() const
{
    return m_conf.enabled;
}

bool AwsClient::connected() const
{
    return m_connected;
}

const AwsClientConfig& AwsClient::conf() const
{
    return m_conf;
}

bool AwsClient::loadConf(GKeyFile* conf_file)
{
    g_autoptr(GError) error = nullptr;

    auto read_string = [&conf_file](const char* section, const char* key, std::string& set_to)
    {
        g_autoptr(GError) error = nullptr;
        g_autofree gchar *value = g_key_file_get_string(conf_file, section, key, &error);
        if (value == nullptr)
        {
            AFB_ERROR("Can't read %s/%s from config", section, key);
            return false;
        }
        if (!value[0])
        {
            AFB_ERROR("Value %s/%s is empty", section, key);
            return false;
        }
        set_to = value;
        return true;
    };

    auto check_file = [](const std::string& path)
    {
        if (!std::filesystem::exists(path))
        {
            AFB_ERROR("File %s doesn't exists", path.c_str());
            return false;
        }
        return true;
    };

    //-- AWS parameters:
    m_conf.enabled = g_key_file_get_boolean(conf_file, "AwsCloudConnection", "Enabled", &error);

    if (!m_conf.enabled)
        return true; // don't check other settings in this case

    if (!read_string("AwsCloudConnection", "MqttHost", m_conf.mqtt_host) ||
            !read_string("AwsCloudConnection", "MqttClientId", m_conf.mqtt_client_id) ||
            !read_string("AwsCloudConnection", "MqttOutTopic", m_conf.mqtt_out_topic) ||
            !read_string("AwsCloudConnection", "MqttInTopic", m_conf.mqtt_in_topic) ||
            !read_string("AwsCloudConnection", "ThingName", m_conf.thing_name) ||
            !read_string("AwsCloudConnection", "RootCaCert", m_conf.root_ca_cert_path) ||
            !read_string("AwsCloudConnection", "DeviceCert", m_conf.device_cert_path) ||
            !read_string("AwsCloudConnection", "DevicePrivKey", m_conf.device_priv_key_path))
    return false;

    m_conf.mqtt_port = (uint16_t)g_key_file_get_uint64(conf_file, "AwsCloudConnection", "MqttPort", &error);
    if (!m_conf.mqtt_port)
    {
        AFB_ERROR("Value AwsCloudConnection/MqttPort is not configured");
        return false;
    }

    if (!check_file(m_conf.root_ca_cert_path) || !check_file(m_conf.device_cert_path) || !check_file(m_conf.device_priv_key_path))
    return false;

    return true;
}