Skip to content

Instantly share code, notes, and snippets.

@whytarun
Last active July 2, 2024 17:40
Show Gist options
  • Save whytarun/0959738d62287e54afa99dce446eb98a to your computer and use it in GitHub Desktop.
Save whytarun/0959738d62287e54afa99dce446eb98a to your computer and use it in GitHub Desktop.
if (!usbManager!!.hasPermission(usbDevice)) {
usbManager!!.requestPermission(usbDevice, mPendingIntent)
}
private val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (ACTION_USB_PERMISSION.equals(intent.action, ignoreCase = true)) {
runOnUiThread {
val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) && device != null) {
usbDevice = device
if (permissionUpdater != null)
permissionUpdater?.onSuccess()
} else {
if (permissionUpdater != null)
permissionUpdater?.onError()
}
}
}
}
}
fun getUsbComm(): UsbCommHandler? {
if (usbCommHandler == null) {
val driver = usbDevice?.let { UsbDriver(it) }
if (driver != null) {
val usbConnection = usbManager!!.openDevice(driver.getDevice())
usbCommHandler = UsbCommHandler()
usbCommHandler?.initHandler(driver, usbConnection, userPreferences, appDatabase)
mUsbCommunication = UsbCommunication.getInstance()
mUsbCommunication.setUsbDriver(object : IUsbDriver {
override fun getSerialPort(): IUsbSerialPort {
return object : IUsbSerialPort {
override fun write(src: ByteArray, timeout: Int) {
if (ThirdMainViewModel.stopFlag) return
driver.getPort()?.write(src, timeout)
}
override fun initialiseDriverConnection() {
if (ThirdMainViewModel.stopFlag) return
driver.getPort()?.let {
if (!it.isOpen()) {
it.open(usbConnection)
it.setParameters(
UsbSerialPort.BAUD_RATE,
UsbSerialPort.DATA_BITS_8,
UsbSerialPort.STOP_BITS_1,
UsbSerialPort.PARITY_NONE
)
it.setDTR(true)
}
}
}
override fun read(dest: ByteArray, timeout: Int): Int? {
return driver.getPort()?.read(dest, timeout)
}
}
}
})
}
}
return usbCommHandler
}
private fun setupReceiver(permissionUpdater: PermissionUpdater?) {
this.permissionUpdater = permissionUpdater
usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
Executors.newSingleThreadExecutor().execute {
registerReceiver(usbReceiver, IntentFilter(ACTION_USB_PERMISSION))
isUSBMgrRegisterd = true
}
val deviceList = usbManager!!.deviceList
if (deviceList.size != 0) {
for (device in deviceList.keys) {
val usbDevice = deviceList[device]
if (usbDevice?.vendorId == 10985 && usbDevice.productId == 256) {
foundDevice = true
if (!usbManager!!.hasPermission(usbDevice)) {
usbManager!!.requestPermission(usbDevice, mPendingIntent)
} else {
this.usbDevice = usbDevice
if(permissionUpdater!=null)
permissionUpdater.onSuccess()
}
}
}
if (!foundDevice && deviceList.size != 0) {
// Handle device not found scenario
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment