Skip to content

Commit

Permalink
Handle OperationCanceledException more intricately. Fixes debugging r…
Browse files Browse the repository at this point in the history
…econnect without breaking other non-breaking situations for getting the exception.
  • Loading branch information
alexischr committed Dec 12, 2024
1 parent bcce9f7 commit 68f1983
Showing 1 changed file with 33 additions and 26 deletions.
59 changes: 33 additions & 26 deletions Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Meadow.Hcom
namespace Meadow.Hcom
{
public partial class SerialConnection
{
Expand Down Expand Up @@ -52,6 +52,33 @@ private async Task ListenerProc()
var delimiter = new byte[] { 0x00 };
var receivedLength = 0;

async Task ReOpen() // local function
{
Debug.WriteLine($"Device reset detected");

var timeout = 20;
try { _port.Close(); } catch { } // Swallow any exceptions on close - there is nothing we can do about it

while (!_port.IsOpen)
{
if (timeout-- < 0)
{
return;
}

try
{
Open();
Debug.WriteLine($"Port re-opened");
}
catch
{
Debug.WriteLine($"Failed to re-open port");
}
await Task.Delay(100);
}
}

while (!_isDisposed)
{
if (_port.IsOpen)
Expand All @@ -65,31 +92,9 @@ private async Task ListenerProc()
{
receivedLength = _port.Read(readBuffer, 0, readBuffer.Length);
}
catch (OperationCanceledException)
{
Debug.WriteLine($"Device reset detected");

var timeout = 20;

while (!_port.IsOpen)
catch (InvalidOperationException)
{
await Task.Delay(500);

if (timeout-- < 0)
{
return;
}

try
{
Open();
Debug.WriteLine($"Port re-opened");
}
catch
{
Debug.WriteLine($"Failed to re-open port");
}
}
await ReOpen();
goto read;
}

Expand Down Expand Up @@ -335,7 +340,9 @@ private async Task ListenerProc()
catch (OperationCanceledException)
{
// this happens on disconnect - could be cable pulled, could be device reset
Debug.WriteLine($"Operation Cancelled");
Debug.WriteLine($"Operation Cancelled. Port open: {_port.IsOpen}");
if (!_port.IsOpen) { await ReOpen();
}
}
catch (Exception ex)
{
Expand Down

0 comments on commit 68f1983

Please sign in to comment.