Xin Zhang / Mbed OS samplemqtt

Dependencies:   azure-iot-c-sdk-f767zi

Fork of samplemqtt by Xin Zhang

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers iothub_client_sample_mqtt.c Source File

iothub_client_sample_mqtt.c

00001 // Copyright (c) Microsoft. All rights reserved.
00002 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
00003 
00004 #include <stdio.h>
00005 #include <stdlib.h>
00006 
00007 #include "azure-iot-sdk-c/iothub_client/inc/iothub_client.h"
00008 #include "azure-iot-sdk-c/iothub_client/inc/iothub_message.h"
00009 #include "azure-iot-sdk-c/c-utility/inc/azure_c_shared_utility/threadapi.h"
00010 #include "azure-iot-sdk-c/c-utility/inc/azure_c_shared_utility/crt_abstractions.h"
00011 #include "azure-iot-sdk-c/c-utility/inc/azure_c_shared_utility/platform.h"
00012 #include "azure-iot-sdk-c/iothub_client/inc/iothubtransportmqtt.h"
00013 #include "azure-iot-sdk-c/certs/certs.h"
00014 
00015 /*String containing Hostname, Device Id & Device Key in the format:                         */
00016 /*  "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"                */
00017 /*  "HostName=<host_name>;DeviceId=<device_id>;SharedAccessSignature=<device_sas_token>"    */
00018 static const char* connectionString = "HostName=test822.azure-devices.net;DeviceId=F767822;SharedAccessKey=O/65swintBRyPNxWhecZ0w8ZsnUG5bvzPXf4ChMv+Vw=";
00019 static int callbackCounter;
00020 static char msgText[1024];
00021 static char propText[1024];
00022 static bool g_continueRunning;
00023 #define MESSAGE_COUNT 5
00024 #define DOWORK_LOOP_NUM     3
00025 
00026 
00027 typedef struct EVENT_INSTANCE_TAG
00028 {
00029     IOTHUB_MESSAGE_HANDLE messageHandle;
00030     size_t messageTrackingId;  // For tracking the messages within the user callback.
00031 } EVENT_INSTANCE;
00032 
00033 static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
00034 {
00035     int* counter = (int*)userContextCallback;
00036     const char* buffer;
00037     size_t size;
00038     MAP_HANDLE mapProperties;
00039     const char* messageId;
00040     const char* correlationId;
00041 
00042     // Message properties
00043     if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL)
00044     {
00045         messageId = "<null>";
00046     }
00047 
00048     if ((correlationId = IoTHubMessage_GetCorrelationId(message)) == NULL)
00049     {
00050         correlationId = "<null>";
00051     }
00052 
00053     // Message content
00054     if (IoTHubMessage_GetByteArray(message, (const unsigned char**)&buffer, &size) != IOTHUB_MESSAGE_OK)
00055     {
00056         (void)printf("unable to retrieve the message data\r\n");
00057     }
00058     else
00059     {
00060         (void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n Data: <<<%.*s>>> & Size=%d\r\n", *counter, messageId, correlationId, (int)size, buffer, (int)size);
00061         // If we receive the work 'quit' then we stop running
00062         if (size == (strlen("quit") * sizeof(char)) && memcmp(buffer, "quit", size) == 0)
00063         {
00064             g_continueRunning = false;
00065         }
00066     }
00067 
00068     // Retrieve properties from the message
00069     mapProperties = IoTHubMessage_Properties(message);
00070     if (mapProperties != NULL)
00071     {
00072         const char*const* keys;
00073         const char*const* values;
00074         size_t propertyCount = 0;
00075         if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
00076         {
00077             if (propertyCount > 0)
00078             {
00079                 size_t index;
00080 
00081                 printf(" Message Properties:\r\n");
00082                 for (index = 0; index < propertyCount; index++)
00083                 {
00084                     (void)printf("\tKey: %s Value: %s\r\n", keys[index], values[index]);
00085                 }
00086                 (void)printf("\r\n");
00087             }
00088         }
00089     }
00090 
00091     /* Some device specific action code goes here... */
00092     (*counter)++;
00093     return IOTHUBMESSAGE_ACCEPTED;
00094 }
00095 
00096 static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
00097 {
00098     EVENT_INSTANCE* eventInstance = (EVENT_INSTANCE*)userContextCallback;
00099     (void)printf("Confirmation[%d] received for message tracking id = %lu with result = %s\r\n", callbackCounter, eventInstance->messageTrackingId, ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
00100     /* Some device specific action code goes here... */
00101     callbackCounter++;
00102     IoTHubMessage_Destroy(eventInstance->messageHandle);
00103 }
00104 
00105 void iothub_client_sample_mqtt_run(void)
00106 {
00107     IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
00108 
00109     EVENT_INSTANCE messages[MESSAGE_COUNT];
00110 
00111     g_continueRunning = true;
00112     srand((unsigned int)time(NULL));
00113     double avgWindSpeed = 10.0;
00114     
00115     callbackCounter = 0;
00116     int receiveContext = 0;
00117 
00118     if (platform_init() != 0)
00119     {
00120         (void)printf("Failed to initialize the platform.\r\n");
00121     }
00122     else
00123     {
00124         if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol)) == NULL)
00125         {
00126             (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
00127         }
00128         else
00129         {
00130             bool traceOn = true;
00131             IoTHubClient_LL_SetOption(iotHubClientHandle, "logtrace", &traceOn);
00132 
00133             // For mbed add the certificate information
00134             if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
00135             {
00136                 printf("failure to set option \"TrustedCerts\"\r\n");
00137             }
00138 
00139 
00140             /* Setting Message call back, so we can receive Commands. */
00141             if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
00142             {
00143                 (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
00144             }
00145             else
00146             {
00147                 (void)printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n");
00148 
00149                 /* Now that we are ready to receive commands, let's send some messages */
00150                 size_t iterator = 0;
00151                 do
00152                 {
00153                     if (iterator < MESSAGE_COUNT)
00154                     {
00155                         sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f}", avgWindSpeed + (rand() % 4 + 2));
00156                         if ((messages[iterator].messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL)
00157                         {
00158                             (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n");
00159                         }
00160                         else
00161                         {
00162                             messages[iterator].messageTrackingId = iterator;
00163                             MAP_HANDLE propMap = IoTHubMessage_Properties(messages[iterator].messageHandle);
00164                             (void)sprintf_s(propText, sizeof(propText), "PropMsg_%lu", iterator);
00165                             if (Map_AddOrUpdate(propMap, "PropName", propText) != MAP_OK)
00166                             {
00167                                 (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
00168                             }
00169 
00170                             if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messages[iterator].messageHandle, SendConfirmationCallback, &messages[iterator]) != IOTHUB_CLIENT_OK)
00171                             {
00172                                 (void)printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n");
00173                             }
00174                             else
00175                             {
00176                                 (void)printf("IoTHubClient_LL_SendEventAsync accepted message [%d] for transmission to IoT Hub.\r\n", (int)iterator);
00177                             }
00178                         }
00179                     }
00180                     IoTHubClient_LL_DoWork(iotHubClientHandle);
00181                     ThreadAPI_Sleep(1);
00182 
00183                     iterator++;
00184                 } while (g_continueRunning);
00185 
00186                 (void)printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
00187                 size_t index = 0;
00188                 for (index = 0; index < DOWORK_LOOP_NUM; index++)
00189                 {
00190                     IoTHubClient_LL_DoWork(iotHubClientHandle);
00191                     ThreadAPI_Sleep(1);
00192                 }
00193             }
00194             IoTHubClient_LL_Destroy(iotHubClientHandle);
00195         }
00196         platform_deinit();
00197     }
00198 }
00199