串口助手是怎么做出来的 :第二节,串口助手功能的实现及验证

文/樊晓鑫

python3.7和wxPython版

具体的环境如下:

#########################################################################################################
# pyserial   3.4
# wxPython   4.0.7.post2
# Python 3.7.6rc1 (tags/v3.7.6rc1:bd18254b91, Dec 11 2019, 19:31:14) [MSC v.1916 32 bit (Intel)] on win32
#########################################################################################################

上一节内容主要介绍了串口助手界面的实现及串口通信原理的介绍。

这一节,我们就来浏览一下串口助手功能实现的源代码。

1, 界面的实现代码如下:(serialMainUI.py)

# -*- coding: utf-8 -*-
#########################################################################################################
# pyserial   3.4
# Python 3.7.6rc1 (tags/v3.7.6rc1:bd18254b91, Dec 11 2019, 19:31:14) [MSC v.1916 32 bit (Intel)] on win32
#########################################################################################################

import wx


class serialFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"串口助手", pos=wx.DefaultPosition,
                          size=wx.Size(559, 568), style=wx.DEFAULT_FRAME_STYLE)

        self.panel = wx.Panel(self, -1)

        # 在屏幕中央显示界面
        self.CenterOnScreen()

        ################################################################################################################
        ################################################################################################################
        sergrid = wx.GridBagSizer(0, 0)
        sergrid.SetFlexibleDirection(wx.BOTH)
        sergrid.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        self.m_staticText1 = wx.StaticText(self.panel, wx.ID_ANY, u"串口选择", wx.Point(1, 1), wx.DefaultSize, 0)
        self.m_staticText1.Wrap(-1)
        sergrid.Add(self.m_staticText1, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_rcvtext = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(300, 200),
                                     wx.TE_AUTO_URL | wx.TE_LEFT | wx.TE_MULTILINE)
        sergrid.Add(self.m_rcvtext, wx.GBPosition(0,2), wx.GBSpan(8,2), wx.ALL, 6)

        self.m_send2but = wx.Button(self.panel, wx.ID_ANY, u"发送2", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add( self.m_send2but, wx.GBPosition(9, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr2but = wx.Button(self.panel, wx.ID_ANY, u"清空2", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_clr2but, wx.GBPosition(9, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_send3but = wx.Button(self.panel, wx.ID_ANY, u"发送3", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_send3but, wx.GBPosition(10, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr3but = wx.Button(self.panel, wx.ID_ANY, u"清空3", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add( self.m_clr3but, wx.GBPosition( 10, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )

        self.m_send3but = wx.Button(self.panel, wx.ID_ANY, u"发送4", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_send3but, wx.GBPosition(11, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr4but = wx.Button(self.panel, wx.ID_ANY, u"清空4", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_clr4but, wx.GBPosition(11, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_send5but = wx.Button(self.panel, wx.ID_ANY, u"发送5", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_send5but, wx.GBPosition(12, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr5but = wx.Button(self.panel, wx.ID_ANY, u"清空5", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_clr5but, wx.GBPosition(12, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_send6but = wx.Button(self.panel, wx.ID_ANY, u"发送6", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_send6but, wx.GBPosition(13, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr6but = wx.Button(self.panel, wx.ID_ANY, u"清空6", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_clr6but, wx.GBPosition(13, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        m_comsetChoices = [u"COM1", u"COM2", u"COM3", u"COM4", u"COM5", u"COM6", u"COM7", u"COM8", u"COM9", u"COM10"]
        self.m_comset = wx.ComboBox(self.panel, wx.ID_ANY, u"COM1", wx.DefaultPosition, wx.DefaultSize, m_comsetChoices,
                                    0)
        self.m_comset.SetSelection(0)
        sergrid.Add(self.m_comset, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_openser = wx.Button(self.panel, wx.ID_ANY, u"打开串口", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add( self.m_openser, wx.GBPosition(5, 0), wx.GBSpan(1, 1), wx.ALL, 8)

        self.m_clrRcvText = wx.Button(self.panel, wx.ID_ANY, u"清空接收", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_clrRcvText, wx.GBPosition(6, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_rcvBox = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_rcvBox, wx.GBPosition(6, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_send1but = wx.Button(self.panel, wx.ID_ANY, u"发送1", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_send1but, wx.GBPosition(8, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_clr1but = wx.Button(self.panel, wx.ID_ANY, u"清空1", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add( self.m_clr1but, wx.GBPosition( 8, 1 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )

        self.m_textCtrl5 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1),
                                    wx.HSCROLL | wx.TE_AUTO_URL)
        sergrid.Add(self.m_textCtrl5, wx.GBPosition(8, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox2 = wx.CheckBox( self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox2.SetValue(True)
        sergrid.Add( self.m_checkBox2, wx.GBPosition(8, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox3 = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox3.SetValue(True)
        sergrid.Add(self.m_checkBox3, wx.GBPosition(9, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox4 = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox4.SetValue(True)
        sergrid.Add(self.m_checkBox4, wx.GBPosition(10, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox5 = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox5.SetValue(True)
        sergrid.Add(self.m_checkBox5, wx.GBPosition(11, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox6 = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox6.SetValue(True)
        sergrid.Add(self.m_checkBox6, wx.GBPosition(12, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_checkBox7 = wx.CheckBox(self.panel, wx.ID_ANY, u"16进制", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox7.SetValue(True)
        sergrid.Add(self.m_checkBox7, wx.GBPosition(13, 3), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_textCtrl6 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        sergrid.Add(self.m_textCtrl6, wx.GBPosition(9, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_textCtrl7 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        sergrid.Add(self.m_textCtrl7, wx.GBPosition(10, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_textCtrl8 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        sergrid.Add(self.m_textCtrl8, wx.GBPosition(11, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_textCtrl9 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        sergrid.Add(self.m_textCtrl9, wx.GBPosition(12, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_textCtrl10 = wx.TextCtrl(self.panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), 0)
        sergrid.Add(self.m_textCtrl10, wx.GBPosition(13, 2), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_closeser = wx.Button(self.panel, wx.ID_ANY, u"关闭串口", wx.DefaultPosition, wx.DefaultSize, 0)
        sergrid.Add(self.m_closeser, wx.GBPosition(5, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_staticText6 = wx.StaticText(self.panel, wx.ID_ANY, u"校验位:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_staticText6.Wrap(-1)
        sergrid.Add(self.m_staticText6, wx.GBPosition(3, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_staticText7 = wx.StaticText(self.panel, wx.ID_ANY, u"停止位:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_staticText7.Wrap(-1)
        sergrid.Add(self.m_staticText7, wx.GBPosition(4, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        m_comboBox4Choices = [u"None", u"Odd", u"Even", u"Mark", u"Space"]
        self.m_comboBox4 = wx.ComboBox(self.panel, wx.ID_ANY, u"None", wx.DefaultPosition, wx.DefaultSize,
                                    m_comboBox4Choices, 0)
        sergrid.Add(self.m_comboBox4, wx.GBPosition(3, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        m_comboBox5Choices = [u"1", u"1.5", u"2"]
        self.m_comboBox5 = wx.ComboBox(self.panel, wx.ID_ANY, u"1", wx.DefaultPosition, wx.DefaultSize,
                                    m_comboBox5Choices, 0)
        sergrid.Add(self.m_comboBox5, wx.GBPosition(4, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_staticText5 = wx.StaticText(self.panel, wx.ID_ANY, u"数据位:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_staticText5.Wrap(-1)
        sergrid.Add( self.m_staticText5, wx.GBPosition(2, 0), wx.GBSpan(1, 1), wx.ALL, 5)

        m_comboBox2Choices = [u"9600", u"19200", u"38400", u"57600", u"115200", u"230400", u"460800", u"921600",
                            wx.EmptyString, wx.EmptyString]
        self.m_comboBox2 = wx.ComboBox(self.panel, wx.ID_ANY, u"9600", wx.DefaultPosition, wx.DefaultSize,
                                    m_comboBox2Choices, 0)
        sergrid.Add(self.m_comboBox2, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        m_comboBox3Choices = [ u"8", u"7", u"6", u"5" ]
        self.m_comboBox3 = wx.ComboBox(self.panel, wx.ID_ANY, u"8", wx.DefaultPosition, wx.DefaultSize,
                                    m_comboBox3Choices, 0)
        sergrid.Add(self.m_comboBox3, wx.GBPosition(2, 1), wx.GBSpan(1, 1), wx.ALL, 5)

        self.m_staticText4 = wx.StaticText(self.panel, wx.ID_ANY, u"波特率:", wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_staticText4.Wrap(-1)
        sergrid.Add(self.m_staticText4, wx.GBPosition(1, 0), wx.GBSpan(1, 1), wx.ALL, 5)
        ################################################################################################################
        # layout
        self.panel.SetSizerAndFit(sergrid)
        self.panel.Layout()

        self.Centre(wx.BOTH)
        ################################################################################################################
        ################################################################################################################

2, 串口主要功能的实现代码如下:(SerialDeal.py)

# -*- coding: utf-8 -*-
#########################################################################################################
# pyserial   3.4
# Python 3.7.6rc1 (tags/v3.7.6rc1:bd18254b91, Dec 11 2019, 19:31:14) [MSC v.1916 32 bit (Intel)] on win32
#########################################################################################################
import os
import time
from time import *
import binascii
import logging
import serial

cwd = os.getcwd()
print(cwd)


class serDeal(object):
	def __init__(self, Port="COM6", BaudRate=9600, ByteSize=8, Parity="N", Stopbits=1, timeout=None,
				xonxof=0, rtscts=0):
		self.serSer = None
		self.alive = False
		self.port = Port
		self.baudrate = BaudRate
		self.bytesize = ByteSize
		self.parity = Parity
		self.stopbits = Stopbits
		self.timeout = timeout
		self.thresholdValue = 64
		self.receive_data = ""
	
	def start(self):
		self.serSer = serial.Serial()
		self.serSer.port = self.port
		self.serSer.baudrate= self.baudrate
		self.serSer.bytesize = self.bytesize
		self.serSer.parity = self.parity
		self.serSer.stopbits = self.stopbits
		self.serSer.timeout = self.timeout
		
		try:
			self.serSer.open()
			if self.serSer.isOpen():
				self.alive = True
		except Exception as e:
			self.alive = False
			logging.error(e)
	
	def stop(self):
		while self.alive:
			try:
				number = self.serSer.inWaiting()
				if number:
					self.receive_data += self.serSer.read(number).decode().replace(binascii.unhexlify("00").decode(), "")
					if self.thresholdValue <= len(self.receive_data):
						self.receive_data = ""
			except Exception as e:
				logging.error(e)
	
	def readcom(self):
		# we can deal with the UART output
		clear_time = 0
		while 1:
			sleep(0.05)
			reading = self.serSer.readall()
			if len(reading) > 0:
				LOG = self.serSer.port + ":" + reading
				print(LOG)
				self.__conservelog(LOG)
				clear_time = 0
			else:
				clear_time = clear_time + 1

			if clear_time > 10:
				break
	
	def write(self, data, isHex=False):
		if self.alive:
			if self.serSer.isOpen:
				if isHex:
					data = binascii.unhexlify(data)
					print(data)
				print(data)
				print(data.encode())
				self.serSer.write(data.encode())
	
	# support input from Console
	def write_serial_con(self):
		while 1:
			command = input()
			for character in command:
				self.serSer.write(character)
			self.serSer.write('\r')
	
	def write_serial(self, command):
		for character in command:
			self.serSer.write(character)
		self.serSer.write('\r')
		self.readcom()
				
	# 发送指令的完整流程
	def send_cmd(self, cmd):
		self.port.write(cmd)
		response = self.port.readall()
		response = self.convert_hex(response)
		return response
	
	# 转成16进制的函数
	def convert_hex(self, string):
		res = []
		result = []
		for item in string:
			res.append(item)
		for i in res:
			result.append(hex(i))
		
		return result
	
	def __conservelog(self, read_data):
		with open('testlog', 'a+') as writelog:
			writelog.write(time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))+': '+read_data+'\r')
	
	def close_serial(self):
		self.serSer.close()

3, 串口界面与功能绑定在一起,具体代码如下:(mainUI.py)

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#########################################################################################################
# pyserial   3.4
# Python 3.7.6rc1 (tags/v3.7.6rc1:bd18254b91, Dec 11 2019, 19:31:14) [MSC v.1916 32 bit (Intel)] on win32
#########################################################################################################
import time
import datetime
import threading
import binascii
import platform
import logging
import SerialDeal 
import serialMainUI
import serial
import wx
import wx.xrc

if platform.system() == "Windows":
    from serial.tools import list_ports
elif platform.system() == "Linux":
    import glob, os, re

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')


class MainSerialUI(serialMainUI.serialFrame):
    def __init__(self, parent=None):
        super(MainSerialUI, self).__init__(parent)
        self.ser = None
        self.receive_count = 0
        self.receive_data = ""
        self.list_box_serial = None
        # self.port = None
        # self.baudrate = None
        # self.bytesize = None
        # self.stopbit = None
        #################################################################################################
        # methods for every widget
        #################################################################################################
        self.do_ui()
        #################################################################################################
        #################################################################################################

    def __del__(self):
        if platform.system() == "Linux":
            try:
                self.ser.SetStopEvent()
            except:
                pass

    def _debug_(self):
        plist = list(list_ports.comports())

        if len(plist) <= 0:
            print("The Serial port can't find!")
        else:
            plist_0 =list(plist[0])
            serialName = plist_0[0]
            serialFd = serial.Serial(serialName)
            print("check which port was really used >",serialFd.name)

    def do_ui(self):
        # 打开串口
        self.m_openser.Bind(wx.EVT_BUTTON, self.OnButtonClick)
        # 关闭串口
        self.m_closeser.Bind(wx.EVT_BUTTON, self.OnButtonClick)
        # 清空接受区
        self.m_clrRcvText.Bind(wx.EVT_BUTTON, self.OnButtonClick)
        # 发送按钮1功能实现
        self.m_send1but.Bind(wx.EVT_BUTTON, self.OnButtonClick)
        # 清空按钮1功能实现
        self.m_clr1but.Bind(wx.EVT_BUTTON, self.OnButtonClick)

    def OnButtonClick(self, event):
        # 打开串口
        if event.GetEventObject() == self.m_openser:
            try:
                # port
                self.port = self.m_comset.GetValue()
                print("com is {}" .format(self.port))
                # baudrate
                self.baudrate = int(self.m_comboBox2.GetValue())
                print("buadrate is {}" .format(self.baudrate))
                # bytesize
                self.bytesize = int(self.m_comboBox3.GetValue())
                print("bytesize is {}" .format(self.bytesize))
                # parity
                self.parity = self.m_comboBox4.GetValue()
                print("parity is {}" .format(self.parity))
                if self.parity == u"None":
                    self.parity = serial.PARITY_NONE
                elif self.parity == u"Odd":
                    self.parity = serial.PARITY_ODD
                elif self.parity == u"Even":
                    self.parity = serial.PARITY_EVEN
                elif self.parity == u"Mark":
                    self.parity = serial.PARITY_MARK
                elif self.parity == u"Space":
                    self.parity = serial.PARITY_SPACE
                else:
                    print("parity error...")
                # stopbit
                self.stopbit = self.m_comboBox5.GetValue()
                print ("stopbit is {}" .format(self.stopbit))
                if self.stopbit == u"1":
                    self.stopbit = serial.STOPBITS_ONE
                elif self.stopbit == u"1.5":
                    self.stopbit = serial.STOPBITS_ONE_POINT_FIVE
                elif self.stopbit == u"2":
                    self.stopbit = serial.STOPBITS_TWO
                else:
                    print("stopbit error...")

                self.ser = SerialDeal.serDeal(Port=self.port,
                                            BaudRate=self.baudrate,
                                            ByteSize=self.bytesize,
                                            Parity=self.parity,
                                            Stopbits=self.stopbit)

                self.ser.start()
                print(u"opener --> self.ser.alive is {}" .format(self.ser.alive))
                if self.ser.alive:
                    print('success')
                    self.thread_read = threading.Thread(target=self.SerRead)
                    self.thread_read.setDaemon(True)
                    self.thread_read.start()
                    self.m_openser.Disable()
                    self.m_closeser.Enable()
            except serial.SerialException as e:
                logging.error(e)
                print(e)
                print(u'打开串口失败')
            event.Skip()

        # 关闭串口
        elif event.GetEventObject() == self.m_closeser:
            print(u"before : closer --> self.ser.alive is {}" .format(self.ser.alive))
            if self.ser.alive:
                self.ser.alive = False
            print(u"after : closer --> self.ser.alive is {}" .format(self.ser.alive))
            self.ser.close_serial()
            self.m_openser.Enable()
            self.m_closeser.Disable()

        # 清空接受区
        elif event.GetEventObject() == self.m_clrRcvText:
            print(u"接受区清空")
            self.m_rcvtext.Clear()
            print(u"Receive --> over")
            event.Skip()

        # 发送按钮1功能实现
        elif event.GetEventObject() == self.m_send1but:
            print(u"发送按钮1")
            try:
                if self.ser.alive:
                    send_data = ''
                    send_data += str(self.m_textCtrl5.GetValue())
                    self.ser.write(send_data)
                else:
                    wx.MessageBox(u"请注意,串口没有打开!!!", u"提示", wx.YES_NO | wx.CANCEL )
            except AttributeError as e:
                print(e)
                wx.MessageBox(u"请注意,串口没有打开!!!", u"提示", wx.YES_NO | wx.CANCEL )
            print(u"send 1 --> over")

        # 清空按钮1功能实现
        elif event.GetEventObject() == self.m_clr1but:
            print(u"清空按钮1")
            self.m_textCtrl5.Clear()
            print(u"clear 1 --> over")

    # 接收数据功能的实现

    def SerRead(self):
        while self.ser.alive:

            n = self.ser.serSer.inWaiting()
            try:
                self.receive_data = ""
                if n:
                    # print("self.ser.serSer.read(n) = {}" .format(self.ser.serSer.read(n)))
                    # print("self.m_rcvBox.GetValue() = {}" .format(self.m_rcvBox.GetValue()))
                    rev_data = self.ser.serSer.read(n).decode()
                    self.receive_data += rev_data.replace(binascii.unhexlify("00").decode(), "")
                    print("receive_data is {}" .format(self.receive_data))

                    # 接收显示是否为Hex
                    print("self.m_rcvBox.GetValue()={}, type is {}" .format(self.m_rcvBox.GetValue(), type(self.m_rcvBox.GetValue())))
                    if self.m_rcvBox.GetValue():
                        print("hex16")
                        print("self.receive_data = {}" .format(self.receive_data))
                        print("self.receive_data.encode()={}" .format(self.receive_data.encode()))
                        self.receive_data = self.space_b2a_hex(self.receive_data)
                        # self.receive_data = self.receive_data - 18
                    print("read5")
                    # ongoing
                    self.m_rcvtext.AppendText(self.receive_data)
                    self.receive_data = ""
            except Exception as e:
                logging.error(e)
                self.receive_data = ""
                self.ser.stop()
                self.ser = None

    def space_b2a_hex(self, data):
        """
        格式化接收到的数据字符串
         示例:123 --> 0x31 0x32 0x33 --> 49 50 51
        """
        new_data_list = []
        new_data = ""

        hex_data = binascii.b2a_hex(data.encode())
        temp_data = ""

        for index, value in enumerate(hex_data.decode()):
            temp_data += value
            if len(temp_data) >= 2:
                new_data_list.append(temp_data)
                temp_data = ""

        for index, value in enumerate(new_data_list):
            if index % 25 == 0 and index != 0:
                new_data += "\n"
            new_data += value
            new_data += " "
        print(u"new_data = {}" .format(new_data))
        return new_data


class SerialAPP(wx.App):
    def __init__(self):
        # 如果要重写 __init__, 必须调用wx.App的__init__,否则OnInit方法不会被调用
        wx.App.__init__(self)

    def OnInit(self):
        self.frame = MainSerialUI(None)
        self.frame.Show(True)

        return True


def main():
    App = SerialAPP()
    App.MainLoop()


if __name__ == '__main__':
    main()

接着,我们就用虚拟串口驱动(VSPD)来验证一下串口助手软件的功能。

首先,先来研究一下虚拟串口驱动的用法,所谓工欲善其事必先利其器,所以虚拟串口驱动就是这把利器,但是我们会体会到什么叫磨刀不误砍柴工。

第一步,先安装软件,点击下图中的vspd.exe文件。

第二步,将Cracked文件中的vspdconfig.exe和vspdctl.dll文件拷贝到虚拟串口驱动的安装目录下,如下面我电脑中的安装路径。

第三步,复制完后,然后点击vspdconfig.exe,便会出现下图中的界面。

第四步,点击添加端口按钮,左边会出现两个Virtual ports(虚拟串口) :COM1和COM2,如下界面所示。

第五步,点击命中左侧的COM1或者COM2,注意 :COM口是成对出现的,添加的时候,我认为你们应该注意到了 ,如下界面所示。

第六步,从设备管理器里面会发现多了两个虚拟接口。

 

最后,让我们用虚拟串口驱动来验证一下这款串口助手软件的功能是否如我们期望的那样。

首先,在COM1打一个串口助手软件,然后在COM2再打开一个串口助手软件。

最后呢,下面就用虚拟串口驱动验证串口助手软件的功能,具体看下面的动图。

PS : 附加中的代码与文章中的代码稍微有点区别,请以文中的代码为准。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值