我在使用python代码时遇到了一些困难。我有Rpi2和SIM900模块连接。即使我可以收到短信,我也可以拨打电话,接听电话,发短信。但把所有这些放在一起让我很头疼。我已经滚动浏览谷歌,现在我发现即使结果也一直都是这样,所以我在0点进一步。
所以我的议程是我会发送短信给SimModule。如果短信将从批准的列表中的电话号码到达,Python会读取传入的短信,并且包含特定号码的特定代码:
短信的例子
RV -> make call to cell no: 49
RI -> make call to cell no: 48
MV -> make call to cell no: 47
MI -> make call to cell no: 46
到目前为止,我已经可以使用以下代码阅读短信
import serial
import time
import sys
class sim900(object):
def __init__(self):
self.open()
def open(self):
self.ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=5)
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'#gets incoming sms that has not been read
print self.SendCommand(command,getline=True)
data = self.ser.readall()
print data
self.ser.close()
def Call49(self):
self.ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=5)
self.ser.write('ATD49;\r')
time.sleep(1)
time.sleep(1)
self.ser.write(chr(26))
# responce = ser.read(50)
self.ser.close()
print "calling"
def Call48(self):
self.ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=5)
self.ser.write('ATD48;\r')
time.sleep(1)
self.ser.write(chr(26))
# responce = ser.read(50)
self.ser.close()
print "calling"
h = sim900()
h.GetAllSMS()
我可以阅读短信(见下文)
AT+CMGL="ALL"
AT+CMGL="ALL"
+CMGL: 1,"REC READ","+30000000000","","17/08/27,23:28:51+08"
RV
+CMGL: 2,"REC READ","+30000000000","","17/08/28,00:34:12+08"
RI
OK
现在如何在短信" def GetAllSMS"中添加功能?电话号码+30000000000将与文本RV一起存在,它将执行" def Call48"如果它是RI,它将执行" def Call47"
一些帮助将不胜感激。 Tnx提前。
答案 0 :(得分:1)
正确解析调制解调器响应可能很棘手(例如,请参阅this answer)。如果您打算使用消息传递功能以及语音呼叫和USSD请求,您可能最终会重新创建python-gsmmodem library :)但是在您解析SMS响应的特殊情况下,您可以使用此代码(改编自提及蟒-GSMMODEM)。
import re
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
result = self.SendCommand('AT+CMGL="ALL"\r\n')
msg_lines = []
msg_index = msg_status = number = msg_time = None
cmgl_re = re.compile('^\+CMGL: (\d+),"([^"]+)","([^"]+)",[^,]*,"([^"]+)"$')
# list of (number, time, text)
messages = []
for line in result:
cmgl_match = cmgl_re.match(line)
if cmgl_match:
# New message; save old one if applicable
if msg_index != None and len(msg_lines) > 0:
msg_text = '\n'.join(msg_lines)
msg_lines = []
messages.append((number, msg_time, msg_text))
msg_index, msg_status, number, msg_time = cmgl_match.groups()
msg_lines = []
else:
if line != 'OK':
msg_lines.append(line)
if msg_index != None and len(msg_lines) > 0:
msg_text = '\n'.join(msg_lines)
msg_lines = []
messages.append((number, msg_time, msg_text))
return messages
此函数将读取所有SMS并将其作为元组列表返回:[("+30000000000", "17/08/28,00:34:12+08", "RI"), ("+30000000000", "17/08/28,00:34:12+08", "RV")
...迭代该列表以检查数字是否有效并采取必要的措施:
for number, date, command in messages:
if number != "+30000000000":
continue
if command == 'RI':
self.call_1()
elif command == 'RV':
self.call_2()