Example #1
0
        public void ToggleLight()
        {
            SerialPort oCon = (SerialPort)this.HttpContext.Application["SerialSensor"];
            var        sc   = new SerialClient();

            sc.ToggleLight(oCon);
        }
        public void SignRequestSerial(SignRequest request)
        {
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedPort))
            {
                throw new Exception("Port can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedDataBits))
            {
                throw new Exception("DataBits can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedBaudRate))
            {
                throw new Exception("BaudRate can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedParity))
            {
                throw new Exception("Parity can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedStopBits))
            {
                throw new Exception("StopBits can not be null.");
            }
            string requestString = JsonConvert.SerializeObject(request);

            SerialClient _client = new SerialClient(Const.Locator.ParameterSetting.SelectedPort,
                                                    int.Parse(Const.Locator.ParameterSetting.SelectedBaudRate),
                                                    (Parity)Enum.Parse(typeof(Parity), Const.Locator.ParameterSetting.SelectedParity),
                                                    int.Parse(Const.Locator.ParameterSetting.SelectedDataBits),
                                                    (StopBits)Enum.Parse(typeof(StopBits), Const.Locator.ParameterSetting.SelectedStopBits));

            _client.Open();
            _client.Complated -= _signTcpClient_Complated;
            _client.Complated += _signTcpClient_Complated;
            _client.Send(0x02, requestString);
        }
Example #3
0
        public void Run_Then_Response_N_Rounds()
        {
            IClient cli        = new SerialClient(COM.Port101);
            IComm   serialComm = new WrappedComm(cli);

            string sets = @"CmdType,Sent
response,[12 34 56]
response,[34 56 78]";

            serialComm.Setup(sets);
            serialComm.Open();
            Task.Run(() => serialComm.Run());

            IClient client = new SerialClient(COM.Port102);

            client.Open();
            client.Send(Conv.StrHexToBytes("12 34"));
            byte[] rev0 = client.Rev();
            client.Send(Conv.StrHexToBytes("45 67"));
            byte[] rev1 = client.Rev();
            client.Send(Conv.StrHexToBytes("78 90"));
            client.ReadTimeOut = 10;
            byte[] rev2 = client.Rev();
            client.Close();

            serialComm.Stop();
            serialComm.Close();
            Assert.AreEqual("12 34 56", Conv.BytesToStrHex(rev0));
            Assert.AreEqual("34 56 78", Conv.BytesToStrHex(rev1));
            Assert.AreEqual(0, rev2.Length);
        }
Example #4
0
        public override StepResult ExecuteStep(object parameters)
        {
            // Fusion parameters
            var param = parameters as Parameters;

            // add custom plugin log
            InfinityService.Log.Info($"Fusion Parameter 1 : Serial Com Port = {param?.ComPortNumber}");

            _tokenSource          = new CancellationTokenSource();
            _taskCompletionSource = new TaskCompletionSource <StepResult>();

            // Serial port
            _serialClient = new SerialClient(param?.ComPortNumber);
            _serialClient.OpenCom();
            _serialClient.SerialDataReceived += SerialDataReceived;

            Application.Current.Dispatcher.Invoke(() =>
            {
                // Display Fusion parameters
                _viewModel.SerialPortNumber = param?.ComPortNumber;

                _viewModel.KeyboardData       = "Keyboard ---";
                _viewModel.SerialDataReceived = "Serial Data ---";
            });

            _taskCompletionSource.Task.Wait(_tokenSource.Token);
            return(_taskCompletionSource.Task.Result);
        }
Example #5
0
 public void AddSerialClient(String uri)
 {
     if (_serialClient == null)
     {
         _serialClient = new SerialClient(_binding, _baseUri.ToString() + uri);
     }
 }
Example #6
0
        private void Connect()
        {
            if (m_serialClient != null)
            {
                Disconnect();
            }

            string connectionString =
                "port=" + ComboBoxSerialPorts.Text +
                "; baudrate=" + ComboBoxSerialBaudRates.Text +
                "; parity=" + ComboBoxSerialParities.Text +
                "; stopbits=" + ComboBoxSerialStopBits.Text +
                "; databits=" + TextBoxSerialDataBits.Text +
                "; dtrenable=" + CheckBoxSerialDTR.Checked.ToString() +
                "; rtsenable=" + CheckBoxSerialRTS.Checked.ToString();

            // Wire up serial client events
            m_serialClient = new SerialClient();
            m_serialClient.SettingsCategory       = ComboBoxSerialPorts.Text;
            m_serialClient.ConnectionAttempt     += m_serialClient_ConnectionAttempt;
            m_serialClient.ConnectionEstablished += m_serialClient_ConnectionEstablished;
            m_serialClient.ConnectionException   += m_serialClient_ConnectionException;
            m_serialClient.ConnectionTerminated  += m_serialClient_ConnectionTerminated;
            m_serialClient.ReceiveDataComplete   += m_serialClient_ReceiveDataComplete;
            m_serialClient.ReceiveDataException  += m_serialClient_ReceiveDataException;
            m_serialClient.SendDataComplete      += m_serialClient_SendDataComplete;
            m_serialClient.SendDataException     += m_serialClient_SendDataException;
            m_serialClient.ConnectionString       = connectionString;
            m_serialClient.ConnectAsync();
        }
Example #7
0
        public void ConnectDevice()
        {
            if (String.IsNullOrEmpty(DevicePort))
            {
                throw new Exception("The 'DevicePort' property has not been set.");
            }

            if (DeviceBaudRate == 0)
            {
                throw new Exception("The 'DeviceBaudRate' property has not been set.");
            }

            Console.WriteLine("Enabling target hardware device...");

            DeviceClient = new SerialClient(DevicePort, DeviceBaudRate);

            try {
                DeviceClient.Open();
            } catch (IOException ex) {
                HandleConnectionIOException("target", DevicePort, DeviceBaudRate, ex);
            }

            DeviceIsEnabled = true;

            Console.WriteLine("");
        }
Example #8
0
        public void Rev_out_of_time()
        {
            IClient cli = new SerialClient(COM.Port101);

            cli.Open();
            cli.ReadTimeOut = 10;
            byte[] rev = cli.Rev();
            cli.Close();

            Assert.AreEqual(0, rev.Length);
        }
Example #9
0
        public string GetSensors()
        {
            SerialPort oCon = (SerialPort)this.HttpContext.Application["SerialSensor"]; // We put the serial connection in here so that it's a global object

            var         sc = new SerialClient();
            SensorModel stats;

            try
            {
                stats = sc.SensorReadLine(oCon);
                string output = JsonConvert.SerializeObject((object)stats);
                return(output);
            }
            catch (Exception ex)
            {
                return("error: " + ex.Message);
            }
        }
Example #10
0
 private void Disconnect()
 {
     if (m_serialClient != null)
     {
         // Unwire serial client events
         m_serialClient.Disconnect();
         m_serialClient.ConnectionAttempt     -= m_serialClient_ConnectionAttempt;
         m_serialClient.ConnectionEstablished -= m_serialClient_ConnectionEstablished;
         m_serialClient.ConnectionException   -= m_serialClient_ConnectionException;
         m_serialClient.ConnectionTerminated  -= m_serialClient_ConnectionTerminated;
         m_serialClient.ReceiveDataComplete   -= m_serialClient_ReceiveDataComplete;
         m_serialClient.ReceiveDataException  -= m_serialClient_ReceiveDataException;
         m_serialClient.SendDataComplete      -= m_serialClient_SendDataComplete;
         m_serialClient.SendDataException     -= m_serialClient_SendDataException;
         m_serialClient.Dispose();
         m_serialClient = null;
     }
 }
Example #11
0
        public DeviceInfo ReadDeviceInfoFromSerial(string port)
        {
            Console.WriteLine("Reading device info from serial port...");

            var serialPort = new SerialPort(port, 9600);
            var client     = new SerialClient(serialPort);

            if (!client.Port.IsOpen)
            {
                try
                {
                    client.Open();
                }
                catch (Exception ex)
                {
                    return(null);
                }

                Console.WriteLine("Opened serial port");

                Thread.Sleep(2000);
            }

            var builder = new StringBuilder();

            Console.WriteLine("----- Start Output -----");

            while (client.Port.BytesToRead > 0 && builder.ToString().IndexOf(Extractor.EndDeviceInfoText) == -1)
            {
                var output = builder.ToString();
                var line   = client.ReadLine().Trim();

                Console.WriteLine(line);

                builder.AppendLine(line);
            }

            Console.WriteLine("----- End Output -----");

            var deviceInfo = Extractor.ExtractInfo(port, builder.ToString());

            return(deviceInfo);
        }
Example #12
0
        public string Send(string port, string value)
        {
            var serialPort = new SerialPort(port, 9600);
            var client     = new SerialClient(serialPort);

            client.Open();

            Thread.Sleep(2000);

            client.WriteLine(value);

            Thread.Sleep(2000);

            var response = client.Read();

            client.Close();

            return(response);
        }
Example #13
0
        public static void StatueRequestSerial(string request)
        {
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedPort))
            {
                throw new Exception("Port can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedDataBits))
            {
                throw new Exception("DataBits can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedBaudRate))
            {
                throw new Exception("BaudRate can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedParity))
            {
                throw new Exception("Parity can not be null.");
            }
            if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedStopBits))
            {
                throw new Exception("StopBits can not be null.");
            }
            if (string.IsNullOrWhiteSpace(request))
            {
                throw new Exception("Request can not be null.");
            }

            StopBits ss = (StopBits)Enum.Parse(typeof(StopBits), Const.Locator.ParameterSetting.SelectedStopBits);


            SerialClient _client = new SerialClient(Const.Locator.ParameterSetting.SelectedPort,
                                                    int.Parse(Const.Locator.ParameterSetting.SelectedBaudRate),
                                                    (Parity)Enum.Parse(typeof(Parity), Const.Locator.ParameterSetting.SelectedParity),
                                                    int.Parse(Const.Locator.ParameterSetting.SelectedDataBits),
                                                    (StopBits)Enum.Parse(typeof(StopBits), Const.Locator.ParameterSetting.SelectedStopBits));

            _client.Open();
            _client.Complated += _statusTcpClient_Complated;
            _client.Send(0x01, request);
        }
Example #14
0
        public void InitByPort()
        {
            IClient cli        = new SerialClient(COM.Port101);
            IComm   serialComm = new WrappedComm(cli);
            string  sets       = @"CmdType,Sent
response,[34 56 78]";

            serialComm.Setup(sets);
            serialComm.Open();
            Task.Run(() => serialComm.Run());

            IClient client = new SerialClient(COM.Port102);

            client.Open();
            client.Send(Conv.StrHexToBytes("12 34"));
            byte[] rev0 = client.Rev();
            client.Close();

            serialComm.Stop();
            serialComm.Close();
            Assert.AreEqual("34 56 78", Conv.BytesToStrHex(rev0));
        }
Example #15
0
        public static void Main(string[] args)
        {
            var arguments = new Arguments(args);

            IsVerbose = arguments.Contains("v");
            var userId         = GetConfigValue(arguments, "UserId");
            var pass           = GetConfigValue(arguments, "Password");
            var host           = GetConfigValue(arguments, "Host");
            var deviceName     = GetConfigValue(arguments, "DeviceName");
            var serialPortName = GetConfigValue(arguments, "SerialPort");
            var serialBaudRate = Convert.ToInt32(GetConfigValue(arguments, "SerialBaudRate"));
            var topicPrefix    = "/" + userId;
            var useTopicPrefix = Convert.ToBoolean(ConfigurationSettings.AppSettings["UseTopicPrefix"]);

            SerialPort port = null;

            if (String.IsNullOrEmpty(serialPortName))
            {
                Console.WriteLine("Serial port not specified. Detecting.");
                var detector = new SerialPortDetector();
                port           = detector.Detect();
                serialPortName = port.PortName;
            }
            else
            {
                Console.WriteLine("Serial port specified");
                port = new SerialPort(serialPortName, serialBaudRate);
            }

            Console.WriteLine("Device name: " + GetConfigValue(arguments, "DeviceName"));
            Console.WriteLine("Port name: " + serialPortName);

            var deviceTopic = "/" + deviceName;

            if (useTopicPrefix)
            {
                deviceTopic = topicPrefix + deviceTopic;
            }

            Console.WriteLine(deviceTopic + "/[Key]");

            if (port == null)
            {
                Console.WriteLine("Error: Device port not found.");
            }
            else
            {
                Console.WriteLine("Serial port: " + port.PortName);

                Client = new SerialClient(port);

                try {
                    Client.Open();

                    Console.WriteLine(Client.Read());

                    var isRunning = true;

                    var mqttClient = new MqttClient(host);

                    var clientId = Guid.NewGuid().ToString();

                    mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                    mqttClient.Connect(clientId, userId, pass);


                    var subscribeTopics = GetSubscribeTopics(arguments);
                    foreach (var topic in subscribeTopics)
                    {
                        mqttClient.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                    }


                    while (isRunning)
                    {
                        var output = "";

                        /*while (!output.Contains(";;"))
                         * {
                         * //	Thread.Sleep(1);
                         *      output += Client.Read ();
                         * }*/

                        //Console.WriteLine("----- Serial output");
                        //Console.WriteLine(output);
                        //Console.WriteLine("-----");

                        var topics = new List <string>();

                        //Publish (arguments, mqttClient, output, topics);

                        //Thread.Sleep(10);
                    }

                    Client.Close();
                } catch (IOException ex) {
                    Console.WriteLine("Error: Please ensure device is connected to port '" + serialPortName + "' and not already in use.\n\n" + ex.Message);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Create a communications client
        /// </summary>
        /// <remarks>
        /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file"
        /// </remarks>
        /// <returns>A communications client.</returns>
        /// <param name="connectionString">Connection string for the client.</param>
        public static IClient Create(string connectionString)
        {
            Dictionary<string, string> connectionData = connectionString.ParseKeyValuePairs();
            IClient client = null;
            string protocol;

            if (connectionData.TryGetValue("protocol", out protocol))
            {
                connectionData.Remove("protocol");
                StringBuilder settings = new StringBuilder();

                foreach (string key in connectionData.Keys)
                {
                    settings.Append(key);
                    settings.Append("=");
                    settings.Append(connectionData[key]);
                    settings.Append(";");
                }

                switch (protocol.ToLower())
                {
                    case "tcp":
                        client = new TcpClient(settings.ToString());
                        break;
                    case "udp":
                        client = new UdpClient(settings.ToString());
                        break;
                    case "file":
                        client = new FileClient(settings.ToString());
                        break;
                    case "serial":
                        client = new SerialClient(settings.ToString());
                        break;
                    default:
                        throw new ArgumentException(protocol + " is not a valid transport protocol.");
                }
            }
            else
            {
                throw new ArgumentException("Transport protocol must be specified.");
            }

            return client;
        }
Example #17
0
        private void Connect()
        {
            if (m_serialClient != null)
                Disconnect();

            string connectionString =
                            "port=" + ComboBoxSerialPorts.Text +
                            "; baudrate=" + ComboBoxSerialBaudRates.Text +
                            "; parity=" + ComboBoxSerialParities.Text +
                            "; stopbits=" + ComboBoxSerialStopBits.Text +
                            "; databits=" + TextBoxSerialDataBits.Text +
                            "; dtrenable=" + CheckBoxSerialDTR.Checked.ToString() +
                            "; rtsenable=" + CheckBoxSerialRTS.Checked.ToString();

            // Wire up serial client events
            m_serialClient = new SerialClient();
            m_serialClient.SettingsCategory = ComboBoxSerialPorts.Text;
            m_serialClient.ConnectionAttempt += m_serialClient_ConnectionAttempt;
            m_serialClient.ConnectionEstablished += m_serialClient_ConnectionEstablished;
            m_serialClient.ConnectionException += m_serialClient_ConnectionException;
            m_serialClient.ConnectionTerminated += m_serialClient_ConnectionTerminated;
            m_serialClient.ReceiveDataComplete += m_serialClient_ReceiveDataComplete;
            m_serialClient.ReceiveDataException += m_serialClient_ReceiveDataException;
            m_serialClient.SendDataComplete += m_serialClient_SendDataComplete;
            m_serialClient.SendDataException += m_serialClient_SendDataException;
            m_serialClient.ConnectionString = connectionString;
            m_serialClient.ConnectAsync();
        }
Example #18
0
 private void Disconnect()
 {
     if (m_serialClient != null)
     {
         // Unwire serial client events
         m_serialClient.Disconnect();
         m_serialClient.ConnectionAttempt -= m_serialClient_ConnectionAttempt;
         m_serialClient.ConnectionEstablished -= m_serialClient_ConnectionEstablished;
         m_serialClient.ConnectionException -= m_serialClient_ConnectionException;
         m_serialClient.ConnectionTerminated -= m_serialClient_ConnectionTerminated;
         m_serialClient.ReceiveDataComplete -= m_serialClient_ReceiveDataComplete;
         m_serialClient.ReceiveDataException -= m_serialClient_ReceiveDataException;
         m_serialClient.SendDataComplete -= m_serialClient_SendDataComplete;
         m_serialClient.SendDataException -= m_serialClient_SendDataException;
         m_serialClient.Dispose();
         m_serialClient = null;
     }
 }
 public SerialClientWrapper(SerialClient client)
 {
     Client = client;
 }
 public SerialClientWrapper(SerialPort port)
 {
     Client = new SerialClient(port);
 }
 public ArduinoSerialDevice(string portName, int baudRate)
 {
     Client = new SerialClient(portName, baudRate);
 }
Example #22
0
        /// <summary>
        /// Create a communications client
        /// </summary>
        /// <remarks>
        /// Note that typical connection string should be prefixed with a "protocol=tcp", "protocol=udp", "protocol=serial" or "protocol=file"
        /// </remarks>
        /// <returns>A communications client.</returns>
        /// <param name="connectionString">Connection string for the client.</param>
        public static IClient Create(string connectionString)
        {
            Dictionary<string, string> connectionSettings = connectionString.ParseKeyValuePairs();
            IClient client;
            string protocol;

            if (connectionSettings.TryGetValue("protocol", out protocol))
            {
                connectionSettings.Remove("protocol");
                StringBuilder settings = new StringBuilder();

                foreach (string key in connectionSettings.Keys)
                {
                    settings.Append(key);
                    settings.Append("=");
                    settings.Append(connectionSettings[key]);
                    settings.Append(";");
                }

                // Create a client instance for the specified protocol.
                switch (protocol.Trim().ToLower())
                {
                    case "tls":
                        client = new TlsClient(settings.ToString());
                        break;
                    case "tcp":
                        client = new TcpClient(settings.ToString());
                        break;
                    case "udp":
                        client = new UdpClient(settings.ToString());
                        break;
                    case "file":
                        client = new FileClient(settings.ToString());
                        break;
                    case "serial":
                        client = new SerialClient(settings.ToString());
                        break;
                    case "zeromq":
                        client = new ZeroMQClient(settings.ToString());
                        break;
                    default:
                        throw new ArgumentException(protocol + " is not a valid transport protocol");
                }

                // Apply client settings from the connection string to the client.
                foreach (KeyValuePair<string, string> setting in connectionSettings)
                {
                    PropertyInfo property = client.GetType().GetProperty(setting.Key);
                    if (property != null)
                        property.SetValue(client, Convert.ChangeType(setting.Value, property.PropertyType), null);
                }
            }
            else
            {
                throw new ArgumentException("Transport protocol must be specified");
            }

            return client;
        }
        private void Send()
        {
            switch (Const.Locator.ParameterSetting.CommModel)
            {
            case Commom.CommModel.NetPort:    //网口通讯
                if (string.IsNullOrWhiteSpace(Cmd))
                {
                    throw new Exception("Request cmd can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Request))
                {
                    throw new Exception("Request can not be null.");
                }

                _netClient = new TcpHelper();
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SdcUrl))
                {
                    MessageBoxEx.Show("EFD URL can not be null.", MessageBoxButton.OK);
                    return;
                }
                string[] sdc = Const.Locator.ParameterSetting.SdcUrl.Split(':');
                if (sdc != null && sdc.Count() != 2)
                {
                    MessageBoxEx.Show("EFD URL is not in the right format.", MessageBoxButton.OK);
                    return;
                }
                bool isConn = _netClient.Connect(IPAddress.Parse(sdc[0]), int.Parse(sdc[1]));
                if (!isConn)
                {
                    MessageBoxEx.Show("Failed to connect to EFD.", MessageBoxButton.OK);
                    return;
                }

                _netClient.Complated -= _client_Complated;
                _netClient.Complated += _client_Complated;
                switch (Cmd)
                {
                case "Status":
                    _netClient.Send(0x01, Request);
                    break;

                case "Sign":
                    _netClient.Send(0x02, Request);
                    break;

                case "Report":
                    _netClient.Send(0x04, Request);
                    break;

                default:
                    break;
                }
                _netClient.ReciveAsync();
                break;

            case Commom.CommModel.SerialPort:    //串口通讯
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedPort))
                {
                    throw new Exception("Port can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedDataBits))
                {
                    throw new Exception("DataBits can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedBaudRate))
                {
                    throw new Exception("BaudRate can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedParity))
                {
                    throw new Exception("Parity can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Const.Locator.ParameterSetting.SelectedStopBits))
                {
                    throw new Exception("StopBits can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Cmd))
                {
                    throw new Exception("Request cmd can not be null.");
                }
                if (string.IsNullOrWhiteSpace(Request))
                {
                    throw new Exception("Request can not be null.");
                }
                _client = new SerialClient(Const.Locator.ParameterSetting.SelectedPort,
                                           int.Parse(Const.Locator.ParameterSetting.SelectedBaudRate),
                                           (Parity)Enum.Parse(typeof(Parity), Const.Locator.ParameterSetting.SelectedParity),
                                           int.Parse(Const.Locator.ParameterSetting.SelectedDataBits),
                                           (StopBits)Enum.Parse(typeof(StopBits), Const.Locator.ParameterSetting.SelectedStopBits));
                _client.Open();
                _isCanSend         = false;
                _client.Complated += _client_Complated;
                switch (Cmd)
                {
                case "Status":
                    _client.Send(0x01, Request);
                    break;

                case "Sign":
                    _client.Send(0x02, Request);
                    break;

                case "Report":
                    _client.Send(0x04, Request);
                    break;

                default:
                    break;
                }
                break;

            default:
                break;
            }
        }
Example #24
0
        public void Run()
        {
            DevicesDirectory = Path.GetFullPath(DevicesDirectory);

            Console.WriteLine("Devices directory:");
            Console.WriteLine(DevicesDirectory);

            Console.WriteLine("Device Name: " + DeviceName);
            Console.WriteLine("MQTT Host: " + MqttHost);
            Console.WriteLine("MQTT Username: "******"MQTT Port: " + MqttPort);

            LoadDeviceList();

            SerialPort port = null;

            if (String.IsNullOrEmpty(SerialPortName))
            {
                Console.WriteLine("Serial port not specified. Detecting.");
                var detector = new SerialPortDetector();
                port           = detector.Detect();
                SerialPortName = port.PortName;
            }
            else
            {
                Console.WriteLine("Serial port specified");
                port = new SerialPort(SerialPortName, SerialBaudRate);
            }

            Console.WriteLine("Device name: " + DeviceName);
            Console.WriteLine("Serial port name: " + SerialPortName);

            if (port == null)
            {
                Console.WriteLine("Error: Device port not found.");
            }
            else
            {
                Console.WriteLine("Serial port: " + port.PortName);

                Client = new SerialClient(port);

                EnsurePortIsOpen();

                SetupMQTT();

                // Wait until the first line arrives
                Client.ReadLine();

                var isRunning = true;
                while (isRunning)
                {
                    try {
                        RunLoop();

                        Thread.Sleep(10);
                    } catch (Exception ex) {
                        Console.WriteLine("An error occurred:");
                        Console.WriteLine(ex.ToString());
                        Console.WriteLine();
                        Console.WriteLine("Waiting for 30 seconds then retrying");

                        SendErrorEmail(ex, DeviceName, SmtpServer, EmailAddress);

                        Thread.Sleep(30 * 1000);

                        Run();
                    }
                }
            }
        }