add exception handling
This commit is contained in:
@@ -33,32 +33,48 @@ class UsbService : Service() {
|
|||||||
var bus: UsbServiceListener? = null
|
var bus: UsbServiceListener? = null
|
||||||
|
|
||||||
fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) {
|
fun connect(driver: UsbSerialDriver, connection: UsbDeviceConnection) {
|
||||||
mPort = driver.ports[0] // Most devices have just one port (port 0)
|
try {
|
||||||
mPort.open(connection)
|
mPort = driver.ports[0]
|
||||||
mPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
mPort.open(connection)
|
||||||
isUsbConnected = true
|
mPort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||||
Log.d(TAG, "My Usb Connected ${mPort.driver}")
|
isUsbConnected = true
|
||||||
|
Log.d(TAG, "My Usb Connected ${mPort.driver}")
|
||||||
|
|
||||||
val usbIoManager = SerialInputOutputManager(mPort,
|
val usbIoManager = SerialInputOutputManager(mPort,
|
||||||
object : SerialInputOutputManager.Listener {
|
object : SerialInputOutputManager.Listener {
|
||||||
override fun onNewData(data: ByteArray?) {
|
override fun onNewData(data: ByteArray?) {
|
||||||
listener?.onUsbRead(data)
|
listener?.onUsbRead(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onRunError(e: Exception?) {
|
override fun onRunError(e: Exception?) {
|
||||||
Log.e(TAG, "onRunError() called inside eventDrivenWrite()")
|
Log.e(TAG, "onRunError() called inside eventDrivenWrite()")
|
||||||
listener?.onUsbError(e)
|
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() {
|
fun disconnect() {
|
||||||
if (isUsbConnected) {
|
try {
|
||||||
mPort.close()
|
if (isUsbConnected) {
|
||||||
isUsbConnected = false;
|
mPort.close()
|
||||||
Log.d(TAG, "My Usb disconnected:: ${mPort.driver}")
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user