示例#1
0
        private bool AttemptConnection(string portName)
        {
            CleanupConnection();

            port = new SerialPort(portName, baudRate);
            try
            {
                port.Open();
            }  catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException || ex is System.IO.IOException)
                {
                    _logger.Log(LogLevel.Warning, $"Failed to open connection at port {portName}");
                    return(false);
                }

                throw;
            }

            // Using Invoke() to force handling from main thread
            mailbox           = new SerialMailbox(port, () => dataReceivedAction.Invoke(), _logger);
            connectionMonitor = new ConnectionMonitor(sendHello,
                                                      (connected) => SetState(connected ? State.Connected : State.Disconnected),
                                                      _logger);
            updateConnectionStatus($"Opening port {portName}");
            return(true);
        }
示例#2
0
        private void CleanupConnection()
        {
            if (connectionMonitor != null)
            {
                connectionMonitor.Dispose();
                connectionMonitor = null;
            }

            if (mailbox != null)
            {
                mailbox.Dispose();
                mailbox = null;
            }

            if (port != null)
            {
                port.Close();
                port = null;
            }
        }