예제 #1
0
 def sms(self):
     self.ser.write(b'AT+CMGL=0\r\n')
     ser_output = self.ser.readlines()
     print(ser_output)
     if len(ser_output) > 2:
         log.info('SendRecvSmsTask {0} {1} recv_message: {2}'.format(
             self.com, ser_output))
         next_parse_flag = False
         for code in ser_output:
             code = code.decode()
             print("code: ", code)
             if next_parse_flag:
                 code = code.strip()
                 log.info('SendRecvSmsTask decodeSmsPdu {0}'.format(code))
                 print("codestrip: ", code)
                 msg_data = decodeSmsPdu(code)
                 log.info('SendRecvSmsTask {0} {1} msg_data: {2}'.format(
                     self.com, msg_data))
                 print("msg_data: ", msg_data)
                 delsms = "AT+CMGD={0}\r\n".format(msg_index_no).encode()
                 print("delete:", delsms)
                 self.ser.write(delsms)
                 next_parse_flag = False
             elif code[:6] == '+CMGL:' and code[9:10] == "0":
                 msg_index_no = code[7:8]
                 next_parse_flag = True
예제 #2
0
 def listStoredSmsWithIndex(self, status=Sms.STATUS_ALL, memory=None):
     self._setSmsMemory(readDelete=memory)
     messages = []
     cmglRegex = re.compile(r'^\+CMGL:\s*(\d+),\s*(\d+),.*$')
     readPdu = False
     result = self.write('AT+CMGL={0}'.format(status))
     for line in result:
         if not readPdu:
             cmglMatch = cmglRegex.match(line)
             if cmglMatch:
                 msgIndex = int(cmglMatch.group(1))
                 msgStat = int(cmglMatch.group(2))
                 readPdu = True
         else:
             try:
                 smsDict = decodeSmsPdu(line)
             except Exception as e:
                 logging.error(' at %s', 'Modem.listStoredSmsWithIndex', exc_info=e)
                 pass
             else:
                 if smsDict['type'] == 'SMS-DELIVER':
                     sms = ReceivedSms(self, int(msgStat), smsDict['number'], smsDict['time'], smsDict['text'], smsDict['smsc'], smsDict.get('udh', []))
                 elif smsDict['type'] == 'SMS-STATUS-REPORT':
                     sms = StatusReport(self, int(msgStat), smsDict['reference'], smsDict['number'], smsDict['time'], smsDict['discharge'], smsDict['status'])
                 sms.msgIndex = msgIndex
                 messages.append(sms)
                 readPdu = False
     return messages
예제 #3
0
    def get_all_sms(self):
        allmsgs = 'd' + self.execute_atcmd('AT+CMGL=4')
        allmsgs = re.findall("(?<=\+CMGL:).+\r\n.+(?=\n*\r\n\r\n)", allmsgs)
        msglist = []
        tpdu_header = 0
        multi_sms_construct = ""
        print(">> Fetching inbox...")
        for msg in allmsgs:
            try:
                pdu = re.search(r'[0-9A-F]{20,}', msg).group(0)
            except AttributeError:
                print(">> Error: cannot find pdu text", msg)
                continue
            try:
                smsdata = PduDecoder.decodeSmsPdu(pdu)
            except ValueError as e:
                print(">> Error: conversion to pdu (cannot decode "
                      "odd-length)")
                print(">> Error: ", e)
                continue
            except IndexError:
                print(">> Error: convertion to pdu (pop from empty array)")
                continue

            if smsdata == "":
                continue
            try:
                txtnum = re.search(r'(?<= )[0-9]{1,2}(?=,)', msg).group(0)
            except AttributeError:
                print(">> Error: message may not have correct "
                      "construction", msg)
                continue

            txtdatetimeStr = smsdata['time'] + td(hours=8)
            txtdatetimeStr = txtdatetimeStr.strftime('%Y-%m-%d %H:%M:%S')

            if smsdata['tpdu_length'] < 159:
                if tpdu_header != 0:
                    tpdu_header = self.increamentHexPDU(tpdu_header)
                    if (tpdu_header in pdu):
                        smsdata['text'] = multi_sms_construct + smsdata['text']
                        tpdu_header = self.increamentHexPDU(tpdu_header)
                        smsItem = GsmSms(txtnum, smsdata['number'].strip('+'),
                                         str(smsdata['text']), txtdatetimeStr)
                        msglist.append(smsItem)
                else:
                    smsdata['text'] = smsdata['text']
                    smsItem = GsmSms(txtnum, smsdata['number'].strip('+'),
                                     str(smsdata['text']), txtdatetimeStr)
                    msglist.append(smsItem)
            else:
                multi_sms_construct = multi_sms_construct + smsdata['text']
                tpdu_header = pdu[54:66]
        return msglist
