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

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