Improve USB connection handling by preventing connection attempts when already connected

chore/offband-rebrand
just_stuff_tm 7 months ago committed by just-stuff-tm
parent 9a0572e8e4
commit 115689ad95

@ -238,30 +238,45 @@ class MainActivity : FlutterActivity() {
baudRate: Int, baudRate: Int,
result: MethodChannel.Result, result: MethodChannel.Result,
) { ) {
usbIoExecutor.execute {
try { try {
closeUsbConnection() closeUsbConnection()
val driver = UsbSerialProber.getDefaultProber().probeDevice(device) val driver = UsbSerialProber.getDefaultProber().probeDevice(device)
if (driver == null) { if (driver == null) {
result.error("usb_driver_missing", "No USB serial driver for ${device.deviceName}", null) mainHandler.post {
return result.error(
"usb_driver_missing",
"No USB serial driver for ${device.deviceName}",
null,
)
}
return@execute
} }
val connection = usbManager.openDevice(device) val connection = usbManager.openDevice(device)
if (connection == null) { if (connection == null) {
mainHandler.post {
result.error( result.error(
"usb_open_failed", "usb_open_failed",
"UsbManager could not open ${device.deviceName}", "UsbManager could not open ${device.deviceName}",
null, null,
) )
return }
return@execute
} }
val port = firstPort(driver) val port = firstPort(driver)
if (port == null) { if (port == null) {
connection.close() connection.close()
result.error("usb_port_missing", "No USB serial port exposed by ${device.deviceName}", null) mainHandler.post {
return result.error(
"usb_port_missing",
"No USB serial port exposed by ${device.deviceName}",
null,
)
}
return@execute
} }
port.open(connection) port.open(connection)
@ -303,12 +318,17 @@ class MainActivity : FlutterActivity() {
manager.start() manager.start()
} }
mainHandler.post {
result.success(null) result.success(null)
}
} catch (error: Exception) { } catch (error: Exception) {
closeUsbConnection() closeUsbConnection()
mainHandler.post {
result.error("usb_connect_failed", error.message, null) result.error("usb_connect_failed", error.message, null)
} }
} }
}
}
private fun firstPort(driver: UsbSerialDriver): UsbSerialPort? { private fun firstPort(driver: UsbSerialDriver): UsbSerialPort? {
return driver.ports.firstOrNull() return driver.ports.firstOrNull()

@ -425,6 +425,13 @@ class _UsbScreenState extends State<UsbScreen> {
if (selectedPort == null || selectedPort.isEmpty) { if (selectedPort == null || selectedPort.isEmpty) {
return; return;
} }
if (_connector.state != MeshCoreConnectionState.disconnected) {
setState(() {
_isConnecting = false;
_errorText = null;
});
return;
}
final rawPortName = normalizeUsbPortName(selectedPort); final rawPortName = normalizeUsbPortName(selectedPort);
setState(() { setState(() {

Loading…
Cancel
Save

Powered by TurnKey Linux.