Hello @KS Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.
When you say the issue happens in specific environments, do these environments have a tendency of poor networking conditions? How often do we see this behavior, and can this be replicated on demand?
You have also mentioned that you were able to ping the IoT Hub endpoint and could get the result immediately. I want to check and make sure if you have tested this from the same network as your device and during the time the device client fails to authenticate.
I am not sure if it is possible to get more detailed error details aside from Disconnected and reason: Retry_Expired. You can catch the connection change status by adding the following piece of code in your device client application.
deviceClient1.SetConnectionStatusChangesHandler((status, reason) =>
{
Console.WriteLine($"Connection status changed to {status} with reason {reason}");
if (reason == ConnectionStatusChangeReason.Retry_Expired)
{
Console.WriteLine("Connection retry period has expired. Please check your network connection and try again.");
}
else if (reason == ConnectionStatusChangeReason.Communication_Error)
{
Console.WriteLine("A communication error has occurred. Please check your connection string and try again.");
}
// Add more error handling code here...
});
When the connection is successful the reason for the handler would be Connection_Ok
The code base uses an internal Logging class that can be used to capture additional information from this event. Here is an example on how we can leverage this class method to capture additional details.
public void SetConnectionStatusChangesHandler(ConnectionStatusChangesHandler statusChangesHandler)
{
if (Logging.IsEnabled)
Logging.Info(this, statusChangesHandler, nameof(SetConnectionStatusChangesHandler));
}
For more details on how to use and leverage this, please refer the InternalClient Class sample. In addition to this, there is another sample code I have found in the repository that lets you provide a customer time span for client to wait before it closes the connection. Please find the MethodSample.cs class for this implementation. Kindly note that this also relies on cancellation token expiry.
Hope this helps. Please let us know if you have any additional questions.
If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.