当前位置:编程学习 > C#/ASP.NET >>

USB hid 通讯问题

最近做HID通讯,采用了网上教常见的通讯例子,(例子中的通讯类名为"hid.cs")。现在通讯出现了两个问题,当设备传送过来的数据较大时,一:偶尔出现接收的数据不完整(丢包)的情况。二:接收的数据包,颠倒的情况。
不知大家是否遇见过,如何解决?? --------------------编程问答-------------------- 将通讯类的部分代码贴一下,大家一查就知道是那个例子了。

        public string  Write(report r,string Type)
        {
            
            byte[] buffer = null;
            if (deviceOpened)
            {
                //try
                //{
                    buffer = new byte[outputReportLength];
                    buffer[0] = r.reportID;
                    int maxBufferLength = 0;
                    if (r.reportBuff.Length < outputReportLength - 1)
                        maxBufferLength = r.reportBuff.Length;
                    else
                        maxBufferLength = outputReportLength - 1;
                    for (int i = 1; i < maxBufferLength; i++)
                        buffer[i] = r.reportBuff[i - 1];
                    hidDevice.Write(buffer, 0, OutputReportLength);
                    //CommandType = string.Empty;
                    CommandType = Type;
                    BeginAsyncRead();
                //}
                //catch
                //{
                //    EventArgs ex = new EventArgs();
                //    OnDeviceRemoved(ex);//发出设备移除消息
                //    CloseDevice();
                //    throw;
                //}

            }
        /// <summary>
        /// 开始一次异步读
        /// </summary>
        /// <param name="commandType"></param>
        private void BeginAsyncRead()
        {
            byte[] inputBuff = new byte[InputReportLength];
            
            hidDevice.BeginRead(inputBuff, 0, InputReportLength, new AsyncCallback(ReadCompleted), inputBuff);            
        }
        /// <summary>
        /// 异步读取结束,发出有数据到达事件
        /// </summary>
        /// <param name="iResult">这里是输入报告的数组</param>
        private void ReadCompleted(IAsyncResult iResult)
        {
            byte[] readBuff = (byte[])(iResult.AsyncState);
            //try
            //{
                hidDevice.EndRead(iResult);//读取结束,如果读取错误就会产生一个异常
                byte[] reportData= new byte[readBuff.Length - 1];
                for (int i = 1; i < readBuff.Length; i++)
                    reportData[i - 1] = readBuff[i];
                report e = new report(readBuff[0], reportData);
                OnDataReceived(e); //发出数据到达消息
                BeginAsyncRead();//启动下一次读操作
            //}
            //catch (IOException e)//读写错误,设备已经被移除
            //{
            //    EventArgs ex = new EventArgs();
            //    OnDeviceRemoved(ex);//发出设备移除消息
            //    CloseDevice();

            //}
        }


--------------------编程问答-------------------- 和什么设备通信?
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,