python hid完整代码
时间: 2024-08-12 17:01:39 浏览: 92
python通过USB-HID通信的控制台程序
在Python中,使用hid库操作HID(Human Interface Device)设备的基本流程如下,这里提供了一个简化的示例,展示如何连接、读取和关闭设备:
```python
import hid
# 找到第一个可用的HID设备
device = hid.enumerate()
vendor_id = device['vendor_id']
product_id = device['product_id']
serial_number = device.get('serial_number', 'Unknown')
print(f"Found HID device: Vendor={vendor_id}, Product={product_id} (Serial={serial_number})")
# 打开设备
try:
device_handle = hid.open(vendor_id, product_id)
except Exception as e:
print(f"Error opening device: {str(e)}")
exit(1)
# 获取设备描述符
try:
descriptor = device_handle.read(hid.HID_DEVICE_SIZE)
except hid.Error as e:
print(f"Error reading descriptor: {str(e)}")
device_handle.close()
exit(1)
# 遍历输入报告并打印
for report in descriptor[4:]:
input_report = {
"id": report,
"data": list(report[1:])
}
print(f"Input Report ID: {input_report['id']} Data: {input_report['data']}")
# 关闭设备
device_handle.close()
阅读全文