diff --git a/src/PepperDash.Essentials.Core/Comm and IR/ComPortController.cs b/src/PepperDash.Essentials.Core/Comm and IR/ComPortController.cs index ec679fae5..e6a9773f5 100644 --- a/src/PepperDash.Essentials.Core/Comm and IR/ComPortController.cs +++ b/src/PepperDash.Essentials.Core/Comm and IR/ComPortController.cs @@ -38,6 +38,8 @@ public class ComPortController : Device, IBasicCommunicationWithStreamDebugging ComPort Port; ComPort.ComPortSpec Spec; + private readonly object _deactivateLock = new object(); + private bool _isDeactivated; /// /// Constructor @@ -59,6 +61,8 @@ public ComPortController(string key, Func @@ -81,6 +85,7 @@ public ComPortController(string key, ComPort port, ComPort.ComPortSpec spec) //IsConnected = new BoolFeedback(CommonBoolCue.IsConnected, () => true); RegisterAndConfigureComPort(); + CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler; } private void RegisterAndConfigureComPort() @@ -114,14 +119,6 @@ private void RegisterAndConfigureComPort() Port.SerialDataReceived += Port_SerialDataReceived; } - /// - /// Destructor - /// - ~ComPortController() - { - Port.SerialDataReceived -= Port_SerialDataReceived; - } - void Port_SerialDataReceived(ComPort ReceivingComPort, ComPortSerialDataEventArgs args) { OnDataReceived(args.SerialData); @@ -150,12 +147,34 @@ void OnDataReceived(string s) if (!eventSubscribed) Debug.LogMessage(LogEventLevel.Warning, this, "Received data but no handler is registered"); } + void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType) + { + if (programEventType == eProgramStatusEventType.Stopping) + { + Deactivate(); + } + } + /// /// Deactivate method /// /// public override bool Deactivate() { + lock (_deactivateLock) + { + if (_isDeactivated) + return true; + + _isDeactivated = true; + } + + CrestronEnvironment.ProgramStatusEventHandler -= CrestronEnvironment_ProgramStatusEventHandler; + + if (Port == null) + return true; + + Port.SerialDataReceived -= Port_SerialDataReceived; return Port.UnRegister() == eDeviceRegistrationUnRegistrationResponse.Success; }