Search code examples
c++windowsusbhandlehid

How to test USB HID handle as invalid due to device being replugged


In Windows 7 I have a handle to a custom USB HID device. I'm trying to determine if the handle is no longer able to access the device because the device has been unplugged and re-plugged. When this happens I/O attempts using WriteFile fail. However I am looking for a way to test the handle before doing any I/O to determine if the HID device handle is still valid. And when I say valid I mean handle is connected to device such that I will be able to do I/O to the device. I understand that technically the handle itself may be valid even when it has lost connection to the physical device. The current method in my code is to test by using an attempt to open a new handle to the device and if this succeeds then handle is valid and if it fails handle is not valid. This detects disconnect as expected if the device is unplugged at the time of the test. The problem with this is that if the device has been plugged back in then the test open succeeds but the actual handle used to do I/O (opened before the disconnected/reconnect) is no longer connected to the device. I'm looking for a benign call I can do with the actual I/O handle that will tell me if the device is connected but without doing any actual I/O.

I've tried a few calls so far but none return an indication of the device connection as I require.

DWORD handleInformation;
LARGE_INTEGER size = { 0, 0 };
BOOL isConnected;

isConnected = GetFileSizeEx(m_HidWriteHandle, &size);
isConnected = GetHandleInformation(m_HidWriteHandle, &handleInformation);

GetFileSizeEx always fails and GetLastError() reports (1) Invalid Function

GetHandleInformation always succeeds even when device has been disconnected/reconnected and handle is not able to access device.


Solution

  • The call to use is HidD_GetAttributes(handle, &attributes)

    // Try to get the HID attributes.  This will fail if device is
    // unplugged or has been unplugged since CreateFile() call that
    // created m_HidWritehandle
    HIDD_ATTRIBUTES Attributes;
    Attributes.Size = sizeof(Attributes);
    m_HidPresent = HidD_GetAttributes(m_HidWriteHandle, &Attributes) != 0;
    

    This will return false even if device has been plugged back in and thus can be used as an indicator of need to reconnect to HID device.