felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.78k stars 581 forks source link

syncRead fail after writing large syncWrite #368

Open bronek999 opened 8 months ago

bronek999 commented 8 months ago

I have application with lot of small USB transfers. My single transfer looks: Android write header+data with CRC and packet length. After receiving whole packet lenght by USB device, is verified CRC and if it is correct, send ACK (1 byte) ...there is some operations and also result operation result (text 3~120bytes) . Finished by "\n\r"

Everything works fine with small packets. I tried it may be 800.000 times without any error. But when I send large data packet (2kB~13kB) I always receive ACK from USB device, but text response is sometimes missing or uncorrect. Uncorrect means that I receive substring of valid response. Large packet transfer fail randomly. May be one time from ten times...

My receive procedure (after valid ACK received) is

        long time = System.currentTimeMillis();
        String received = "";
        while (true) {
            DataAvailable = usbService.read(read_buffer, 10);
            if (DataAvailable > 0) {
                for (int i = 0; i < DataAvailable; i++) {
                    received = received + (char) read_buffer[i];
                    if (read_buffer[i] == 13) {
                        stop = true;
                        int Pos = received.indexOf("Blok=");
                        if (Pos == 1) {
                            received = received.substring(6);
                            FBlokySprav = received.substring(0, received.length() - 3);
                            received = received.substring(0, received.indexOf(","));
                            int RecBlokNo = Integer.valueOf(received);
                            LastBlokyOK = FBlokySprav;
                            if (Typ == 0)
                                return RecBlokNo;
                            else if (BlokNo == RecBlokNo)
                                return 1;
                        }
                    }
                }
            }
            if ((System.currentTimeMillis() - time) > TimeOut) {
                break;
            }
            if (stop) break;
        }

ACK reading is byte [] read_buffer = new byte[1]; int readed = usbService.read(read_buffer, 1000);

USB device is STM32 CDC device. I have connected it in debuging mode, when large transfer fails, I stop STM32 and watch his registers. Valid response was sent and whole USB message was flushed to USB.

CDC device STM32 works correctly, it is used with PC without any problems.

I tried rewrite code and remove synchronized operations. Large transfers works fine