1.记录串口日志
import serial,time,re
import serial.tools.list_ports
def port_log():
# 创建串口对象
ser = serial.Serial(port="COM4", baudrate=115200,stopbits=1,timeout=0.5)
# 判断串口是否打开
if ser.isOpen():
print('open success.')
while True:
if ser.in_waiting:
# 读数据
read_msghex = ser.readline()
str=read_msghex.decode('utf-8')
# 打开日志文件
port_log = open('../opt/port_log.txt', mode='a', encoding='utf-8')
if (str == "exit"): # 退出标志
break
else:
print("收到数据:",time.strftime('%Y/%m/%d %H:%M:%S ', time.localtime(time.time())),str,file=port_log)
# 切记关闭文件
port_log.close()
else:
print('open failed.')
# 关闭串口
ser.close()
if __name__ == '__main__':
port_log()
2.控制串口,检查串口回复,记录日志
import serial,time,re
import serial.tools.list_ports
def port_test(send,msg):
# 创建串口对象
ser = serial.Serial(port="COM6", baudrate=9600,stopbits=1,timeout=0.5)
# 判断串口是否打开
if ser.isOpen():
# print('open success.')
while True:
# 发送数据,这里只支持 bytes 类型的数据
send_len = ser.write(bytes.fromhex(send))
# print('send data length: {}'.format(send_len))
# 读取数据,读取的内容也是 bytes 类型
read_msghex = ser.readline().hex()
msg_list = re.findall(".{2}", read_msghex.upper())
read_msg = " ".join(msg_list)
# 打开日志文件
port_check_log = open('../opt/port_check_log.txt', mode='a', encoding='utf-8')
if read_msg ==msg:
print(time.strftime('%Y/%m/%d %H:%M:%S ', time.localtime(time.time()))+'pass')
else:
print(time.strftime('%Y/%m/%d %H:%M:%S ', time.localtime(time.time()))+str(read_msg),file=port_check_log)
# 切记关闭文件
port_check_log.close()
time.sleep(7200)
else:
print('open failed.')
# 关闭串口
ser.close()
if __name__ == '__main__':
# 控制空调开关
port_test('01 06 0F A0 00 01 4B 3C','01 06 0F A0 00 01 4B 3C')