python3操作USB设备

本文以读取USB无线测量设备数据举例说明。需要用到pyusb模块和libusb-1.0.dll,详细说明如下。

一、配置libusb-1.0.dll

下载libusb-1.0.22.7z,根据操作系统来选择对应的动态库,如下:

  • 32位操作系统:复制MS32\dll\libusb-1.0.dll到C:\Windows\SysWOW64

  • 64位操作系统:复制 MS64\dll\libusb-1.0.dll到C:\Windows\System32

二、安装USB驱动

  1. 打开zadig-2.5.exe
  2. 选择菜单:Options->List All Devices,列出当前电脑所有USB设备,键盘和鼠标USB设备不用考虑
  3. 在设备列表中选择USB设备,点击“Replace Driver”按钮安装USB驱动

三、查询USB设备的idVendor和idProduct

  1. 打开zadig-2.5.exe
  2. 选择菜单:Options->List All Devices,列出当前电脑所有USB设备,键盘和鼠标USB设备不用考虑
  3. USB ID后面的两个值,分别对应:idVendor和idProduct

四、代码

  • 查询所有USB设备信息
    def get_usb_devlists():
        all_devs = usb.core.find(find_all=True)
        dev_list = []
        for d in all_devs:
            key = '{0}{1}'.format(hex(d.idVendor), hex(d.idProduct))
            try:
                dev_u = usb.core.find(idVendor=d.idVendor, idProduct=d.idProduct)
                dev_u.reset()
                if dev_u:
                    dev_u.set_configuration()  # added this line
                    cfg = dev_u.get_active_configuration()  # exception: access violation writing 0x0000000000000000
                    intf = cfg[(0, 0)]
                    ep = intf[0]

                    dev_list.append(key)
                    
                    if key in CUsb.dev_dict:  # 避免重复加入
                        continue

                    CUsb.dev_dict[key] = {
     'idVendor': d.idVendor, 'idProduct': d.idProduct, 'thread': False}
                    
            except Exception as e:
                err_str = str(e)
                print("error!", err_str)
  • 读取USB设备数据
	    def __init__(self, VID: int=None, PID: int=None, dev=None, ep=None):
        self.VID = VID
        self.PID = PID
        self.dev_u = None
        self.ep = None
        if VID and PID:
           try:
               self.dev_u = usb.core.find(idVendor=VID, idProduct=PID)
               if self.dev_u:
                   # get the configuration
                   self.dev_u.set_configuration()  # added this line
                   cfg = self.dev_u.get_active_configuration()
                   # get interface 0
                   intf = cfg[(0, 0)]
                   # print(self.dev_u)
                   # get endpoints 1
                   self.ep = intf[0]
               else:
                   print("Can't find device!")
           except Exception as e:
               print('__init__: ', e)
	
    def read_data(self):
        if not self.ep:
            return []

        key_dict = {
     30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9',
                    39: '0', 40: '\n', 55: '.'}
        result_list = []
        data = []
        n = 0
        inter = 16
        while (40 not in data) or n < 1:  # 40表示'\n',是数据截止符
            n += 1
            try:
                if self.ep:
                    data += self.ep.read(8, 1000)  # timeout:1000毫秒
            except Exception as e:
                err_str = str(e)
                # print('-----------------------', err_str)

        count = len(data)
        # print(count, len(data), data)
        tmp_data = [data[i:i + inter] for i in range(0, count, inter)]
        # print(self.ep.bEndpointAddress, len(tmp_data), tmp_data)
        result_list.append('')  # 创建初始值
        for idx, tmp in enumerate(tmp_data):
            data_str = self.get_value_form_8_byte(tmp)
            if data_str == '\n':  # 截止符
                result_list[-1] += data_str
                if idx < len(tmp_data)-1:  # 处理下一个,创建初始值
                    result_list.append('')
                continue

            if (data_str == '' or data_str == '0') and result_list[-1] == '':  # 过滤数字前面的0
                continue
            result_list[-1] += data_str
        result_list[-1] = ('0' + result_list[-1]) if (result_list[-1][0] == '.') else result_list[-1]  # 处理小数点前面没有0的情况
        return [i for i in result_list if ('\n' in i) and ('.' in i)]  # 丢掉异常数据

你可能感兴趣的:(python3,python)