aboutsummaryrefslogtreecommitdiffstats
path: root/src/cloudproxy-bindings.cpp
blob: 1a40730c1b0ddd738bae54032c8b1155b65d2bbe (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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
 * Copyright (C) 2020 MERA
 *
 * 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 <afb/afb-binding.h>
#include <json-c/json.h>

#include <memory>
#include <algorithm>

#include <iothub.h>
#include <iothub_device_client.h>
#include <iothub_client_options.h>
#include <iothub_message.h>
#include <iothubtransportmqtt.h>
#include <azure_c_shared_utility/threadapi.h> // ThreadAPI_Sleep()
#include <azure_c_shared_utility/tickcounter.h> // tickcounter_ms_t

#include "hmi-debug.h"
#include "utils.h"
#include "ClientManager.h"

#include <glib.h>

static const char* API_name{"cloudproxy"};

static std::string g_connectionString;
static IOTHUB_DEVICE_CLIENT_HANDLE g_device_handle{nullptr};
static bool g_iot_inited{false};



static utils::scope_exit g_destroy([]{
    if (g_iot_inited)
    {
        if (g_device_handle)
            IoTHubDeviceClient_Destroy(g_device_handle);

        IoTHub_Deinit();
    }
});


static bool loadConf()
{
    const char* CONF_FILE_PATH{"/etc/config.ini"};
    const char* DEFAULT_ETC_PATH{"/etc/cloudproxy-service"};
    const char *p = getenv("AFM_APP_INSTALL_DIR");
    if(!p)
    {
        HMI_ERROR("cloudproxy-service", "AFM_APP_INSTALL_DIR is not set, try to find conf in %s", DEFAULT_ETC_PATH);
        p = DEFAULT_ETC_PATH;
    }

    std::string conf_path = p;
    conf_path += CONF_FILE_PATH;

    g_autoptr(GKeyFile) conf_file = g_key_file_new();
    g_autoptr(GError) error = nullptr;

    if (!conf_file || !g_key_file_load_from_file(conf_file, conf_path.c_str(), G_KEY_FILE_NONE, &error))
    {
        HMI_ERROR("cloudproxy-service", "can't load file %s", conf_path.c_str());
        return false;
    }

    g_autofree gchar *value = g_key_file_get_string(conf_file, "AzureCloudConnection", "DeviceConnectionString", &error);
    if (value == nullptr)
    {
        HMI_ERROR("cloudproxy-service", "can't read DeviceConnectionString from config %d", conf_path.c_str());
        return false;
    }

    g_connectionString = value;
    if (g_connectionString.empty())
    {
        HMI_ERROR("cloudproxy-service", "DeviceConnectionString is empty");
        return false;
    }

    return true;
}


//--------------  Iot callbacks
static void connection_status_callback(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* user_context)
{
    HMI_NOTICE("cloudproxy-service", "%s called: result %d, reason %d", __FUNCTION__, result, reason);

    (void)reason;
    (void)user_context;
    // This sample DOES NOT take into consideration network outages.
    if (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED && reason == IOTHUB_CLIENT_CONNECTION_OK)
    {
        HMI_NOTICE("cloudproxy-service", "The device client is connected to iothub");
    }
    else
    {
        HMI_NOTICE("cloudproxy-service", "The device client has been disconnected");
    }
}

static IOTHUBMESSAGE_DISPOSITION_RESULT receive_msg_callback(IOTHUB_MESSAGE_HANDLE message, void* user_context)
{
    HMI_NOTICE("cloudproxy-service", "%s called", __FUNCTION__);
    (void)user_context;
    const char* messageId;
    const char* correlationId;

    IOTHUBMESSAGE_CONTENT_TYPE content_type = IoTHubMessage_GetContentType(message);

    if (content_type == IOTHUBMESSAGE_BYTEARRAY)
    {
        const unsigned char* buff_msg;
        size_t buff_len;

        if (IoTHubMessage_GetByteArray(message, &buff_msg, &buff_len) != IOTHUB_MESSAGE_OK)
        {
            HMI_ERROR("cloudproxy-service", "Failure retrieving byte array message");
        }
        else
        {
            HMI_NOTICE("cloudproxy-service", "Received Binary message, size %d, data '%.*s'", (int)buff_len, (int)buff_len, buff_msg);
        }

        const char* app_id = IoTHubMessage_GetProperty(message, "application_id");
        HMI_NOTICE("cloudproxy-service", "Received property 'application_id': %s", (app_id ? app_id : "<unavailable>"));

        if (app_id && app_id[0])
            ClientManager::instance().emitReceivedMessage(app_id, std::string((const char*)buff_msg, buff_len));
        else
            HMI_ERROR("cloudproxy-service", "Can't emit SendMessageConfirmation: appid is not valid");
    }
    else if (content_type == IOTHUBMESSAGE_STRING)
    {
        const char* string_msg = IoTHubMessage_GetString(message);
        if (string_msg == nullptr)
        {
            HMI_NOTICE("cloudproxy-service", "Failure retrieving String message");
        }
        else
        {
            HMI_NOTICE("cloudproxy-service", "Received String message, size %d, data '%s'", strlen(string_msg), string_msg);
        }

        const char* app_id = IoTHubMessage_GetProperty(message, "application_id");
        HMI_NOTICE("cloudproxy-service", "Received property 'application_id': %s", (app_id ? app_id : "<unavailable>"));

        if (app_id && app_id[0])
            ClientManager::instance().emitReceivedMessage(app_id, string_msg);
        else
            HMI_ERROR("cloudproxy-service", "Can't emit SendMessageConfirmation: appid is not valid");
    }
    else
    {
        HMI_ERROR("cloudproxy-service", "Unsupported message content type");
    }

    return IOTHUBMESSAGE_ACCEPTED;
}


static int device_method_callback(const char* method_name, const unsigned char* payload, size_t size, unsigned char** response, size_t* resp_size, void* userContextCallback)
{
    HMI_NOTICE("cloudproxy-service", "%s called, method_name %s", __FUNCTION__, method_name);

    const char* device_id = (const char*)userContextCallback;
    char* end = nullptr;
    int newInterval;

    int status = 501;
    const char* RESPONSE_STRING = "{ \"Response\": \"Unknown method requested.\" }";

    HMI_NOTICE("cloudproxy-service", "Device Method called for device %s", device_id);
    HMI_NOTICE("cloudproxy-service", "Device Method name:    %s", method_name);
    HMI_NOTICE("cloudproxy-service", "Device Method payload: %.*s", (int)size, (const char*)payload);

    HMI_NOTICE("cloudproxy-service", "Response status: %d", status);
    HMI_NOTICE("cloudproxy-service", "Response payload: %s", RESPONSE_STRING);

    *resp_size = strlen(RESPONSE_STRING);
    if ((*response = (unsigned char*)malloc(*resp_size)) == NULL)
    {
        status = -1;
    }
    else
    {
        memcpy(*response, RESPONSE_STRING, *resp_size);
    }

    return status;
}


static void send_confirm_callback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
    HMI_NOTICE("cloudproxy-service", "%s called, result %d", __FUNCTION__, result);
    (void)userContextCallback;
    // When a message is sent this callback will get invoked

    HMI_NOTICE("cloudproxy-service", "Confirmation callback result %s", MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));

    const char* appid = (const char*)userContextCallback;
    if (!appid || !appid[0])
    {
        HMI_ERROR("cloudproxy-service", "Confirmation callback: appid is not set");

        if (userContextCallback)
            free(userContextCallback);

        return;
    }

    ClientManager::instance().emitSendMessageConfirmation(appid, result == IOTHUB_CLIENT_CONFIRMATION_OK);
    free(userContextCallback);
}
//--------------