예제 #4
0
    def get_all_sms(self):
        allmsgs = 'd' + self.execute_atcmd('AT+CMGL=4')
        allmsgs = re.findall("(?<=\+CMGL:).+\r\n.+(?=\n*\r\n\r\n)", allmsgs)
        msglist = []

        for msg in allmsgs:
            try:
                pdu = re.search(r'[0-9A-F]{20,}', msg).group(0)
            except AttributeError:
                print(">> Error: cannot find pdu text", msg)
                continue
            try:
                smsdata = PduDecoder.decodeSmsPdu(pdu)
            except ValueError as e:
                print(">> Error: conversion to pdu (cannot decode "
                      "odd-lllength)")
                print(">> Error: ", e)
                continue
            except IndexError:
                print(">> Error: convertion to pdu (pop from empty array)")
                continue

            # smsdata = self.manage_multi_messages(smsdata) | REFACTOR THIS

            if smsdata == "":
                continue
            try:
                txtnum = re.search(r'(?<= )[0-9]{1,2}(?=,)', msg).group(0)
            except AttributeError:
                print(">> Error: message may not have correct "
                      "construction", msg)
                continue

            txtdatetimeStr = smsdata['time'] + td(hours=8)
            txtdatetimeStr = txtdatetimeStr.strftime('%Y-%m-%d %H:%M:%S')

            try:
                smsItem = GsmSms(txtnum, smsdata['number'].strip('+'),
                                 str(smsdata['text']), txtdatetimeStr)
                sms_msg = str(smsdata['text'])
                if len(sms_msg) < 30:
                    print("<<", sms_msg)
                else:
                    print("<<", sms_msg[:10], "...", sms_msg[-20:])

                msglist.append(smsItem)
            except UnicodeEncodeError:
                print(">> Unknown character error. Skipping message")
                continue
        return msglist
예제 #5
0
파일: getSMS.py 프로젝트: weahwww/python
 def sms(self):
     self.ser.write(b'AT+CMGL=0\r\n')  # PDU模式下读取所有未读消息
     ser_output = self.ser.readlines()
     if len(ser_output) > 2:
         log.info('SendRecvSmsTask {0} recv_message: {1}'.format(self.com, ser_output))
         next_parse_flag = False
         for code in ser_output:
             code = code.decode()
             if next_parse_flag:
                 code = code.strip()
                 log.info('SendRecvSmsTask decodeSmsPdu {0}'.format(code))
                 msg_data = decodeSmsPdu(code)
                 log.info('SendRecvSmsTask {0} msg_data: {1}'.format(self.com, msg_data))
                 next_parse_flag = False
             elif code[:6] == '+CMGL:':
                 next_parse_flag = True
예제 #6
0
파일: getSMS.py 프로젝트: weahwww/python
 def sms(self):
     self.ser.write(b'AT+CMGL=0\r\n')  # PDU模式下读取所有未读消息
     ser_output = self.ser.readlines()
     if len(ser_output) > 2:
         log.info('SendRecvSmsTask {0} recv_message: {1}'.format(
             self.com, ser_output))
         next_parse_flag = False
         for code in ser_output:
             code = code.decode()
             if next_parse_flag:
                 code = code.strip()
                 log.info('SendRecvSmsTask decodeSmsPdu {0}'.format(code))
                 msg_data = decodeSmsPdu(code)
                 log.info('SendRecvSmsTask {0} msg_data: {1}'.format(
                     self.com, msg_data))
                 next_parse_flag = False
             elif code[:6] == '+CMGL:':
                 next_parse_flag = True
