Python 2.7 使用pyserial的AT命令不用于接收sms
这是用python编写的代码片段,用于通过usb调制解调器接收sms。当我运行程序时,我得到的只是一条状态消息OK.,但没有其他消息。我如何解决这个问题以打印我收到的消息Python 2.7 使用pyserial的AT命令不用于接收sms,python-2.7,sms,modem,at-command,pyserial,Python 2.7,Sms,Modem,At Command,Pyserial,这是用python编写的代码片段,用于通过usb调制解调器接收sms。当我运行程序时,我得到的只是一条状态消息OK.,但没有其他消息。我如何解决这个问题以打印我收到的消息 import serial class HuaweiModem(object): def __init__(self): self.open() def open(self): self.ser = serial.Serial('/dev/ttyUSB_utps_modem
import serial
class HuaweiModem(object):
def __init__(self):
self.open()
def open(self):
self.ser = serial.Serial('/dev/ttyUSB_utps_modem', 115200, timeout=1)
self.SendCommand('ATZ\r')
self.SendCommand('AT+CMGF=1\r')
def SendCommand(self,command, getline=True):
self.ser.write(command)
data = ''
if getline:
data=self.ReadLine()
return data
def ReadLine(self):
data = self.ser.readline()
print data
return data
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r'
print self.SendCommand(command,getline=False)
self.ser.timeout = 2
data = self.ser.readline()
print data
while data !='':
data = self.ser.readline()
if data.find('+cmgl')>0:
print data
h = HuaweiModem()
h.GetAllSMS()
在GetAllSMS中,我注意到两件事: 1您使用的是self.ser.readline而不是self.readline,因此在收到OK最终响应之前,GetAllSMS将不会尝试打印除第一个响应行之外的任何内容,并且此时数据。find'+cmgl'>0将永远不匹配 这就是问题所在吗 2将打印self.sendcommand,getline=False调用函数,就像它被写为self.sendcommand,getline=False一样?只是检查一下,因为我自己不写python 在任何情况下,您都应该在解析时稍微返工一下
def SendCommand(self,command, getline=True):
这里的getline参数不是一个很好的抽象。省略SendCommand函数的读取响应。您应该实现对调制解调器返回的响应的正确解析,并在外部处理。一般情况下
self.SendCommand('AT+CSOMECMD\r')
data = self.ser.readline()
while ! IsFinalResult(data):
data = self.ser.readline()
print data # or do whatever you want with each line
对于没有显式处理响应的命令,可以实现执行上述操作的SendCommandWaitForFinalResponse函数。
有关IsFinalResult函数的更多信息,请参阅答案。您遇到问题的地方在GetAllSMS函数中。现在用你的函数替换我的GeTALLSMS函数,看看会发生什么
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r' #to get all messages both read and unread
print self.SendCommand(command,getline=False)
while 1:
self.ser.timeout = 2
data = self.ser.readline()
print data
还是这个
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r' #to get all messages both read and unread
print self.SendCommand(command,getline=False)
self.ser.timeout = 2
data = self.ser.readall() #you can also u read(10000000)
print data
就这些