您所在的位置:小祥子 » 编程 » Python » 正文

USB 调试工具(pyusb/pywinusb)

时间:2015-04-28 编辑:jakey.chen 来源:本站整理

项目地址:USB-HID-TEST

整体预览图(win8下的效果):

======================

项目结构:

COM

--hidHelper.py

--usbHelper.py

UI

--Adaptive.py

--HID_TESTUI.py

--PyTkinter.py

main.py

======================

UI文件夹:

使用PyTkinter来初始化一些颜色配置(个人喜好)

实现代码:

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 
 '''
 Tkinter控件初始化配置(默认为深色)
 '''
 __author__ = "jakey.chen"
 __version__ = "v1.0"
 
 
 import Tkinter as tk
 
 g_default_theme = "dark"
 # g_default_theme = "default"
 
 class PyButton(tk.Button):
     '''
     Button
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Button.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "activebackground": "#00B2EE",
                                 "activeforeground": "#E0EEEE",
                                 "bg": "#008B8B",
                                 "fg": "#FFFFFF"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyLabel(tk.Label):
     '''
     Label
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Label.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#E0EEEE"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyLabelFrame(tk.LabelFrame):
     '''
     Frame
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.LabelFrame.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#1E90FF"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyListbox(tk.Listbox):
     '''
     Listbox
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Listbox.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#1E90FF",
                                 "selectbackground": "#00B2EE"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyText(tk.Text):
     '''
     Text
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Text.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#1E90FF"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyCheckbutton(tk.Checkbutton):
     '''
     Checkbutton
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Checkbutton.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#FFFFFF",
                                 "activebackground": "#292929",
                                 "activeforeground": "#FFFFFF",
                                 "selectcolor": "#292929"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 class PyRadiobutton(tk.Radiobutton):
     '''
     Radiobutton
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Radiobutton.__init__(self, master, self.temp) 
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#FFFFFF",
                                 "activebackground": "#292929",
                                 "selectcolor": "#292929"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 
 class PyEntry(tk.Entry):
     '''
     Entry
     '''
     def __init__(self, master, theme=g_default_theme, **kv):
         self.theme = theme
         self.kv = kv
         self.temp = dict()
         self.choose_theme()
         tk.Entry.__init__(self, master, self.temp)
 
     def choose_theme(self):
         if self.theme == "dark":
             dark_theme_dict = {
                                 "bg": "#292929",
                                 "fg": "#E0EEEE",
                                 "insertbackground": "#E0EEEE"
                               }
             for key,value in dark_theme_dict.items():
                 self.temp[key] = value
 
             for key,value in self.kv.items():
                 self.temp[key] = value
 
 if __name__ == '__main__':
     root = tk.Tk()
     root.configure(bg="#292929")
     PyButton(root, text="1234", font=("Monaco", 12)).pack()
     PyLabel(root, text="123", font=("Monaco", 15)).pack()
     PyCheckbutton(root, text="123", font=("Monaco", 15)).pack()
     PyEntry(root, font=("Monaco", 15)).pack()
     PyText(root, font=("Monaco", 15), height=2, width=20).pack()
     listbox_0 = PyListbox(root, height=2, font=("Monaco", 15))
     listbox_0.pack()
     for i in range(2):
         listbox_0.insert("end", i)
     radio_intvar = tk.IntVar()
     PyRadiobutton(root, text="001", variable=radio_intvar, value=0, font=("Monaco", 15)).pack()
     PyRadiobutton(root, text="002", variable=radio_intvar, value=1, font=("Monaco", 15)).pack()
     radio_intvar.set(1)
 
     root.mainloop()

主界面构建不表,使用LabelFrame通过grid布局组成

具体自行查看项目代码

======================

COM文件夹

Windows下:

使用pywinusb

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 
 '''
 win下使用的HID设备通讯帮助类
 '''
 __author__ = "jakey.chen"
 __version__ = "v1.0"
 
 
 import pywinusb.hid as hid
 
 
 class hidHelper(object):
     def __init__(self, vid=0x1391, pid=0x2111):
         self.alive = False
         self.device = None
         self.report = None
         self.vid = vid
         self.pid = pid
 
     def start(self):
         '''
         开始,打开HID设备
         '''
         _filter = hid.HidDeviceFilter(vendor_id = self.vid, product_id = self.pid)
         hid_device = _filter.get_devices()
         if len(hid_device) > 0:
             self.device = hid_device[0]
             self.device.open()
             self.report = self.device.find_output_reports()
             self.alive = True
 
     def stop(self):
         '''
         停止,关闭HID设备
         '''
         self.alive = False
         if self.device:
             self.device.close()
 
     def setcallback(self):
         '''
         设置接收数据回调函数
         '''
         if self.device:
             self.device.set_raw_data_handler(self.read)
 
     def read(self, data):
         '''
         接收数据回调函数
         '''
         print([hex(item).upper() for item in data[1:]])
 
     def write(self, send_list):
         '''
         向HID设备发送数据
         '''
         if self.device:
             if self.report:
                 self.report[0].set_raw_data(send_list)
                 bytes_num = self.report[0].send()
                 return bytes_num
 
 
 if __name__ == '__main__':
     myhid = hidHelper()
     myhid.start()
     if myhid.alive:
         myhid.setcallback()
         send_list = [0x00 for i in range(65)]
         myhid.write(send_list)
         import time
         time.sleep(0.5)
         myhid.stop()

Linux(我使用的是Ubuntu14.04)下:

 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 
 '''
 linux下使用的usb设备通讯帮助类
 '''
 __author__ = "jakey.chen"
 __version__ = "v1.0"
 
 
 import threading
 import usb.util
 import usb.core
 
 
 class usbHelper(object):
     def __init__(self, vid=0x1391, pid=0x2111):
         self.alive = False
         self.handle = None
         self.size = 64
         self.vid = vid
         self.pid = pid
 
     def start(self):
         '''
         开始,打开usb设备
         '''
         self.dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
         if self.dev != None:
             self.ep_in = self.dev[0][(0,0)][0].bEndpointAddress
             self.ep_out = self.dev[0][(0,0)][1].bEndpointAddress
             self.size = self.dev[0][(0,0)][1].wMaxPacketSize
         self.open()
         self.alive = True
 
     def stop(self):
         '''
         停止,关闭usb设备,释放接口
         '''
         self.alive = False
         if self.handle:
             self.handle.releaseInterface()
 
     def open(self):
         '''
         打开usb设备
         '''
         busses = usb.busses()
         for bus in busses:
             devices = bus.devices
             for device in devices:
                 if device.idVendor == self.vid and device.idProduct == self.pid:
                     self.handle = device.open()
                     # Attempt to remove other drivers using this device.
                     if self.dev.is_kernel_driver_active(0):
                         try:
                             self.handle.detachKernelDriver(0)
                         except Exception as e:
                             self.alive = False
                     try:
                         self.handle.claimInterface(0)
                     except Exception as e:
                         self.alive = False
 
     def read(self, size=64, timeout=0):
         '''
         读取usb设备发过来的数据
         '''
         if size >= self.size:
             self.size = size
 
         if self.handle:
             data = self.handle.interruptRead(self.ep_in, self.size, timeout)
 
         try:
             data_list = data.tolist()
             return data_list
         except:
             return list()
 
     def write(self, send_list, timeout=1000):
         '''
         发送数据给usb设备
         '''
         if self.handle:
             bytes_num = self.handle.interruptWrite(self.ep_out, send_list, timeout)
             return bytes_num
 
 if __name__ == '__main__':
     import time
     dev = usbHelper()
 
     dev.start()
 
     send_list = [0xAA for i in range(64)]
     dev.write(send_list)
     # time.sleep(0.25)
     while True: 
         try:
             mylist = dev.read()
             print mylist
             if mylist[1] == 0x02: 
                 break
         except:
             dev.stop()
             break
     dev.stop()

======================

主函数:界面逻辑。不表,自行查看。

关键词:工具 win