Search code examples
c++usbhid

USB-HID Read/Write (Overlapped) WaitForSingleObject does not return C++


I am trying to communicate with device through usb hid. At some point I want to read data from the device using winapi. I start by creating file

HidDeviceObject = CreateFile (
                          (LPCTSTR)DevicePath,
                          GENERIC_READ | GENERIC_WRITE,
                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                          NULL, //&SecurityAttributes, 
                          OPEN_EXISTING,
                          FILE_FLAG_OVERLAPPED, 
                          NULL);

This part seems to work has already been tested. Then I create a thread when initializing my app. The thread looks like this

int result;
BOOL fWaitingOnRead = FALSE;
while(TRUE)
{
    if(!write)
    {
        if (HidDeviceObject != INVALID_HANDLE_VALUE)
        {
            HIDOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

            result = ReadFile(HidDeviceObject, &InputReport, Capabilities.InputReportByteLength, &NumberOfBytesRead, &HIDOverlapped);
            if (GetLastError() != ERROR_IO_PENDING)   
            // Error
            else
                fWaitingOnRead = TRUE;

            if(fWaitingOnRead)
                DWORD dwRes = WaitForSingleObject(HIDOverlapped.hEvent, INFINITE);


        }
    } 
}

This code is executed knowing that there is periodically data coming from my other usb device. But the problem is that WaitForSingleObject does not return. Of course by putting a value of for example 500ms instead of INFINITE will get me a timeout code. So what would be the reason for this behavior. Thanks


Solution

  • You're looking for GetOverlappedResult instead of WaitForSingleObject. Don't pick out the event, use the whole OVERLAPPED object.

    GetOverlappedResultEx accepts a tiemout value, if you need the 500 milliseconds again.