//-------------- help functions
static bool createConnection()
{
    HMI_NOTICE("cloudproxy-service", "%s called", __FUNCTION__);

    if (g_device_handle)
    {
        HMI_WARNING("cloudproxy-service", "connection already created");
        return true;
    }

    g_device_handle = IoTHubDeviceClient_CreateFromConnectionString(g_connectionString.c_str(), MQTT_Protocol);
    if (!g_device_handle)
    {
        HMI_ERROR("cloudproxy-service", "Failure creating IoTHubDeviceClient device");
        return false;
    }

    bool traceOn = false;
    IoTHubDeviceClient_SetOption(g_device_handle, OPTION_LOG_TRACE, &traceOn);
    IoTHubDeviceClient_SetConnectionStatusCallback(g_device_handle, connection_status_callback, nullptr);
    IoTHubDeviceClient_SetMessageCallback(g_device_handle, receive_msg_callback, nullptr);
    IoTHubDeviceClient_SetDeviceMethodCallback(g_device_handle, device_method_callback, nullptr);

    tickcounter_ms_t ms_delay = 10;
    IoTHubDeviceClient_SetOption(g_device_handle, OPTION_DO_WORK_FREQUENCY_IN_MS, &ms_delay); // DoWork multithread

    return true;
}

//--------------


static void pingSample(afb_req_t request)
{
   static int pingcount = 0;
   afb_req_success_f(request, json_object_new_int(pingcount), "Ping count = %d", pingcount);
   HMI_NOTICE("cloudproxy-service", "Verbosity macro at level notice invoked at ping invocation count = %d", pingcount);
   pingcount++;
}


static bool initAzureSdk()
{
    //Allow program to try to establish connection several times
    if (!g_iot_inited)
    {
        if(IoTHub_Init())
        {
            HMI_ERROR("cloudproxy-service","Azure IoTHub_Init() failed");
        }
        else
        {
            g_iot_inited = true;
        }
    }

    return g_iot_inited;
}

