Better shutdown handling

pull/7/head
LeapwardKoex 2024-02-11 23:34:51 +13:00
parent 752b5453a5
commit 6f364833a8
2 changed files with 27 additions and 10 deletions

View File

@ -45,6 +45,7 @@ internal class MaiTouchComConnector
{
OnConnectStatusChange("Conecting...");
serialPort = new SerialPort(virtualPort, 9600, Parity.None, 8, StopBits.One);
serialPort.WriteTimeout = 100;
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.Open();
Console.WriteLine("Serial port opened successfully.");
@ -65,6 +66,7 @@ internal class MaiTouchComConnector
}
}
catch (TimeoutException) { }
catch (Exception ex)
{
OnConnectError();
@ -86,15 +88,27 @@ internal class MaiTouchComConnector
}
}
public async void Disconnect()
public async Task Disconnect()
{
_shouldReconnect = false;
if (serialPort?.IsOpen == true)
{
serialPort.Close();
serialPort.Dispose();
}
_connected = false;
try
{
serialPort.DtrEnable = false;
serialPort.RtsEnable = false;
serialPort.DataReceived -= SerialPort_DataReceived;
await Task.Delay(200);
if (serialPort.IsOpen == true)
{
serialPort.DiscardInBuffer();
serialPort.DiscardOutBuffer();
serialPort.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
@ -137,8 +151,11 @@ internal class MaiTouchComConnector
}
void SendTouchscreenState()
{
if (_connected)
{
var currentState = _buttonState.GetCurrentState();
serialPort?.Write(currentState, 0, currentState.Length);
}
}
}

View File

@ -101,7 +101,7 @@ public partial class MainWindow : Window
var dataContext = (MainWindowViewModel)DataContext;
if (dataContext.IsExitWithSinmaiEnabled)
{
connector.Disconnect();
await connector.Disconnect();
Application.Current.Shutdown();
}
}
@ -154,7 +154,7 @@ public partial class MainWindow : Window
var dataContext = (MainWindowViewModel)DataContext;
var enabled = !dataContext.IsAutomaticPositioningEnabled;
dataContext.IsAutomaticPositioningEnabled = !enabled;
Properties.Settings.Default.IsAutomaticPositioningEnabled = enabled;
Properties.Settings.Default.IsAutomaticPositioningEnabled = dataContext.IsAutomaticPositioningEnabled;
Properties.Settings.Default.Save();
}