/// <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); //发出数据到达消息 if (!deviceOpened) { return; } BeginAsyncRead(); //启动下一次读操作 } catch //读写错误,设备已经被移除 { //MyConsole.WriteLine("设备无法连接,请重新插入设备"); EventArgs ex = new EventArgs(); OnDeviceRemoved(ex); //发出设备移除消息 CloseDevice(); } }
/// <summary> /// 事件:数据到达,处理此事件以接收输入数据 /// </summary> protected virtual void OnDataReceived(report e) { lock (lockThis) { recvLen = 0; for (int i = 0; i < e.reportBuff.Length; i++) { recvBuff[i] = e.reportBuff[i]; recvLen++; } } }
/// <summary> /// /// </summary> /// <param name="buffer"></param> /// <returns></returns> public HID_RETURN Write(report r) { if (deviceOpened) { try { byte[] 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 = 0; i < maxBufferLength; i++) { buffer[i + 1] = r.reportBuff[i]; } recvLen = 0; hidDevice.Write(buffer, 0, OutputReportLength); return(HID_RETURN.SUCCESS); } catch { EventArgs ex = new EventArgs(); OnDeviceRemoved(ex); //发出设备移除消息 CloseDevice(); return(HID_RETURN.NO_DEVICE_CONECTED); } } return(HID_RETURN.WRITE_FAILD); }