@@ -374,7 +374,7 @@ internal class UsbGadgetManager(val gadgetUserPreferences: GadgetUserPreferences
374374
375375 @Throws(IOException ::class )
376376 private fun enableGadget () {
377- val udc: String? = System .getProperty( " sys.usb.controller " )
377+ val udc = getUDC( )
378378
379379 UDC_PATH .writer(options = arrayOf(StandardOpenOption .SYNC )).use {
380380 // This part seems to happen implicitly
@@ -405,6 +405,46 @@ internal class UsbGadgetManager(val gadgetUserPreferences: GadgetUserPreferences
405405 }
406406 }
407407 }
408+
409+ @Throws(IOException ::class )
410+ fun getUDC (): String {
411+ // NOTE:
412+ // Reading the "sys.usb.controller" property will return null when (I think) the gadget is disabled.
413+ // My guess is it returns the *active* UDC, so I can't read the UDC when it's inactive. So we're doing
414+ // it this way instead.
415+
416+ val udcList: List <Path > = run {
417+ val udcDirectoryPath = Path (" /sys/class/udc" )
418+
419+ udcDirectoryPath.listDirectoryEntries()
420+ }
421+ Timber .d(" UDC value from file listing is: $udcList " )
422+
423+ val udcPath: Path = if (udcList.isEmpty()) {
424+ // TODO: What do we even do at this point
425+ Path (" " )
426+ } else if (udcList.size == 1 ) {
427+ udcList.first()
428+ } else {
429+ // There's more than one, attempt to filter it down I guess
430+ val filteredList = udcList.filter { it.isSymbolicLink() }
431+
432+ if (filteredList.isEmpty()) {
433+ // Just use the unfiltered list I guess
434+ udcList.first()
435+ } else if (filteredList.size == 1 ) {
436+ filteredList.first()
437+ } else {
438+ Timber .w(" filtered list of UDCs has more than one, using first one: $udcList " )
439+
440+ filteredList.first()
441+ }
442+ }
443+
444+ val udc = udcPath.name
445+
446+ return udc
447+ }
408448}
409449
410450@JvmInline
0 commit comments