示例#1
0
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var serialPort = sender as SerialPort;

            if (null == serialPort)
            {
                throw new ArgumentNullException(nameof(sender));
            }

            // Sometimes the serialport reports data, even if the port was closed.
            if (!serialPort.IsOpen)
            {
                return;
            }

            // Only deal with the arival of chars, ignore all other events
            if (e.EventType == SerialData.Chars)
            {
                var count     = serialPort.BytesToRead;
                var buffer    = new byte[count];
                var bytesRead = serialPort.Read(buffer, 0, count);

                Debug.Assert(bytesRead == count, "Bytes read not count");

                // Add the read bytes to the end of the buffer
                InputBuffer.AddRange(buffer);

                try
                {
                    var commandBlock = new CommandBlock();
                    while (null != commandBlock)
                    {
                        if (CommandBlock.TryParse(InputBuffer, out commandBlock))
                        {
                            InputBuffer.Clear();

                            Serial.DiscardInBuffer();
                            Serial.DiscardOutBuffer();

                            var response = ProcessRequest(commandBlock);

                            Send(response);
                        }
                    }
                }
                catch (ArgumentException)
                {
                }
            }
        }