这是我用来轮询通过串行端口连接到我的笔记本电脑的 GSM 调制解调器收到的新消息的功能。我创建了一个串行对象“电话”,用于读取和写入数据。
'phone' 将数据读入列表 x。
当我收到一条新消息时,我得到的响应格式如下:
+CMTI: "SM",0
这里0是索引,表示消息在SIM卡上存储的索引位置。以下代码用于轮询列表 x,其中包含我正在从串行端口读取和写入的数据。我正在使用正则表达式来解析已转换为字符串 myRegexableString 的 x 以查看我是否收到通知。
def poll(x):
myRegexableString = "".join(x)
print "Printing myRegexableString"
pprint(myRegexableString)
regex = re.compile(r'\+CMTI: "SM",(\d+)')
lst = []
for l in myRegexableString:
for m in [regex.search(l)]:
if myRegexableString:
lst.append(m)
print "You have received a new message!"
我想将上述代码用于检查网络注册的 AT 命令。在执行其他命令或任何命令时,我也需要轮询新消息,但为了这个问题,我将举网络注册的例子。以下是它在不使用轮询功能的情况下正常运行的方式。
AT+CREG? #command
+CREG: 0,1 #response
OK #status
现在这是代码。
def register():
print "Checking for network registration"
phone.write(b'AT+CREG?\r')
sleep()
x=phone.read(50)
sleep()
print x
现在假设我在这里包括轮询代码将更改为
def register():
print "Checking for network registeration"
phone.write(b'AT+CREG?\r')
sleep()
x=phone.read(50)
poll(x)
sleep()
print x
我从更改后的代码中得到的输出是
Checking for network registeration
Printing myRegexableString
'AT+CREG?\r\r\n+CREG: 0,1\r\n\r\nOK\r\n'
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
You have received a new message!
AT+CREG?
+CREG: 0,1
OK
为什么会打印“您收到一条新消息!” 很多次?
特别是当我没有收到新消息时!
请帮忙。