Search code examples
javaandroidusbtransferbulk

successfully received bulk transfer data but its length was not enough


I'm working on bulk transfer Android. I send and receive the data to/from USB successfully. The data that I send is cbwBuffer which is a command that tells USB that I want to read USB start in which sector and how many sector. Below is my code.

byte cswBuffer[] = new byte[18432];
iRes = conn.bulkTransfer(epOUT, cbwBuffer, 31, 500);//send data
iRes2 = conn.bulkTransfer(epIN, cswBuffer, 18432, 500);//receive data

The received data should be exactly 18432. However, iRes2 equals to 16384, means that data that I received is only 16384 bytes, not 18432 bytes. I inspect the cswBuffer(received data) and find out that my data is only correct from 0 index to 16384 index but where is the rest? I mean the data was not enough. I need 18432-16384=2048 bytes more.

18432 means I read 36 sectors of my USB since 1 sector = 512 bytes. I just realized that if I read more than 32 sectors, I will always get 16384 bytes.


Solution

  • The conclusion I found is the maximum data length can be received is 16384 bytes. If want more than that, just put another one of iRes = conn.bulkTransfer(epIN, cswBuffer, remaining, 500) and the remaining data will be received.

    So I need to chunk the data where each data is at most 16384 bytes.

     if (noOfSector > 32) {
                    //CHUNK DATA
                    int maxLength = 16384;
                    int lengthReceivedData = 0;
                    int remaining;
                    int chunkSize = (noOfSector + 32 - 1) / 32;int first= chuckSize;
                    byte[] receivedData = new byte[maxLength];
                    while (chunkSize > 1) {
                        cswBuffer = new byte[maxLength];
                        iRes = conn.bulkTransfer(epIN, cswBuffer, maxLength, 500);
    
                        if (chunkSize == first) {//if first time do this
                            receivedData = cswBuffer;
                        } else {
    
                            receivedData = concatenateByteArrays(receivedData, cswBuffer);
                        }
    
                        chunkSize--;
                        lengthReceivedData += maxLength;
                    }
                    remaining = sectorLength - lengthReceivedData;
                    if (chunkSize == 1) {//last one sector
                        cswBuffer = new byte[remaining];
                        iRes = conn.bulkTransfer(epIN, cswBuffer, remaining, 500);
                        receivedData = concatenateByteArrays(receivedData, cswBuffer);
                        finalBuffer = receivedData;
                    }
                    //END CHUNK DATA