Send Modbus RTU Frames Over a BLE UART Bridge from Android

Short answer: treat the BLE link as a serial pipe. Write each Modbus request as bytes to the write characteristic, collect the reply from notifications until the expected length arrives, check the CRC, and only then send the next request. Use a queue and a timeout so requests never overlap.

The architecture

  1. A BLE manager that owns the GATT connection (see our Kotlin Flow BLE wrapper).
  2. A Modbus client that builds requests and parses replies.
  3. A serial queue that allows one request in flight.

Request and response flow

class ModbusClient(private val ble: BleManager) {
    private val mutex = Mutex()

    suspend fun readRegisters(id: Int, start: Int, count: Int): List<Int> =
        mutex.withLock {
            val request = buildRead(id, start, count)   // see CRC16 post
            val expected = 5 + 2 * count
            ble.write(request)
            val reply = withTimeout(1500) { ble.collectBytes(expected) }
            check(crcOk(reply)) { "CRC mismatch" }
            parse(reply)
        }
}

The Mutex guarantees only one request is in flight. write and collectBytes are helpers you add to your BLE manager: the second gathers notification chunks until the expected number of bytes has arrived.

Chunking

A Modbus request is short, but if your MTU is the default 23, the maximum payload is 20 bytes, so a long write request (function 16 with many registers) must be split. See chunking over BLE.

Handle failures

  • Timeout: retry once or twice, then report the device as not responding.
  • CRC mismatch: discard the buffer and retry.
  • Exception reply: stop retrying and show the code, as explained in our function and exception codes post.
  • Disconnect: clear the buffer and queue.

Polling

Poll on a fixed interval from a coroutine and read as many registers as the device allows in one request. Fewer, larger reads are faster than many small ones.

FAQ

Can I send two Modbus requests at once over BLE?

No. Modbus RTU is request and response, so wait for the reply or a timeout before the next request.

Where should this code live?

In a repository or manager class injected with Hilt, not in an Activity.

Related: Modbus RTU Basics for Android Developers and the Bluetooth and IoT hub.

Register maps differ by manufacturer. Always confirm addresses, scaling and word order in your device manual.