/// <summary>
        /// Initialize and connect the disigtal system.
        /// </summary>
        public override bool Connect()
        {
            Logger.LogDebug(this, "[CLASS].Connect()");

            try
            {
                LenzBufferManager.Clear();

                this.SerialPort = new SerialPort(this.PortName, this.BaudRate, Parity.None, 8, StopBits.One);
                //this.SerialPort.Parity = Parity.None;
                this.SerialPort.Handshake = Handshake.None;
                //this.SerialPort.DataBits = 8;
                //this.SerialPort.StopBits = StopBits.One;
                this.SerialPort.RtsEnable      = false;
                this.SerialPort.DtrEnable      = false;
                this.SerialPort.WriteTimeout   = this.ReadWriteTimeout;
                this.SerialPort.ReadTimeout    = this.ReadWriteTimeout;
                this.SerialPort.ReadBufferSize = 1024;

                if (this.SerialPort != null && !this.SerialPort.IsOpen)
                {
                    this.SerialPort.DataReceived += SerialPort_DataReceived;
                    this.SerialPort.Open();

                    // Send information
                    this.OnInformationReceived(new SystemConsoleEventArgs(SystemConsoleEventArgs.MessageType.Information, "{0} connected", this.Name));

                    // Send a system & interface information request to verify communication and to show system info as well
                    this.SystemInformation();
                    Thread.Sleep(250);
                    this.InterfaceInformation();

                    // Start the acknowledgement signal timer
                    if (this.KeepaliveSignalInterval > 0)
                    {
                        this.AcknowledgementTimer          = new System.Timers.Timer(this.KeepaliveSignalInterval);
                        this.AcknowledgementTimer.Elapsed += AcknowledgementTimer_Elapsed;
                        this.AcknowledgementTimer.Start();
                    }

                    this.Status = SystemStatus.Connected;

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(this, ex);

                this.OnInformationReceived(new SystemConsoleEventArgs(SystemConsoleEventArgs.MessageType.Error, ex.Message));

                this.SerialPort.Dispose();

                return(false);
            }
        }
        public static List <List <byte> > DataReceived(List <byte> receivedBytes)
        {
            // Add new bytes to the buffer
            LenzBufferManager.RxBuffer.AddRange(receivedBytes);

            // Parse command packets
            return(LenzBufferManager.GetPackets());
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            IResponse response;

            //SerialPort xpressnetSerialPort = (SerialPort)sender;
            if (this.SerialPort.BytesToRead <= 0)
            {
                return;
            }

            // this.SerialPort.ReadBufferSize = 1024;

            List <byte> rxBytes = new List <byte>();

            rxBytes.AddRange(System.Text.Encoding.ASCII.GetBytes(this.SerialPort.ReadExisting()));

            if (this.DebugMode)
            {
                this.OnInformationReceived(new SystemConsoleEventArgs(SystemConsoleEventArgs.MessageType.Debug,
                                                                      "RX -> {0}",
                                                                      BinaryUtils.ToString(rxBytes)));
            }

            foreach (List <byte> command in LenzBufferManager.DataReceived(rxBytes))
            {
                response = this.GetResponse(command);
                if (response != null)
                {
                    this.OnCommandReceived(new SystemCommandEventArgs(response));
                }
            }

            if (this.DebugMode)
            {
                this.OnInformationReceived(new SystemConsoleEventArgs(SystemConsoleEventArgs.MessageType.Debug,
                                                                      "BUFFER -> {0}",
                                                                      BinaryUtils.ToString(LenzBufferManager.RxBuffer)));
            }
        }
        private static List <List <byte> > GetPackets()
        {
            bool                discard        = false;
            bool                reading        = false;
            int                 remWindowStart = -1;
            int                 remWindowEnd   = -1;
            List <byte>         currentCommand = null;
            List <List <byte> > commands       = new List <List <byte> >();

            for (int i = 0; i < LenzBufferManager.RxBuffer.Count; i++)
            {
                // The buffer should always start with a package. If the first bytes of the buffer don't
                // correspond to a valid command, discard bytes until a valid command header is detected
                if ((i == 0 || i == 1) && LenzBufferManager.RxBuffer[i] != COMMAND_DELIMITER)
                {
                    discard = true;
                }

                // A command header is detected
                if (!reading && i < LenzBufferManager.RxBuffer.Count - 1 && LenzBufferManager.RxBuffer[i] == COMMAND_DELIMITER && LenzBufferManager.RxBuffer[i + 1] == COMMAND_DELIMITER)
                {
                    if (remWindowStart < 0)
                    {
                        remWindowStart = i;
                    }

                    discard        = false;
                    reading        = true;
                    currentCommand = new List <byte>();
                    i++;
                }
                else if (!discard)
                {
                    if (currentCommand != null)
                    {
                        currentCommand.Add(LenzBufferManager.RxBuffer[i]);
                        if (LenzBufferManager.IsValidCommand(currentCommand) || LenzBufferManager.IsInterfaceCommand(currentCommand))
                        {
                            remWindowEnd = i;
                            commands.Add(currentCommand);
                            discard = true;
                            reading = false;
                        }
                        else if (LenzBufferManager.IsDiscardableResponse(currentCommand))
                        {
                            remWindowEnd = i;
                            discard      = true;
                            reading      = false;
                        }
                    }
                }
            }

            // Remove readed packets
            if (remWindowEnd > 0)
            {
                LenzBufferManager.RxBuffer.RemoveRange(remWindowStart, remWindowEnd - remWindowStart + 1);
            }

            return(commands);
        }