Adds disconnection handling

Fixes #114
This commit is contained in:
Morten Nielsen 2024-11-19 20:33:29 -08:00
parent db04b280e4
commit 2ed285ee75
2 changed files with 33 additions and 2 deletions

View file

@ -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);
}
/// <summary>
/// Performs a read operation of the stream
/// </summary>
@ -219,6 +239,11 @@ namespace NmeaParser
/// </summary>
public event EventHandler<NmeaMessageReceivedEventArgs>? MessageReceived;
/// <summary>
/// Raised when a device raises the same error multiple times and can't recover.
/// </summary>
public event EventHandler<Exception> DeviceDisconnected;
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>

View file

@ -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;