35
35
#define HUB_CONNECT_TIMEOUT_TICKS (10 * TX_TIMER_TICKS_PER_SECOND)
36
36
#define DPS_REGISTER_TIMEOUT_TICKS (3 * TX_TIMER_TICKS_PER_SECOND)
37
37
38
+ static UINT exponential_backoff_with_jitter (UINT * exponential_retry_count )
39
+ {
40
+ float jitter_percent = (MAX_EXPONENTIAL_BACKOFF_JITTER_PERCENT / 100.0f ) * (rand () / ((float )RAND_MAX ));
41
+ UINT base_delay = MAX_EXPONENTIAL_BACKOFF_IN_SEC ;
42
+
43
+ base_delay = (1 << * exponential_retry_count ) * INITIAL_EXPONENTIAL_BACKOFF_IN_SEC ;
44
+
45
+ if (base_delay > MAX_EXPONENTIAL_BACKOFF_IN_SEC )
46
+ {
47
+ base_delay = MAX_EXPONENTIAL_BACKOFF_IN_SEC ;
48
+ }
49
+ else
50
+ {
51
+ (* exponential_retry_count )++ ;
52
+ }
53
+
54
+ return (base_delay * (1 + jitter_percent )) * TX_TIMER_TICKS_PER_SECOND ;
55
+ }
56
+
38
57
static VOID connection_status_callback (NX_AZURE_IOT_HUB_CLIENT * hub_client_ptr , UINT status )
39
58
{
40
59
if (status == NX_SUCCESS )
@@ -44,6 +63,19 @@ static VOID connection_status_callback(NX_AZURE_IOT_HUB_CLIENT* hub_client_ptr,
44
63
else
45
64
{
46
65
printf ("Connection failure from IoT Hub (0x%08x)\r\n" , status );
66
+
67
+ UINT connect_status = NX_AZURE_IOT_FAILURE ;
68
+ UINT retry_count = 0 ;
69
+ while (connect_status )
70
+ {
71
+ printf ("Reconnecting to IoT Hub...\r\n" );
72
+
73
+ if ((connect_status = nx_azure_iot_hub_client_connect (hub_client_ptr , NX_TRUE , HUB_CONNECT_TIMEOUT_TICKS )))
74
+ {
75
+ printf ("Failed reconnect on nx_azure_iot_hub_client_connect (0x%08x)\r\n" , connect_status );
76
+ tx_thread_sleep (exponential_backoff_with_jitter (& retry_count ));
77
+ }
78
+ }
47
79
}
48
80
}
49
81
@@ -637,7 +669,6 @@ UINT azure_iot_nx_client_dps_create(AZURE_IOT_NX_CONTEXT* context, CHAR* dps_id_
637
669
return status ;
638
670
}
639
671
640
-
641
672
// Null terminate returned values
642
673
context -> azure_iot_hub_hostname [iot_hub_hostname_len ] = 0 ;
643
674
context -> azure_iot_device_id [iot_device_id_len ] = 0 ;
0 commit comments