-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathsample_azure_iot.c
628 lines (525 loc) · 27.5 KB
/
sample_azure_iot.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/* Copyright (c) Microsoft Corporation.
Licensed under the MIT License. */
/* Standard includes. */
#include <string.h>
#include <stdio.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo Specific configs. */
#include "demo_config.h"
/* Azure Provisioning/IoT Hub library includes */
#include "azure_iot_hub_client.h"
#include "azure_iot_provisioning_client.h"
/* Exponential backoff retry include. */
#include "backoff_algorithm.h"
/* Transport interface implementation include header for TLS. */
#include "transport_tls_socket.h"
/* Crypto helper header. */
#include "crypto.h"
/*-----------------------------------------------------------*/
/* Compile time error for undefined configs. */
#if !defined( democonfigHOSTNAME ) && !defined( democonfigENABLE_DPS_SAMPLE )
#error "Define the config democonfigHOSTNAME by following the instructions in file demo_config.h."
#endif
#if !defined( democonfigENDPOINT ) && defined( democonfigENABLE_DPS_SAMPLE )
#error "Define the config dps endpoint by following the instructions in file demo_config.h."
#endif
#ifndef democonfigROOT_CA_PEM
#error "Please define Root CA certificate of the IoT Hub(democonfigROOT_CA_PEM) in demo_config.h."
#endif
#if defined( democonfigDEVICE_SYMMETRIC_KEY ) && defined( democonfigCLIENT_CERTIFICATE_PEM )
#error "Please define only one auth democonfigDEVICE_SYMMETRIC_KEY or democonfigCLIENT_CERTIFICATE_PEM in demo_config.h."
#endif
#if !defined( democonfigDEVICE_SYMMETRIC_KEY ) && !defined( democonfigCLIENT_CERTIFICATE_PEM )
#error "Please define one auth democonfigDEVICE_SYMMETRIC_KEY or democonfigCLIENT_CERTIFICATE_PEM in demo_config.h."
#endif
/*-----------------------------------------------------------*/
/**
* @brief The maximum number of retries for network operation with server.
*/
#define sampleazureiotRETRY_MAX_ATTEMPTS ( 5U )
/**
* @brief The maximum back-off delay (in milliseconds) for retrying failed operation
* with server.
*/
#define sampleazureiotRETRY_MAX_BACKOFF_DELAY_MS ( 5000U )
/**
* @brief The base back-off delay (in milliseconds) to use for network operation retry
* attempts.
*/
#define sampleazureiotRETRY_BACKOFF_BASE_MS ( 500U )
/**
* @brief Timeout for receiving CONNACK packet in milliseconds.
*/
#define sampleazureiotCONNACK_RECV_TIMEOUT_MS ( 10 * 1000U )
/**
* @brief The Telemetry message published in this example.
*/
#define sampleazureiotMESSAGE "Hello World : %d !"
/**
* @brief The reported property payload to send to IoT Hub
*/
#define sampleazureiotPROPERTY "{ \"PropertyIterationForCurrentConnection\": \"%d\" }"
/**
* @brief Time in ticks to wait between each cycle of the demo implemented
* by prvMQTTDemoTask().
*/
#define sampleazureiotDELAY_BETWEEN_DEMO_ITERATIONS_TICKS ( pdMS_TO_TICKS( 5000U ) )
/**
* @brief Timeout for MQTT_ProcessLoop in milliseconds.
*/
#define sampleazureiotPROCESS_LOOP_TIMEOUT_MS ( 500U )
/**
* @brief Delay (in ticks) between consecutive cycles of MQTT publish operations in a
* demo iteration.
*
* Note that the process loop also has a timeout, so the total time between
* publishes is the sum of the two delays.
*/
#define sampleazureiotDELAY_BETWEEN_PUBLISHES_TICKS ( pdMS_TO_TICKS( 2000U ) )
/**
* @brief Transport timeout in milliseconds for transport send and receive.
*/
#define sampleazureiotTRANSPORT_SEND_RECV_TIMEOUT_MS ( 2000U )
/**
* @brief Transport timeout in milliseconds for transport send and receive.
*/
#define sampleazureiotProvisioning_Registration_TIMEOUT_MS ( 3 * 1000U )
/**
* @brief Wait timeout for subscribe to finish.
*/
#define sampleazureiotSUBSCRIBE_TIMEOUT ( 10 * 1000U )
/*-----------------------------------------------------------*/
/**
* @brief Unix time.
*
* @return Time in milliseconds.
*/
uint64_t ullGetUnixTime( void );
/*-----------------------------------------------------------*/
/* Define buffer for IoT Hub info. */
#ifdef democonfigENABLE_DPS_SAMPLE
static uint8_t ucSampleIotHubHostname[ 128 ];
static uint8_t ucSampleIotHubDeviceId[ 128 ];
static AzureIoTProvisioningClient_t xAzureIoTProvisioningClient;
#endif /* democonfigENABLE_DPS_SAMPLE */
static uint8_t ucPropertyBuffer[ 32 ];
static uint8_t ucScratchBuffer[ 128 ];
/* Each compilation unit must define the NetworkContext struct. */
struct NetworkContext
{
TlsTransportParams_t * pParams;
};
static AzureIoTHubClient_t xAzureIoTHubClient;
/*-----------------------------------------------------------*/
#ifdef democonfigENABLE_DPS_SAMPLE
/**
* @brief Gets the IoT Hub endpoint and deviceId from Provisioning service.
* This function will block for Provisioning service for result or return failure.
*
* @param[in] pXNetworkCredentials Network credential used to connect to Provisioning service
* @param[out] ppucIothubHostname Pointer to uint8_t* IoT Hub hostname return from Provisioning Service
* @param[in,out] pulIothubHostnameLength Length of hostname
* @param[out] ppucIothubDeviceId Pointer to uint8_t* deviceId return from Provisioning Service
* @param[in,out] pulIothubDeviceIdLength Length of deviceId
*/
static uint32_t prvIoTHubInfoGet( NetworkCredentials_t * pXNetworkCredentials,
uint8_t ** ppucIothubHostname,
uint32_t * pulIothubHostnameLength,
uint8_t ** ppucIothubDeviceId,
uint32_t * pulIothubDeviceIdLength );
#endif /* democonfigENABLE_DPS_SAMPLE */
/**
* @brief The task used to demonstrate the MQTT API.
*
* @param[in] pvParameters Parameters as passed at the time of task creation. Not
* used in this example.
*/
static void prvAzureDemoTask( void * pvParameters );
/**
* @brief Connect to endpoint with reconnection retries.
*
* If connection fails, retry is attempted after a timeout.
* Timeout value will exponentially increase until maximum
* timeout value is reached or the number of attempts are exhausted.
*
* @param pcHostName Hostname of the endpoint to connect to.
* @param ulPort Endpoint port.
* @param pxNetworkCredentials Pointer to Network credentials.
* @param pxNetworkContext Point to Network context created.
* @return uint32_t The status of the final connection attempt.
*/
static uint32_t prvConnectToServerWithBackoffRetries( const char * pcHostName,
uint32_t ulPort,
NetworkCredentials_t * pxNetworkCredentials,
NetworkContext_t * pxNetworkContext );
/*-----------------------------------------------------------*/
/**
* @brief Static buffer used to hold MQTT messages being sent and received.
*/
static uint8_t ucMQTTMessageBuffer[ democonfigNETWORK_BUFFER_SIZE ];
/*-----------------------------------------------------------*/
/**
* @brief Cloud message callback handler
*/
static void prvHandleCloudMessage( AzureIoTHubClientCloudToDeviceMessageRequest_t * pxMessage,
void * pvContext )
{
( void ) pvContext;
LogInfo( ( "Cloud message payload : %.*s \r\n",
pxMessage->ulPayloadLength,
pxMessage->pvMessagePayload ) );
}
/*-----------------------------------------------------------*/
/**
* @brief Command message callback handler
*/
static void prvHandleCommand( AzureIoTHubClientCommandRequest_t * pxMessage,
void * pvContext )
{
LogInfo( ( "Command payload : %.*s \r\n",
pxMessage->ulPayloadLength,
pxMessage->pvMessagePayload ) );
AzureIoTHubClient_t * xHandle = ( AzureIoTHubClient_t * ) pvContext;
if( AzureIoTHubClient_SendCommandResponse( xHandle, pxMessage, 200,
NULL, 0 ) != eAzureIoTSuccess )
{
LogInfo( ( "Error sending command response\r\n" ) );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Property mesage callback handler
*/
static void prvHandlePropertiesMessage( AzureIoTHubClientPropertiesResponse_t * pxMessage,
void * pvContext )
{
( void ) pvContext;
switch( pxMessage->xMessageType )
{
case eAzureIoTHubPropertiesGetMessage:
LogInfo( ( "Device property document GET received" ) );
break;
case eAzureIoTHubPropertiesReportedResponseMessage:
LogInfo( ( "Device property reported property response received" ) );
break;
case eAzureIoTHubPropertiesWritablePropertyMessage:
LogInfo( ( "Device property desired property received" ) );
break;
default:
LogError( ( "Unknown property message" ) );
}
LogInfo( ( "Property document payload : %.*s \r\n",
pxMessage->ulPayloadLength,
pxMessage->pvMessagePayload ) );
}
/*-----------------------------------------------------------*/
/**
* @brief Setup transport credentials.
*/
static uint32_t prvSetupNetworkCredentials( NetworkCredentials_t * pxNetworkCredentials )
{
pxNetworkCredentials->xDisableSni = pdFALSE;
/* Set the credentials for establishing a TLS connection. */
pxNetworkCredentials->pucRootCa = ( const unsigned char * ) democonfigROOT_CA_PEM;
pxNetworkCredentials->xRootCaSize = sizeof( democonfigROOT_CA_PEM );
#ifdef democonfigCLIENT_CERTIFICATE_PEM
pxNetworkCredentials->pucClientCert = ( const unsigned char * ) democonfigCLIENT_CERTIFICATE_PEM;
pxNetworkCredentials->xClientCertSize = sizeof( democonfigCLIENT_CERTIFICATE_PEM );
pxNetworkCredentials->pucPrivateKey = ( const unsigned char * ) democonfigCLIENT_PRIVATE_KEY_PEM;
pxNetworkCredentials->xPrivateKeySize = sizeof( democonfigCLIENT_PRIVATE_KEY_PEM );
#endif
return 0;
}
/*-----------------------------------------------------------*/
/**
* @brief Azure IoT demo task that gets started in the platform specific project.
* In this demo task, middleware API's are used to connect to Azure IoT Hub.
*/
static void prvAzureDemoTask( void * pvParameters )
{
int lPublishCount = 0;
uint32_t ulScratchBufferLength = 0U;
const int lMaxPublishCount = 5;
NetworkCredentials_t xNetworkCredentials = { 0 };
AzureIoTTransportInterface_t xTransport;
NetworkContext_t xNetworkContext = { 0 };
TlsTransportParams_t xTlsTransportParams = { 0 };
AzureIoTResult_t xResult;
uint32_t ulStatus;
AzureIoTHubClientOptions_t xHubOptions = { 0 };
AzureIoTMessageProperties_t xPropertyBag;
bool xSessionPresent;
#ifdef democonfigENABLE_DPS_SAMPLE
uint8_t * pucIotHubHostname = NULL;
uint8_t * pucIotHubDeviceId = NULL;
uint32_t pulIothubHostnameLength = 0;
uint32_t pulIothubDeviceIdLength = 0;
#else
uint8_t * pucIotHubHostname = ( uint8_t * ) democonfigHOSTNAME;
uint8_t * pucIotHubDeviceId = ( uint8_t * ) democonfigDEVICE_ID;
uint32_t pulIothubHostnameLength = sizeof( democonfigHOSTNAME ) - 1;
uint32_t pulIothubDeviceIdLength = sizeof( democonfigDEVICE_ID ) - 1;
#endif /* democonfigENABLE_DPS_SAMPLE */
( void ) pvParameters;
/* Initialize Azure IoT Middleware. */
configASSERT( AzureIoT_Init() == eAzureIoTSuccess );
ulStatus = prvSetupNetworkCredentials( &xNetworkCredentials );
configASSERT( ulStatus == 0 );
#ifdef democonfigENABLE_DPS_SAMPLE
/* Run DPS. */
if( ( ulStatus = prvIoTHubInfoGet( &xNetworkCredentials, &pucIotHubHostname,
&pulIothubHostnameLength, &pucIotHubDeviceId,
&pulIothubDeviceIdLength ) ) != 0 )
{
LogError( ( "Failed on sample_dps_entry!: error code = 0x%08x\r\n", ulStatus ) );
return;
}
#endif /* democonfigENABLE_DPS_SAMPLE */
xNetworkContext.pParams = &xTlsTransportParams;
for( ; ; )
{
/* Attempt to establish TLS session with IoT Hub. If connection fails,
* retry after a timeout. Timeout value will be exponentially increased
* until the maximum number of attempts are reached or the maximum timeout
* value is reached. The function returns a failure status if the TCP
* connection cannot be established to the IoT Hub after the configured
* number of attempts. */
ulStatus = prvConnectToServerWithBackoffRetries( ( const char * ) pucIotHubHostname,
democonfigIOTHUB_PORT,
&xNetworkCredentials, &xNetworkContext );
configASSERT( ulStatus == 0 );
/* Fill in Transport Interface send and receive function pointers. */
xTransport.pxNetworkContext = &xNetworkContext;
xTransport.xSend = TLS_Socket_Send;
xTransport.xRecv = TLS_Socket_Recv;
/* Init IoT Hub option */
xResult = AzureIoTHubClient_OptionsInit( &xHubOptions );
configASSERT( xResult == eAzureIoTSuccess );
xHubOptions.pucModuleID = ( const uint8_t * ) democonfigMODULE_ID;
xHubOptions.ulModuleIDLength = sizeof( democonfigMODULE_ID ) - 1;
xResult = AzureIoTHubClient_Init( &xAzureIoTHubClient,
pucIotHubHostname, pulIothubHostnameLength,
pucIotHubDeviceId, pulIothubDeviceIdLength,
&xHubOptions,
ucMQTTMessageBuffer, sizeof( ucMQTTMessageBuffer ),
ullGetUnixTime,
&xTransport );
configASSERT( xResult == eAzureIoTSuccess );
#ifdef democonfigDEVICE_SYMMETRIC_KEY
xResult = AzureIoTHubClient_SetSymmetricKey( &xAzureIoTHubClient,
( const uint8_t * ) democonfigDEVICE_SYMMETRIC_KEY,
sizeof( democonfigDEVICE_SYMMETRIC_KEY ) - 1,
Crypto_HMAC );
configASSERT( xResult == eAzureIoTSuccess );
#endif /* democonfigDEVICE_SYMMETRIC_KEY */
/* Sends an MQTT Connect packet over the already established TLS connection,
* and waits for connection acknowledgment (CONNACK) packet. */
LogInfo( ( "Creating an MQTT connection to %s.\r\n", pucIotHubHostname ) );
xResult = AzureIoTHubClient_Connect( &xAzureIoTHubClient,
false, &xSessionPresent,
sampleazureiotCONNACK_RECV_TIMEOUT_MS );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTHubClient_SubscribeCloudToDeviceMessage( &xAzureIoTHubClient, prvHandleCloudMessage,
&xAzureIoTHubClient, sampleazureiotSUBSCRIBE_TIMEOUT );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTHubClient_SubscribeCommand( &xAzureIoTHubClient, prvHandleCommand,
&xAzureIoTHubClient, sampleazureiotSUBSCRIBE_TIMEOUT );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTHubClient_SubscribeProperties( &xAzureIoTHubClient, prvHandlePropertiesMessage,
&xAzureIoTHubClient, sampleazureiotSUBSCRIBE_TIMEOUT );
configASSERT( xResult == eAzureIoTSuccess );
/* Get property document after initial connection */
xResult = AzureIoTHubClient_GetProperties( &xAzureIoTHubClient );
configASSERT( xResult == eAzureIoTSuccess );
/* Create a bag of properties for the telemetry */
xResult = AzureIoT_MessagePropertiesInit( &xPropertyBag, ucPropertyBuffer, 0, sizeof( xPropertyBag ) );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoT_MessagePropertiesAppend( &xPropertyBag, ( uint8_t * ) "name", sizeof( "name" ) - 1,
( uint8_t * ) "value", sizeof( "value" ) - 1 );
configASSERT( xResult == eAzureIoTSuccess );
/* Publish messages with QoS1, send and process Keep alive messages. */
for( lPublishCount = 0; lPublishCount < lMaxPublishCount; lPublishCount++ )
{
ulScratchBufferLength = snprintf( ( char * ) ucScratchBuffer, sizeof( ucScratchBuffer ),
sampleazureiotMESSAGE, lPublishCount );
xResult = AzureIoTHubClient_SendTelemetry( &xAzureIoTHubClient,
ucScratchBuffer, ulScratchBufferLength,
&xPropertyBag, eAzureIoTHubMessageQoS1, NULL );
configASSERT( xResult == eAzureIoTSuccess );
LogInfo( ( "Attempt to receive publish message from IoT Hub.\r\n" ) );
xResult = AzureIoTHubClient_ProcessLoop( &xAzureIoTHubClient,
sampleazureiotPROCESS_LOOP_TIMEOUT_MS );
configASSERT( xResult == eAzureIoTSuccess );
if( lPublishCount % 2 == 0 )
{
/* Send reported property every other cycle */
ulScratchBufferLength = snprintf( ( char * ) ucScratchBuffer, sizeof( ucScratchBuffer ),
sampleazureiotPROPERTY, lPublishCount / 2 + 1 );
xResult = AzureIoTHubClient_SendPropertiesReported( &xAzureIoTHubClient,
ucScratchBuffer, ulScratchBufferLength,
NULL );
configASSERT( xResult == eAzureIoTSuccess );
}
/* Leave Connection Idle for some time. */
LogInfo( ( "Keeping Connection Idle...\r\n\r\n" ) );
vTaskDelay( sampleazureiotDELAY_BETWEEN_PUBLISHES_TICKS );
}
xResult = AzureIoTHubClient_UnsubscribeProperties( &xAzureIoTHubClient );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTHubClient_UnsubscribeCommand( &xAzureIoTHubClient );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTHubClient_UnsubscribeCloudToDeviceMessage( &xAzureIoTHubClient );
configASSERT( xResult == eAzureIoTSuccess );
/* Send an MQTT Disconnect packet over the already connected TLS over
* TCP connection. There is no corresponding response for the disconnect
* packet. After sending disconnect, client must close the network
* connection. */
xResult = AzureIoTHubClient_Disconnect( &xAzureIoTHubClient );
configASSERT( xResult == eAzureIoTSuccess );
/* Close the network connection. */
TLS_Socket_Disconnect( &xNetworkContext );
/* Wait for some time between two iterations to ensure that we do not
* bombard the IoT Hub. */
LogInfo( ( "Demo completed successfully.\r\n" ) );
LogInfo( ( "Short delay before starting the next iteration.... \r\n\r\n" ) );
vTaskDelay( sampleazureiotDELAY_BETWEEN_DEMO_ITERATIONS_TICKS );
}
}
/*-----------------------------------------------------------*/
#ifdef democonfigENABLE_DPS_SAMPLE
/**
* @brief Get IoT Hub endpoint and device Id info, when Provisioning service is used.
* This function will block for Provisioning service for result or return failure.
*/
static uint32_t prvIoTHubInfoGet( NetworkCredentials_t * pXNetworkCredentials,
uint8_t ** ppucIothubHostname,
uint32_t * pulIothubHostnameLength,
uint8_t ** ppucIothubDeviceId,
uint32_t * pulIothubDeviceIdLength )
{
NetworkContext_t xNetworkContext = { 0 };
TlsTransportParams_t xTlsTransportParams = { 0 };
AzureIoTResult_t xResult;
AzureIoTTransportInterface_t xTransport;
uint32_t ucSamplepIothubHostnameLength = sizeof( ucSampleIotHubHostname );
uint32_t ucSamplepIothubDeviceIdLength = sizeof( ucSampleIotHubDeviceId );
uint32_t ulStatus;
/* Set the pParams member of the network context with desired transport. */
xNetworkContext.pParams = &xTlsTransportParams;
ulStatus = prvConnectToServerWithBackoffRetries( democonfigENDPOINT, democonfigIOTHUB_PORT,
pXNetworkCredentials, &xNetworkContext );
configASSERT( ulStatus == 0 );
/* Fill in Transport Interface send and receive function pointers. */
xTransport.pxNetworkContext = &xNetworkContext;
xTransport.xSend = TLS_Socket_Send;
xTransport.xRecv = TLS_Socket_Recv;
xResult = AzureIoTProvisioningClient_Init( &xAzureIoTProvisioningClient,
( const uint8_t * ) democonfigENDPOINT,
sizeof( democonfigENDPOINT ) - 1,
( const uint8_t * ) democonfigID_SCOPE,
sizeof( democonfigID_SCOPE ) - 1,
( const uint8_t * ) democonfigREGISTRATION_ID,
sizeof( democonfigREGISTRATION_ID ) - 1,
NULL, ucMQTTMessageBuffer, sizeof( ucMQTTMessageBuffer ),
ullGetUnixTime,
&xTransport );
configASSERT( xResult == eAzureIoTSuccess );
#ifdef democonfigDEVICE_SYMMETRIC_KEY
xResult = AzureIoTProvisioningClient_SetSymmetricKey( &xAzureIoTProvisioningClient,
( const uint8_t * ) democonfigDEVICE_SYMMETRIC_KEY,
sizeof( democonfigDEVICE_SYMMETRIC_KEY ) - 1,
Crypto_HMAC );
configASSERT( xResult == eAzureIoTSuccess );
#endif /* democonfigDEVICE_SYMMETRIC_KEY */
do
{
xResult = AzureIoTProvisioningClient_Register( &xAzureIoTProvisioningClient,
sampleazureiotProvisioning_Registration_TIMEOUT_MS );
} while( xResult == eAzureIoTErrorPending );
configASSERT( xResult == eAzureIoTSuccess );
xResult = AzureIoTProvisioningClient_GetDeviceAndHub( &xAzureIoTProvisioningClient,
ucSampleIotHubHostname, &ucSamplepIothubHostnameLength,
ucSampleIotHubDeviceId, &ucSamplepIothubDeviceIdLength );
configASSERT( xResult == eAzureIoTSuccess );
AzureIoTProvisioningClient_Deinit( &xAzureIoTProvisioningClient );
/* Close the network connection. */
TLS_Socket_Disconnect( &xNetworkContext );
*ppucIothubHostname = ucSampleIotHubHostname;
*pulIothubHostnameLength = ucSamplepIothubHostnameLength;
*ppucIothubDeviceId = ucSampleIotHubDeviceId;
*pulIothubDeviceIdLength = ucSamplepIothubDeviceIdLength;
return 0;
}
#endif /* democonfigENABLE_DPS_SAMPLE */
/*-----------------------------------------------------------*/
/**
* @brief Connect to server with backoff retries.
*/
static uint32_t prvConnectToServerWithBackoffRetries( const char * pcHostName,
uint32_t port,
NetworkCredentials_t * pxNetworkCredentials,
NetworkContext_t * pxNetworkContext )
{
TlsTransportStatus_t xNetworkStatus;
BackoffAlgorithmStatus_t xBackoffAlgStatus = BackoffAlgorithmSuccess;
BackoffAlgorithmContext_t xReconnectParams;
uint16_t usNextRetryBackOff = 0U;
/* Initialize reconnect attempts and interval. */
BackoffAlgorithm_InitializeParams( &xReconnectParams,
sampleazureiotRETRY_BACKOFF_BASE_MS,
sampleazureiotRETRY_MAX_BACKOFF_DELAY_MS,
sampleazureiotRETRY_MAX_ATTEMPTS );
/* Attempt to connect to IoT Hub. If connection fails, retry after
* a timeout. Timeout value will exponentially increase till maximum
* attempts are reached.
*/
do
{
LogInfo( ( "Creating a TLS connection to %s:%u.\r\n", pcHostName, port ) );
/* Attempt to create a mutually authenticated TLS connection. */
xNetworkStatus = TLS_Socket_Connect( pxNetworkContext,
pcHostName, port,
pxNetworkCredentials,
sampleazureiotTRANSPORT_SEND_RECV_TIMEOUT_MS,
sampleazureiotTRANSPORT_SEND_RECV_TIMEOUT_MS );
if( xNetworkStatus != eTLSTransportSuccess )
{
/* Generate a random number and calculate backoff value (in milliseconds) for
* the next connection retry.
* Note: It is recommended to seed the random number generator with a device-specific
* entropy source so that possibility of multiple devices retrying failed network operations
* at similar intervals can be avoided. */
xBackoffAlgStatus = BackoffAlgorithm_GetNextBackoff( &xReconnectParams, configRAND32(), &usNextRetryBackOff );
if( xBackoffAlgStatus == BackoffAlgorithmRetriesExhausted )
{
LogError( ( "Connection to the IoT Hub failed, all attempts exhausted." ) );
}
else if( xBackoffAlgStatus == BackoffAlgorithmSuccess )
{
LogWarn( ( "Connection to the IoT Hub failed [%d]. "
"Retrying connection with backoff and jitter [%d]ms.",
xNetworkStatus, usNextRetryBackOff ) );
vTaskDelay( pdMS_TO_TICKS( usNextRetryBackOff ) );
}
}
} while( ( xNetworkStatus != eTLSTransportSuccess ) && ( xBackoffAlgStatus == BackoffAlgorithmSuccess ) );
return xNetworkStatus == eTLSTransportSuccess ? 0 : 1;
}
/*-----------------------------------------------------------*/
/*
* @brief Create the task that demonstrates the AzureIoTHub demo
*/
void vStartDemoTask( void )
{
/* This example uses a single application task, which in turn is used to
* connect, subscribe, publish, unsubscribe and disconnect from the IoT Hub */
xTaskCreate( prvAzureDemoTask, /* Function that implements the task. */
"AzureDemoTask", /* Text name for the task - only used for debugging. */
democonfigDEMO_STACKSIZE, /* Size of stack (in words, not bytes) to allocate for the task. */
NULL, /* Task parameter - not used in this case. */
tskIDLE_PRIORITY, /* Task priority, must be between 0 and configMAX_PRIORITIES - 1. */
NULL ); /* Used to pass out a handle to the created task - not used in this case. */
}
/*-----------------------------------------------------------*/