Search code examples
javaandroidusbhid

USB HID on Android


I'm trying to read data from the custom made USB device (working as slave) in Android. I was able to write the data to the device with this code:

UsbRequest request = new UsbRequest();
request.initialize(_outConnection, _outEndpoint);

int bufferDataLength = _outEndpoint.getMaxPacketSize();

ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
buffer.put(bytes);
if (request.queue(buffer, bufferDataLength)) {
            UsbRequest req = _outConnection.requestWait(); }

I see the result on the debug board that my device is connected to. I'm trying the same approach for reading data, but apparently that doesn't work:

int siz = 1; 
ByteBuffer res = ByteBuffer.allocate(siz + 1);
UsbRequest request = new UsbRequest();
request.initialize(_inConnection, _inEndpoint);
request.queue(res, siz); // This return false always

What am I doing wrong? I have no idea of the size of the packet sent back - but I assume that 1 byte I would be always able to read.

My device has HID interface with two interrupt endpoints (IN and OUT)


Solution

  • I have no idea what fixed the problem, but now it works. I have rewritten everything from scratch. I think I didn't use this code (I thought it is for user notification and I don't need that. But appears it is something else) - and that was the main reason why it didn't work:

    // Create and intent and request a permission.
        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(_context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        _context.registerReceiver(mUsbReceiver, filter);
    

    Several things that I did and which helped me to implement stable connection are:

    1) Closing and opening the connection each time I need it. I know this is sounds strange, but this is the only way I could make it stable. If I try to use long-living connection, for some reason it gets corrupted and stops from working after some time.

    2) Reading continously in never-ending while loop. I also put some short sleeps in all my threads - that helped to read in more real time manner.

    3) Locking the device (synchronized). I do not open both write and read connections simultaneously.

    I didn't have much hours assigned for this project, and this project is only a demo - so all of this suited us well. I think if spent a little more time, some of these things could have been rewritten to more nice ones.