Проблема PyUSB с Windows

#python #libusb #pyusb

#python #libusb #pyusb

Вопрос:

Pyusb некорректно работает с моим ПК. На этом форуме нет темы о моей проблеме. Подробности ниже. Я пытаюсь запустить простой скрипт, который должен отображать информацию о USB-устройствах:

 import usb.core
import usb.util
for device in usb.core.find(find_all=True):
    print(device)
  

И после этого я получаю 2 ошибки: usb.core.Ошибка USBError: [Ошибка № 2] Объект не найден и не реализован Ошибка: операция не поддерживается или не реализована на этой платформе

журнал

  DEVICE ID 8087:8008 on Bus 001 Address 003 =================
 bLength                :   0x12 (18 bytes)
 bDescriptorType        :    0x1 Device
 bcdUSB                 :  0x200 USB 2.0
 bDeviceClass           :    0x9 Hub
 bDeviceSubClass        :    0x0
 bDeviceProtocol        :    0x1
 bMaxPacketSize0        :   0x40 (64 bytes)
 idVendor               : 0x8087
 idProduct              : 0x8008
 bcdDevice              :    0x5 Device 0.05
 iManufacturer          :    0x0
 iProduct               :    0x0
 iSerialNumber          :    0x0
 bNumConfigurations     :    0x1
  CONFIGURATION 1: 0 mA ====================================
   bLength              :    0x9 (9 bytes)
   bDescriptorType      :    0x2 Configuration
   wTotalLength         :   0x19 (25 bytes)
   bNumInterfaces       :    0x1
   bConfigurationValue  :    0x1
   iConfiguration       :    0x0
   bmAttributes         :   0xe0 Self Powered, Remote Wakeup
   bMaxPower            :    0x0 (0 mA)
    INTERFACE 0: Hub =======================================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x0
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x9 Hub
     bInterfaceSubClass :    0x0
     bInterfaceProtocol :    0x0
     iInterface         :    0x0
      ENDPOINT 0x81: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x81 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x1 (1 bytes)
       bInterval        :    0xc
DEVICE ID 1c4f:0026 on Bus 003 Address 001 =================
 bLength                :   0x12 (18 bytes)
 bDescriptorType        :    0x1 Device
 bcdUSB                 :  0x110 USB 1.1
 bDeviceClass           :    0x0 Specified at interface
 bDeviceSubClass        :    0x0
 bDeviceProtocol        :    0x0
 bMaxPacketSize0        :    0x8 (8 bytes)
 idVendor               : 0x1c4f
 idProduct              : 0x0026
 bcdDevice              :  0x110 Device 1.1
 iManufacturer          :    0x1 Error Accessing String
 iProduct               :    0x2 Error Accessing String
 iSerialNumber          :    0x0
 bNumConfigurations     :    0x1
  CONFIGURATION 1: 98 mA ===================================
   bLength              :    0x9 (9 bytes)
   bDescriptorType      :    0x2 Configuration
   wTotalLength         :   0x3b (59 bytes)
   bNumInterfaces       :    0x2
   bConfigurationValue  :    0x1
   iConfiguration       :    0x0
   bmAttributes         :   0xa0 Bus Powered, Remote Wakeup
   bMaxPower            :   0x31 (98 mA)
    INTERFACE 0: Human Interface Device ====================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x0
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x3 Human Interface Device
     bInterfaceSubClass :    0x1
     bInterfaceProtocol :    0x1
     iInterface         :    0x0
      ENDPOINT 0x81: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x81 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x8 (8 bytes)
       bInterval        :    0xa
    INTERFACE 1: Human Interface Device ====================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x1
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x3 Human Interface Device
     bInterfaceSubClass :    0x0
     bInterfaceProtocol :    0x0
     iInterface         :    0x0
      ENDPOINT 0x82: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x82 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x3 (3 bytes)
       bInterval        :    0xa
