pyvisa / pyvisa-py

A pure python PyVISA backend
https://pyvisa-py.readthedocs.io
MIT License
282 stars 120 forks source link

Detatch USBTMC kernel driver when device has more than one interface #184

Open darsor opened 5 years ago

darsor commented 5 years ago

I have a sensor which implements two USB interfaces, one is USB HID, the other is USBTMC.

Currently when connecting to a USB device, pyvisa-py detatches any kernel driver from the first interface (here).

In the case of this sensor, the USBTMC interface is interface number 1, not 0. In order to use the device I have to manually detach the kernel driver using pyusb, before opening it with pyvisa.

usb_dev = usb.core.find(idVendor=xxxx, idProduct=yyyy)
if usb_dev and usb_dev.is_kernel_driver_active(1):
    usb_dev.detach_kernel_driver(1)

For reference, the error message generated was

Traceback (most recent call last):
  File "./test.py", line 14, in <module>
    device = rm.open_resource(device_id)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa/highlevel.py", line 1724, in open_resource
    res.open(access_mode, open_timeout)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa/resources/resource.py", line 209, in open
    self.session, status = self._resource_manager.open_bare_resource(self._resource_name, access_mode, open_timeout)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa/highlevel.py", line 1681, in open_bare_resource
    return self.visalib.open(self.session, resource_name, access_mode, open_timeout)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa-py/highlevel.py", line 194, in open
    sess = cls(session, resource_name, parsed, open_timeout)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa-py/sessions.py", line 213, in __init__
    self.after_parsing()
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa-py/usb.py", line 201, in after_parsing
    self.parsed.serial_number)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa-py/protocols/usbtmc.py", line 256, in __init__
    super(USBTMC, self).__init__(vendor, product, serial_number, **kwargs)
  File "/home/dsorensen/.local/lib/python2.7/site-packages/pyvisa-py/protocols/usbtmc.py", line 186, in __init__
    raise Exception('failed to set configuration\n %s' % e)
Exception: failed to set configuration
 [Errno 16] Resource busy

and dmesg reported

usbfs: interface 1 claimed by usbtmc while 'test.py' sets config #1
MatthieuDartiailh commented 5 years ago

Thanks for the report. If you have an elegant solution to automatically handle this, do not hesitate to share it !

charkster commented 5 years ago

I am seeing this issue too when using my new Raspberry Pi 4... I can't see the "detach kernel driver" command in the pyusb log file. When using my Raspberry Pi 3 and 2 I can see the "detach kernel driver" in the log file. I have no idea why there is a difference.