/// <summary>
        ///
        /// </summary>
        /// <param name="bClearBuffer">true: remove the returned command data from the queue if the command data is valid (a complete IRUARTCommand data)</param>
        /// <returns></returns>
        public IRUARTCommand GetCommandData(Boolean bClearBuffer = false)
        {
            lock (mLock)
            {
                Byte[]        data    = mDataList.Cast <Byte>().ToArray <Byte>();
                IRUARTCommand uartCmd = new IRUARTCommand(data);
                if (uartCmd.IsValidCommand)
                {
                    if (bClearBuffer)
                    {
                        RemoveHead(uartCmd.CommandBytes.Length);
                    }
                    return(uartCmd);
                }

                return(null);
            }
        }
Exemplo n.º 2
0
        private void UartDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;

            int bytesToRead;

            byte[] tmpData = null;


            byte[] tmpAll     = null;
            byte[] all        = null;
            int    totalBytes = 0;
            int    readBytes  = 0;

            while ((bytesToRead = sp.BytesToRead) > 0)
            {
                tmpData   = new byte[bytesToRead];
                readBytes = sp.Read(tmpData, 0, bytesToRead);

                totalBytes += readBytes;

                if (null != all)
                {
                    tmpAll = all;
                    all    = new byte[tmpAll.Length + tmpData.Length];
                    Array.Copy(tmpAll, 0, all, 0, tmpAll.Length);
                    Array.Copy(tmpData, 0, all, tmpAll.Length, tmpData.Length);
                }
                else
                {
                    all = tmpData;
                }
            }

            // debug
            if (null != all)
            {
                String info = String.Format("Data Received: {0} bytes:", all.Length);
                for (int i = 0; i < all.Length; i++)
                {
                    info += String.Format("{0:X2} ", all[i]);
                }
                Console.WriteLine(info);
            }

            mUartDataQueue.AppendData(all);

            while (true)
            {
                IRUARTCommand uartCommand = mUartDataQueue.GetCommandData(true);
                if ((null != uartCommand) && uartCommand.IsValidCommand)
                {
                    if (mPackageReceiveCallback != null)
                    {
                        mPackageReceiveCallback.OnReceivedPackageData(uartCommand.CommandBytes);
                    }
                }
                else
                {
                    break;
                }
            }
        }