Search code examples
c#usblibusbdotnet

How can I determine why ControlTransfer method of LibUsbDotNet in C# returns false?


I am trying to use the ControlTransfer method of the LibUsbDotNet C# library to communicate with a USB device but the method keeps returning false. My code is as follows:

private bool writeCtrlMsg(int value, int index, byte[] buffer)
{
    if (buffer == null || buffer.Length == 0)
        throw new ArgumentException("Null or invalid length param.", "buffer");
    if (_rtlUSBDongle == null)
        throw new DongleNotOpeningException();
    if (!_rtlUSBDongle.IsOpen && !_rtlUSBDongle.Open())
        throw new DongleConnectionException();

    var shortVal = (short)value;
    var shortIndex = (short)index;

    var usbSetupPacket = new UsbSetupPacket(
        (byte)(UsbCtrlFlags.Direction_Out | UsbCtrlFlags.RequestType_Vendor | UsbCtrlFlags.Recipient_Device),
        0,
        value,
        index,
        buffer.Length
    );

    var result = _rtlUSBDongle.ControlTransfer(ref usbSetupPacket, buffer, buffer.Length, out var lengthTransferred);
    var errorCode = GetLastError();
    var errorCodeHex = errorCode.ToString("X");
    return result;
}

One example of a method call would be: writeCtrlMsg(0x34, 0x619, new byte[] { 0x83 }). No matter what values I use the ControlTransfer method keeps returning false. I couldn't find anything in the documentation about error handling or when this method returns false. I used the GetLastError call to see if I get any errors and it consistently returns 31 (or 0x1F), however I couldn't find anything online about this error.

This is the only other question I was able to find on SO about this and the answer suggests to use 0x0 for the last parameter in the UsbSetupPacket constructor call. Tried, still returns false.

Any ideas?


Solution

  • Have you tried using the following two:

    LastErrorNumber

    UsbDevice.LastErrorNumber
    

    Returns the last error number reported by LibUsbDotNet.

    And

    LastErrorString

    UsbDevice.LastErrorString
    

    http://libusbdotnet.sourceforge.net/V2/html/f3942add-f073-3881-7146-0673415cee3b.htm