串口测试案例

import time
import serial
cmd0 = b'defaultconfig\r\n'
cmd1 = b'login 0 admin 12345678\r\n'
cmd2 = b'newuser 1 config 12345678\r\n'
cmd3 = b'exit\r\n'
cmd4 = b'login 1 config 12345678\r\n'
cmd5 = b'ifconfig eth0 192.168.3.4\r\n'
cmd6 = b'addrule f 0 0.0.0.0 0.0.0.0 0 0.0.0.0 0.0.0.0 0 0 2\r\n'
cmd7 = b'addrule i 0 0.0.0.0 0.0.0.0 0 0 0 0 0\r\n'
cmd8 = b'setsnserial COM2 1 0 0 9600 8 1 n n eth0 9090 0.0.0.0 0 512 200 0.0.0.0 0.0.0.0 0 13900000000\r\n'
cmd9 = b'saveconfig\r\n'


while 1:
try:
ser = serial.Serial("COM3",115200,timeout=0.5)
if ser.is_open == True:
print("串口已打开,等待连接....")
else:
print("\u001b[31m 串口打开失败\u001b[0m")
time.sleep(0.2)
ser.write(cmd0)
try:
if ser.read(100).decode("GBk").split()[-2] == "不支持的命令":
print("\u001b[31m 设备第二次运行,无法初始化\u001b[0m")
except Exception as e:
if str(e).strip() == "list index out of range":
ser.close()
continue
else:
pass
time.sleep(0.2)
ser.write(cmd1)
if ser.read(100).decode("GBk").split()[-2] == "success":
print("login登录成功!")
else:
print("\u001b[31m login登录失败!\u001b[0m")
continue
time.sleep(0.2)
ser.write(cmd2)
if ser.read(100).decode("GBk").split()[-2] == "用户已存在":
print("\u001b[38;5;11m用户已存在.....\u001b[0m")
else:
print("用户创建成功!")
time.sleep(0.2)
ser.write(cmd3)
if ser.read(100).decode("GBk").split()[0] == "exit":
print("login退出成功!")
else:
print("\u001b[31m login退出失败!\u001b[0m")
continue
time.sleep(0.2)
ser.write(cmd4)
if ser.read(100).decode("GBk").split()[-2] == "success":
print("config登录成功!")
else:
print("\u001b[31m config登录失败!\u001b[0m")
continue
time.sleep(0.2)
ser.write(cmd5)
if ser.read(100).decode("GBk").split()[-2] == "192.168.3.4":
print("eth0设置成功!")
else:
print("\u001b[31m eth0设置失败!\u001b[0m")
continue
time.sleep(0.2)
ser.write(cmd6)
if ser.read(100).decode("GBk").split()[-2] == "success":
print("转发规则创建成功!")
else:
print("\u001b[38;5;11m转发规则已存在\u001b[0m")
time.sleep(0.2)
ser.write(cmd7)
if ser.read(100).decode("GBk").split()[-2] == "success":
print("入站规则创建成功!")
else:
print("\u001b[38;5;11m入站规则已存在\u001b[0m")
time.sleep(0.2)
ser.write(cmd8)
if ser.read(200).decode("GBk").split()[-2] == "success":
print("串口转发设置成功!")
else:
print("\u001b[31m 串口转发设置失败!\u001b[0m")
ser.close()
time.sleep(5)
# break

except Exception as e:
try:
if str(e).split()[-3].split("'")[-2].strip()=="系统找不到指定的文件。":
print("\u001b[31m COM3接口未插入\u001b[0m")
time.sleep(1)
continue
elif str(e).split()[-3].split("'")[-2].strip() == "拒绝访问。":
print("\u001b[31m COM3拒绝访问。\u001b[0m")
time.sleep(1)
ser.close()
continue
else:
print("\u001b[31m COM3串口被占用\u001b[0m")
except Exception as e:
continue

  上一篇:串口超级命令行 下一篇:github超时解决  

湘ICP备19016894号 © 2019 小钱