Companion Lab: Android Bluetooth Classic RFCOMM
Companion Lab: Android Bluetooth Classic RFCOMM
Companion Lab: Android Bluetooth Classic RFCOMM
This chapter’s main build uses BLE/GATT. RFCOMM is a different path: it is a reliable stream transport over Bluetooth Classic (BR/EDR), commonly used for serial-style links. Do not label an RFCOMM socket as a BLE characteristic. Android pairs devices before the RFCOMM connection; pairing is not proof that the application protocol or actuator command is safe.
On Android 12 and later, request BLUETOOTH_SCAN for discovery and BLUETOOTH_CONNECT for paired-device access and connections. Earlier Android versions have different manifest/location rules, so gate behaviour by platform version and follow the current Android permission guide. Show the learner why the permission is needed, handle denial, cancel discovery before connecting, and never select a device by display name alone: retain its address/identity and the expected service UUID.
private val SERVICE_ID: UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // lab SPP UUID
suspend fun acceptOne(adapter: BluetoothAdapter) = withContext(Dispatchers.IO) {
adapter.listenUsingRfcommWithServiceRecord("IoT GPIO lab", SERVICE_ID).use { server ->
server.accept().use { socket -> handleFrames(socket) }
}
}
suspend fun connectOne(adapter: BluetoothAdapter, device: BluetoothDevice) =
withContext(Dispatchers.IO) {
adapter.cancelDiscovery()
device.createRfcommSocketToServiceRecord(SERVICE_ID).use { socket ->
socket.connect()
socket.outputStream.bufferedWriter(Charsets.US_ASCII).use { writer ->
writer.write("SET LED 1\n")
writer.flush()
val reply = socket.inputStream.bufferedReader(Charsets.US_ASCII).readLine()
check(reply == "OK LED 1") { "unexpected acknowledgement: $reply" }
}
}
}
private fun handleFrames(socket: BluetoothSocket) {
val allowed = setOf("SET LED 0", "SET LED 1", "GET STATUS")
val reader = socket.inputStream.bufferedReader(Charsets.US_ASCII)
val writer = socket.outputStream.bufferedWriter(Charsets.US_ASCII)
while (true) {
val frame = reader.readLine() ?: break
val safeFrame = frame.take(65)
val response = when {
frame.length > 64 -> "ERR FRAME_TOO_LONG"
safeFrame !in allowed -> "ERR COMMAND_DENIED"
else -> applyBoundedLabCommand(safeFrame) // returns an explicit OK/ERR line
}
writer.write("$response\n")
writer.flush()
}
}The newline is the frame boundary; the 64-byte ceiling prevents an unbounded line; the allowlist rejects arbitrary pin numbers, shell text, and energising commands outside the lab. applyBoundedLabCommand must map logical names to fixed outputs, enforce electrical and timing limits in the device firmware, default outputs to a safe state on disconnect, and return an acknowledgement only after the device applies or rejects the change.
Run these mutations and retain timestamped client/server logs:
- Deny the runtime permission and prove discovery/connection stops cleanly.
- Discover the device, pair through the system UI, cancel discovery, and connect with the same UUID on both ends.
- Send one valid command split across multiple writes; newline framing must still produce one command.
- Send an unknown command and a line longer than 64 bytes; neither may change an output.
- Move out of range, close both socket streams, restore safe output, and reconnect with bounded exponential backoff and a user-visible cancel action.
- Reboot the peer and prove stale buffered commands are not replayed without a fresh application decision.
RFCOMM supplies a byte stream, not command authentication, freshness, electrical interlocking, or fail-safe behaviour. Pairing, application identity, command authorization, sequence/freshness, device-side limits, physical safety, acknowledgement, timeout, and disconnect recovery are separate evidence.