0

I am using com.github.mik3y:usb-serial-for-android.

Only some packets reach correctly, some packets lose their length. Sometimes I get a full packet, but usually the response is truncated. And the very first package is correct.

 private val readerReceiver = Runnable {
        while (!_needStopThread) {
            port.write("scn20 500000000 1500000000 5000000 200 20 10700000 8500 8\\r\\n".toByteArray(),200)
            var data = ByteArray(4096)
            val len = port.read(data, 200)
            data = data.copyOf(len)
            if  (data.isNotEmpty()) {
                callBack(String(data, 0, len))
            }
        }
        _needStopThread = false
    }

I tried using serial without a library, it didn't help. I tried to collect packages into one, but the essence does not change, it is part of the package that is cut off.

Vsevolod
  • 13
  • 3
  • Serial port doesn't have the concept of "packet". Even you supply a string in a single write operation, it is not guaranteed that the whole string will reach the other end as a whole by the time the other side perform a read operation. Try buffering the received data yourself and read multiple times until you get the expected length. It might also be more intuitive to use event driven read depends on the use cases. – Ricky Mo Aug 08 '23 at 09:39
  • I tried buffering, it's written about. It doesn't help because the string very rarely reaches the end. (It will not continue on the next reading.) I tried to use SerialInputOutputManager, if buffering bytearray from onNewData, then all the same, the subsequent onNewData call is not a continuation of the previous one. How can this be fixed? – Vsevolod Aug 08 '23 at 09:51
  • Some problem in your code but not necessarily related:`data = data.copyOf(len)` mutated `data`, which cause the next read only get `len` bytes of buffer space to read into. Use another variable instead of mutating `data`. – Ricky Mo Aug 08 '23 at 10:02
  • It might be helpful to try and open an issue in the GitHub project directly. The people there will most likely be more familiar with this. https://github.com/mik3y/usb-serial-for-android/issues – Tomer Shemesh Aug 08 '23 at 19:46

0 Answers0