Skip to content

Commit cd17938

Browse files
authored
Add rudimentary reconnection logic back into samples (#292)
1 parent e96602e commit cd17938

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

core/src/azure_iot_nx/azure_iot_nx_client.c

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,25 @@
3535
#define HUB_CONNECT_TIMEOUT_TICKS (10 * TX_TIMER_TICKS_PER_SECOND)
3636
#define DPS_REGISTER_TIMEOUT_TICKS (3 * TX_TIMER_TICKS_PER_SECOND)
3737

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+
3857
static VOID connection_status_callback(NX_AZURE_IOT_HUB_CLIENT* hub_client_ptr, UINT status)
3958
{
4059
if (status == NX_SUCCESS)
@@ -44,6 +63,19 @@ static VOID connection_status_callback(NX_AZURE_IOT_HUB_CLIENT* hub_client_ptr,
4463
else
4564
{
4665
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+
}
4779
}
4880
}
4981

@@ -637,7 +669,6 @@ UINT azure_iot_nx_client_dps_create(AZURE_IOT_NX_CONTEXT* context, CHAR* dps_id_
637669
return status;
638670
}
639671

640-
641672
// Null terminate returned values
642673
context->azure_iot_hub_hostname[iot_hub_hostname_len] = 0;
643674
context->azure_iot_device_id[iot_device_id_len] = 0;

0 commit comments

Comments
 (0)