writeLongCharacteristic

fun writeLongCharacteristic(serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray, callback: (Int) -> Unit)

Writes a large value to a characteristic using sequential chunked writes.

This method automatically splits the data into chunks that fit within the current MTU size and writes them sequentially. If the value is small enough to fit in a single write (within MTU - 3 bytes for ATT header), it delegates to the regular writeCharacteristic method.

This is useful for writing values larger than the negotiated MTU, such as firmware updates, large configuration blobs, or any data that exceeds the maximum single-write payload size.

The state machine must be in ConnectionState.Ready for this operation to succeed. Each chunk write has its own timeout applied via operationTimeoutMs.

Note: This implementation writes chunks sequentially using standard write operations. It does NOT use BLE Reliable Write (prepared writes with execute), which would provide atomicity but requires different device-side handling. For most use cases, sequential writes are sufficient and more widely supported.

Chunk Size Calculation

  • Default MTU: 23 bytes (if no MTU negotiation has occurred)

  • Chunk size: MTU - 3 bytes (ATT protocol header)

  • Example: With MTU of 247, chunk size is 244 bytes

Parameters

serviceUuid

The UUID of the GATT service containing the characteristic.

characteristicUuid

The UUID of the characteristic to write to.

value

The full byte array value to write. Can be larger than MTU.

callback

Invoked with the final status code when all chunks have been written or when an error occurs. BluetoothGatt.GATT_SUCCESS indicates all chunks were written successfully.

See also

Throws

if Bluetooth permissions are not granted.