/// <summary> /// Safely closes a connection by notifying listeners before and after the connection is closed. /// </summary> public static void DestroyConnection() { if (ELM327Connection._singleton._connection != null && ELM327Connection._singleton._connection.IsOpen) { lock (ELM327Connection._singleton._connection) { // Notify our listeners that the connection is closing if (ELM327Connection.ConnectionClosingEvent != null) { ELM327Connection.ConnectionClosingEvent(); } try { // Stop operations ELM327Connection._singleton._elm327device.StopOperations(); ELM327Connection._singleton._elm327device = null; ELM327Connection._singleton._connection.Close(); } catch (Exception e) { log.Error("Error while attempting to close ELM327 SerialPort connection.", e); } // Notify our listeners that the connection has closed if (ELM327Connection.ConnectionDestroyedEvent != null) { ELM327Connection.ConnectionDestroyedEvent(); } ELM327Connection._singleton._connection = null; } } }
/// <summary> /// Stores a reference to the SerialPort with the new connection and notifies listeners. /// </summary> /// <param name="connection">SerialPort with the new connection.</param> public static void ConnectionEstablished(SerialPort connection, ConnectionSettings connectionSettings) { ELM327Connection._singleton._connection = connection; lock (ELM327Connection._singleton._connection) { ELM327Connection._singleton._elm327device = new ELM327(ELM327Connection._singleton._connection, connectionSettings); ELM327Connection._singleton._elm327device.ConnectionLost += ELM327Connection.DestroyConnection; // If we could not start operations, stop everything if (!(ELM327Connection._singleton._elm327device.StartOperations())) { // Log an error log.Error("Error occurred when attempting to start operations on ELM327 device."); // Close connection try { ELM327Connection._singleton._connection.Close(); } catch (IOException e) { log.Error("Error occurred while trying to close connection after a failed attempt to start ELM327 operations.", e); } // Clear everything ELM327Connection._singleton._connection = null; ELM327Connection._singleton._elm327device = null; return; } // If a connection has been successfully established, load our protocol handlers // and notify our listeners that the connection is live and read for communication if (ELM327Connection.ConnectionEstablishedEvent != null) { ELM327Connection._singleton._elm327device.ClearHandlers(); foreach (Type nextHandlerType in _loadedHandlerTypes) { ELM327Connection._singleton._elm327device.AddHandler(nextHandlerType); } ELM327Connection.ConnectionEstablishedEvent(connection); } } }