1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
import serial import sys import time import filecmp import serial.tools.list_ports
def sendInfo(strInfo): try: print ('['+time.strftime("%Y-%m-%d %X")+']发→◇'+strInfo.decode()) except Exception: print ('['+time.strftime("%Y-%m-%d %X")+']发→◇', end='') print(strInfo) def recvInfo(strInfo): try: print ('['+time.strftime("%Y-%m-%d %X")+']收←◆'+strInfo.decode()) except Exception: print ('['+time.strftime("%Y-%m-%d %X")+']收←◆', end='') print(strInfo)
def list_comport(): plist = list(serial.tools.list_ports.comports()) if len(plist) <= 0: print("没有发现端口!") else: for aport in plist: print("可用端口名>>>",aport[0],"-",aport)
plist_0 = list(plist[0]) serialName = plist_0[0]
try: serialFd = serial.Serial(serialName, 9600, timeout=60) print("可用端口名>>>", serialFd.name) return serialFd.name except: print('无法打开串口') sys.exit(0)
def waitForCmdOKRsp(timeout): timeout *=10 while True: n=ser.inWaiting() if n: line = ser.read(n) recvInfo(line.decode()) i=line.find(b'OK') if i>=0: break time.sleep(0.1) timeout-=1 if (timeout<=0): print('[INFO]等待AT命令返回OK超时') sys.exit(0) def waitForCmdRsp(timeout): timeout *=10 while True: n=ser.inWaiting() if n: line = ser.read(n).decode() recvInfo(line) return time.sleep(0.1) timeout-=1 if(timeout<=0): print('[INFO]等待AT命令返回超时') break def sendAT_Cmd(serInstance,atCmdStr,waitforOk,timeout): sendInfo(atCmdStr) serInstance.write(atCmdStr.encode('utf-8')) if(waitforOk == 1): waitForCmdOKRsp(timeout) else: waitForCmdRsp(timeout)
def scanport(): plist = list(serial.tools.list_ports.comports()) if len(plist) <= 0: print("没有发现端口!") else: for aport in plist: print("可用端口名>>>",aport) return plist
portlist = scanport() for a in portlist: print(a)
comport='COM5'
try: ser = serial.Serial(port=comport, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0) if ser.isOpen() : print("[INFO]%s open success" % comport) else : print("[INFO]%s open failed" % comport) except: print ("[INFO]请查看是否成功打开设备端口:"+comport) sys.exit() sendAT_Cmd(ser,'AT\r\n',1, 5)
|