Skip to content

Commit

Permalink
Add rudimentary reconnection logic back into samples (#292)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanwinter authored Sep 9, 2021
1 parent e96602e commit cd17938
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion core/src/azure_iot_nx/azure_iot_nx_client.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@
#define HUB_CONNECT_TIMEOUT_TICKS (10 * TX_TIMER_TICKS_PER_SECOND)
#define DPS_REGISTER_TIMEOUT_TICKS (3 * TX_TIMER_TICKS_PER_SECOND)

static UINT exponential_backoff_with_jitter(UINT* exponential_retry_count)
{
float jitter_percent = (MAX_EXPONENTIAL_BACKOFF_JITTER_PERCENT / 100.0f) * (rand() / ((float)RAND_MAX));
UINT base_delay = MAX_EXPONENTIAL_BACKOFF_IN_SEC;

base_delay = (1 << *exponential_retry_count) * INITIAL_EXPONENTIAL_BACKOFF_IN_SEC;

if (base_delay > MAX_EXPONENTIAL_BACKOFF_IN_SEC)
{
base_delay = MAX_EXPONENTIAL_BACKOFF_IN_SEC;
}
else
{
(*exponential_retry_count)++;
}

return (base_delay * (1 + jitter_percent)) * TX_TIMER_TICKS_PER_SECOND;
}

static VOID connection_status_callback(NX_AZURE_IOT_HUB_CLIENT* hub_client_ptr, UINT status)
{
if (status == NX_SUCCESS)
Expand All @@ -44,6 +63,19 @@ static VOID connection_status_callback(NX_AZURE_IOT_HUB_CLIENT* hub_client_ptr,
else
{
printf("Connection failure from IoT Hub (0x%08x)\r\n", status);

UINT connect_status = NX_AZURE_IOT_FAILURE;
UINT retry_count = 0;
while (connect_status)
{
printf("Reconnecting to IoT Hub...\r\n");

if ((connect_status = nx_azure_iot_hub_client_connect(hub_client_ptr, NX_TRUE, HUB_CONNECT_TIMEOUT_TICKS)))
{
printf("Failed reconnect on nx_azure_iot_hub_client_connect (0x%08x)\r\n", connect_status);
tx_thread_sleep(exponential_backoff_with_jitter(&retry_count));
}
}
}
}

Expand Down Expand Up @@ -637,7 +669,6 @@ UINT azure_iot_nx_client_dps_create(AZURE_IOT_NX_CONTEXT* context, CHAR* dps_id_
return status;
}


// Null terminate returned values
context->azure_iot_hub_hostname[iot_hub_hostname_len] = 0;
context->azure_iot_device_id[iot_device_id_len] = 0;
Expand Down

0 comments on commit cd17938

Please sign in to comment.