gpt4 book ai didi

python - 在 Python 中与 USB 设备通信

转载 作者:太空狗 更新时间:2023-10-30 02:12:56 26 4
gpt4 key购买 nike

我想与 USB 设备通信并向其发送数据。我能够找到该设备,但在将设备与内核驱动程序连接时,它给出了 USB 错误:资源繁忙。以下是我的代码:

import usb

dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
dev.set_configuration()

cfg = dev.get_active_configuration()

dev.attach_kernel_driver(interface)

interface_number = cfg[(0, 0)].bInterfaceNumber
alternate_settting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber=interface_number,
bAlternateSetting=alternate_setting)

ep = usb.util.find_descriptor(
intf, custom_match=lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)

dev.detach_kernel_driver(interface)

ep.write("\r" + linea1[:19] + "\n\r" + " " * (20 - len(linea2)) + linea2)

最佳答案

假设您使用 Linux 和 libusb-1.0 作为 PyUSB 的后端库。

根据libusb documentation :

// Detach a kernel driver from an interface.
// If successful, you will then be able to claim the interface and perform I/O.
int libusb_detach_kernel_driver (libusb_device_handle *dev,
int interface_number)

// Re-attach an interface's kernel driver, which was previously
// detached using libusb_detach_kernel_driver().
int libusb_attach_kernel_driver(libusb_device_handle *dev,
int interface_number)

所以基本上,您需要调用detach_kernel_driver首先从设备接口(interface)分离已经附加的内核驱动程序(如果有的话),这样您就可以在您的代码中与它通信(它要么是你的代码,要么是一些内核驱动程序与设备的接口(interface)对话)。完成后,您可能需要调用 attach_kernel_driver 再次重新附加内核驱动程序。

我相信如果您可以确保没有为给定设备加载内核驱动程序(或在运行代码之前手动卸载它),则无需调用任何这些 C 函数/Python 方法。

编辑:

我刚刚让这段代码(基于您的示例)正常工作。注意:为简单起见,我将 0 硬编码为 detach_kernel_driverattach_kernel_driver 的接口(interface)编号 - 我想你应该让它更聪明。

import usb

dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)

reattach = False
if dev.is_kernel_driver_active(0):
reattach = True
dev.detach_kernel_driver(0)

dev.set_configuration()
cfg = dev.get_active_configuration()

interface_number = cfg[(0,0)].bInterfaceNumber
alternate_settting = usb.control.get_interface(dev, interface_number)
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number,
bAlternateSetting = alternate_settting)

ep = usb.util.find_descriptor(intf,custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT)
ep.write("test\n\r")

# This is needed to release interface, otherwise attach_kernel_driver fails
# due to "Resource busy"
usb.util.dispose_resources(dev)

# It may raise USBError if there's e.g. no kernel driver loaded at all
if reattach:
dev.attach_kernel_driver(0)

关于python - 在 Python 中与 USB 设备通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12542799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com