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

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