现在的位置: 首页 > 综合 > 正文

在comPort发送事件中获取返回数据

2013年10月20日 ⁄ 综合 ⁄ 共 1437字 ⁄ 字号 评论关闭

       /// <summary>协议类</summary>
        public class Protocol
        {
            public Protocol()
            {
                m_Port = new System.IO.Ports.SerialPort();
                m_Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(m_Port_DataReceived);
                m_CommData = new CommData();
                m_Event = new System.Threading.ManualResetEvent(false);  //初始化为阻塞状态
            }

            private System.Threading.ManualResetEvent m_Event = null;        //定义

           public bool SendData(ProtocolDataFormat sendData, ref ProtocolDataFormat receivedData, int waitTimeout)
            {

                     //开始发送数据
                    m_Event.Reset();        //将信号设置为不发送状态
                    try
                    {
                        m_Port.Write(byteSendData, 0, byteSendData.Length);
                    }
                    catch(Exception e)
                    {
                       // throw e; // new Exception("发送数据错误!");
                        return false;
                    }

                   m_Event.WaitOne(waitTimeout);     //如果获得信号(既信号为发送状态),线程继续执行,如果没有获得信号,等待waitTimeout之后,线程继续执行

                   if (m_CommData.IsReceived && waitTimeout != 0) //接收到返回值
                    {
                        if (m_CommData.ErrorNum == 0 && m_CommData.IsTimeOut == false)   //接收到正确的数据
                        {
                            receivedData = m_CommData.ReceivedData.Clone();  //复制串口接收的数据
                            return sendData.Command == receivedData.Command;
                        }
                        else return false;
                    }

           }

            

             /// <summary>数据接收处理</summary>
            private void DataReceived()
            {

                       //接收代码

                        m_CommData.IsReceived = true;
                        m_Event.Set();   //接收完毕,将信号设置为有信号状态

             }

}

抱歉!评论已关闭.