From 95533aab0d55336aabfee09d35d661ad514a9b9e Mon Sep 17 00:00:00 2001 From: Pritimay Sarkar Date: Thu, 29 Feb 2024 10:14:16 +0530 Subject: [PATCH] add exception handling --- .../presentation/testRight/UsbService.kt | 56 ++++++++++++------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/com/example/hpostesting/presentation/testRight/UsbService.kt b/app/src/main/java/com/example/hpostesting/presentation/testRight/UsbService.kt index cf240ab..5b3ef28 100644 --- a/app/src/main/java/com/example/hpostesting/presentation/testRight/UsbService.kt +++ b/app/src/main/java/com/example/hpostesting/presentation/testRight/UsbService.kt @@ -33,32 +33,48 @@ class UsbService : Service() { var bus: UsbServiceListener? = null fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) { - mPort = driver.ports[0] // Most devices have just one port (port 0) - mPort.open(connection) - mPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE) - isUsbConnected = true - Log.d(TAG, "My Usb Connected ${mPort.driver}") + try { + mPort = driver.ports[0] + mPort.open(connection) + mPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE) + isUsbConnected = true + Log.d(TAG, "My Usb Connected ${mPort.driver}") - val usbIoManager = SerialInputOutputManager(mPort, - object : SerialInputOutputManager.Listener { - override fun onNewData(data: ByteArray?) { - listener?.onUsbRead(data) - } + val usbIoManager = SerialInputOutputManager(mPort, + object : SerialInputOutputManager.Listener { + override fun onNewData(data: ByteArray?) { + listener?.onUsbRead(data) + } - override fun onRunError(e: Exception?) { - Log.e(TAG, "onRunError() called inside eventDrivenWrite()") - listener?.onUsbError(e) - } + override fun onRunError(e: Exception?) { + Log.e(TAG, "onRunError() called inside eventDrivenWrite()") + listener?.onUsbError(e) + } + }) - }) - usbIoManager.start(); + usbIoManager.start() + } catch (ioException: IOException) { + Log.e(TAG, "IOException during USB connection: ${ioException.message}", ioException) + listener?.onUsbError(ioException) + } catch (e: Exception) { + Log.e(TAG, "Error connecting USB: ${e.message}", e) + listener?.onUsbError(e) + } } fun disconnect() { - if (isUsbConnected) { - mPort.close() - isUsbConnected = false; - Log.d(TAG, "My Usb disconnected:: ${mPort.driver}") + try { + if (isUsbConnected) { + mPort.close() + isUsbConnected = false + Log.d(TAG, "USB Port closed successfully:: ${mPort.driver}") + } else { + Log.d(TAG, "USB Port is not connected") + } + } catch (e: IOException) { + Log.e(TAG, "Error closing USB Port: ${e.message}", e) + } catch (e: Exception) { + Log.e(TAG, "An unexpected error occurred: ${e.message}", e) } }