static SerialCommunicationHandler ConnectToDevice(string device)
        {
            if (_commHandler != null && _commHandler.Connected)
            {
                ConsoleOutput.Warning($"COMMFACTORY: Already connected to {device}...");
                return(null);
            }

            ConsoleOutput.Info($"COMMFACTORY: Attempting to connect to device {device}...");
            if (device.StartsWith("Serial : "))
            {
                string comPort = device.Substring("Serial : ".Length);
                return(new SerialCommunicationHandler(comPort));
            }
            return(null);
        }
Example #2
0
        private async Task <bool> EnsurePortIsOpen()
        {
            if (!_port.IsOpen)
            {
                try
                {
                    ConsoleOutput.Info(string.Format("SERIAL: Port {0} is not open, attempting to open...", _portName));
                    _port.Open();

                    ConsoleOutput.Info(string.Format("SERIAL: Checking if buffer contains data", _portName));
                    string preCheck = _port.ReadExisting();
                    if (!string.IsNullOrEmpty(preCheck))
                    {
                        ConsoleOutput.Error(string.Format("SERIAL: Possible problem, data already in buffer: {0}", preCheck));
                        ConsoleOutput.Warning("SERIAL: Flushing serial buffers...");
                        _port.DiscardInBuffer();
                        _port.DiscardOutBuffer();
                    }
                    else
                    {
                        ConsoleOutput.Success("SERIAL: No exising serial data in buffer, all good...");
                    }
                    await Task.Delay(750); // Arduino resets on connection. Give it time to start up.

                    ConsoleOutput.Info("SERIAL: Port is open, sending initial [:I#] command..");
                    _port.Write(":I#");

                    ConsoleOutput.Success("SERIAL: Connected!");
                    return(true);
                }
                catch (Exception ex)
                {
                    ConsoleOutput.Error(string.Format("SERIAL: Failed to open the port. {0}", ex.Message));
                    return(false);
                }
            }


            ConsoleOutput.Warning("SERIAL: Flushing serial buffers...");
            _port.DiscardInBuffer();
            _port.DiscardOutBuffer();
            Console.WriteLine("SERIAL: Port {0} is open, continuing...", _portName);
            return(true);
        }