Python on M1 MBP trying to connect to USB devices - NoBackendError: No backend available
Asked Answered
M

1

8

I am trying to connect with Python to my USB devices.

The final result should be a connection to my Blood Pressure Monitor but I am failing already to connect to ANY device.

My simple code - which I found here - is bellow. The Product- and Vendor ID I got from Apple Menu > About this Mac > System Information

import usb.core
import usb.util

# find our device
dev = usb.core.find(idVendor=0x0781, idProduct=0x55a4)

# was it found?
if dev is None:
    raise ValueError('Device not found')

# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()

# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]

ep = usb.util.find_descriptor(
    intf,
    # match the first OUT endpoint
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_OUT)

assert ep is not None

# write the data
ep.write('test')

But I get always NoBackendError: No backend available from dev = usb.core.find(idVendor=0x0781, idProduct=0x55a4)

For the connection I installed pyusb in my Python env and with Homebrew libusb on my mac.

I have no clue how to get a connection or even a simple list via iteration with all my connected Product- and Vendor IDs.

Mayfield answered 16/1, 2022 at 10:46 Comment(0)
S
20

This error is to be expected if pyusb cannot find the dynamic libraries of libusb.

Installing libusb with Homebrew is not sufficient. Homebrew puts the relevant files in /opt/homebrew/Cellar/libusb/1.0.24/lib and creates symbolic links in /opt/homebrew/lib. But pyusb is not aware of these paths.

You have two main options:

  • Add /opt/homebrew/lib to the environment variable DYLD_LIBRARY_PATH. For a permanent setup, add it to ~/.zshenv:
export DYLD_LIBRARY_PATH="/opt/homebrew/lib:$DYLD_LIBRARY_PATH"
  • Create a symbolic link in your home directory. This takes advantage of the fact that ~/lib is a default fallback path for libraries:
ln -s /opt/homebrew/lib ~/lib
Sociopath answered 16/1, 2022 at 14:18 Comment(2)
I didn't have the DYLD_LIBRARY_PATH environment variable, but the second option worked fine. Thanks!Demagogic
Leaving a comment for the future me. DYLD_LIBRARY_PATH needs to be set before installing pyusb and if it wasn't, then it can be "hacked" to work with the symlink trick. So I'm guessing that the "right" way would be to set the DYLD_LIBRARY_PATH and then re-install the package. Oh, and PYUSB_DEBUG=debug python my_code_with_pyusb.py to see the logsAgro

© 2022 - 2024 — McMap. All rights reserved.