How to keep reading response from Modbus RTU controller in my Android app using SerialPort?

98 Views Asked by At

I am developing an Android app which is reading and writing input and holding registers and it has to keep doing this process 24x7 without stopping.

I have a method which takes request frame to write using outputstream object and then read the response using inputstream object and then continue this process in infinite loop.

But my issue is that method after some time stops reading and writing anything and I have to restart the app again to start that method to continue reading and writing.

suspend fun readAndWriteRegisters(
    mOutputStream: OutputStream?, mInputStream: InputStream?, responseSize: Int,
    requestFrame: ByteArray, onDataReceived: (ByteArray) -> Unit
) {
    withContext(Dispatchers.IO) {
        try {
            val bufferedInputStream = BufferedInputStream(mInputStream)
            val bufferedOutputStream = BufferedOutputStream(mOutputStream)
            
            bufferedOutputStream.write(requestFrame)
            bufferedOutputStream.flush()

            val responseFrame = ByteArray(responseSize)

            delay(500) //waiting for 500ms between write and read

            bufferedInputStream.mark(0)
            val size = bufferedInputStream.read(responseFrame)
           
            if (size > 0 && isValidResponse(responseFrame)) {
                onDataReceived(responseFrame)
            } 

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

I have tried Android's withTimeout method to set timeout after it stops so that I can restart writing process in the catch block. But that is also not working as expected.

0

There are 0 best solutions below