问题描述
我正在尝试使用pyusb为我的代码创建USB驱动程序对象,并且读取操作的返回始终返回"1",我在网上搜索了一段时间,但找不到任何解决方案,请尝试帮助我了解我在做什么错.
I'm trying to create USB driver object using pyusb for my code, and the return from reading operation always return '1', I search the web for a while, and I couldn't find any solution, please try to help me understand what am I'm doing wrong.
环境特性:在Windows 10上将python 3.7与pycharm一起使用当然,在安装pyusb模块之后,导入了所有必需的软件包(usb.core,usb.util).
Environmental properties:Using python 3.7 with pycharm on windows 10.Imported all necessary packages (usb.core, usb.util) of course after installing the pyusb module.
我要构建的对象:
class UsbDev:
def __init__(self, VID, PID):
self.output_ep = None
self.input_ep = None
self.VID = VID
self.PID = PID
self.dev = usb.core.find(idVendor = self.VID, idProduct = self.PID)
if self.dev is None:
raise AttributeError('USB device is not connected...')
def check_device(self, dev_name=None):
if dev_name is None:
raise ValueError("device name provided is None")
if self.dev.product != dev_name:
raise ValueError('Wrong type of product connected to host')
def config_device(self):
self.dev.set_configuration()
cfg = self.dev.get_active_configuration()
self.output_ep = usb.util.find_descriptor(cfg[(0, 0)], custom_match=lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)
self.input_ep = usb.util.find_descriptor(cfg[(0, 0)], custom_match=lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)
def read_string(self):
if self.input_ep is not None:
ret_array = self.dev.read(self.input_ep.bEndpointAddress,
self.input_ep.wMaxPacketSize)
self.dev.clear_halt(self.input_ep)
return ''.join([chr(x) for x in ret_array]) # always returns 1
测试用例:
driver = ud(0x0403, 0xed72) # HAMEG HO720 Serial Port
driver.check_device('HAMEG HO720')
driver.config_device()
driver.send("*IDN?")
print(driver.read_string())
预期输出:
推荐答案
几天后,我自己解决了这个问题.似乎某些USB设备需要终止符(在我的情况下是换行符'\ n'),因此在发送带有换行符的消息后,该设备便开始回复.
After a few days, I've solved the problem myself.It appears that some USB devices require a termination character (in my case it was newline char '\n') so upon sending a message with newline the device started to reply.
我希望我的案子对你们有帮助.
I hope that my case helps you guys.
这篇关于pyusb读取操作始终返回"1"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!