connection resets when using set_configuration in PyUSB

894 views Asked by At

I've recently updated my android phone to Marshmallow. Unfortunately for me, that broke my python code.

using PyUSB, I can get the device to enter accessory mode. Unfortunately, I can no longer read/write to the device, as now using set_configuration() resets the connection, causing the device to exit accessory mode and re-enter MTP mode.

dev = list(usb.core.find(find_all=True))[0]
dev.ctrl_transfer(0xc0,51,data_or_wLength=2)
dev.ctrl_transfer(0x40,52,wIndex=0,data_or_wLength='SAMSUNG')
dev.ctrl_transfer(0x40,52,wIndex=1,data_or_wLength='SAMSUNG_Android')
dev.ctrl_transfer(0x40,52,wIndex=2,data_or_wLength='16DIGITSERIALNUM')
dev.ctrl_transfer(0x40,52,wIndex=3,data_or_wLength='AOA')
dev.ctrl_transfer(0x40,52,wIndex=4,data_or_wLength='Whatever')
dev.ctrl_transfer(0x40,52,wIndex=5,data_or_wLength='4')
dev.ctrl_transfer(0x40,53)
time.sleep(5)
dev = list(usb.core.find(find_all=True))[0]
dev.set_configuration() ## Aaaaaand we're back to MTP...

I can't find any way around this; no references to this problem. Only solution I can some up with is to learn C and use libusb directly, assuming the PyUSB module is to blame...

1

There are 1 answers

2
user1999728 On BEST ANSWER

Well, this isn't a good solution, but just in case anyone else just happens to come across this problem and find this:

The problem is with the specific backend (libusb0), which sends a message to reset configuration or something like that if an interface is already claimed. In some devices (mine, for example), this causes a programmatic reset of the connection.

My workaround involves using thelibusb1 backend when re-acquiring the device in accessory mode, since it doesn't cause a reset. But since libusb1 won't let me do control transfers, I need to switch between backends.

from usb.backend import libusb0, libusb1, and then be0,be1 = libusb0.get_backend(),libusb1.get_backend().

Then just specify the backend as a parameter to usb.core.find