Python通过AT阅读短信

时间:2016-05-02 13:51:42

标签: python python-2.7 pyserial at-command

我99%完成了我的脚本,但遇到了问题

我试图在python中显示从GSM调制解调器中收到的短信。

到目前为止,我可以看到文字已经出现,但无法显示信息。

我知道 self.ser.readlines()以列表形式返回

import serial
import time
class TextMessage:
    def connectPhone(self):
        self.ser = serial.Serial('COM14', 460800, timeout=5) #for mine this was ttyUSB0 but could be ttyUSB1 etc. good idea to runs ls usb and find out that way
        time.sleep(1)

    def read(self):
        self.ser.write('ATZ\r')
        time.sleep(1)
        self.ser.write('AT+CMGF=1\r')# put in textmode
        time.sleep(1)
        self.ser.write('''AT+CMGL="ALL"''' + '''\r''') #fetch all sms's
        read = self.ser.readlines()
        for msg in read:
         if "+CMGL" in msg: #+CMGL looks for all SMS messages
          print msg 

    def disconnectPhone(self):
        self.ser.close()

sms = TextMessage()
sms.connectPhone()
sms.read()
sms.disconnectPhone()
raw_input("Press anykey to exit")

这是输出

AT+CMGL="ALL"
+CMGL: 0,"REC READ","+61xxxxxxxxx",,"16/04/30,19:53:38+38"

+CMGL: 1,"REC READ","+61xxxxxxxxx",,"16/05/02,14:47:53+38"

+CMGL: 2,"REC READ","+61xxxxxxxxx",,"16/05/02,21:27:58+38"

我想要的输出是

+CMGL: 0,"REC READ","+61xxxxxxxxx",,"16/04/30,19:53:38+38"

Test back

+CMGL: 1,"REC READ","+61xxxxxxxxx",,"16/05/02,14:47:53+38"

Im a message

+CMGL: 2,"REC READ","+61xxxxxxxxx",,"16/05/02,21:27:58+38"

TEST TEST TEST

有人可以帮忙吗?

如果删除了输出

ATZ

OK

AT+CMGF=1

Ok


AT+GCML="ALL"

+CMGL: 0,"REC READ","+61xxxxxxxxx",,"16/04/30,19:53:38+38" 
Test back
+CMGL: 1,"REC READ","+61xxxxxxxxx",,"16/05/02,14:47:53+38" 
Im a message 
+CMGL: 2,"REC READ","+61xxxxxxxxx",,"16/05/02,21:27:58+38"
TEST TEST TEST


OK

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助

#!/usr/bin/env python2.7

import serial
import time
class TextMessage:
    def connectPhone(self):
        self.ser = serial.Serial('/dev/ttyUSB2', 9600, timeout=5) #for mine this was ttyUSB0 but could be ttyUSB1 etc. good idea to runs ls usb and find out that way
        time.sleep(1)

    def read(self):
        self.ser.write('ATZ\r')
        time.sleep(1)
        self.ser.write('AT+CMGF=1\r')# put in textmode
        time.sleep(1)
        self.ser.write('''AT+CMGL="ALL"''' + '''\r''') #fetch all sms's
        read = self.ser.readlines()
        i=0
        for msg in read:
         if "+CMGL" in msg: #+CMGL looks for all SMS messages
          bvb = 'AT+CMGR={}'.format(str(i)) + '\r'
          self.ser.write(bvb) #fetch all sms's
          ead = self.ser.readlines()
          for x in ead:
            print (x)
            print (i)
          i=i+1

    def disconnectPhone(self):
        self.ser.close()

sms = TextMessage()
sms.connectPhone()
sms.read()
sms.disconnectPhone()
raw_input("Press anykey to exit")