Skip to content

Commit

Permalink
Merge pull request #606 from WildernessLabs/refix-debugger-reconnect
Browse files Browse the repository at this point in the history
Refix debugger reconnect
  • Loading branch information
adrianstevens authored Dec 13, 2024
2 parents 60a92d2 + 68f1983 commit 10639bd
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 10639bd

Please sign in to comment.