首页
/ python-libusb1 项目技术文档

python-libusb1 项目技术文档

2024-12-20 21:46:18作者:幸俭卉

1. 安装指南

依赖项

  • CPython 3.6+pypy 2.0+:较旧版本可能也能工作,但不推荐使用,因为没有为这些版本设置自动化回归测试。
  • libusb-1.0:需要安装 libusb-1.0 库。

支持的操作系统

python-libusb1 可以在以下操作系统上运行:

  • GNU/Linux
  • Windows(原生 DLL 或通过 Cygwin)
  • OSX(通过 MacPorts、Fink 或 Homebrew)
  • FreeBSD(包括 Debian GNU/kFreeBSD)
  • OpenBSD

安装步骤

  1. 通过 PyPI 安装

    $ pip install libusb1
    
  2. 从源码安装最新版本

    $ git clone https://github.com/vpelletier/python-libusb1.git
    $ cd python-libusb1
    $ pip install .
    

Windows 安装注意事项

  • 通过 PyPI 安装的 wheel 包会自动安装 libusb DLL 到 usb1 模块中。
  • 安装时不会安装驱动程序,因此需要根据设备选择使用 libusbk 或 WinUSB,并使用 Zadig 或其他工具安装相应的驱动。
  • 从源码安装时不会安装 DLL,因此需要手动安装 libusb 库,并确保 ctypes 可以找到它。

检查发布文件签名

  • 下载发布文件并记录其 URL。
  • 下载其分离签名文件,方法是在发布文件 URL 后添加 .asc
  • 将发布密钥添加到 gnupg 密钥环中(KEYS 文件在主仓库中),并使用 gnupg 验证签名。
  • 安装已下载的发布文件。

2. 项目使用说明

查找设备并获取独占访问权限

import usb1
with usb1.USBContext() as context:
    handle = context.openByVendorIDAndProductID(
        VENDOR_ID,
        PRODUCT_ID,
        skip_on_error=True,
    )
    if handle is None:
        # 设备不存在或用户无权访问设备
    with handle.claimInterface(INTERFACE):
        # 在已声明的接口上执行操作

同步 I/O

while True:
    data = handle.bulkRead(ENDPOINT, BUFFER_SIZE)
    # 处理数据...

异步 I/O(带错误处理)

def processReceivedData(transfer):
    if transfer.getStatus() != usb1.TRANSFER_COMPLETED:
        # 传输未成功完成,没有数据可读
        return
    data = transfer.getBuffer()[:transfer.getActualLength()]
    # 处理数据...
    # 数据处理完成后重新提交传输
    transfer.submit()

# 构建传输对象列表并提交以启动传输
transfer_list = []
for _ in range(TRANSFER_COUNT):
    transfer = handle.getTransfer()
    transfer.setBulk(
        usb1.ENDPOINT_IN | ENDPOINT,
        BUFFER_SIZE,
        callback=processReceivedData,
    )
    transfer.submit()
    transfer_list.append(transfer)
# 只要有一个传输提交,就继续循环
while any(x.isSubmitted() for x in transfer_list):
    try:
        context.handleEvents()
    except usb1.USBErrorInterrupted:
        pass

3. 项目 API 使用文档

USBContext 类

  • USBContext.__init__(self):初始化 USB 上下文。
  • USBContext.getDeviceList(self):获取设备列表,返回 USBDevice 实例列表。

USBDevice 类

  • USBDevice.getBusNumber(self):获取设备的总线号。

USBError 异常

  • usb1.USBError:错误状态被转换为 USBError 异常,状态值作为 value 实例属性。

4. 项目安装方式

通过 PyPI 安装

$ pip install libusb1

从源码安装

$ git clone https://github.com/vpelletier/python-libusb1.git
$ cd python-libusb1
$ pip install .

Windows 安装注意事项

  • 通过 PyPI 安装的 wheel 包会自动安装 libusb DLL 到 usb1 模块中。
  • 从源码安装时不会安装 DLL,因此需要手动安装 libusb 库,并确保 ctypes 可以找到它。

通过以上步骤,您可以顺利安装并使用 python-libusb1 项目。

登录后查看全文
热门项目推荐