我有一个 USB 设备,其代码如下
import usb.core
import usb.util
device = usb.core.find(idVendor=0xC251, idProduct=0x2201)
print(device)
produces
DEVICE ID c251:2201 on Bus 002 Address 020 =================
bLength : 0x12 (18 bytes)
bDescriptorType : 0x1 Device
bcdUSB : 0x200 USB 2.0
bDeviceClass : 0x0 Specified at interface
bDeviceSubClass : 0x0
bDeviceProtocol : 0x0
bMaxPacketSize0 : 0x40 (64 bytes)
idVendor : 0xc251
idProduct : 0x2201
bcdDevice : 0x100 Device 1.0
iManufacturer : 0x1 LASER Driver
iProduct : 0x2 LASER Driver IJS
iSerialNumber : 0x3 0001A0000000
bNumConfigurations : 0x1
CONFIGURATION 1: 100 mA ==================================
bLength : 0x9 (9 bytes)
bDescriptorType : 0x2 Configuration
wTotalLength : 0x22 (34 bytes)
bNumInterfaces : 0x1
bConfigurationValue : 0x1
iConfiguration : 0x0
bmAttributes : 0xc0 Self Powered
bMaxPower : 0x32 (100 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 : 0x0
bInterfaceProtocol : 0x0
iInterface : 0x4 HID
ENDPOINT 0x81: Interrupt IN ==========================
bLength : 0x7 (7 bytes)
bDescriptorType : 0x5 Endpoint
bEndpointAddress : 0x81 IN
bmAttributes : 0x3 Interrupt
wMaxPacketSize : 0x40 (64 bytes)
bInterval : 0x1
在Python 3下的Ubuntu 20.04中。可以看出,没有OUT
端点。我不是 USB 专家,但据我所知,我们需要一个输出端点来将数据发送到设备,因此该设备看起来像一个只读设备。
但是,我知道有某种方法可以向设备发送/写入数据,因为它是一个激光控制器,并且在 Windows 中我可以打开/关闭激光、更改强度等。我有部分 C++ 源代码该控制器用于 Windows,它使用hidapi https://github.com/libusb/hidapi。根据的文档hid_write https://codedocs.xyz/GerryFerdinandus/hidapi/group__API.html#gad14ea48e440cf5066df87cc6488493af当没有其他输出端点时,它会写入“控制端点”,这里似乎就是这种情况。所以现在我想使用Python复制这个PyUSB https://github.com/pyusb/pyusb.
到目前为止我有这个
import usb.core
import usb.util
import array
device = usb.core.find(idVendor=0xC251, idProduct=0x2201)
if device is None:
raise RuntimeError('Device not found')
interface = device[0].interfaces()[0]
endpoint = device[0].interfaces()[0].endpoints()[0] # This is the in endpoint, I can read the status of the laser from here and it works fine.
if device.is_kernel_driver_active(interface.bInterfaceNumber):
device.detach_kernel_driver(interface.bInterfaceNumber)
cmd = chr(90) # This is the command to turn off the laser.
packet = chr(0) + cmd + chr(0)*(64-len(cmd)-1) # The first byte has to be always 0, see https://codedocs.xyz/GerryFerdinandus/hidapi/group__API.html#gad14ea48e440cf5066df87cc6488493af
packet = array.array('B', [ord(c) for c in packet])
bytes_sent = endpoint.write(packet)
print(bytes_sent) # This prints out 64 so it is fine.
这似乎正在书写,但激光什么也没做(它应该关闭)。我怀疑它以某种方式写入“IN端点”而不是“控制端点”。我想发送这个packet
到控制端点。如何才能做到这一点?
PD:我也尝试过
device.write(0x0, packet)
但这会产生ValueError: Invalid endpoint address 0x0
.