Azure IoT / Mbed 2 deprecated simplesample_mqtt

Dependencies:   EthernetInterface NTPClient mbed-rtos mbed wolfSSL azure_c_shared_utility iothub_client azure_umqtt_c iothub_mqtt_transport serializer

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers simplesample_mqtt.c Source File

simplesample_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 //
00005 // IMPORTANT: Please read and understand serializer limitations and alternatives as
00006 //            described ../../readme.md before beginning to use the serializer.
00007 //
00008 
00009 #include <stdlib.h>
00010 
00011 #include <stdio.h>
00012 #include <stdint.h>
00013 
00014 /* This sample uses the _LL APIs of iothub_client for example purposes.
00015 That does not mean that MQTT only works with the _LL APIs.
00016 Simply changing the using the convenience layer (functions not having _LL)
00017 and removing calls to _DoWork will yield the same results. */
00018 
00019 #include "azure_c_shared_utility/threadapi.h"
00020 #include "azure_c_shared_utility/platform.h"
00021 #include "serializer.h"
00022 #include "iothub_client_ll.h"
00023 #include "iothubtransportmqtt.h"
00024 
00025 #ifdef MBED_BUILD_TIMESTAMP
00026 #define SET_TRUSTED_CERT_IN_SAMPLES
00027 #endif // MBED_BUILD_TIMESTAMP
00028 
00029 #ifdef SET_TRUSTED_CERT_IN_SAMPLES
00030 #include "certs.h"
00031 #endif // SET_TRUSTED_CERT_IN_SAMPLES
00032 
00033 
00034 /*String containing Hostname, Device Id & Device Key in the format:             */
00035 /*  "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"    */
00036 static const char* connectionString = "[device connection string]";
00037 
00038 // Define the Model
00039 BEGIN_NAMESPACE(WeatherStation);
00040 
00041 DECLARE_MODEL(ContosoAnemometer,
00042 WITH_DATA(ascii_char_ptr, DeviceId),
00043 WITH_DATA(int, WindSpeed),
00044 WITH_DATA(float, Temperature),
00045 WITH_DATA(float, Humidity),
00046 WITH_ACTION(TurnFanOn),
00047 WITH_ACTION(TurnFanOff),
00048 WITH_ACTION(SetAirResistance, int, Position)
00049 );
00050 
00051 END_NAMESPACE(WeatherStation);
00052 
00053 static char propText[1024];
00054 
00055 EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device)
00056 {
00057     (void)device;
00058     (void)printf("Turning fan on.\r\n");
00059     return EXECUTE_COMMAND_SUCCESS;
00060 }
00061 
00062 EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device)
00063 {
00064     (void)device;
00065     (void)printf("Turning fan off.\r\n");
00066     return EXECUTE_COMMAND_SUCCESS;
00067 }
00068 
00069 EXECUTE_COMMAND_RESULT SetAirResistance(ContosoAnemometer* device, int Position)
00070 {
00071     (void)device;
00072     (void)printf("Setting Air Resistance Position to %d.\r\n", Position);
00073     return EXECUTE_COMMAND_SUCCESS;
00074 }
00075 
00076 void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
00077 {
00078     unsigned int messageTrackingId = (unsigned int)(uintptr_t)userContextCallback;
00079 
00080     (void)printf("Message Id: %u Received.\r\n", messageTrackingId);
00081 
00082     (void)printf("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
00083 }
00084 
00085 static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size, ContosoAnemometer *myWeather)
00086 {
00087     static unsigned int messageTrackingId;
00088     IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
00089     if (messageHandle == NULL)
00090     {
00091         printf("unable to create a new IoTHubMessage\r\n");
00092     }
00093     else
00094     {
00095         MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);
00096         (void)sprintf_s(propText, sizeof(propText), myWeather->Temperature > 28 ? "true" : "false");
00097         if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
00098         {
00099             (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
00100         }
00101 
00102         if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
00103         {
00104             printf("failed to hand over the message to IoTHubClient");
00105         }
00106         else
00107         {
00108             printf("IoTHubClient accepted the message for delivery\r\n");
00109         }
00110         IoTHubMessage_Destroy(messageHandle);
00111     }
00112     messageTrackingId++;
00113 }
00114 
00115 /*this function "links" IoTHub to the serialization library*/
00116 static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
00117 {
00118     const unsigned char* buffer;
00119     size_t size;
00120     if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
00121     {
00122         (void)printf("unable to IoTHubMessage_GetByteArray\r\n");
00123     }
00124     else
00125     {
00126         /*buffer is not zero terminated*/
00127         char* temp = malloc(size + 1);
00128         if (temp == NULL)
00129         {
00130             (void)printf("failed to malloc\r\n");
00131         }
00132         else
00133         {
00134             (void)memcpy(temp, buffer, size);
00135             temp[size] = '\0';
00136             EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp);
00137             if (executeCommandResult != EXECUTE_COMMAND_SUCCESS)
00138             {
00139                 (void)printf("Execute command failed\r\n");
00140             }
00141             free(temp);
00142         }
00143     }
00144     // MQTT can only accept messages
00145     return IOTHUBMESSAGE_ACCEPTED;
00146 }
00147 
00148 void simplesample_mqtt_run(void)
00149 {
00150     if (platform_init() != 0)
00151     {
00152         (void)printf("Failed to initialize platform.\r\n");
00153     }
00154     else
00155     {
00156         if (serializer_init(NULL) != SERIALIZER_OK)
00157         {
00158             (void)printf("Failed on serializer_init\r\n");
00159         }
00160         else
00161         {
00162             IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
00163             srand((unsigned int)time(NULL));
00164             int avgWindSpeed = 10;
00165             float minTemperature = 20.0;
00166             float minHumidity = 60.0;
00167 
00168             if (iotHubClientHandle == NULL)
00169             {
00170                 (void)printf("Failed on IoTHubClient_LL_Create\r\n");
00171             }
00172             else
00173             {
00174 #ifdef SET_TRUSTED_CERT_IN_SAMPLES
00175                 // For mbed add the certificate information
00176                 if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
00177                 {
00178                     (void)printf("failure to set option \"TrustedCerts\"\r\n");
00179                 }
00180 #endif // SET_TRUSTED_CERT_IN_SAMPLES
00181 
00182 
00183                 ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer);
00184                 if (myWeather == NULL)
00185                 {
00186                     (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n");
00187                 }
00188                 else
00189                 {
00190                     if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK)
00191                     {
00192                         printf("unable to IoTHubClient_SetMessageCallback\r\n");
00193                     }
00194                     else
00195                     {
00196                         myWeather->DeviceId = "myFirstDevice";
00197                         myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2);
00198                         myWeather->Temperature = minTemperature + (rand() % 10);
00199                         myWeather->Humidity = minHumidity + (rand() % 20);
00200                         {
00201                             unsigned char* destination;
00202                             size_t destinationSize;
00203                             if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed, myWeather->Temperature, myWeather->Humidity) != CODEFIRST_OK)
00204                             {
00205                                 (void)printf("Failed to serialize\r\n");
00206                             }
00207                             else
00208                             {
00209                                 sendMessage(iotHubClientHandle, destination, destinationSize, myWeather);
00210                                 free(destination);
00211                             }
00212                         }
00213 
00214                         /* wait for commands */
00215                         while (1)
00216                         {
00217                             IoTHubClient_LL_DoWork(iotHubClientHandle);
00218                             ThreadAPI_Sleep(100);
00219                         }
00220                     }
00221 
00222                     DESTROY_MODEL_INSTANCE(myWeather);
00223                 }
00224                 IoTHubClient_LL_Destroy(iotHubClientHandle);
00225             }
00226             serializer_deinit();
00227         }
00228         platform_deinit();
00229     }
00230 }