From 68f1983a81149c41625e5b0b49e9af86fb30f8cc Mon Sep 17 00:00:00 2001 From: Alexis Christoforides Date: Wed, 11 Dec 2024 21:28:31 -0800 Subject: [PATCH] Handle OperationCanceledException more intricately. Fixes debugging reconnect without breaking other non-breaking situations for getting the exception. --- .../SerialConnection.ListenerProc.cs | 59 +++++++++++-------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs index 1b449d9c..a0b1323f 100644 --- a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs +++ b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs @@ -1,4 +1,4 @@ -namespace Meadow.Hcom +namespace Meadow.Hcom { public partial class SerialConnection { @@ -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) @@ -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; } @@ -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) {