예제 #7
0
 def sms(self):
     self.ser.write(b'AT+CMGL=0\r\n')
     ser_output = self.ser.readlines()
     print(ser_output)
     if len(ser_output) > 2:
         log.info('SendRecvSmsTask {0} {1} recv_message: {2}'.format(self.com, ser_output))
         next_parse_flag = False
         for code in ser_output:
             code = code.decode()
             print("code: ", code)
             if next_parse_flag:
                 code = code.strip()
                 log.info('SendRecvSmsTask decodeSmsPdu {0}'.format(code))
                 print("codestrip: ", code)
                 msg_data = decodeSmsPdu(code)
                 log.info('SendRecvSmsTask {0} {1} msg_data: {2}'.format(self.com, msg_data))
                 print("msg_data: ", msg_data)
                 delsms = "AT+CMGD={0}\r\n".format(msg_index_no).encode()
                 print("delete:",delsms)
                 self.ser.write(delsms)
                 next_parse_flag = False
             elif code[:6] == '+CMGL:' and code[9:10] == "0":
                 msg_index_no = code[7:8]
                 next_parse_flag = True
예제 #8
0
    def get_all_sms(self, network):
        allmsgs = 'd' + self.at_cmd('AT+CMGL=4')
        # print allmsgs.replace('\r','@').replace('\n','$')
        # allmsgs = allmsgs.replace("\r\nOK\r\n",'').split("+CMGL")[1:]

        allmsgs = re.findall("(?<=\+CMGL:).+\r\n.+(?=\n*\r\n\r\n)",allmsgs)
        #if allmsgs:
        #    temp = allmsgs.pop(0) #removes "=ALL"
        msglist = []
        
        for msg in allmsgs:
            try:
                pdu = re.search(r'[0-9A-F]{20,}',msg).group(0)
            except AttributeError:
                # particular msg may be some extra strip of string 
                print (">> Error: cannot find pdu text", msg)
                # log_error("wrong construction\n"+msg[0])
                continue

            try:
                smsdata = PduDecoder.decodeSmsPdu(pdu)
            except ValueError:
                print (">> Error: conversion to pdu (cannot decode odd-length)")
                continue
            except IndexError:
                print (">> Error: convertion to pdu (pop from empty array)")
                continue

            smsdata = self.manage_multi_messages(smsdata)
            if smsdata == "":
                continue

            try:
                txtnum = re.search(r'(?<= )[0-9]{1,2}(?=,)',msg).group(0)
            except AttributeError:
                # particular msg may be some extra strip of string 
                print (">> Error: message may not have correct construction", msg)
                # log_error("wrong construction\n"+msg[0])
                continue
            
            txtdatetimeStr = smsdata['date'] + td(hours=8)

            txtdatetimeStr = txtdatetimeStr.strftime('%Y-%m-%d %H:%M:%S')

    #        print smsdata['text']
            try:        
                smsItem = GsmSms(txtnum, smsdata['number'].strip('+'), 
                    str(smsdata['text']), txtdatetimeStr)

                sms_msg = str(smsdata['text'])
                if len(sms_msg) < 30:
                    print (sms_msg)
                else:
                    print (sms_msg[:10], "...", sms_msg[-20:])

                msglist.append(smsItem)
            except UnicodeEncodeError:
                print (">> Unknown character error. Skipping message")
                continue

        return msglist
예제 #9
0
 def __init__(self, index, status, pdu_body):
     self.set_index(index)
     self.status = status
     self.pdu_body = pdu_body
     self.message = decodeSmsPdu(pdu_body)
     print(self.message)