开发者

HID Device. Best way to do event handling?

I'm using an HID device to connect to a CAN bus with several different types of sensors attached. Some of them respond quickly, others have more latency.

I'm using this USB HID Component for C# as a .dll in visual basic, which works great. http://www.codeproject.com/KB/cs/USB_HID.aspx

My current code for sending and receivin开发者_StackOverflow中文版g commands is somewhat troublesome. Sometimes commands and sent but not received fast enough. The problem can be with the sensor, not the actual vb code. We want the program to continue monitoring the other sensors, and not hang for too long.

Currently I'm using event handlers and loops, but I'm wondering if this might be better done by threading? or if my routine is the best for this situation.

Code Snippets:

CANUSB_Class.vb

Public Sub DataReceivedHandler(ByVal sender As Object, ByVal dataReceived As DataRecievedEventArgs)
     For Each byteReceived As Byte In dataReceived.data
         rxDataStruct.dataPacket(rxDataStruct.InPacketLength) = byteReceived
         rxDataStruct.InPacketLength += 1
     Next
     rxDataReady = True

MainParsingRoutine.vb

sendCommand = False
CANPort.rxDataReady = False
     Try
          Do
              Tries += 1
              If Tries > 4 Then
                  Exit Do
              End If
              CANTimer.Start()
              CANPort.transmitPacket(OutCANPacket)

              'Wait for Return Packet
              Do Until CANPort.rxDataReady = True Or _ 
                      CANTimer.ElapsedMilliseconds > timeout
                  System.Threading.Thread.Sleep(0)
              Loop
              If CANPORT.rxDataReady = True Then
                  sendCommand = True 
          Loop Until sendCommand = True


If anyone is developing a HID device and stumbles across this page I ended up using the ManualResetEvent.

In the CANUSB class the next line would be:

resetEvent.Set()

and then in the MainParsingRoutine.vb I changed:

Do Until CANPort.rxDataReady = True Or _ 
                  CANTimer.ElapsedMilliseconds > timeout
              System.Threading.Thread.Sleep(0)
          Loop
          If CANPORT.rxDataReady = True Then
              sendCommand = True

to:

CANUSB.resetEvent.WaitOne(100)

which times out after 100ms.

Works very well with our HID device, much better than our previous FTDI usb-serial device.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