From 2ed285ee75a266625a8b1ec394daab9ff1c3d5cc Mon Sep 17 00:00:00 2001 From: Morten Nielsen Date: Tue, 19 Nov 2024 20:33:29 -0800 Subject: [PATCH] Adds disconnection handling Fixes #114 --- src/NmeaParser/NmeaDevice.cs | 27 ++++++++++++++++++++- src/SampleApp.WinDesktop/MainWindow.xaml.cs | 8 +++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/NmeaParser/NmeaDevice.cs b/src/NmeaParser/NmeaDevice.cs index 691168c..ccb084f 100644 --- a/src/NmeaParser/NmeaDevice.cs +++ b/src/NmeaParser/NmeaDevice.cs @@ -70,6 +70,7 @@ namespace NmeaParser System.Diagnostics.Debug.WriteLine("Starting parser..."); m_ParserTask = Task.Run(async () => { + int failcounter = 0; byte[] buffer = new byte[1024]; while (!token.IsCancellationRequested) { @@ -77,8 +78,17 @@ namespace NmeaParser try { readCount = await ReadAsync(buffer, 0, 1024, token).ConfigureAwait(false); + failcounter = 0; + } + catch(System.Exception ex) + { + failcounter++; + if (failcounter > 10) + { + OnDisconnecting(ex); + break; + } } - catch { } if (token.IsCancellationRequested) break; if (readCount > 0) @@ -90,6 +100,16 @@ namespace NmeaParser }); } + private async void OnDisconnecting(Exception ex) + { + try + { + await this.CloseAsync().ConfigureAwait(false); + } + catch { } + DeviceDisconnected.Invoke(this, ex); + } + /// /// Performs a read operation of the stream /// @@ -219,6 +239,11 @@ namespace NmeaParser /// public event EventHandler? MessageReceived; + /// + /// Raised when a device raises the same error multiple times and can't recover. + /// + public event EventHandler DeviceDisconnected; + /// /// Releases unmanaged and - optionally - managed resources. /// diff --git a/src/SampleApp.WinDesktop/MainWindow.xaml.cs b/src/SampleApp.WinDesktop/MainWindow.xaml.cs index 435b788..639674f 100644 --- a/src/SampleApp.WinDesktop/MainWindow.xaml.cs +++ b/src/SampleApp.WinDesktop/MainWindow.xaml.cs @@ -84,6 +84,7 @@ namespace SampleApp.WinDesktop if (currentDevice != null) { currentDevice.MessageReceived -= device_MessageReceived; + currentDevice.DeviceDisconnected -= device_DeviceDisconnected; if (currentDevice.IsOpen) await currentDevice.CloseAsync(); currentDevice.Dispose(); @@ -110,7 +111,7 @@ namespace SampleApp.WinDesktop MessagePanel.Children.Remove(child); } currentDevice.MessageReceived += device_MessageReceived; - + currentDevice.DeviceDisconnected += device_DeviceDisconnected; if (device is NmeaParser.NmeaFileDevice) currentDeviceInfo.Text = string.Format("NmeaFileDevice( file={0} )", ((NmeaParser.NmeaFileDevice)device).FileName); else if (device is NmeaParser.SerialPortDevice) @@ -130,6 +131,11 @@ namespace SampleApp.WinDesktop view3d.GnssMonitor = monitor; } + private void device_DeviceDisconnected(object sender, Exception e) + { + MessageBox.Show("Device disconnected: " + e.Message); + } + private void Monitor_LocationChanged(object sender, EventArgs e) { var mon = sender as GnssMonitor;