本文首发于在下的个人博客blog.keysking.com
前段时间有个项目,要用stm32跟一个比较大,比较重的设备进行频繁的串口通信,因为设备移动起来不方便,遂想写个脚本,代替设备,对stm32的通信逻辑进行测试.
于是有了以下代码:
# coding=utf-8
import serial
import threading
import csv
import random
identitys_csv = csv.reader(open('./identitys.csv','r'))
# identitys_csv = csv.reader(open('./identitys_less.csv','r'))
identitys = list()
ser = serial.Serial("COM13",9600)
askData = bytes([0xA0, 0x0D, 0x01, 0x8A, 0x00, 0x01, 0x01, 0x01, 0x02, 0x01, 0x03, 0x01, 0x00, 0x0A, 0xB4])
def receiveFunc():
print("---------------测试开始--------------")
serData = bytes()
while len(identitys) != 0:
if ser.inWaiting() > 0 :
out = ser.read(1)
serData += out
if len(serData) == 15:
if serData == askData:
print("-------------设备请求数据------------")
num = random.randint(5,15)
if num > len(identitys):
num = len(identitys)
print("--------------发送"+str(num)+"个数据------------")
for identity in identitys[0:num]:
print(identity)
identityFormatData = transToFormat(identity)
ser.write(identityFormatData)
for i in identityFormatData:
print('0x%02x'%i,end=' ')
print("")
del identitys[0:num]
else:
print("------------不知是啥的数据-----------")
for i in out:
print('0x%02x'%i,end=' ')
print("")
serData = bytes()
print("---------------测试结束--------------")
def transToFormat(identity):
if identity[-1] == "X":
identity = identity.replace("X",":")
formatData = bytes([0xA0,0x13,0x01,0x8A,0x00,0x00,0x00])
for i in range(len(identity)//2):
temp = ((identity[2*i].encode('utf-8')[0] - 0x30) << 4) + (identity[2*i+1].encode('utf-8')[0] - 0x30)
formatData += bytes([temp])
formatData += bytes([0x00,0x00,0x00,0x00])
checkSum = 0
for i in formatData:
checkSum += i
checkSum = checkSum & 0x00FF
checkSum = 0x100 - checkSum
if checkSum == 256:
checkSum = 0
formatData += bytes([checkSum])
return formatData
if __name__== '__main__':
print("---------正在读取测试数据列表--------")
for i in identitys_csv:
identitys.append(i[0])
print("---------共"+str(len(identitys))+"条测试数据--------")
receiveThread = threading.Thread(target=receiveFunc,name="receive")
receiveThread.start()
主要作用是将存在csv文件中的很多身份证信息取出来,然后等stm32那边通过串口发来请求信息(ackData)的时候,就随机取5到15个身份证信息,按照一定数据格式发送给stm32.