source: azure_iot_hub/trunk/app_iothub_client/src/client.c@ 389

Last change on this file since 389 was 389, checked in by coas-nagasima, 5 years ago

ビルドが通るよう更新

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 9.7 KB
Line 
1// Copyright (c) Microsoft. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4#include <stdio.h>
5#include <stdlib.h>
6
7/* This sample uses the _LL APIs of iothub_client for example purposes.
8That does not mean that HTTP only works with the _LL APIs.
9Simply changing the using the convenience layer (functions not having _LL)
10and removing calls to _DoWork will yield the same results. */
11
12#include "azure_c_shared_utility/threadapi.h"
13#include "azure_c_shared_utility/crt_abstractions.h"
14#include "azure_c_shared_utility/platform.h"
15#include "azure_c_shared_utility/shared_util_options.h"
16#include "iothub_client_ll.h"
17#include "iothub_message.h"
18#include "iothubtransporthttp.h"
19#include "iothubtransportmqtt_websockets.h"
20
21#ifdef _MSC_VER
22extern int sprintf_s(char* dst, size_t dstSizeInBytes, const char* format, ...);
23#endif // _MSC_VER
24
25#if 1//def MBED_BUILD_TIMESTAMP
26#define SET_TRUSTED_CERT_IN_SAMPLES
27#endif // MBED_BUILD_TIMESTAMP
28
29#ifdef SET_TRUSTED_CERT_IN_SAMPLES
30#include "certs.h"
31#endif // SET_TRUSTED_CERT_IN_SAMPLES
32
33/*String containing Hostname, Device Id & Device Key in the format: */
34/* "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>" */
35/* "HostName=<host_name>;DeviceId=<device_id>;SharedAccessSignature=<device_sas_token>" */
36static const char* connectionString = "[device connection string]";
37
38
39static int callbackCounter;
40static bool g_continueRunning;
41static char msgText[1024];
42static char propText[1024];
43#define MESSAGE_COUNT 5
44#define DOWORK_LOOP_NUM 3
45
46
47typedef struct EVENT_INSTANCE_TAG
48{
49 IOTHUB_MESSAGE_HANDLE messageHandle;
50 size_t messageTrackingId; // For tracking the messages within the user callback.
51} EVENT_INSTANCE;
52
53static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
54{
55 int* counter = (int*)userContextCallback;
56 const char* buffer;
57 size_t size;
58 MAP_HANDLE mapProperties;
59 const char* messageId;
60 const char* correlationId;
61 const char* contentType;
62 const char* contentEncoding;
63
64 // Message properties
65 if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL)
66 {
67 messageId = "<null>";
68 }
69
70 if ((correlationId = IoTHubMessage_GetCorrelationId(message)) == NULL)
71 {
72 correlationId = "<null>";
73 }
74
75 if ((contentType = IoTHubMessage_GetContentTypeSystemProperty(message)) == NULL)
76 {
77 contentType = "<null>";
78 }
79
80 if ((contentEncoding = IoTHubMessage_GetContentEncodingSystemProperty(message)) == NULL)
81 {
82 contentEncoding = "<null>";
83 }
84
85 // Message content
86 if (IoTHubMessage_GetByteArray(message, (const unsigned char**)&buffer, &size) != IOTHUB_MESSAGE_OK)
87 {
88 printf("unable to retrieve the message data\r\n");
89 }
90 else
91 {
92 (void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n Content-Type: %s\r\n Content-Encoding: %s\r\n Data: <<<%.*s>>> & Size=%d\r\n",
93 *counter, messageId, correlationId, contentType, contentEncoding, (int)size, buffer, (int)size);
94 // If we receive the work 'quit' then we stop running
95 if (size == (strlen("quit") * sizeof(char)) && memcmp(buffer, "quit", size) == 0)
96 {
97 g_continueRunning = false;
98 }
99 }
100
101 // Retrieve properties from the message
102 mapProperties = IoTHubMessage_Properties(message);
103 if (mapProperties != NULL)
104 {
105 const char*const* keys;
106 const char*const* values;
107 size_t propertyCount = 0;
108 if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
109 {
110 if (propertyCount > 0)
111 {
112 size_t index;
113
114 printf(" Message Properties:\r\n");
115 for (index = 0; index < propertyCount; index++)
116 {
117 (void)printf("\tKey: %s Value: %s\r\n", keys[index], values[index]);
118 }
119 (void)printf("\r\n");
120 }
121 }
122 }
123
124 /* Some device specific action code goes here... */
125 (*counter)++;
126 return IOTHUBMESSAGE_ACCEPTED;
127}
128
129static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
130{
131 EVENT_INSTANCE* eventInstance = (EVENT_INSTANCE*)userContextCallback;
132
133 (void)printf("Confirmation[%d] received for message tracking id = %zu with result = %s\r\n", callbackCounter, eventInstance->messageTrackingId, MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
134
135 /* Some device specific action code goes here... */
136 callbackCounter++;
137 IoTHubMessage_Destroy(eventInstance->messageHandle);
138}
139
140void iothub_client_run(void)
141{
142 IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
143
144 EVENT_INSTANCE messages[MESSAGE_COUNT];
145 double avgWindSpeed = 10.0;
146 double minTemperature = 20.0;
147 double minHumidity = 60.0;
148 int receiveContext = 0;
149
150 g_continueRunning = true;
151
152 srand((unsigned int)time(NULL));
153
154 callbackCounter = 0;
155
156 if (platform_init() != 0)
157 {
158 (void)printf("Failed to initialize the platform.\r\n");
159 }
160 else
161 {
162#if 0
163 (void)printf("Starting the IoTHub client sample HTTP...\r\n");
164 IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = HTTP_Protocol;
165#else
166 (void)printf("Starting the IoTHub client sample MQTT...\r\n");
167 IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = MQTT_WebSocket_Protocol;
168#endif
169
170 if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, protocol)) == NULL)
171 {
172 (void)printf("ERROR: iotHubClientHandle is NULL!\r\n");
173 }
174 else
175 {
176#if 0
177 HTTP_PROXY_OPTIONS proxy_options;
178 proxy_options.host_address = "proxy.example.com";
179 proxy_options.port = 8080;
180 proxy_options.username = NULL;
181 proxy_options.password = NULL;
182 if (IoTHubClient_LL_SetOption(iotHubClientHandle, OPTION_HTTP_PROXY, &proxy_options) != IOTHUB_CLIENT_OK)
183 {
184 printf("failure to set option \"HTTP Proxy\"\r\n");
185 }
186
187 long curl_verbose = 1;
188 if (IoTHubClient_LL_SetOption(iotHubClientHandle, OPTION_CURL_VERBOSE, &curl_verbose) != IOTHUB_CLIENT_OK)
189 {
190 printf("failure to set option \"CURL Verbose\"\r\n");
191 }
192#endif
193 unsigned int timeout = 241000;
194 // Because it can poll "after 9 seconds" polls will happen effectively // at ~10 seconds.
195 // Note that for scalabilty, the default value of minimumPollingTime
196 // is 25 minutes. For more information, see:
197 // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
198 unsigned int minimumPollingTime = 9;
199 if (IoTHubClient_LL_SetOption(iotHubClientHandle, "timeout", &timeout) != IOTHUB_CLIENT_OK)
200 {
201 printf("failure to set option \"timeout\"\r\n");
202 }
203
204 if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
205 {
206 printf("failure to set option \"MinimumPollingTime\"\r\n");
207 }
208
209#ifdef SET_TRUSTED_CERT_IN_SAMPLES
210 // For mbed add the certificate information
211 if (IoTHubClient_LL_SetOption(iotHubClientHandle, OPTION_TRUSTED_CERT, certificates) != IOTHUB_CLIENT_OK)
212 {
213 printf("failure to set option \"TrustedCerts\"\r\n");
214 }
215#endif // SET_TRUSTED_CERT_IN_SAMPLES
216 /* Setting Message call back, so we can receive Commands. */
217 if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK)
218 {
219 (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
220 }
221 else
222 {
223 (void)printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n");
224
225 /* Now that we are ready to receive commands, let's send some messages */
226 int iterator = 0;
227 double temperature = 0;
228 double humidity = 0;
229 do
230 {
231 //(void)printf("iterator: [%d], callbackCounter: [%d]. \r\n", iterator, callbackCounter);
232
233 if (iterator < MESSAGE_COUNT && (iterator <= callbackCounter))
234 {
235 temperature = minTemperature + (rand() % 10);
236 humidity = minHumidity + (rand() % 20);
237 sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", avgWindSpeed + (rand() % 4 + 2), temperature, humidity);
238 if ((messages[iterator].messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL)
239 {
240 (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n");
241 }
242 else
243 {
244 MAP_HANDLE propMap;
245
246 messages[iterator].messageTrackingId = iterator;
247
248 propMap = IoTHubMessage_Properties(messages[iterator].messageHandle);
249 (void)sprintf_s(propText, sizeof(propText), temperature > 28 ? "true" : "false");
250 if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK)
251 {
252 (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n");
253 }
254
255 (void)IoTHubMessage_SetContentTypeSystemProperty(messages[iterator].messageHandle, "application/json");
256 (void)IoTHubMessage_SetContentEncodingSystemProperty(messages[iterator].messageHandle, "utf-8");
257
258 if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messages[iterator].messageHandle, SendConfirmationCallback, &messages[iterator]) != IOTHUB_CLIENT_OK)
259 {
260 (void)printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n");
261 }
262 else
263 {
264 (void)printf("IoTHubClient_LL_SendEventAsync accepted message [%d] for transmission to IoT Hub.\r\n", iterator);
265 }
266 }
267 }
268
269 IoTHubClient_LL_DoWork(iotHubClientHandle);
270 ThreadAPI_Sleep(1);
271
272 iterator++;
273
274 if (callbackCounter >= MESSAGE_COUNT)
275 {
276 printf("exit\n");
277 break;
278 }
279 } while (g_continueRunning);
280
281 (void)printf("iothub_client_sample_http has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM);
282 for (size_t index = 0; index < DOWORK_LOOP_NUM; index++)
283 {
284 IoTHubClient_LL_DoWork(iotHubClientHandle);
285 ThreadAPI_Sleep(1);
286 }
287 }
288 IoTHubClient_LL_Destroy(iotHubClientHandle);
289 }
290 platform_deinit();
291 }
292}
293
294int iothub_client_main(int argc, char **argv)
295{
296 iothub_client_run();
297 return 0;
298}
Note: See TracBrowser for help on using the repository browser.