diff --git a/ykonsole-iconsole/src/main/kotlin/net/aiterp/git/ykonsole2/infrastructure/IConsole.kt b/ykonsole-iconsole/src/main/kotlin/net/aiterp/git/ykonsole2/infrastructure/IConsole.kt index 155b897..b643274 100644 --- a/ykonsole-iconsole/src/main/kotlin/net/aiterp/git/ykonsole2/infrastructure/IConsole.kt +++ b/ykonsole-iconsole/src/main/kotlin/net/aiterp/git/ykonsole2/infrastructure/IConsole.kt @@ -35,14 +35,16 @@ class IConsole : ActiveDriver() { private var btCommandInput: BluetoothGattCharacteristic? = null private fun onConnect(device: Device, output: FlowBus) { - tryingSince = Instant.now() - if (!device.connectionString.startsWith("iconsole:")) { logger.info("Ignoring non-iConsole $device") return } val connectionString = device.connectionString.substring("iconsole:".length) + central?.stopScan() + current?.cancelConnection() + tryingSince = Instant.now() + val cbPeripheral = object : BluetoothPeripheralCallback() { override fun onServicesDiscovered(peripheral: BluetoothPeripheral, services: MutableList) { logger.info("Checking device...") @@ -156,9 +158,11 @@ class IConsole : ActiveDriver() { override fun onDiscoveredPeripheral(peripheral: BluetoothPeripheral, scanResult: ScanResult) { logger.info("Connecting to ${peripheral.name} (${peripheral.address})...") - tryingSince = null - central?.connectPeripheral(peripheral, cbPeripheral) - central?.stopScan() + if (tryingSince != null) { + tryingSince = null + central?.connectPeripheral(peripheral, cbPeripheral) + central?.stopScan() + } } override fun onDisconnectedPeripheral(peripheral: BluetoothPeripheral, status: BluetoothCommandStatus) { @@ -167,6 +171,15 @@ class IConsole : ActiveDriver() { output.emitBlocking(Disconnected) } } + + override fun onConnectionFailed(peripheral: BluetoothPeripheral, status: BluetoothCommandStatus) { + central?.stopScan() + + runBlocking { + output.emit(ErrorOccurred("Failure: $status")) + output.emit(Disconnected) + } + } } central = BluetoothCentralManager(cbScan).apply {