Untitled

 avatar
unknown
plain_text
a year ago
2.2 kB
6
Indexable
 private fun connectToUsb(result: Result) {
    val deviceList = usbManager.deviceList
    if (deviceList.isEmpty()) {
      result.error("NO_DEVICE", "No USB device found", null)
      return
    }

    // For simplicity, we're just connecting to the first device found
    usbDevice = deviceList.values.first()

    val permissionIntent = PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE)
    val filter = IntentFilter(ACTION_USB_PERMISSION)
    context.registerReceiver(usbReceiver, filter)

    usbManager.requestPermission(usbDevice, permissionIntent)

    // The result will be handled in the BroadcastReceiver
  }

  private val usbReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
      if (ACTION_USB_PERMISSION == intent.action) {
        synchronized(this) {
          val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)

          if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
            device?.apply {
              // Open a connection to the device
              usbConnection = usbManager.openDevice(this)
              usbInterface = this.getInterface(0)  // Assume the first interface is the one we want

              usbConnection?.claimInterface(usbInterface, true)

              channel.invokeMethod("onUsbConnected", null)
            }
          } else {
            channel.invokeMethod("onUsbPermissionDenied", null)
          }
        }
      }
    }
  }

  private fun disconnectFromUsb(result: Result) {
    usbConnection?.releaseInterface(usbInterface)
    usbConnection?.close()
    usbConnection = null
    usbInterface = null
    usbDevice = null
    result.success(null)
  }

  private fun getUsbDevices(result: Result) {
    val deviceList = usbManager.deviceList
    val devices = deviceList.values.map { device ->
      mapOf(
        "deviceName" to device.deviceName,
        "productId" to device.productId,
        "vendorId" to device.vendorId
      )
    }
    result.success(devices)
  }
Editor is loading...
Leave a Comment