Python 调用 GSM A6
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 调用 GSM A6相关的知识,希望对你有一定的参考价值。
代码速记:
#encoding: utf-8 #author: walker #date: #summary: import time import serial.tools.list_ports # 打印所有串口名 def PrintAllSerialPortName(): serailPortList = list(serial.tools.list_ports.comports()) print(‘serail port number: %d‘ % len(serailPortList)) if len(serailPortList) < 1: print("Not found serail port!") return for serailPort in serailPortList: serialFd = serial.Serial(list(serailPort)[0], 9600, timeout=60) print(‘serail port name:%s‘ % serialFd.name) print(serialFd.port) print(type(serialFd)) serialFd.close() class Messager(object): # 构造函数,打开端口 def __init__(self): self.sePort = serial.Serial(port=‘COM3‘, baudrate=19200, bytesize=8, stopbits=1, timeout=3) # 析构函数,关闭端口 def __del__(self): #self.sePort.close() pass # 重新打开端口 def reopen(self): print(‘reopen ...‘) self.sePort.close() self.sePort = serial.Serial(port=‘COM3‘, baudrate=19200, bytesize=8, stopbits=1, timeout=3) time.sleep(3) # 执行指令 # 返回从串口读取的返回值 def execCmd(self, cmd, end=‘\r‘): cmd = cmd + end bCmd = cmd.encode(‘ascii‘) print(‘write:%s‘ % bCmd) self.sePort.write(bCmd) response = self.sePort.readall() print(‘read :%s‘ % response) print() return response # 发送英文短信 # 正确返回 True;错误返回 False def __sendMessageEn(self, phoneNumber, message): if not self.execCmd(‘AT+CMGF=1‘).endswith(b‘\r\nOK\r\n‘): #设置TEXT MODE return False if not self.execCmd(‘AT+CSCS="GSM"‘).endswith(b‘\r\nOK\r\n‘): return False if not self.execCmd(‘AT+CMGS="%s"‘ % phoneNumber).endswith(b‘\r\n> ‘): return False # 十六进制的1A为结束符 if not self.execCmd(message + ‘\x1A‘, end=‘‘).endswith(b‘\r\nOK\r\n‘): return False return True # 调用私有方法 __sendMessageEn # 在失败时重新打开串口 def sendMessageEn(self, phoneNumber, message): for _ in range(0, 3): if self.__sendMessageEn(phoneNumber, message): break self.reopen() if __name__ == ‘__main__‘: messager.sendMessageEn(‘18688754379‘, ‘xxx‘) messager.sendMessageEn(‘18688754379‘, ‘zzz‘)
*** walker ***
本文出自 “walker的流水账” 博客,请务必保留此出处http://walkerqt.blog.51cto.com/1310630/1970472
以上是关于Python 调用 GSM A6的主要内容,如果未能解决你的问题,请参考以下文章