static void sendMessage(afb_req_t request)
{
    HMI_NOTICE("cloudproxy-service", "%s called", __FUNCTION__);

    json_object* object = afb_req_json(request);
    if (!object)
    {
        HMI_ERROR("cloudproxy-service", "Can't parse request");
        afb_req_fail_f(request, "failed", "called %s", __FUNCTION__);
        return;
    }

    const std::string appid{utils::get_application_id(request)};
    std::string data;
    json_object *obj_data;
    if(!json_object_object_get_ex(object, "data", &obj_data))
    {
        HMI_ERROR("cloudproxy-service", "can't obtain application_id or data from request");
        return;
    }
    data = json_object_get_string(obj_data);

    if (!g_device_handle && !createConnection())
    {
        HMI_ERROR("cloudproxy-service", "Can't create connection to cloud");
        afb_req_fail_f(request, "failed", "called %s", __FUNCTION__);
        return;
    }

    IOTHUB_MESSAGE_HANDLE message_handle = IoTHubMessage_CreateFromString(data.c_str());

    utils::scope_exit message_handle_destroy([&message_handle](){
        // The message is copied to the sdk, so the we can destroy it
        if (message_handle)
            IoTHubMessage_Destroy(message_handle);
    });

    if (!message_handle)
    {
        HMI_ERROR("cloudproxy-service", "Can't create IoTHubMessage message");
        afb_req_fail_f(request, "failed", "called %s", __FUNCTION__);
        return;
    }

    IoTHubMessage_SetProperty(message_handle, "application_id", appid.c_str());

    if (IoTHubDeviceClient_SendEventAsync(g_device_handle, message_handle, send_confirm_callback, strdup(appid.c_str())))
    {
        HMI_ERROR("cloudproxy-service", "Can't send IoTHubMessage message");
        afb_req_fail_f(request, "failed", "called %s", __FUNCTION__);
        return;
    }

    afb_req_success(request, json_object_new_object(), __FUNCTION__);
}


static void subscribe(afb_req_t request)
{
    HMI_NOTICE("cloudproxy-service", "%s called", __FUNCTION__);

    std::string req_appid{utils::get_application_id(request)};
    if(req_appid.empty())
    {
        HMI_ERROR("cloudproxy-service", "Can't subscribe: empty appid");
        afb_req_fail_f(request, "%s failed: application_id is not defined in request", __FUNCTION__);
        return;
    }

    if (!ClientManager::instance().handleRequest(request, __FUNCTION__, req_appid))
    {
        HMI_ERROR("cloudproxy-service", "%s failed in handleRequest", __FUNCTION__);
        afb_req_fail_f(request, "%s failed", __FUNCTION__);
    }
    else
    {
        afb_req_success(request, json_object_new_object(), __FUNCTION__);
    }
}

static void unsubscribe(afb_req_t request)
{
    HMI_NOTICE("cloudproxy-service", "%s called", __FUNCTION__);

    std::string req_appid{utils::get_application_id(request)};
    if(req_appid.empty())
    {
        HMI_ERROR("cloudproxy-service", "Can't unsubscribe: empty appid");
        afb_req_fail_f(request, "%s failed: application_id is not defined in request", __FUNCTION__);
        return;
    }

    if (!ClientManager::instance().handleRequest(request, __FUNCTION__, req_appid))
    {
        HMI_ERROR("cloudproxy-service", "%s failedin handleRequest", __FUNCTION__);
        afb_req_fail_f(request, "%s failed", __FUNCTION__);
    }
    else
    {
        afb_req_success(request, json_object_new_object(), __FUNCTION__);
    }
}

/*
 * array of the verbs exported to afb-daemon
 */
static const afb_verb_t verbs[]= {
    /* VERB'S NAME                 FUNCTION TO CALL                  */
    { .verb="ping",              .callback=pingSample             },
    { .verb="sendMessage",       .callback=sendMessage            },
    { .verb="subscribe",         .callback=subscribe              },
    { .verb="unsubscribe",       .callback=unsubscribe            },
    {nullptr } /* marker for end of the array */
};


static int preinit(afb_api_t api)
{
    HMI_NOTICE("cloudproxy-service", "binding preinit (was register)");

    if (!loadConf())
    {
        HMI_ERROR("cloudproxy-service", "Can't load configuration file or configuration is wrong");
        return -1;
    }

    if (!initAzureSdk())
    {
        HMI_ERROR("cloudproxy-service", "Can't initialize Azure SDK");
        return -1;
    }

    return 0;
}


static int init(afb_api_t api)
{
    HMI_NOTICE("cloudproxy-service","binding init");
    return (g_iot_inited ? 0 : -1);
}

const afb_binding_t afbBindingExport = {
    .api = "cloudproxy",
    .specification = nullptr,
    .info = nullptr,
    .verbs = verbs,
    .preinit = preinit,
    .init = init,
    .onevent = nullptr
};