Traceback (most recent call last):
  File "f:newpyvenvlibsite-packagesusbcore.py", line 746, in __str__
    for configuration in self:
  File "f:newpyvenvlibsite-packagesusbcore.py", line 1128, in __iter__
    yield Configuration(self, i)
  File "f:newpyvenvlibsite-packagesusbcore.py", line 603, in __init__
    desc = backend.get_configuration_descriptor(
  File "f:newpyvenvlibsite-packagesusbbackendlibusb1.py", line 773, in get_configuration_descriptor
    _check(self.lib.libusb_get_config_descriptor(
  File "f:newpyvenvlibsite-packagesusbbackendlibusb1.py", line 604, in _check
    raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 2] Entity not found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "usbtesta.py", line 31, in <module>
    print(device)
  File "f:newpyvenvlibsite-packagesusbcore.py", line 750, in __str__
    configuration = self.get_active_configuration()
  File "f:newpyvenvlibsite-packagesusbcore.py", line 909, in get_active_configuration
    return self._ctx.get_active_configuration(self)
  File "f:newpyvenvlibsite-packagesusbcore.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "f:newpyvenvlibsite-packagesusbcore.py", line 247, in get_active_configuration
    self.managed_open()
  File "f:newpyvenvlibsite-packagesusbcore.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "f:newpyvenvlibsite-packagesusbcore.py", line 131, in managed_open
    self.handle = self.backend.open_device(self.dev)
  File "f:newpyvenvlibsite-packagesusbbackendlibusb1.py", line 804, in open_device
    return _DeviceHandle(dev)
  File "f:newpyvenvlibsite-packagesusbbackendlibusb1.py", line 652, in __init__
    _check(_lib.libusb_open(self.devid, byref(self.handle)))
  File "f:newpyvenvlibsite-packagesusbbackendlibusb1.py", line 600, in _check
    raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform
  

Я видел аналогичную проблему в Интернете, но возникла проблема с работой с конкретным USB-устройством, и она была решена путем установки Zadig и выбора правильного драйвера. Этот способ мне не помогает, потому что я работаю не с каким-либо USB-устройством, а только с кодом, пытающимся просмотреть список устройств. Проблема не в PATH.
Я попытался запустить свой скрипт со следующей конфигурацией: win10, python 3.8.5, а также 3.7.9, pyusb 1.1.0, libusb 1.0.23b1 / libusb-win32.
Если я запущу скрипт с помощью libusb-win32 (libusb0.dll ) ничего не происходит, python просто возвращает пустую строку и ожидает новой команды. Если я запускаю скрипт с libusb, python показывает эти ошибки выше в этом сообщении. Первая ошибка исчезает, когда я добавляю в строку скрипта set_configuration()

 for device in usb.core.find(find_all=True):
    print(device)
    device.set_configuration()
  

Но как исправить вторую ошибку?
В той же конфигурации в Mac os (pyusb, libusb 1.0, python 3.7.9) этот скрипт успешно запущен

screen_mac

Как ни странно, но этот скрипт работает успешно:

 for device in usb.core.find(find_all=True):
    print(device.bDeviceClass) # running only if i indicate parameter of variable "device" like here
  

Также странно, что pyusb находит некоторые USB-устройства (как вы можете видеть в журнале), но в конце появляются ошибки. На другом КОМПЬЮТЕРЕ мой скрипт вообще не запускается, ошибки появляются сразу после запуска.
Итак, как я могу увидеть список подключенных устройств? Я рад получить любую помощь

Ответ №1:

введите результат описания изображения здесь

     import sys
    import ctypes as ct
    import libusb as usb
    
    
    def print_devs(devs):
    
        path = (ct.c_uint8 * 8)()
    
        i = 0
        while devs[i]:
            dev = devs[i]
    
            desc = usb.device_descriptor()
            r = usb.get_device_descriptor(dev, ct.byref(desc))
            if r < 0:
                print("failed to get device descriptor", file=sys.stderr)
                return
    
            print("{:04x}:{:04x} (bus {:d}, device {:d})".format(
                  desc.idVendor, desc.idProduct,
                  usb.get_bus_number(dev), usb.get_device_address(dev)), end="")
    
            r = usb.get_port_numbers(dev, path, ct.sizeof(path))
            if r > 0:
                print(" path: {:d}".format(path[0]), end="")
                for j in range(1, r):
                    print(".{:d}".format(path[j]), end="")
    
            print()
            i  = 1
    
    
    def main():
    
        r = usb.init(None)
        if r < 0:
            return r
    
        try:
            devs = ct.POINTER(ct.POINTER(usb.device))()
            cnt = usb.get_device_list(None, ct.byref(devs))
            if cnt < 0:
                return cnt
    
            print_devs(devs)
    
            usb.free_device_list(devs, 1)
        finally:
            usb.exit(None)
    
        return 0
    
    
    sys.exit(main() or 0)
  

Комментарии:

1. Спасибо, ваш скрипт запускается. Я новичок в работе с USB-устройствами, поэтому я также хочу спросить, можете ли вы дать мне какие-либо советы о том, что я должен знать для работы с USB? Например, я знаю, что такое идентификатор поставщика / продукта, но я не знаю других параметров устройства, поэтому я не могу получить его с помощью кода. Кроме того, ваш код содержит библиотеку ‘ctypes’, которая пока недоступна для меня. Где я могу увидеть все параметры устройства, такие как производитель, название?